blob: e1f1f9ac0e897bb242c8292e1e3d6b8d76beaaa9 [file] [log] [blame]
Ash Wilsondd580ce2014-08-28 15:37:55 -04001package testhelper
2
3import (
4 "encoding/json"
5 "io/ioutil"
6 "net/http"
Ash Wilson0ab4d612014-08-29 11:10:13 -04007 "net/http/httptest"
Ash Wilsondd580ce2014-08-28 15:37:55 -04008 "net/url"
9 "reflect"
10 "testing"
11)
12
Ash Wilson0ab4d612014-08-29 11:10:13 -040013var (
14 // Mux is a multiplexer that can be used to register handlers.
15 Mux *http.ServeMux
16
17 // Server is an in-memory HTTP server for testing.
18 Server *httptest.Server
19)
20
21// SetupHTTP prepares the Mux and Server.
22func SetupHTTP() {
23 Mux = http.NewServeMux()
24 Server = httptest.NewServer(Mux)
25}
26
27// TeardownHTTP releases HTTP-related resources.
28func TeardownHTTP() {
29 Server.Close()
30}
31
32// Endpoint returns a fake endpoint that will actually target the Mux.
33func Endpoint() string {
34 return Server.URL + "/"
35}
36
Ash Wilsondd580ce2014-08-28 15:37:55 -040037// TestFormValues ensures that all the URL parameters given to the http.Request are the same as values.
38func TestFormValues(t *testing.T, r *http.Request, values map[string]string) {
39 want := url.Values{}
40 for k, v := range values {
41 want.Add(k, v)
42 }
43
44 r.ParseForm()
45 if !reflect.DeepEqual(want, r.Form) {
46 t.Errorf("Request parameters = %v, want %v", r.Form, want)
47 }
48}
49
50// TestMethod checks that the Request has the expected method (e.g. GET, POST).
51func TestMethod(t *testing.T, r *http.Request, expected string) {
52 if expected != r.Method {
53 t.Errorf("Request method = %v, expected %v", r.Method, expected)
54 }
55}
56
57// TestHeader checks that the header on the http.Request matches the expected value.
58func TestHeader(t *testing.T, r *http.Request, header string, expected string) {
59 if actual := r.Header.Get(header); expected != actual {
60 t.Errorf("Header %s = %s, expected %s", header, actual, expected)
61 }
62}
63
64// TestBody verifies that the request body matches an expected body.
65func TestBody(t *testing.T, r *http.Request, expected string) {
66 b, err := ioutil.ReadAll(r.Body)
67 if err != nil {
68 t.Errorf("Unable to read body: %v", err)
69 }
70 str := string(b)
71 if expected != str {
72 t.Errorf("Body = %s, expected %s", str, expected)
73 }
74}
75
76// TestJSONRequest verifies that the JSON payload of a request matches an expected structure, without asserting things about
77// whitespace or ordering.
78func TestJSONRequest(t *testing.T, r *http.Request, expected string) {
79 b, err := ioutil.ReadAll(r.Body)
80 if err != nil {
81 t.Errorf("Unable to read request body: %v", err)
82 }
83
Ash Wilsondd580ce2014-08-28 15:37:55 -040084 var actualJSON interface{}
85 err = json.Unmarshal(b, &actualJSON)
86 if err != nil {
87 t.Errorf("Unable to parse request body as JSON: %v", err)
88 }
89
Ash Wilson3315cf92014-10-23 10:27:35 -040090 CheckJSONEquals(t, expected, actualJSON)
Ash Wilsondd580ce2014-08-28 15:37:55 -040091}