Ash Wilson | dd580ce | 2014-08-28 15:37:55 -0400 | [diff] [blame^] | 1 | package testhelper |
| 2 | |
| 3 | import ( |
| 4 | "encoding/json" |
| 5 | "io/ioutil" |
| 6 | "net/http" |
| 7 | "net/url" |
| 8 | "reflect" |
| 9 | "testing" |
| 10 | ) |
| 11 | |
| 12 | // TestFormValues ensures that all the URL parameters given to the http.Request are the same as values. |
| 13 | func TestFormValues(t *testing.T, r *http.Request, values map[string]string) { |
| 14 | want := url.Values{} |
| 15 | for k, v := range values { |
| 16 | want.Add(k, v) |
| 17 | } |
| 18 | |
| 19 | r.ParseForm() |
| 20 | if !reflect.DeepEqual(want, r.Form) { |
| 21 | t.Errorf("Request parameters = %v, want %v", r.Form, want) |
| 22 | } |
| 23 | } |
| 24 | |
| 25 | // TestMethod checks that the Request has the expected method (e.g. GET, POST). |
| 26 | func TestMethod(t *testing.T, r *http.Request, expected string) { |
| 27 | if expected != r.Method { |
| 28 | t.Errorf("Request method = %v, expected %v", r.Method, expected) |
| 29 | } |
| 30 | } |
| 31 | |
| 32 | // TestHeader checks that the header on the http.Request matches the expected value. |
| 33 | func TestHeader(t *testing.T, r *http.Request, header string, expected string) { |
| 34 | if actual := r.Header.Get(header); expected != actual { |
| 35 | t.Errorf("Header %s = %s, expected %s", header, actual, expected) |
| 36 | } |
| 37 | } |
| 38 | |
| 39 | // TestBody verifies that the request body matches an expected body. |
| 40 | func TestBody(t *testing.T, r *http.Request, expected string) { |
| 41 | b, err := ioutil.ReadAll(r.Body) |
| 42 | if err != nil { |
| 43 | t.Errorf("Unable to read body: %v", err) |
| 44 | } |
| 45 | str := string(b) |
| 46 | if expected != str { |
| 47 | t.Errorf("Body = %s, expected %s", str, expected) |
| 48 | } |
| 49 | } |
| 50 | |
| 51 | // TestJSONRequest verifies that the JSON payload of a request matches an expected structure, without asserting things about |
| 52 | // whitespace or ordering. |
| 53 | func TestJSONRequest(t *testing.T, r *http.Request, expected string) { |
| 54 | b, err := ioutil.ReadAll(r.Body) |
| 55 | if err != nil { |
| 56 | t.Errorf("Unable to read request body: %v", err) |
| 57 | } |
| 58 | |
| 59 | var expectedJSON interface{} |
| 60 | err = json.Unmarshal([]byte(expected), &expectedJSON) |
| 61 | if err != nil { |
| 62 | t.Errorf("Unable to parse expected value as JSON: %v", err) |
| 63 | } |
| 64 | |
| 65 | var actualJSON interface{} |
| 66 | err = json.Unmarshal(b, &actualJSON) |
| 67 | if err != nil { |
| 68 | t.Errorf("Unable to parse request body as JSON: %v", err) |
| 69 | } |
| 70 | |
| 71 | if !reflect.DeepEqual(expectedJSON, actualJSON) { |
| 72 | t.Errorf("Response body did not contain the correct JSON.") |
| 73 | } |
| 74 | } |