-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathmock_server_test.go
85 lines (77 loc) · 1.99 KB
/
mock_server_test.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
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
package brightbox
import (
"encoding/json"
"fmt"
"io"
"io/ioutil"
"net/http"
"strings"
"testing"
"gotest.tools/v3/assert"
)
func readJSON(name string) string {
content, err := ioutil.ReadFile("testdata/" + name + ".json")
if err != nil {
panic(err)
}
return string(content)
}
type APIMock struct {
*testing.T
ExpectMethod string
ExpectURL string
ExpectBody interface{}
GiveStatus int
GiveBody string
GiveHeaders map[string]string
}
func (a *APIMock) ServeHTTP(w http.ResponseWriter, r *http.Request) {
if a.ExpectMethod != "" && r.Method != a.ExpectMethod {
assert.Equal(a, a.ExpectMethod, r.Method, "method didn't match")
}
if a.ExpectURL != "" && r.URL.String() != a.ExpectURL {
assert.Equal(a, a.ExpectURL, r.URL.String(), "url didn't match")
}
switch expectBody := a.ExpectBody.(type) {
case string:
b, _ := io.ReadAll(r.Body)
tb := strings.TrimSpace(string(b))
if expectBody != tb {
a.Fatalf("Expected request body %q but got %q", expectBody, tb)
}
case map[string]interface{}:
case map[string]string:
var decodedReqBody map[string]interface{}
b, _ := io.ReadAll(r.Body)
err := json.Unmarshal(b, &decodedReqBody)
if err != nil {
a.Fatalf("Couldn't parse request body json: %s", err)
}
for key, value := range expectBody {
decodedVal, ok := decodedReqBody[key]
if !ok {
a.Errorf("Expected key %q in request body but was missing", key)
} else if fmt.Sprintf("%s", expectBody[key]) != fmt.Sprintf("%s", decodedVal) {
assert.Equal(a, value, decodedReqBody[key], fmt.Sprintf("Key %q in request body doesn't match", key))
}
}
for key := range decodedReqBody {
_, ok := expectBody[key]
if !ok {
a.Errorf("Unexpected key %q found in request body json", key)
}
}
}
w.Header().Set("Content-Type", "application/json")
for k, v := range a.GiveHeaders {
w.Header().Set(k, v)
}
if a.GiveStatus > 0 {
w.WriteHeader(a.GiveStatus)
} else {
w.WriteHeader(200)
}
if a.GiveBody != "" {
w.Write([]byte(a.GiveBody))
}
}