Skip to content

Commit

Permalink
test(internal/tree): 减少性能测试中不必要的干扰项
Browse files Browse the repository at this point in the history
  • Loading branch information
caixw committed May 26, 2024
1 parent bc9cfbd commit 2e98033
Showing 1 changed file with 8 additions and 42 deletions.
50 changes: 8 additions & 42 deletions internal/tree/bench_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,6 @@ package tree

import (
"net/http"
"net/http/httptest"
"testing"

"github.com/issue9/assert/v4"
Expand Down Expand Up @@ -42,58 +41,25 @@ func BenchmarkTree_Handler(b *testing.B) {
8: "/posts/2.html/2/author",
}

ctx := types.NewContext()
for i := range b.N {
ctx.Reset()
l := len(paths)

// 确保数据是正确返回的
for i := range l {
ctx := types.NewContext()
index := i % len(paths)
ctx.Path = paths[index]
node, h, ok := tree.Handler(ctx, http.MethodGet)
a.True(ok).
NotNil(node).
NotNil(h)
}
}

func BenchmarkTree_ServeHTTP(b *testing.B) {
a := assert.New(b, false)
tree := NewTestTree(a, true, nil, syntax.NewInterceptors())

// 添加路由项
a.NotError(tree.Add("/", rest.BuildHandler(a, 201, "", nil), nil, http.MethodGet))
a.NotError(tree.Add("/posts/{id}", rest.BuildHandler(a, 202, "", nil), nil, http.MethodGet))
a.NotError(tree.Add("/posts/{id}/author", rest.BuildHandler(a, 203, "", nil), nil, http.MethodGet))
a.NotError(tree.Add("/posts/1/author", rest.BuildHandler(a, 204, "", nil), nil, http.MethodGet))
a.NotError(tree.Add("/posts/{id:\\d+}", rest.BuildHandler(a, 205, "", nil), nil, http.MethodGet))
a.NotError(tree.Add("/posts/{id:\\d+}/author", rest.BuildHandler(a, 206, "", nil), nil, http.MethodGet))
a.NotError(tree.Add("/page/{page:\\d*}", rest.BuildHandler(a, 207, "", nil), nil, http.MethodGet)) // 可选的正则节点
a.NotError(tree.Add("/posts/{id}/{page}/author", rest.BuildHandler(a, 208, "", nil), nil, http.MethodGet))

// 与上面路路依次相对,其 键名+201 即为其返回的状态码。
paths := map[int]string{
0: "/",
1: "/posts/1.html/page",
2: "/posts/2.html/author",
3: "/posts/1/author",
4: "/posts/2",
5: "/posts/2/author",
6: "/page/",
7: "/posts/2.html/2/author",
}

b.ResetTimer()
ctx := types.NewContext()
for i := range b.N {
ctx.Reset()
index := i % len(paths)
index := i % l
ctx.Path = paths[index]
node, h, ok := tree.Handler(ctx, http.MethodGet)
a.True(ok).
NotNil(node).
NotNil(h)

w := httptest.NewRecorder()
r, err := http.NewRequest(http.MethodGet, paths[index], nil)
a.NotError(err).NotNil(r)
h.ServeHTTP(w, r)
a.Equal(w.Result().StatusCode, index+201)
tree.Handler(ctx, http.MethodGet)
}
}

0 comments on commit 2e98033

Please sign in to comment.