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

Community realm. Read the code first. Community realm, deployed by its author. Read the code before you interact or send coins.

markov_test.gno

2.40 Kb · 83 lines
 1package markov
 2
 3import (
 4	"strings"
 5	"testing"
 6
 7	"gno.land/p/nt/uassert/v0"
 8)
 9
10func TestPrefixShiftKey(t *testing.T) {
11	p := make(Prefix, PrefixLen)
12	uassert.Equal(t, " ", p.key(), "initial key is two empty words joined")
13
14	p.shift("hello")
15	uassert.Equal(t, " hello", p.key(), "after one shift")
16
17	p.shift("world")
18	uassert.Equal(t, "hello world", p.key(), "after two shifts window is full")
19
20	p.shift("again")
21	uassert.Equal(t, "world again", p.key(), "oldest word drops off")
22}
23
24func TestBuildCountsAndSuffixes(t *testing.T) {
25	c := New()
26	added := c.Build("a b a b a b")
27	uassert.Equal(t, 6, added, "six words tokenized")
28
29	words, _ := c.Stats()
30	uassert.Equal(t, 6, words, "word counter matches")
31
32	// prefixes seen: " "->[a], " a"->[b], "a b"->[a,a], "b a"->[b,b]
33	uassert.True(t, c.table.Has("a b"), "prefix 'a b' recorded")
34	ab := c.table.Get("a b").(*suffixList)
35	uassert.Equal(t, 2, len(ab.words), "'a b' followed twice")
36	uassert.Equal(t, "a", ab.words[0], "'a b' is always followed by 'a'")
37
38	// whitespace-only / empty adds nothing
39	uassert.Equal(t, 0, c.Build("   "), "blank text adds no words")
40}
41
42func TestGenerateDeterministicAndBounded(t *testing.T) {
43	c := New()
44	c.Build("one two three four one two three five one two six")
45
46	a := strings.Join(c.Generate(8, 42), " ")
47	b := strings.Join(c.Generate(8, 42), " ")
48	uassert.Equal(t, a, b, "same seed => identical output")
49
50	// the walk is seed-sensitive: across a spread of seeds at least one
51	// diverges from the seed-42 output (some seeds may coincidentally match).
52	sensitive := false
53	for _, s := range []uint64{1, 7, 13, 12345, 8675309} {
54		if strings.Join(c.Generate(8, s), " ") != a {
55			sensitive = true
56			break
57		}
58	}
59	uassert.True(t, sensitive, "output varies with the seed")
60
61	// non-positive n and empty corpus both yield nothing
62	uassert.Equal(t, 0, len(c.Generate(0, 1)), "n<=0 yields no words")
63	empty := New()
64	uassert.Equal(t, 0, len(empty.Generate(10, 1)), "empty corpus yields no words")
65}
66
67func TestStatsAndIterate(t *testing.T) {
68	c := New()
69	c.Build("a b a b a b")
70
71	words, prefixes := c.Stats()
72	uassert.Equal(t, 6, words, "total words")
73	uassert.Equal(t, 4, prefixes, "distinct prefixes")
74
75	seen := 0
76	stopped := c.Iterate(func(prefix string, suffixes []string) bool {
77		uassert.True(t, len(suffixes) > 0, "each prefix has suffixes")
78		seen++
79		return false
80	})
81	uassert.Equal(t, 4, seen, "iterated over every prefix")
82	uassert.False(t, stopped, "ran to completion")
83}