1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104
|
package iradix
import (
"reflect"
"sort"
"testing"
)
func TestPathIterator(t *testing.T) {
r := New[any]()
keys := []string{
"foo",
"foo/bar",
"foo/bar/baz",
"foo/baz/bar",
"foo/zip/zap",
"zipzap",
}
for _, k := range keys {
r, _, _ = r.Insert([]byte(k), nil)
}
if r.Len() != len(keys) {
t.Fatalf("bad len: %v %v", r.Len(), len(keys))
}
type exp struct {
inp string
out []string
}
cases := []exp{
{
"f",
[]string{},
},
{
"foo",
[]string{"foo"},
},
{
"foo/",
[]string{"foo"},
},
{
"foo/ba",
[]string{"foo"},
},
{
"foo/bar",
[]string{"foo", "foo/bar"},
},
{
"foo/bar/baz",
[]string{"foo", "foo/bar", "foo/bar/baz"},
},
{
"foo/bar/bazoo",
[]string{"foo", "foo/bar", "foo/bar/baz"},
},
{
"z",
[]string{},
},
}
root := r.Root()
for _, test := range cases {
iter := root.PathIterator([]byte(test.inp))
// Radix tree iteration on our string indices will return values with keys in
// ascending order. So before we check the iteration ordering we must sort
// the expected outputs.
sort.Strings(test.out)
// verify that all the expected values come out in ascending order.
for idx, expected := range test.out {
actual, _, found := iter.Next()
// ensure we found a value (i.e. iteration is finding the correct number of values)
if !found {
t.Fatalf("iteration returned fewer values than expected: %d, actual: %d", len(test.out), idx)
}
// ensure that the values are coming out in the sorted order.
if !reflect.DeepEqual([]byte(expected), actual) {
t.Errorf("expected: %#v", []byte(expected))
t.Errorf("actual: %#v", actual)
t.Fatalf("value returned during iteration doesn't match our expectation (iteration num: %d)", idx)
}
}
// Now ensure there are no trailing values that the tree will output.
_, _, found := iter.Next()
if found {
t.Fatalf("iteration returned more values than expected: %d, actual: %d+", len(test.out), len(test.out)+1)
}
// Verify that continued calls to next on a completed iterator do not panic or return values.
_, _, found = iter.Next()
if found {
t.Fatalf("iteration returned a value after previously indicating iteration was complete")
}
}
}
|