-
Notifications
You must be signed in to change notification settings - Fork 0
/
handler.go
55 lines (47 loc) · 1.17 KB
/
handler.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 testutil
import (
"encoding/json"
"io"
"net/http"
"os"
"testing"
"github.com/google/go-cmp/cmp"
)
func AssertJSON(t *testing.T, want, got []byte) {
t.Helper()
var jw, jg any
if err := json.Unmarshal(want, &jw); err != nil {
t.Fatalf("cannot unmarshal want %q: %v", want, err)
}
if err := json.Unmarshal(got, &jg); err != nil {
t.Fatalf("cannot unmarshal got %q: %v", got, err)
}
if diff := cmp.Diff(jg, jw); diff != "" {
t.Errorf("got differs: (-got +want)\n%s", diff)
}
}
func AssertResponse(t *testing.T, got *http.Response, status int, body []byte) {
t.Helper()
t.Cleanup(func() { _ = got.Body.Close() })
gb, err := io.ReadAll(got.Body)
if err != nil {
t.Fatal(err)
}
if got.StatusCode != status {
t.Fatalf("want status %d, but got %d, body: %q", status, got.StatusCode, gb)
}
if len(gb) == 0 && len(body) == 0 {
// 期待としても実体としてもレスポンスボディがないので
// AssertJSONを呼ぶ必要はない。
return
}
AssertJSON(t, body, gb)
}
func LoadFile(t *testing.T, path string) []byte {
t.Helper()
bt, err := os.ReadFile(path)
if err != nil {
t.Fatalf("cannot read from %q: %v", path, err)
}
return bt
}