From e4ab5185760635c3117c94c0bdc5d9744d5cf57f Mon Sep 17 00:00:00 2001 From: Kevin Wan Date: Thu, 30 Dec 2021 14:21:55 +0800 Subject: [PATCH] test: add more tests (#1391) --- core/search/tree_test.go | 49 ++++++++++++++++++++++++++++++++++++---- 1 file changed, 44 insertions(+), 5 deletions(-) diff --git a/core/search/tree_test.go b/core/search/tree_test.go index b7166e5a..315bef9e 100644 --- a/core/search/tree_test.go +++ b/core/search/tree_test.go @@ -1,9 +1,12 @@ package search import ( + "math/rand" + "strings" "testing" "github.com/stretchr/testify/assert" + "github.com/tal-tech/go-zero/core/stringx" ) type mockedRoute struct { @@ -139,11 +142,9 @@ func TestStrictSearchSibling(t *testing.T) { tree.Add(r.route, r.value) } - for i := 0; i < 1000; i++ { - result, ok := tree.Search(query) - assert.True(t, ok) - assert.Equal(t, 3, result.Item.(int)) - } + result, ok := tree.Search(query) + assert.True(t, ok) + assert.Equal(t, 3, result.Item.(int)) } func TestAddDuplicate(t *testing.T) { @@ -185,3 +186,41 @@ func TestSearchInvalidItem(t *testing.T) { err := tree.Add("/", nil) assert.Equal(t, errEmptyItem, err) } + +func BenchmarkSearchTree(b *testing.B) { + const ( + avgLen = 1000 + entries = 10000 + ) + + tree := NewTree() + generate := func() string { + var buf strings.Builder + size := rand.Intn(avgLen) + avgLen/2 + val := stringx.Randn(size) + prev := 0 + for j := rand.Intn(9) + 1; j < size; j += rand.Intn(9) + 1 { + buf.WriteRune('/') + buf.WriteString(val[prev:j]) + prev = j + } + if prev < size { + buf.WriteRune('/') + buf.WriteString(val[prev:]) + } + return buf.String() + } + index := rand.Intn(entries) + var query string + for i := 0; i < entries; i++ { + val := generate() + if i == index { + query = val + } + tree.Add(val, i) + } + + for i := 0; i < b.N; i++ { + tree.Search(query) + } +}