|
5 | 5 | "encoding/json" |
6 | 6 | "fmt" |
7 | 7 | "reflect" |
| 8 | + "sort" |
8 | 9 | "testing" |
9 | 10 | "time" |
10 | 11 | ) |
@@ -83,6 +84,43 @@ type Book struct { |
83 | 84 | Description *string `jsonapi:"attr,description"` |
84 | 85 | Pages *uint `jsonapi:"attr,pages,omitempty"` |
85 | 86 | PublishedAt time.Time |
| 87 | + Tags []string `jsonapi:"attr,tags"` |
| 88 | +} |
| 89 | + |
| 90 | +func TestMarshall_attrStringSlice(t *testing.T) { |
| 91 | + tags := []string{"fiction", "sale"} |
| 92 | + b := &Book{ID: 1, Tags: tags} |
| 93 | + |
| 94 | + out := bytes.NewBuffer(nil) |
| 95 | + if err := MarshalOnePayload(out, b); err != nil { |
| 96 | + t.Fatal(err) |
| 97 | + } |
| 98 | + |
| 99 | + var jsonData map[string]interface{} |
| 100 | + if err := json.Unmarshal(out.Bytes(), &jsonData); err != nil { |
| 101 | + t.Fatal(err) |
| 102 | + } |
| 103 | + |
| 104 | + jsonTags := jsonData["data"].(map[string]interface{})["attributes"].(map[string]interface{})["tags"].([]interface{}) |
| 105 | + if e, a := len(tags), len(jsonTags); e != a { |
| 106 | + t.Fatalf("Was expecting tags of length %d got %d", e, a) |
| 107 | + } |
| 108 | + |
| 109 | + // Convert from []interface{} to []string |
| 110 | + jsonTagsStrings := []string{} |
| 111 | + for _, tag := range jsonTags { |
| 112 | + jsonTagsStrings = append(jsonTagsStrings, tag.(string)) |
| 113 | + } |
| 114 | + |
| 115 | + // Sort both |
| 116 | + sort.Strings(jsonTagsStrings) |
| 117 | + sort.Strings(tags) |
| 118 | + |
| 119 | + for i, tag := range tags { |
| 120 | + if e, a := tag, jsonTagsStrings[i]; e != a { |
| 121 | + t.Fatalf("At index %d, was expecting %s got %s", i, e, a) |
| 122 | + } |
| 123 | + } |
86 | 124 | } |
87 | 125 |
|
88 | 126 | func TestWithoutOmitsEmptyAnnotationOnRelation(t *testing.T) { |
|
0 commit comments