forked from rcrowley/go-tigertonic
-
Notifications
You must be signed in to change notification settings - Fork 1
/
mocking.go
52 lines (48 loc) · 1.11 KB
/
mocking.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
// Package mocking makes testing Tiger Tonic services easier.
package mocking
import (
"net/http"
"net/url"
)
// Header augments an optional existing http.Header with Accept and
// Content-Type headers as required by Tiger Tonic.
func Header(h http.Header) http.Header {
h0 := make(http.Header)
h0.Add("Accept", "application/json")
h0.Add("Content-Type", "application/json")
if nil != h {
for key, values := range h {
for _, value := range values {
h0.Add(key, value)
}
}
}
return h0
}
// TestableHandler wraps the Handler method from http.ServeMux to make it
// easier to detect in tests.
type TestableHandler interface {
Handler(*http.Request) (http.Handler, string)
}
// URL constructs a url.URL for use in tests and ensures it's routed by the
// given TestableHandler.
func URL(h TestableHandler, method, rawurl string) *url.URL {
u, err := url.ParseRequestURI(rawurl)
if nil != err {
panic(err)
}
if nil != h {
rq := &http.Request{
Method: method,
URL: u,
}
var ok bool
for {
h1, _ := h.Handler(rq)
if h, ok = h1.(TestableHandler); !ok {
break
}
}
}
return u
}