forked from google/jsonapi
-
Notifications
You must be signed in to change notification settings - Fork 0
/
response_test.go
1384 lines (1163 loc) · 32.3 KB
/
response_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
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
package jsonapi
import (
"bytes"
"encoding/json"
"fmt"
"reflect"
"sort"
"strings"
"testing"
"time"
)
func TestMarshalPayload(t *testing.T) {
book := &Book{ID: 1}
books := []*Book{book, {ID: 2}}
var jsonData map[string]interface{}
// One
out1 := bytes.NewBuffer(nil)
if err := MarshalPayload(out1, book, nil, nil); err != nil {
t.Fatalf("marshal one payload: %v", err)
}
if err := json.Unmarshal(out1.Bytes(), &jsonData); err != nil {
t.Fatal(err)
}
if _, ok := jsonData["data"].(map[string]interface{}); !ok {
t.Fatalf("data key did not contain an Hash/Dict/Map")
}
// Many
out2 := bytes.NewBuffer(nil)
if err := MarshalPayload(out2, books, nil, nil); err != nil {
t.Fatalf("marshal many payload: %v", err)
}
if err := json.Unmarshal(out2.Bytes(), &jsonData); err != nil {
t.Fatal(err)
}
if _, ok := jsonData["data"].([]interface{}); !ok {
t.Fatalf("data key did not contain an Array")
}
}
func TestMarshalPayloadWithNulls(t *testing.T) {
books := []*Book{nil, {ID: 101}, nil}
var jsonData map[string]interface{}
out := bytes.NewBuffer(nil)
if err := MarshalPayload(out, books, nil, nil); err != nil {
t.Fatal(err)
}
if err := json.Unmarshal(out.Bytes(), &jsonData); err != nil {
t.Fatal(err)
}
raw, ok := jsonData["data"]
if !ok {
t.Fatalf("data key does not exist")
}
arr, ok := raw.([]interface{})
if !ok {
t.Fatalf("data is not an Array")
}
for i := 0; i < len(arr); i++ {
if books[i] == nil && arr[i] != nil ||
books[i] != nil && arr[i] == nil {
t.Fatalf("restored data is not equal to source")
}
}
}
func TestMarshal_attrStringSlice(t *testing.T) {
tags := []string{"fiction", "sale"}
b := &Book{ID: 1, Tags: tags}
out := bytes.NewBuffer(nil)
if err := MarshalPayload(out, b, nil, nil); err != nil {
t.Fatal(err)
}
var jsonData map[string]interface{}
if err := json.Unmarshal(out.Bytes(), &jsonData); err != nil {
t.Fatal(err)
}
jsonTags := jsonData["data"].(map[string]interface{})["attributes"].(map[string]interface{})["tags"].([]interface{})
if e, a := len(tags), len(jsonTags); e != a {
t.Fatalf("Was expecting tags of length %d got %d", e, a)
}
// Convert from []interface{} to []string
var jsonTagsStrings []string
for _, tag := range jsonTags {
jsonTagsStrings = append(jsonTagsStrings, tag.(string))
}
// Sort both
sort.Strings(jsonTagsStrings)
sort.Strings(tags)
for i, tag := range tags {
if len(jsonTagsStrings)-1 >= i { // Panic insurance
if e, a := tag, jsonTagsStrings[i]; e != a {
t.Fatalf("At index %d, was expecting %s got %s", i, e, a)
}
} else {
t.Errorf("expected index %d to exist in jsonTagsStrings, did not", i)
}
}
}
func TestWithoutOmitsEmptyAnnotationOnRelation(t *testing.T) {
blog := &Blog{}
out := bytes.NewBuffer(nil)
if err := MarshalPayload(out, blog, nil, nil); err != nil {
t.Fatal(err)
}
var jsonData map[string]interface{}
if err := json.Unmarshal(out.Bytes(), &jsonData); err != nil {
t.Fatal(err)
}
relationships := jsonData["data"].(map[string]interface{})["relationships"].(map[string]interface{})
// Verifiy the "posts" relation was an empty array
posts, ok := relationships["posts"]
if !ok {
t.Fatal("Was expecting the data.relationships.posts key/value to have been present")
}
postsMap, ok := posts.(map[string]interface{})
if !ok {
t.Fatal("data.relationships.posts was not a map")
}
postsData, ok := postsMap["data"]
if !ok {
t.Fatal("Was expecting the data.relationships.posts.data key/value to have been present")
}
postsDataSlice, ok := postsData.([]interface{})
if !ok {
t.Fatal("data.relationships.posts.data was not a slice []")
}
if len(postsDataSlice) != 0 {
t.Fatal("Was expecting the data.relationships.posts.data value to have been an empty array []")
}
// Verifiy the "current_post" was a null
currentPost, postExists := relationships["current_post"]
if !postExists {
t.Fatal("Was expecting the data.relationships.current_post key/value to have NOT been omitted")
}
currentPostMap, ok := currentPost.(map[string]interface{})
if !ok {
t.Fatal("data.relationships.current_post was not a map")
}
currentPostData, ok := currentPostMap["data"]
if !ok {
t.Fatal("Was expecting the data.relationships.current_post.data key/value to have been present")
}
if currentPostData != nil {
t.Fatal("Was expecting the data.relationships.current_post.data value to have been nil/null")
}
}
func TestWithOmitsEmptyAnnotationOnRelation(t *testing.T) {
type BlogOptionalPosts struct {
ID int `jsonapi:"primary,blogs"`
Title string `jsonapi:"attr,title"`
Posts []*Post `jsonapi:"relation,posts,omitempty"`
CurrentPost *Post `jsonapi:"relation,current_post,omitempty"`
}
blog := &BlogOptionalPosts{ID: 999}
out := bytes.NewBuffer(nil)
if err := MarshalPayload(out, blog, nil, nil); err != nil {
t.Fatal(err)
}
var jsonData map[string]interface{}
if err := json.Unmarshal(out.Bytes(), &jsonData); err != nil {
t.Fatal(err)
}
payload := jsonData["data"].(map[string]interface{})
// Verify relationship was NOT set
if val, exists := payload["relationships"]; exists {
t.Fatalf("Was expecting the data.relationships key/value to have been empty - it was not and had a value of %v", val)
}
}
func TestWithOmitsEmptyAnnotationOnRelation_MixedData(t *testing.T) {
type BlogOptionalPosts struct {
ID int `jsonapi:"primary,blogs"`
Title string `jsonapi:"attr,title"`
Posts []*Post `jsonapi:"relation,posts,omitempty"`
CurrentPost *Post `jsonapi:"relation,current_post,omitempty"`
}
blog := &BlogOptionalPosts{
ID: 999,
CurrentPost: &Post{
ID: 123,
},
}
out := bytes.NewBuffer(nil)
if err := MarshalPayload(out, blog, nil, nil); err != nil {
t.Fatal(err)
}
var jsonData map[string]interface{}
if err := json.Unmarshal(out.Bytes(), &jsonData); err != nil {
t.Fatal(err)
}
payload := jsonData["data"].(map[string]interface{})
// Verify relationship was set
if _, exists := payload["relationships"]; !exists {
t.Fatal("Was expecting the data.relationships key/value to have NOT been empty")
}
relationships := payload["relationships"].(map[string]interface{})
// Verify the relationship was not omitted, and is not null
if val, exists := relationships["current_post"]; !exists {
t.Fatal("Was expecting the data.relationships.current_post key/value to have NOT been omitted")
} else if val.(map[string]interface{})["data"] == nil {
t.Fatal("Was expecting the data.relationships.current_post value to have NOT been nil/null")
}
}
func TestWithOmitsEmptyAnnotationOnAttribute(t *testing.T) {
type Phone struct {
Number string `json:"number"`
}
type Address struct {
City string `json:"city"`
Street string `json:"street"`
}
type Tags map[string]int
type Author struct {
ID int `jsonapi:"primary,authors"`
Name string `jsonapi:"attr,title"`
Phones []*Phone `jsonapi:"attr,phones,omitempty"`
Address *Address `jsonapi:"attr,address,omitempty"`
Tags Tags `jsonapi:"attr,tags,omitempty"`
}
author := &Author{
ID: 999,
Name: "Igor",
Phones: nil, // should be omitted
Address: nil, // should be omitted
Tags: Tags{"dogs": 1, "cats": 2}, // should not be omitted
}
out := bytes.NewBuffer(nil)
if err := MarshalPayload(out, author, nil, nil); err != nil {
t.Fatal(err)
}
var jsonData map[string]interface{}
if err := json.Unmarshal(out.Bytes(), &jsonData); err != nil {
t.Fatal(err)
}
// Verify that there is no field "phones" in attributes
payload := jsonData["data"].(map[string]interface{})
attributes := payload["attributes"].(map[string]interface{})
if _, ok := attributes["title"]; !ok {
t.Fatal("Was expecting the data.attributes.title to have NOT been omitted")
}
if _, ok := attributes["phones"]; ok {
t.Fatal("Was expecting the data.attributes.phones to have been omitted")
}
if _, ok := attributes["address"]; ok {
t.Fatal("Was expecting the data.attributes.phones to have been omitted")
}
if _, ok := attributes["tags"]; !ok {
t.Fatal("Was expecting the data.attributes.tags to have NOT been omitted")
}
}
func TestMarshalIDPtr(t *testing.T) {
id, _make, model := "5440000", "Ford", "Mustang"
car := &Car{
ID: &id,
Make: &_make,
Model: &model,
}
out := bytes.NewBuffer(nil)
if err := MarshalPayload(out, car, nil, nil); err != nil {
t.Fatal(err)
}
var jsonData map[string]interface{}
if err := json.Unmarshal(out.Bytes(), &jsonData); err != nil {
t.Fatal(err)
}
data := jsonData["data"].(map[string]interface{})
// attributes := data["attributes"].(map[string]interface{})
// Verify that the ID was sent
val, exists := data["id"]
if !exists {
t.Fatal("Was expecting the data.id member to exist")
}
// float is the interface type given by default to numeric values in
// unmarshalled objects. The string representation of the previously
// marshalled object returns an integer so the following test is complementary
floatId := 5440000.0
if val.(float64) != floatId {
t.Fatalf("Was expecting the data.id member to be `%s`, got `%s`", id, val)
}
}
func TestMarshalOnePayload_omitIDString(t *testing.T) {
type Foo struct {
ID string `jsonapi:"primary,foo"`
Title string `jsonapi:"attr,title"`
}
foo := &Foo{Title: "Foo"}
out := bytes.NewBuffer(nil)
if err := MarshalPayload(out, foo, nil, nil); err != nil {
t.Fatal(err)
}
var jsonData map[string]interface{}
if err := json.Unmarshal(out.Bytes(), &jsonData); err != nil {
t.Fatal(err)
}
payload := jsonData["data"].(map[string]interface{})
// Verify that empty ID of type string gets omitted. See:
// https://github.com/google/jsonapi/issues/83#issuecomment-285611425
_, ok := payload["id"]
if ok {
t.Fatal("Was expecting the data.id member to be omitted")
}
}
func TestMarshall_invalidIDType(t *testing.T) {
type badIDStruct struct {
ID *bool `jsonapi:"primary,cars"`
}
id := true
o := &badIDStruct{ID: &id}
out := bytes.NewBuffer(nil)
if err := MarshalPayload(out, o, nil, nil); err != ErrBadJSONAPIID {
t.Fatalf(
"Was expecting a `%s` error, got `%s`", ErrBadJSONAPIID, err,
)
}
}
func TestOmitsEmptyAnnotation(t *testing.T) {
book := &Book{
Author: "aren55555",
PublishedAt: time.Now().AddDate(0, -1, 0),
}
out := bytes.NewBuffer(nil)
if err := MarshalPayload(out, book, nil, nil); err != nil {
t.Fatal(err)
}
var jsonData map[string]interface{}
if err := json.Unmarshal(out.Bytes(), &jsonData); err != nil {
t.Fatal(err)
}
attributes := jsonData["data"].(map[string]interface{})["attributes"].(map[string]interface{})
// Verify that the specifically omitted field were omitted
if val, exists := attributes["title"]; exists {
t.Fatalf("Was expecting the data.attributes.title key/value to have been omitted - it was not and had a value of %v", val)
}
if val, exists := attributes["pages"]; exists {
t.Fatalf("Was expecting the data.attributes.pages key/value to have been omitted - it was not and had a value of %v", val)
}
// Verify the implicitly omitted fields were omitted
if val, exists := attributes["PublishedAt"]; exists {
t.Fatalf("Was expecting the data.attributes.PublishedAt key/value to have been implicitly omitted - it was not and had a value of %v", val)
}
// Verify the unset fields were not omitted
if _, exists := attributes["isbn"]; !exists {
t.Fatal("Was expecting the data.attributes.isbn key/value to have NOT been omitted")
}
}
func TestHasPrimaryAnnotation(t *testing.T) {
testModel := &Blog{
ID: 5,
Title: "Title 1",
CreatedAt: time.Now(),
}
out := bytes.NewBuffer(nil)
if err := MarshalPayload(out, testModel, nil, nil); err != nil {
t.Fatal(err)
}
resp := new(OnePayload)
if err := json.NewDecoder(out).Decode(resp); err != nil {
t.Fatal(err)
}
data := resp.Data
if data.Type != "blogs" {
t.Fatalf("type should have been blogs, got %s", data.Type)
}
if data.ID != 5 {
t.Fatalf("ID not transferred")
}
}
func TestSupportsAttributes(t *testing.T) {
testModel := &Blog{
ID: 5,
Title: "Title 1",
CreatedAt: time.Now(),
}
out := bytes.NewBuffer(nil)
if err := MarshalPayload(out, testModel, nil, nil); err != nil {
t.Fatal(err)
}
resp := new(OnePayload)
if err := json.NewDecoder(out).Decode(resp); err != nil {
t.Fatal(err)
}
data := resp.Data
if data.Attributes == nil {
t.Fatalf("Expected attributes")
}
if data.Attributes["title"] != "Title 1" {
t.Fatalf("Attributes hash not populated using tags correctly")
}
}
func TestOmitsZeroTimes(t *testing.T) {
testModel := &Blog{
ID: 5,
Title: "Title 1",
CreatedAt: time.Time{},
}
out := bytes.NewBuffer(nil)
if err := MarshalPayload(out, testModel, nil, nil); err != nil {
t.Fatal(err)
}
resp := new(OnePayload)
if err := json.NewDecoder(out).Decode(resp); err != nil {
t.Fatal(err)
}
data := resp.Data
if data.Attributes == nil {
t.Fatalf("Expected attributes")
}
if data.Attributes["created_at"] != nil {
t.Fatalf("Created at was serialized even though it was a zero Time")
}
}
func TestMarshalISO8601Time(t *testing.T) {
testModel := &Timestamp{
ID: 5,
Time: time.Date(2016, 8, 17, 8, 27, 12, 23849, time.UTC),
}
out := bytes.NewBuffer(nil)
if err := MarshalPayload(out, testModel, nil, nil); err != nil {
t.Fatal(err)
}
resp := new(OnePayload)
if err := json.NewDecoder(out).Decode(resp); err != nil {
t.Fatal(err)
}
data := resp.Data
if data.Attributes == nil {
t.Fatalf("Expected attributes")
}
if data.Attributes["timestamp"] != "2016-08-17T08:27:12Z" {
t.Fatal("Timestamp was not serialised into ISO8601 correctly")
}
}
func TestMarshalISO8601TimePointer(t *testing.T) {
tm := time.Date(2016, 8, 17, 8, 27, 12, 23849, time.UTC)
testModel := &Timestamp{
ID: 5,
Next: &tm,
}
out := bytes.NewBuffer(nil)
if err := MarshalPayload(out, testModel, nil, nil); err != nil {
t.Fatal(err)
}
resp := new(OnePayload)
if err := json.NewDecoder(out).Decode(resp); err != nil {
t.Fatal(err)
}
data := resp.Data
if data.Attributes == nil {
t.Fatalf("Expected attributes")
}
if data.Attributes["next"] != "2016-08-17T08:27:12Z" {
t.Fatal("Next was not serialised into ISO8601 correctly")
}
}
func TestSupportsLinkable(t *testing.T) {
testModel := &Blog{
ID: 5,
Title: "Title 1",
CreatedAt: time.Now(),
}
out := bytes.NewBuffer(nil)
if err := MarshalPayload(out, testModel, nil, nil); err != nil {
t.Fatal(err)
}
resp := new(OnePayload)
if err := json.NewDecoder(out).Decode(resp); err != nil {
t.Fatal(err)
}
data := resp.Data
if data.Links == nil {
t.Fatal("Expected data.links")
}
links := *data.Links
self, hasSelf := links["self"]
if !hasSelf {
t.Fatal("Expected 'self' link to be present")
}
if _, isString := self.(string); !isString {
t.Fatal("Expected 'self' to contain a string")
}
comments, hasComments := links["comments"]
if !hasComments {
t.Fatal("expect 'comments' to be present")
}
commentsMap, isMap := comments.(map[string]interface{})
if !isMap {
t.Fatal("Expected 'comments' to contain a map")
}
commentsHref, hasHref := commentsMap["href"]
if !hasHref {
t.Fatal("Expect 'comments' to contain an 'href' key/value")
}
if _, isString := commentsHref.(string); !isString {
t.Fatal("Expected 'href' to contain a string")
}
commentsMeta, hasMeta := commentsMap["meta"]
if !hasMeta {
t.Fatal("Expect 'comments' to contain a 'meta' key/value")
}
commentsMetaMap, isMap := commentsMeta.(map[string]interface{})
if !isMap {
t.Fatal("Expected 'comments' to contain a map")
}
commentsMetaObject := Meta(commentsMetaMap)
countsMap, isMap := commentsMetaObject["counts"].(map[string]interface{})
if !isMap {
t.Fatal("Expected 'counts' to contain a map")
}
for k, v := range countsMap {
if _, isNum := v.(float64); !isNum {
t.Fatalf("Exepected value at '%s' to be a numeric (float64)", k)
}
}
}
func TestInvalidLinkable(t *testing.T) {
testModel := &BadComment{
ID: 5,
Body: "Hello World",
}
out := bytes.NewBuffer(nil)
if err := MarshalPayload(out, testModel, nil, nil); err == nil {
t.Fatal("Was expecting an error")
}
}
func TestSupportsMetable(t *testing.T) {
testModel := &Blog{
ID: 5,
Title: "Title 1",
CreatedAt: time.Now(),
}
out := bytes.NewBuffer(nil)
if err := MarshalPayload(out, testModel, nil, nil); err != nil {
t.Fatal(err)
}
resp := new(OnePayload)
if err := json.NewDecoder(out).Decode(resp); err != nil {
t.Fatal(err)
}
data := resp.Data
if data.Meta == nil {
t.Fatalf("Expected data.meta")
}
meta := *data.Meta
if e, a := "extra details regarding the blog", meta["detail"]; e != a {
t.Fatalf("Was expecting meta.detail to be %q, got %q", e, a)
}
}
func TestRelations(t *testing.T) {
testModel := testBlog()
out := bytes.NewBuffer(nil)
if err := MarshalPayload(out, testModel, nil, nil); err != nil {
t.Fatal(err)
}
resp := new(OnePayload)
if err := json.NewDecoder(out).Decode(resp); err != nil {
t.Fatal(err)
}
relations := resp.Data.Relationships
if relations == nil {
t.Fatalf("Relationships were not materialized")
}
if relations["posts"] == nil {
t.Fatalf("Posts relationship was not materialized")
} else {
if relations["posts"].(map[string]interface{})["links"] == nil {
t.Fatalf("Posts relationship links were not materialized")
}
if relations["posts"].(map[string]interface{})["meta"] == nil {
t.Fatalf("Posts relationship meta were not materialized")
}
}
if relations["current_post"] == nil {
t.Fatalf("Current post relationship was not materialized")
} else {
if relations["current_post"].(map[string]interface{})["links"] == nil {
t.Fatalf("Current post relationship links were not materialized")
}
if relations["current_post"].(map[string]interface{})["meta"] == nil {
t.Fatalf("Current post relationship meta were not materialized")
}
}
if len(relations["posts"].(map[string]interface{})["data"].([]interface{})) != 2 {
t.Fatalf("Did not materialize two posts")
}
}
func TestNoRelations(t *testing.T) {
testModel := &Blog{ID: 1, Title: "Title 1", CreatedAt: time.Now()}
out := bytes.NewBuffer(nil)
if err := MarshalPayload(out, testModel, nil, nil); err != nil {
t.Fatal(err)
}
resp := new(OnePayload)
if err := json.NewDecoder(out).Decode(resp); err != nil {
t.Fatal(err)
}
if resp.Included != nil {
t.Fatalf("Encoding json response did not omit included")
}
}
func TestMarshalPayloadWithoutIncluded(t *testing.T) {
data := &Post{
ID: 1,
BlogID: 2,
ClientID: "123e4567-e89b-12d3-a456-426655440000",
Title: "Foo",
Body: "Bar",
Comments: []*Comment{
{
ID: 20,
Body: "First",
},
{
ID: 21,
Body: "Hello World",
},
},
LatestComment: &Comment{
ID: 22,
Body: "Cool!",
},
}
out := bytes.NewBuffer(nil)
if err := MarshalPayloadWithoutIncluded(out, data, nil, nil); err != nil {
t.Fatal(err)
}
resp := new(OnePayload)
if err := json.NewDecoder(out).Decode(resp); err != nil {
t.Fatal(err)
}
if resp.Included != nil {
t.Fatalf("Encoding json response did not omit included")
}
}
func TestMarshalPayload_many(t *testing.T) {
data := []interface{}{
&Blog{
ID: 5,
Title: "Title 1",
CreatedAt: time.Now(),
Posts: []*Post{
{
ID: 1,
Title: "Foo",
Body: "Bar",
},
{
ID: 2,
Title: "Fuubar",
Body: "Bas",
},
},
CurrentPost: &Post{
ID: 1,
Title: "Foo",
Body: "Bar",
},
},
&Blog{
ID: 6,
Title: "Title 2",
CreatedAt: time.Now(),
Posts: []*Post{
{
ID: 3,
Title: "Foo",
Body: "Bar",
},
{
ID: 4,
Title: "Fuubar",
Body: "Bas",
},
},
CurrentPost: &Post{
ID: 4,
Title: "Foo",
Body: "Bar",
},
},
}
out := bytes.NewBuffer(nil)
if err := MarshalPayload(out, data, nil, nil); err != nil {
t.Fatal(err)
}
resp := new(ManyPayload)
if err := json.NewDecoder(out).Decode(resp); err != nil {
t.Fatal(err)
}
d := resp.Data
if len(d) != 2 {
t.Fatalf("data should have two elements")
}
}
func TestMarshalMany_WithSliceOfStructPointers(t *testing.T) {
var data []*Blog
for len(data) < 2 {
data = append(data, testBlog())
}
out := bytes.NewBuffer(nil)
if err := MarshalPayload(out, data, nil, nil); err != nil {
t.Fatal(err)
}
resp := new(ManyPayload)
if err := json.NewDecoder(out).Decode(resp); err != nil {
t.Fatal(err)
}
d := resp.Data
if len(d) != 2 {
t.Fatalf("data should have two elements")
}
}
func TestMarshalManyWithoutIncluded(t *testing.T) {
var data []*Blog
for len(data) < 2 {
data = append(data, testBlog())
}
out := bytes.NewBuffer(nil)
if err := MarshalPayloadWithoutIncluded(out, data, nil, nil); err != nil {
t.Fatal(err)
}
resp := new(ManyPayload)
if err := json.NewDecoder(out).Decode(resp); err != nil {
t.Fatal(err)
}
d := resp.Data
if len(d) != 2 {
t.Fatalf("data should have two elements")
}
if resp.Included != nil {
t.Fatalf("Encoding json response did not omit included")
}
}
func TestMarshalMany_SliceOfInterfaceAndSliceOfStructsSameJSON(t *testing.T) {
structs := []*Book{
{ID: 1, Author: "aren55555", ISBN: "abc"},
{ID: 2, Author: "shwoodard", ISBN: "xyz"},
}
var interfaces []interface{}
for _, s := range structs {
interfaces = append(interfaces, s)
}
// Perform Marshals
structsOut := new(bytes.Buffer)
if err := MarshalPayload(structsOut, structs, nil, nil); err != nil {
t.Fatal(err)
}
interfacesOut := new(bytes.Buffer)
if err := MarshalPayload(interfacesOut, interfaces, nil, nil); err != nil {
t.Fatal(err)
}
// Generic JSON Unmarshal
structsData, interfacesData :=
make(map[string]interface{}), make(map[string]interface{})
if err := json.Unmarshal(structsOut.Bytes(), &structsData); err != nil {
t.Fatal(err)
}
if err := json.Unmarshal(interfacesOut.Bytes(), &interfacesData); err != nil {
t.Fatal(err)
}
// Compare Result
if !reflect.DeepEqual(structsData, interfacesData) {
t.Fatal("Was expecting the JSON API generated to be the same")
}
}
func TestMarshal_InvalidIntefaceArgument(t *testing.T) {
out := new(bytes.Buffer)
if err := MarshalPayload(out, true, nil, nil); err != ErrUnexpectedType {
t.Fatal("Was expecting an error")
}
if err := MarshalPayload(out, 25, nil, nil); err != ErrUnexpectedType {
t.Fatal("Was expecting an error")
}
if err := MarshalPayload(out, Book{}, nil, nil); err != ErrUnexpectedType {
t.Fatal("Was expecting an error")
}
}
func TestMarshal_SkipField(t *testing.T) {
type Foo struct {
ID string `jsonapi:"primary,foo"`
Bar string `jsonapi:"-"`
Baz string `jsonapi:"attr,baz"`
}
f := Foo{
ID: "1",
Bar: "skip me!",
Baz: "don't skip me!",
}
var b bytes.Buffer
if err := MarshalPayload(&b, &f, nil, nil); err != nil {
t.Fatal(err)
}
if idx := strings.Index(b.String(), `"skip me!"`); idx != -1 {
t.Fatal("expected bar to be skipped, was not")
}
}
func TestMarshal_TopLevelLinks(t *testing.T) {
type Foo struct {
ID string `jsonapi:"primary,foo"`
Baz string `jsonapi:"attr,baz"`
}
var foos []*Foo
for i := 0; i < 3; i++ {
foos = append(foos, &Foo{
ID: fmt.Sprintf("%d", i),
Baz: fmt.Sprintf("Baz %d", i),
})
}
testLink := "www.test.com/topLevelLink"
tll := &Links{
"test": testLink,
}
var b bytes.Buffer
if err := MarshalPayload(&b, foos, tll, nil); err != nil {
t.Fatal(err)
}
if idx := strings.Index(b.String(), testLink); idx == -1 {
t.Fatal("expected to find added top level link, did not")
}
}
func TestMarshal_EntityWithSubLinks(t *testing.T) {
data := EntityWithSubLinks{
ID: "42",
Name: "-42-",
}
out := new(bytes.Buffer)
if err := MarshalPayload(out, &data, nil, nil); err != ErrUnexpectedUrlResolverCall {
t.Fatalf("Was expecting NilBaseUrlResolver to complain, instead got '%s'", err)
}
resolverCallCount := 0
resolver := func(id string) (string, error) {
resolverCallCount++
return "https://contoso.com/api/v6/", nil
}
if err := MarshalPayload(out, &data, nil, resolver); err != nil {
t.Fatalf("Was not expecting errors, instead got '%s'", err)
}
if resolverCallCount != 2 {
t.Fatalf("Expected resolver to be called exactly twice, instead it was called %d time(s)", resolverCallCount)
}
}
func testBlog() *Blog {
return &Blog{
ID: 5,
Title: "Title 1",
CreatedAt: time.Now(),
Posts: []*Post{