Search Apps Documentation Source Content File Folder Download Copy Actions Download State String Boolean Number Struct Map Slice Pointer Function Closure Reference Nil Package Type Interface Unknown

trivia_test.gno

2.18 Kb · 78 lines
 1package trivia
 2
 3import (
 4	"strings"
 5	"testing"
 6
 7	"gno.land/p/nt/avl/v0"
 8)
 9
10// resetQuiz re-initializes package globals so each test starts clean; init()
11// only runs once for the whole test binary.
12func resetQuiz(height int64) {
13	current = newRound(1, height)
14	scores = avl.NewTree()
15	totalCorrect = 0
16}
17
18func TestQuestionIndexDeterministic(t *testing.T) {
19	n := len(questions)
20	for _, h := range []int64{0, 1, 42, 12345, -7} {
21		idx := questionIndex(1, h)
22		if idx < 0 || idx >= n {
23			t.Errorf("questionIndex(1, %d) = %d, want in 0..%d", h, idx, n-1)
24		}
25		if again := questionIndex(1, h); again != idx {
26			t.Errorf("questionIndex(1, %d) non-deterministic: %d != %d", h, again, idx)
27		}
28	}
29	// consecutive rounds should walk sequentially through the list
30	first := questionIndex(1, 0)
31	second := questionIndex(2, 0)
32	if second != (first+1)%n {
33		t.Errorf("round 2 index = %d, want %d", second, (first+1)%n)
34	}
35}
36
37// TestAnswerCorrectAdvances exercises the crossing Answer function, so it
38// takes cur realm and calls through cross(cur).
39func TestAnswerCorrectAdvances(cur realm, t *testing.T) {
40	resetQuiz(10)
41	q := questions[current.qIdx]
42	prevRound := current.number
43
44	// wrong answer first: pick any index that isn't correct
45	wrong := (q.correctIdx + 1) % len(q.choices)
46	got := Answer(cross(cur), wrong)
47	if got != "Wrong — try again." {
48		t.Errorf("Answer(wrong) = %q, want wrong message", got)
49	}
50	if current.solved {
51		t.Error("round should not be solved after a wrong answer")
52	}
53
54	got = Answer(cross(cur), q.correctIdx)
55	if !strings.HasPrefix(got, "Correct!") {
56		t.Errorf("Answer(correct) = %q, want it to start with Correct!", got)
57	}
58	if current.number != prevRound+1 {
59		t.Errorf("round number = %d, want %d", current.number, prevRound+1)
60	}
61	if totalCorrect != 1 {
62		t.Errorf("totalCorrect = %d, want 1", totalCorrect)
63	}
64	if len(leaderboard()) != 1 {
65		t.Errorf("leaderboard len = %d, want 1", len(leaderboard()))
66	}
67}
68
69// TestRenderContainsState is a plain read — no cur.
70func TestRenderContainsState(t *testing.T) {
71	resetQuiz(5)
72	out := Render("")
73	for _, want := range []string{"Trivia Quiz", "Round", "Leaderboard"} {
74		if !strings.Contains(out, want) {
75			t.Errorf("Render() missing %q", want)
76		}
77	}
78}