-
Notifications
You must be signed in to change notification settings - Fork 1
/
httpmock.go
75 lines (65 loc) · 2.12 KB
/
httpmock.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 httpmock
import (
"net/http"
"strings"
"testing"
)
// ServeReplay is an http.Handler
// It contains a list of handlers and calls the next handler in the list for each incoming request.
//
// If a request is received and no more handlers are available, ServeReplay calls NoneLeftFunc.
// The default behavior of NoneLeftFunc is to call t.Errorf with some information about the request.
type ServeReplay struct {
t *testing.T
i int
Handlers []http.Handler
NoneLeftFunc func(*testing.T, *http.Request)
}
func defaultNoneLeftFunc(t *testing.T, r *http.Request) {
t.Errorf("http request: %s %s; no more handlers to call", r.Method, r.URL.Path)
}
// NewServeReplay returns a new ServeReplay.
func NewServeReplay(t *testing.T) *ServeReplay {
return &ServeReplay{
t: t,
Handlers: make([]http.Handler, 0),
NoneLeftFunc: defaultNoneLeftFunc,
}
}
// Add appends a handler to ServReplay's handler list.
// It returns itself to allow chaining.
func (h *ServeReplay) Add(handler http.Handler) *ServeReplay {
h.Handlers = append(h.Handlers, handler)
return h
}
// ServeHTTP dispatches the request to the next handler in the list.
func (h *ServeReplay) ServeHTTP(w http.ResponseWriter, r *http.Request) {
if h.i >= len(h.Handlers) {
h.NoneLeftFunc(h.t, r)
} else {
h.Handlers[h.i].ServeHTTP(w, r)
h.i++
}
}
// PathHandler will fail if the request doesn't match based on reqPath.
// If it matches it returns the given response status and body.
//
// reqPath should be of the form `<METHOD> <PATH>`. For example: `GET /foo`.
func PathHandler(t *testing.T, reqPath string, respStatus int, respBody string) http.Handler {
var meth, path string
s := strings.SplitN(reqPath, " ", 2)
if len(s) == 1 {
t.Fatal("reqPath must be of the form `<METHOD> <PATH>`")
}
meth = s[0]
path = s[1]
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if meth == r.Method && path == r.URL.Path {
w.WriteHeader(respStatus)
w.Write([]byte(respBody))
} else {
w.WriteHeader(http.StatusNotFound)
t.Errorf("http request => %s %s; want %s %s", r.Method, r.URL.Path, meth, path)
}
})
}