This repository has been archived by the owner on Dec 31, 2023. It is now read-only.
-
-
Notifications
You must be signed in to change notification settings - Fork 6
/
http.go
59 lines (48 loc) · 1.36 KB
/
http.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
56
57
58
59
package test
import (
"bytes"
"fmt"
jsoniter "github.com/json-iterator/go"
"github.com/mitchellh/mapstructure"
"github.com/stretchr/testify/assert"
"io"
"net/http/httptest"
"testing"
)
func AssertResponseBody(t *testing.T, recorder *httptest.ResponseRecorder, expect any) {
assertResponse(t, recorder, expect, make(map[string]interface{}))
}
func AssertResponseBodySlice(t *testing.T, recorder *httptest.ResponseRecorder, expect any) {
assertResponse(t, recorder, expect, make([]map[interface{}]interface{}, 0))
}
func assertResponse(t *testing.T, recorder *httptest.ResponseRecorder, expect any, expectData any) {
var buf bytes.Buffer
reader := io.TeeReader(recorder.Body, &buf)
respBody, err := io.ReadAll(reader)
if err != nil {
t.Fatalf("unable to read response data: %v", err)
}
resp := struct {
Data interface{} `json:"data"`
}{}
err = jsoniter.Unmarshal(respBody, &resp)
if err != nil {
t.Fatalf("unable to unmarhsall response body: %v", err)
}
decoder, err := mapstructure.NewDecoder(&mapstructure.DecoderConfig{
Result: &expectData,
TagName: "json",
})
if err != nil {
t.Fatalf("unable to create decoder: %v", err)
}
err = decoder.Decode(expect)
if err != nil {
t.Fatalf("unable to marshall expected data: %v", err)
}
got := fmt.Sprint(resp.Data)
if got == "<nil>" {
got = "[]"
}
assert.Equal(t, fmt.Sprint(expectData), got)
}