-
Notifications
You must be signed in to change notification settings - Fork 2
/
ztest.go
55 lines (46 loc) · 1.25 KB
/
ztest.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
53
54
55
package ztest
import (
"encoding/json"
"github.com/stretchr/testify/assert"
"io"
"net/http"
"net/http/httptest"
"testing"
)
type RequestAssertionParams struct {
T *testing.T
Router http.Handler
Responses map[string]interface{}
Method string
URL string
ExpectedStatusCode int
ExpectedResponseKey string
Body io.Reader
}
func MakeRequestAndAssert(params RequestAssertionParams) {
req, err := http.NewRequest(params.Method, params.URL, params.Body)
if err != nil {
params.T.Fatal(err)
}
w := httptest.NewRecorder()
params.Router.ServeHTTP(w, req)
assert.Equal(params.T, params.ExpectedStatusCode, w.Code)
var obtainedResponse interface{}
err = json.Unmarshal(w.Body.Bytes(), &obtainedResponse)
if err != nil {
params.T.Fatal(err)
}
obtainedJSON, err := json.Marshal(obtainedResponse)
if err != nil {
params.T.Fatal(err)
}
expectedVal, exists := params.Responses[params.ExpectedResponseKey]
if !exists {
params.T.Fatalf("Key %s does not exist in testResponses", params.ExpectedResponseKey)
}
expectedJSON, err := json.Marshal(expectedVal)
if err != nil {
params.T.Fatal(err)
}
assert.Equal(params.T, string(expectedJSON), string(obtainedJSON))
}