main
1package serde
2
3import (
4 "bytes"
5 "strings"
6 "testing"
7
8 "github.com/google/jsonapi"
9 "github.com/stretchr/testify/assert"
10 "github.com/stretchr/testify/require"
11)
12
13type example struct {
14 ID string `jsonapi:"primary,examples"`
15 Name string `jsonapi:"attr,name"`
16}
17
18func TestToJSONAPI(t *testing.T) {
19 t.Run("serializes a custom type", func(t *testing.T) {
20 io := bytes.NewBuffer(nil)
21
22 require.NoError(t, ToJSONAPI(io, &example{Name: "Example"}))
23
24 assert.Equal(t, `{"data":{"type":"examples","attributes":{"name":"Example"}}}`+"\n", io.String())
25 })
26
27 t.Run("serializes a jsonapi.ErrorsPayload", func(t *testing.T) {
28 io := bytes.NewBuffer(nil)
29
30 require.NoError(t, ToJSONAPI(io, &jsonapi.ErrorsPayload{
31 Errors: []*jsonapi.ErrorObject{
32 {
33 ID: "id",
34 Title: "Name is required",
35 Status: "400",
36 },
37 },
38 }))
39
40 assert.Equal(t, `{"errors":[{"id":"id","title":"Name is required","status":"400"}]}`+"\n", io.String())
41 })
42}
43
44func TestFromJSONAPI(t *testing.T) {
45 t.Run("from a single item", func(t *testing.T) {
46 io := strings.NewReader(`{"data":{"type":"examples","id":"42","attributes":{"name":"Example"}}}`)
47
48 item, err := FromJSONAPI[example](io)
49
50 require.NoError(t, err)
51 assert.Equal(t, "42", item.ID)
52 assert.Equal(t, "Example", item.Name)
53 })
54}