forked from gavv/httpexpect
-
Notifications
You must be signed in to change notification settings - Fork 0
/
echo_test.go
87 lines (68 loc) · 1.91 KB
/
echo_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
package examples
import (
"net/http"
"net/http/httptest"
"testing"
"github.com/gavv/httpexpect/v2"
)
// Echo JWT token authentication tests.
//
// This test is executed for the EchoHandler() in two modes:
// - via http client
// - via http.Handler
func testEcho(e *httpexpect.Expect) {
type Login struct {
Username string `form:"username"`
Password string `form:"password"`
}
e.POST("/login").WithForm(Login{"ford", "<bad password>"}).
Expect().
Status(http.StatusUnauthorized)
r := e.POST("/login").WithForm(Login{"ford", "betelgeuse7"}).
Expect().
Status(http.StatusOK).JSON().Object()
r.Keys().ContainsOnly("token")
token := r.Value("token").String().Raw()
e.GET("/restricted/hello").
Expect().
Status(http.StatusBadRequest)
e.GET("/restricted/hello").WithHeader("Authorization", "Bearer <bad token>").
Expect().
Status(http.StatusUnauthorized)
e.GET("/restricted/hello").WithHeader("Authorization", "Bearer "+token).
Expect().
Status(http.StatusOK).Body().IsEqual("hello, world!")
auth := e.Builder(func(req *httpexpect.Request) {
req.WithHeader("Authorization", "Bearer "+token)
})
auth.GET("/restricted/hello").
Expect().
Status(http.StatusOK).Body().IsEqual("hello, world!")
}
func TestEchoClient(t *testing.T) {
handler := EchoHandler()
server := httptest.NewServer(handler)
defer server.Close()
e := httpexpect.WithConfig(httpexpect.Config{
BaseURL: server.URL,
Reporter: httpexpect.NewAssertReporter(t),
Printers: []httpexpect.Printer{
httpexpect.NewDebugPrinter(t, true),
},
})
testEcho(e)
}
func TestEchoHandler(t *testing.T) {
handler := EchoHandler()
e := httpexpect.WithConfig(httpexpect.Config{
Client: &http.Client{
Transport: httpexpect.NewBinder(handler),
Jar: httpexpect.NewCookieJar(),
},
Reporter: httpexpect.NewAssertReporter(t),
Printers: []httpexpect.Printer{
httpexpect.NewDebugPrinter(t, true),
},
})
testEcho(e)
}