1 // Copyright 2010 The Go Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style
3 // license that can be found in the LICENSE file.
15 type testCase struct {
16 name string // name of test case
17 source string // source to index
18 lookups []string // strings to lookup
22 var testCases = []testCase{
34 "aaaaaaaaaa", // 10 a's
47 "aaaaaaaaaaa", // 11 a's
66 "barbarabarbarabarbara",
78 "Now is the time for all good men to come to the aid of their country.",
83 "is the time for all good men to come to the aid of their",
89 // find all occurences of s in source; report at most n occurences
90 func find(src, s string, n int) []int {
91 var res vector.IntVector
92 if s != "" && n != 0 {
93 // find at most n occurences of s in src
94 for i := -1; n < 0 || len(res) < n; {
95 j := strings.Index(src[i+1:], s)
107 func testLookups(t *testing.T, src string, x *Index, tc *testCase, n int) {
108 for _, s := range tc.lookups {
109 res := x.Lookup([]byte(s), n)
110 exp := find(tc.source, s, n)
112 // check that the lengths match
113 if len(res) != len(exp) {
114 t.Errorf("test %q, lookup %q (n = %d): expected %d results; got %d", tc.name, s, n, len(exp), len(res))
117 // if n >= 0 the number of results is limited --- unless n >= all results,
118 // we may obtain different positions from the Index and from find (because
119 // Index may not find the results in the same order as find) => in general
120 // we cannot simply check that the res and exp lists are equal
122 // check that there are no duplicates
124 for i, r := range res {
125 if i > 0 && res[i-1] == r {
126 t.Errorf("test %q, lookup %q, result %d (n = %d): found duplicate index %d", tc.name, s, i, n, r)
130 // check that each result is in fact a correct match
131 for i, r := range res {
132 if r < 0 || len(src) <= r {
133 t.Errorf("test %q, lookup %q, result %d (n = %d): index %d out of range [0, %d[", tc.name, s, i, n, r, len(src))
134 } else if !strings.HasPrefix(src[r:], s) {
135 t.Errorf("test %q, lookup %q, result %d (n = %d): index %d not a match", tc.name, s, i, n, r)
140 // all results computed - sorted res and exp must be equal
141 for i, r := range res {
144 t.Errorf("test %q, lookup %q, result %d: expected index %d; got %d", tc.name, s, i, e, r)
153 func TestIndex(t *testing.T) {
154 for _, tc := range testCases {
155 x := New([]byte(tc.source))
156 testLookups(t, tc.source, x, &tc, 0)
157 testLookups(t, tc.source, x, &tc, 1)
158 testLookups(t, tc.source, x, &tc, 10)
159 testLookups(t, tc.source, x, &tc, -1)