1
1
package messagebirdtest
2
2
3
3
import (
4
+ "io/ioutil"
4
5
"net/http"
5
6
"net/http/httptest"
7
+ "net/url"
6
8
"os"
7
9
"testing"
8
10
)
9
11
12
+ type resetFunc func ()
13
+
14
+ type request struct {
15
+ Body []byte
16
+ Method string
17
+ URL * url.URL
18
+ }
19
+
20
+ // Request contains the lastly received http.Request by the fake server.
21
+ var Request request
22
+
10
23
var server * httptest.Server
11
24
12
25
var responseBody []byte
13
- var status int = 200
26
+ var status int
14
27
15
28
// EnableServer starts a fake server, runs the test and closes the server.
16
29
func EnableServer (m * testing.M ) {
@@ -23,6 +36,18 @@ func EnableServer(m *testing.M) {
23
36
24
37
func initAndStartServer () {
25
38
server = httptest .NewTLSServer (http .HandlerFunc (func (w http.ResponseWriter , r * http.Request ) {
39
+ Request = request {
40
+ Method : r .Method ,
41
+ URL : r .URL ,
42
+ }
43
+
44
+ var err error
45
+
46
+ Request .Body , err = ioutil .ReadAll (r .Body )
47
+ if err != nil {
48
+ panic (err .Error ())
49
+ }
50
+
26
51
// status and responseBody are defined in returns.go.
27
52
w .Header ().Set ("Content-Type" , "application/json" )
28
53
w .WriteHeader (status )
@@ -36,20 +61,41 @@ func closeServer() {
36
61
server .Close ()
37
62
}
38
63
64
+ // setRequest sets some basic fields from the http.Request in our global Request
65
+ // struct.
66
+ func setRequest (r * http.Request ) error {
67
+ Request := request {
68
+ Method : r .Method ,
69
+ URL : r .URL ,
70
+ }
71
+
72
+ var err error
73
+
74
+ // Reading from the request body is fine, as it's not used elsewhere.
75
+ // Server always returns fake data/testdata.
76
+ Request .Body , err = ioutil .ReadAll (r .Body )
77
+
78
+ return err
79
+ }
80
+
81
+ func WillReturn (b []byte , s int ) {
82
+ responseBody = b
83
+ status = s
84
+ }
85
+
39
86
// WillReturnTestdata sets the status (s) for the test server to respond with.
40
87
// Additionally it reads the bytes from the relativePath file and returns that
41
88
// for requests. It fails the test if the file can not be read. The path is
42
89
// relative to the testdata directory (the go tool ignores directories named
43
90
// "testdata" in test packages: https://golang.org/cmd/go/#hdr-Test_packages).
44
91
func WillReturnTestdata (t * testing.T , relativePath string , s int ) {
45
- responseBody = testdata (t , relativePath )
46
- status = s
92
+ WillReturn (Testdata (t , relativePath ), s )
47
93
}
48
94
49
95
// WillReturnAccessKeyError sets the response body and status for requests to
50
96
// indicate the request is not allowed due to an incorrect access key.
51
97
func WillReturnAccessKeyError () {
52
- responseBody = []byte (`
98
+ WillReturn ( []byte (`
53
99
{
54
100
"errors": [
55
101
{
@@ -58,6 +104,6 @@ func WillReturnAccessKeyError() {
58
104
"parameter":"access_key"
59
105
}
60
106
]
61
- }` )
62
- status = 401
107
+ }
108
+ ` ), 401 )
63
109
}
0 commit comments