-
Notifications
You must be signed in to change notification settings - Fork 1
/
httperrors_test.go
73 lines (64 loc) · 2.05 KB
/
httperrors_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
package httperrors
import (
"errors"
"net/http"
"net/http/httptest"
"testing"
"github.com/stretchr/testify/assert"
)
func TestNew(t *testing.T) {
t.Run("without message", func(t *testing.T) {
he := New(http.StatusOK, nil)
assert.Equal(t, 200, he.StatusCode)
assert.Equal(t, "OK", he.Message)
})
t.Run("with message", func(t *testing.T) {
he := New(http.StatusOK, "some message")
assert.Equal(t, 200, he.StatusCode)
assert.Equal(t, "some message", he.Message)
})
}
func TestError(t *testing.T) {
testCases := []struct {
name string
code int
message interface{}
result string
}{
{"number", http.StatusInternalServerError, 12345, "500 - 12345"},
{"string", http.StatusNotFound, "test message", "404 - test message"},
{"map", http.StatusBadRequest, map[string]interface{}{"code": 12}, "400 - map[code:12]"},
{"error", http.StatusInternalServerError, errors.New("test error"), "500 - test error"},
{"nil", http.StatusInternalServerError, nil, "500 - Internal Server Error"},
}
for _, testCase := range testCases {
t.Run(testCase.name, func(t *testing.T) {
he := New(testCase.code, testCase.message)
assert.Equal(t, testCase.result, he.Error())
})
}
}
func TestWriteJSON(t *testing.T) {
testCases := []struct {
name string
code int
message interface{}
result string
}{
{"number", http.StatusInternalServerError, 12345, `{"message":12345}`},
{"string", http.StatusNotFound, "test message", `{"message":"test message"}`},
{"map", http.StatusBadRequest, map[string]interface{}{"code": 12}, `{"message":{"code":12}}`},
{"error", http.StatusInternalServerError, errors.New("test error"), `{"message":"test error"}`},
{"nil", http.StatusUnauthorized, nil, `{"message":"Unauthorized"}`},
}
for _, testCase := range testCases {
t.Run(testCase.name, func(t *testing.T) {
he := New(testCase.code, testCase.message)
w := httptest.NewRecorder()
err := he.WriteJSON(w)
assert.NoError(t, err)
assert.Equal(t, testCase.code, w.Code)
assert.Equal(t, testCase.result+"\n", w.Body.String())
})
}
}