-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathzhttp_test.go
112 lines (82 loc) · 1.75 KB
/
zhttp_test.go
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
105
106
107
108
109
110
111
112
package zhttp_test
import (
"context"
"encoding/json"
"errors"
"net/http"
"net/http/httptest"
"testing"
"github.com/duythinht/zhttp"
)
func TestWrapHandlerFunction(t *testing.T) {
type input struct {
Name string `url:"name"`
}
type output struct {
}
name := "hello"
h := zhttp.Handler(func(_ context.Context, in *input) (out *output, err error) {
if in.Name != name {
t.Logf("expected: %s, got: %s", name, in.Name)
t.Fail()
}
return nil, nil
})
w := httptest.NewRecorder()
r := httptest.NewRequest(http.MethodGet, "/?name=hello", nil)
h.ServeHTTP(w, r)
}
func BenchmarkTypeAssertion(b *testing.B) {
errMock := errors.New("mock")
err := zhttp.BadRequest(errMock)
for i := 0; i < b.N; i++ {
if httpErr, ok := err.(zhttp.Error); ok {
httpErr.HTTPError()
}
}
}
func BenchmarkSwitchTypeAssertion(b *testing.B) {
errMock := errors.New("mock")
e := error(zhttp.BadRequest(errMock))
for i := 0; i < b.N; i++ {
switch ex := e.(type) {
case zhttp.Error:
ex.HTTPError()
default:
}
}
}
func BenchmarkHTTPHandlerFunc(b *testing.B) {
type input struct {
}
type output struct {
Message string
}
h := func(w http.ResponseWriter, r *http.Request) {
json.NewEncoder(w).Encode(&output{
Message: "Hello world!",
})
}
w := httptest.NewRecorder()
r, _ := http.NewRequest(http.MethodGet, "", nil)
for i := 0; i < b.N; i++ {
h(w, r)
}
}
func BenchmarkGenericHandler(b *testing.B) {
type input struct {
}
type output struct {
Message string
}
h := zhttp.Handler(func(ctx context.Context, in *input) (*output, error) {
return &output{
Message: "Hello world!",
}, nil
})
w := httptest.NewRecorder()
r, _ := http.NewRequest(http.MethodGet, "", nil)
for i := 0; i < b.N; i++ {
h(w, r)
}
}