/
core_test.go
84 lines (72 loc) · 2.31 KB
/
core_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
package noodle_test
import (
"fmt"
"github.com/andviro/noodle"
"golang.org/x/net/context"
"gopkg.in/tylerb/is.v1"
"net/http"
"net/http/httptest"
"testing"
)
// RunHTTP imitates handling HTTP request, returns response body
func RunHTTP(h http.Handler) string {
r, _ := http.NewRequest("GET", "http://localhost", nil)
w := httptest.NewRecorder()
h.ServeHTTP(w, r)
return w.Body.String()
}
func mwFactory(name string) noodle.Middleware {
return func(next noodle.Handler) noodle.Handler {
varName := "Var" + name
varValue := name + "value"
return func(c context.Context, w http.ResponseWriter, r *http.Request) error {
withVars := context.WithValue(c, varName, varValue)
fmt.Fprintf(w, "%s>", name)
return next(withVars, w, r)
}
}
}
func handlerFactory(name string, keys ...string) noodle.Handler {
return func(ctx context.Context, w http.ResponseWriter, r *http.Request) error {
fmt.Fprintf(w, "%s ", name)
for _, key := range keys {
fmt.Fprintf(w, "[%s=%v]", key, ctx.Value(key))
}
return nil
}
}
func TestNew(t *testing.T) {
is := is.New(t)
n := noodle.New(mwFactory("A"), mwFactory("B")).Then(handlerFactory("H1", "VarA", "VarB"))
res := RunHTTP(n)
is.Equal("A>B>H1 [VarA=Avalue][VarB=Bvalue]", res)
}
func TestUse(t *testing.T) {
is := is.New(t)
n := noodle.New(mwFactory("A"), mwFactory("B")).Use(mwFactory("C")).Then(handlerFactory("H1", "VarA", "VarB", "VarC"))
res := RunHTTP(n)
is.Equal("A>B>C>H1 [VarA=Avalue][VarB=Bvalue][VarC=Cvalue]", res)
}
func TestUseSeparates(t *testing.T) {
is := is.New(t)
root := noodle.New(mwFactory("A"), mwFactory("B"))
chain1 := root.Use(mwFactory("C"))
chain2 := root.Use(mwFactory("D"))
h1 := root.Then(handlerFactory("H1", "VarA", "VarB"))
h2 := chain1.Then(handlerFactory("H1", "VarA", "VarB", "VarC"))
h3 := chain2.Then(handlerFactory("H1", "VarA", "VarB", "VarD"))
res1 := RunHTTP(h1)
res2 := RunHTTP(h2)
res3 := RunHTTP(h3)
is.Equal("A>B>H1 [VarA=Avalue][VarB=Bvalue]", res1)
is.Equal("A>B>C>H1 [VarA=Avalue][VarB=Bvalue][VarC=Cvalue]", res2)
is.Equal("A>B>D>H1 [VarA=Avalue][VarB=Bvalue][VarD=Dvalue]", res3)
}
func TestThen(t *testing.T) {
is := is.New(t)
h := noodle.New().Then(func(ctx context.Context, w http.ResponseWriter, r *http.Request) error {
fmt.Fprintf(w, "Abracadabra")
return nil
})
is.Equal("Abracadabra", RunHTTP(h))
}