forked from google/jsonapi
-
Notifications
You must be signed in to change notification settings - Fork 0
/
errors_test.go
84 lines (76 loc) · 2.41 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
81
82
83
84
package jsonapi
import (
"bytes"
"encoding/json"
"fmt"
"io"
"reflect"
"testing"
)
func TestErrorObjectWritesExpectedErrorMessage(t *testing.T) {
err := &ErrorObject{Title: "Title test.", Detail: "Detail test."}
var input error = err
output := input.Error()
if output != fmt.Sprintf("Error: %s %s\n", err.Title, err.Detail) {
t.Fatal("Unexpected output.")
}
}
func TestMarshalErrorsWritesTheExpectedPayload(t *testing.T) {
var marshalErrorsTableTests = []struct {
Title string
In []*ErrorObject
Out map[string]interface{}
}{
{
Title: "TestFieldsAreSerializedAsNeeded",
In: []*ErrorObject{{ID: "0", Title: "Test title.", Detail: "Test detail", Status: "400", Code: "E1100", Source: &errorSource{Pointer: "/some/source"}}},
Out: map[string]interface{}{"errors": []interface{}{
map[string]interface{}{"id": "0", "title": "Test title.", "detail": "Test detail", "status": "400", "code": "E1100", "source": map[string]interface{}{"pointer": "/some/source"}},
}},
},
{
Title: "TestMetaFieldIsSerializedProperly",
In: []*ErrorObject{{Title: "Test title.", Detail: "Test detail", Meta: &map[string]interface{}{"key": "val"}}},
Out: map[string]interface{}{"errors": []interface{}{
map[string]interface{}{"title": "Test title.", "detail": "Test detail", "meta": map[string]interface{}{"key": "val"}},
}},
},
}
for _, testRow := range marshalErrorsTableTests {
t.Run(testRow.Title, func(t *testing.T) {
buffer, output := bytes.NewBuffer(nil), map[string]interface{}{}
var writer io.Writer = buffer
_ = MarshalErrors(writer, testRow.In)
if err := json.Unmarshal(buffer.Bytes(), &output); err != nil {
t.Fatalf("unmarshal json data: %v", err)
}
if !reflect.DeepEqual(output, testRow.Out) {
t.Fatalf("Expected: \n%#v \nto equal: \n%#v", output, testRow.Out)
}
})
}
}
func TestUnmarshalErrorCode(t *testing.T) {
errorTableTests := []struct {
errJSON []byte
expectedCode string
}{
{
errJSON: []byte(`{"code": "myAppCode"}`),
expectedCode: "myAppCode",
},
{
errJSON: []byte(`{"code": 112}`),
expectedCode: "112",
},
}
for _, test := range errorTableTests {
var output ErrorObject
if err := json.Unmarshal(test.errJSON, &output); err != nil {
t.Fatalf("unmarshal json data: %v", err)
}
if string(output.Code) != test.expectedCode {
t.Errorf("Code is %s, expected %s", string(output.Code), test.expectedCode)
}
}
}