github.com/seeker-insurance/kit@v0.0.13/jsonapi/errors_test.go (about) 1 package jsonapi 2 3 import ( 4 "bytes" 5 "encoding/json" 6 "fmt" 7 "io" 8 "reflect" 9 "testing" 10 ) 11 12 func TestErrorObjectWritesExpectedErrorMessage(t *testing.T) { 13 err := &ErrorObject{Title: "Title test.", Detail: "Detail test."} 14 var input error = err 15 16 output := input.Error() 17 18 if output != fmt.Sprintf("Error: %s %s\n", err.Title, err.Detail) { 19 t.Fatal("Unexpected output.") 20 } 21 } 22 23 func TestMarshalErrorsWritesTheExpectedPayload(t *testing.T) { 24 var marshalErrorsTableTasts = []struct { 25 Title string 26 In []*ErrorObject 27 Out map[string]interface{} 28 }{ 29 { 30 Title: "TestFieldsAreSerializedAsNeeded", 31 In: []*ErrorObject{{ID: "0", Title: "Test title.", Detail: "Test detail", Status: "400", Code: "E1100"}}, 32 Out: map[string]interface{}{"errors": []interface{}{ 33 map[string]interface{}{"id": "0", "title": "Test title.", "detail": "Test detail", "status": "400", "code": "E1100"}, 34 }}, 35 }, 36 { 37 Title: "TestMetaFieldIsSerializedProperly", 38 In: []*ErrorObject{{Title: "Test title.", Detail: "Test detail", Meta: &map[string]interface{}{"key": "val"}}}, 39 Out: map[string]interface{}{"errors": []interface{}{ 40 map[string]interface{}{"title": "Test title.", "detail": "Test detail", "meta": map[string]interface{}{"key": "val"}}, 41 }}, 42 }, 43 } 44 for _, testRow := range marshalErrorsTableTasts { 45 t.Run(testRow.Title, func(t *testing.T) { 46 buffer, output := bytes.NewBuffer(nil), map[string]interface{}{} 47 var writer io.Writer = buffer 48 49 _ = MarshalErrors(writer, testRow.In) 50 json.Unmarshal(buffer.Bytes(), &output) 51 52 if !reflect.DeepEqual(output, testRow.Out) { 53 t.Fatalf("Expected: \n%#v \nto equal: \n%#v", output, testRow.Out) 54 } 55 }) 56 } 57 }