-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathplugin_test.go
More file actions
100 lines (83 loc) · 2.21 KB
/
plugin_test.go
File metadata and controls
100 lines (83 loc) · 2.21 KB
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
package logger
import (
"bytes"
"fmt"
"io"
"log"
"net/http"
"net/http/httptest"
"strings"
"testing"
"gopkg.in/h2non/gentleman.v2/plugin"
"gopkg.in/h2non/gentleman.v2"
)
type httpTestContext struct {
mux *http.ServeMux
server *httptest.Server
}
func newHTTPTestContext() *httpTestContext {
mux := http.NewServeMux()
server := httptest.NewServer(mux)
return &httpTestContext{
mux: mux,
server: server,
}
}
func Test_LoggerRoundTripper(t *testing.T) {
cases := []struct {
createPlugin func(out io.Writer) plugin.Plugin
}{
{
createPlugin: func(out io.Writer) plugin.Plugin {
return New(out)
},
},
{
createPlugin: func(out io.Writer) plugin.Plugin {
return FromLogger(log.New(out, "[gentleman] ", log.LstdFlags))
},
},
}
var (
path = "/ping"
queryKey = "foo"
queryValue = "bar"
reqBody = "{\"baz\": \"qux\"}"
respBody = "{\"message\": \"pong\"}"
status = 201
)
ctx := newHTTPTestContext()
defer ctx.server.Close()
ctx.mux.HandleFunc(path, func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(status)
fmt.Fprint(w, respBody)
})
for _, c := range cases {
buf := bytes.NewBufferString("")
client := gentleman.New().BaseURL(ctx.server.URL).Use(c.createPlugin(buf))
_, err := client.Post().
Path("/ping").
SetQuery(queryKey, queryValue).
BodyString(reqBody).
Send()
if err != nil {
t.Fatalf("Unexpected error %v", err)
}
if got, want := buf.String(), path; !strings.Contains(got, want) {
t.Errorf("logged %q, wanna contain path %q", got, want)
}
if got, want := buf.String(), fmt.Sprintf("%s=%s", queryKey, queryValue); !strings.Contains(got, want) {
t.Errorf("logged %q, wanna contain query %q", got, want)
}
if got, want := buf.String(), reqBody; !strings.Contains(got, want) {
t.Errorf("logged %q, wanna contain request body %q", got, want)
}
if got, want := buf.String(), fmt.Sprint(status); !strings.Contains(got, want) {
t.Errorf("logged %q, wanna contain status code %q", got, want)
}
if got, want := buf.String(), respBody; !strings.Contains(got, want) {
t.Errorf("logged %q, wanna contain response body %q", got, want)
}
}
}