1
- // Utility functions to help writing tests for a Go-Json-Rest app
2
- //
3
- // Go comes with net/http/httptest to help writing test for an http
4
- // server. When this http server implements a JSON REST API, some basic
5
- // checks end up to be always the same. This test package tries to save
6
- // some typing by providing helpers for this particular use case.
7
1
package test
8
2
9
3
import (
@@ -16,8 +10,10 @@ import (
16
10
"testing"
17
11
)
18
12
19
- func MakeRequestWithHeader (method , urlStr string , header http.Header , payload interface {}) * http.Request {
20
- s := ""
13
+ // MakeSimpleRequest returns a http.Request. The returned request object can be
14
+ // further prepared by adding headers and query string parmaters, for instance.
15
+ func MakeSimpleRequest (method string , urlStr string , payload interface {}) * http.Request {
16
+ var s string
21
17
22
18
if payload != nil {
23
19
b , err := json .Marshal (payload )
@@ -31,27 +27,22 @@ func MakeRequestWithHeader(method, urlStr string, header http.Header, payload in
31
27
if err != nil {
32
28
panic (err )
33
29
}
34
- r .Header = header
35
30
r .Header .Set ("Accept-Encoding" , "gzip" )
36
-
37
31
if payload != nil {
38
32
r .Header .Set ("Content-Type" , "application/json" )
39
33
}
40
34
41
35
return r
42
36
}
43
37
44
- func MakeSimpleRequest (method string , urlStr string , payload interface {}) * http.Request {
45
- return MakeRequestWithHeader (method , urlStr , http.Header {}, payload )
46
- }
47
-
38
+ // CodeIs compares the rescorded status code
48
39
func CodeIs (t * testing.T , r * httptest.ResponseRecorder , expectedCode int ) {
49
40
if r .Code != expectedCode {
50
41
t .Errorf ("Code %d expected, got: %d" , expectedCode , r .Code )
51
42
}
52
43
}
53
44
54
- // Test the first value for the given headerKey
45
+ // HeaderIs tests the first value for the given headerKey
55
46
func HeaderIs (t * testing.T , r * httptest.ResponseRecorder , headerKey , expectedValue string ) {
56
47
value := r .HeaderMap .Get (headerKey )
57
48
if value != expectedValue {
@@ -96,6 +87,7 @@ type Recorded struct {
96
87
Recorder * httptest.ResponseRecorder
97
88
}
98
89
90
+ // RunRequest runs a HTTP request through the given handler
99
91
func RunRequest (t * testing.T , handler http.Handler , request * http.Request ) * Recorded {
100
92
recorder := httptest .NewRecorder ()
101
93
handler .ServeHTTP (recorder , request )
0 commit comments