This repository has been archived by the owner on Jul 9, 2021. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
chain_test.go
75 lines (62 loc) · 1.61 KB
/
chain_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
package fusion
import (
"testing"
"github.com/stretchr/testify/assert"
"github.com/valyala/fasthttp"
)
func paramHandler(param string) fasthttp.RequestHandler {
return func(ctx *fasthttp.RequestCtx) {
if ctx.UserValue("params") == nil {
ctx.SetUserValue("params", "")
}
ctx.SetUserValue("params", ctx.UserValue("params").(string) + param)
}
}
func TestHandlersRunInOrder(t *testing.T) {
// given
h1 := paramHandler("1")
h2 := paramHandler("2")
h3 := paramHandler("3")
ctx := &fasthttp.RequestCtx{}
// when
Handlers(h1, h2, h3)(ctx)
// then
assert.Equal(t, ctx.UserValue("params"), "123")
}
func TestStopOnResponseStatus(t *testing.T) {
// given
h1 := paramHandler("1")
h2 := func(ctx *fasthttp.RequestCtx) {
ctx.SetUserValue("params", ctx.UserValue("params").(string) + "2")
ctx.SetStatusCode(fasthttp.StatusBadRequest)
}
h3 := paramHandler("3")
ctx := &fasthttp.RequestCtx{}
// when
Handlers(h1, h2, h3)(ctx)
// then
assert.Equal(t, fasthttp.StatusBadRequest, ctx.Response.StatusCode())
assert.Equal(t, "12", ctx.UserValue("params"))
}
func tagMiddleware(tag string) Middleware {
return func(h fasthttp.RequestHandler) fasthttp.RequestHandler {
return func(ctx *fasthttp.RequestCtx) {
ctx.WriteString(tag)
h(ctx)
}
}
}
var testHandler = func(ctx *fasthttp.RequestCtx) {
ctx.Write([]byte("\n"))
}
func TestMiddlewaresRunInOrder(t *testing.T) {
// given
m1 := tagMiddleware("1")
m2 := tagMiddleware("2")
m3 := tagMiddleware("3")
ctx := &fasthttp.RequestCtx{}
// when
New(m1, m2, m3).Handler(testHandler)(ctx)
// then
assert.Equal(t, "123\n", string(ctx.Response.Body()))
}