-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathresponse_test.go
84 lines (68 loc) · 1.93 KB
/
response_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
package response_test
import (
"net/http"
"testing"
"github.com/go-carrot/response"
"github.com/stretchr/testify/assert"
)
type DummyResult struct {
Value1 string
Value2 string
}
type StackWriter struct {
HeaderInt int
Stack []string
}
func (sw *StackWriter) Write(p []byte) (n int, err error) {
sw.Stack = append(sw.Stack, string(p))
return 0, nil
}
func (sw *StackWriter) WriteHeader(header int) {
sw.HeaderInt = header
}
func (sw *StackWriter) Header() http.Header {
return make(http.Header, 0)
}
func (sw *StackWriter) Peek() string {
if len(sw.Stack) > 0 {
return sw.Stack[len(sw.Stack)-1]
}
return ""
}
func TestResponseNotSet(t *testing.T) {
sw := new(StackWriter)
resp := response.New(sw)
resp.Output()
assert.Equal(t, "{\"meta\":{\"success\":false,\"status_code\":500,\"status_text\":\"Internal Server Error\",\"error_details\":null},\"content\":null}", sw.Peek())
}
func TestResponseSingleDetail(t *testing.T) {
sw := new(StackWriter)
resp := response.New(sw)
resp.SetErrorDetails("Missing Auth")
resp.Output()
assert.Equal(t, sw.HeaderInt, 500)
assert.Equal(t, "{\"meta\":{\"success\":false,\"status_code\":500,\"status_text\":\"Internal Server Error\",\"error_details\":\"Missing Auth\"},\"content\":null}", sw.Peek())
}
func TestSuccessfulResult(t *testing.T) {
sw := new(StackWriter)
resp := response.New(sw)
resp.SetResult(http.StatusOK,
&DummyResult{
Value1: "Hello World",
Value2: "Wow",
},
)
resp.Output()
assert.Equal(t, sw.HeaderInt, 200)
assert.Equal(t, "{\"meta\":{\"success\":true,\"status_code\":200,\"status_text\":\"OK\",\"error_details\":null},\"content\":{\"Value1\":\"Hello World\",\"Value2\":\"Wow\"}}", sw.Peek())
}
func TestJsonRenderFailure(t *testing.T) {
defer func() {
recover()
}()
sw := new(StackWriter)
resp := response.New(sw)
resp.SetResult(http.StatusOK, func() {})
resp.Output()
t.Error("JsonRenderer should fail with content that can not be serialized to JSON")
}