This repository has been archived by the owner on Mar 16, 2019. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 16
/
json_test.go
93 lines (79 loc) · 1.91 KB
/
json_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
86
87
88
89
90
91
92
93
package goat
import (
"bytes"
"net/http/httptest"
"testing"
)
func TestWriteError(t *testing.T) {
// In
code := 500
err := "foo"
// Expected
json := `{
"error": "` + err + `"
}
`
buf := bytes.NewBufferString(json)
w := httptest.NewRecorder()
WriteError(w, code, err)
// Test code
if w.Code != code {
t.Errorf("WriteError should set Code to %i, but did set it to %i", code, w.Code)
}
// Test body
if w.Body == nil {
t.Errorf("WriteError should set Body to %s, but didn't", json)
} else if string(w.Body.Bytes()) == string(buf.Bytes()) {
t.Errorf("WriteError should set Body to %v, but did set it to %v", buf, w.Body)
}
}
func TestWriteJSON(t *testing.T) {
in := map[string]string{
"foo": "bar",
"knock": "knock",
}
json := `{
"foo": "bar",
"knock": "knock"
}
`
buf := bytes.NewBufferString(json)
w := httptest.NewRecorder()
WriteJSON(w, in)
if w.Body == nil {
t.Errorf("WriteJSON should set the Body to %s, but didn't", json)
} else if string(w.Body.Bytes()) == string(buf.Bytes()) {
t.Errorf("WriteJSON set the Body to %v, but should set it to %v", buf, w.Body)
}
// Test error
w = httptest.NewRecorder()
if err := WriteJSON(w, WriteJSON); err == nil {
t.Errorf("WriteJSON should return an error, but didn't")
}
}
func TestWriteJSONWithStatus(t *testing.T) {
// in
code := 201
in := map[string]interface{}{
"foo": "bar",
"bar": "foo",
}
json := `{
"foo": "bar",
"bar": "foo"
}
`
buf := bytes.NewBufferString(json)
w := httptest.NewRecorder()
WriteJSONWithStatus(w, code, in)
// test code
if w.Code != code {
t.Errorf("WriteJSONWithStatus should set Code to %i, but did set it to %i", code, w.Code)
}
// test body
if w.Body == nil {
t.Errorf("WriteJSONWithStatus should set the Body to %s, but didn't", json)
} else if string(w.Body.Bytes()) == string(buf.Bytes()) {
t.Errorf("WriteJSONWithStatus set the Body to %v, but should set it to %v", buf, w.Body)
}
}