-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy patherrors_test.go
80 lines (72 loc) · 2.01 KB
/
errors_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
package httperrors
import (
"encoding/json"
goerrors "errors"
"fmt"
"net/http"
"net/http/httptest"
"reflect"
"testing"
"github.com/stretchr/testify/assert"
)
// assertRespCode is a test helper to assert HTTP response codes.
func assertRespCode(t *testing.T, actual, expected int) {
if actual != expected {
t.Fatalf(
"HTTP response code was %d and expected %d\n",
actual,
expected,
)
}
}
// assertJSONBytes is a test helper to assert two JSON byte slices are equal.
func assertJSONBytes(t *testing.T, actual, expected []byte) {
var j, j2 interface{}
if err := json.Unmarshal(actual, &j); err != nil {
t.Fatal("Could not unmarshal actual response")
}
if err := json.Unmarshal(expected, &j2); err != nil {
t.Fatal("Could not unmarshal actual response")
}
equal := reflect.DeepEqual(j2, j)
if !equal {
t.Fatal("The expected and actual JSON responses are not equal")
}
}
func TestWriteErrorInvalidtokenPanics(t *testing.T) {
defer func() {
if r := recover(); r == nil {
t.Errorf("The code did not panic")
}
}()
w := httptest.NewRecorder()
WriteError(w, -1, "blah")
}
func TestWriteErrorMissingParam(t *testing.T) {
w := httptest.NewRecorder()
WriteError(w, http.StatusBadRequest, "Parameters were missing")
expectedResponse := []byte(`{
"code": 400,
"message": "Bad Request",
"reason": "Parameters were missing"
}`)
assertRespCode(t, w.Code, http.StatusBadRequest)
assertJSONBytes(t, w.Body.Bytes(), expectedResponse)
}
func TestUnableToMarshalJSON(t *testing.T) {
originalMarshalJSON := marshalJSON
defer func() { marshalJSON = originalMarshalJSON }()
marshalJSON = func(interface{}) ([]byte, error) { return []byte{}, fmt.Errorf("TEST_ERROR") }
w := httptest.NewRecorder()
WriteError(w, http.StatusNotFound, "Entity Not Found")
assertRespCode(t, w.Code, 404)
}
func TestErrorList(t *testing.T) {
errs := []error{
goerrors.New("first"),
goerrors.New("second"),
goerrors.New("third"),
}
errlist := New(errs)
assert.Equal(t, "errors: [first second third]", errlist.Error())
}