-
Notifications
You must be signed in to change notification settings - Fork 9
/
marshal_test.go
852 lines (803 loc) · 25.3 KB
/
marshal_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
package jsonapi
import (
"fmt"
"net/url"
"testing"
"github.com/DataDog/jsonapi/internal/is"
)
func TestMarshal(t *testing.T) {
t.Parallel()
articleAPtr := &articleA
articleBPtr := &articleB
articlePtrSlicePtr := &[]*Article{articleAPtr, articleBPtr}
tests := []struct {
description string
given any
expect string
expectError error
}{
{
description: "nil",
given: nil,
expect: nullDataBody,
expectError: nil,
}, {
description: "Article (empty)",
given: Article{},
expect: nullDataBody,
expectError: nil,
}, {
description: "*Article (empty)",
given: new(Article),
expect: "",
expectError: ErrEmptyPrimaryField,
}, {
description: "[]*Article (nil)",
given: []*Article(nil),
expect: emptyManyBody,
expectError: nil,
}, {
description: "[]*Article (empty)",
given: make([]*Article, 0),
expect: emptyManyBody,
expectError: nil,
}, {
description: "Article (missing ID)",
given: Article{Title: "A"},
expect: "",
expectError: ErrEmptyPrimaryField,
}, {
description: "Article",
given: articleA,
expect: articleABody,
expectError: nil,
}, {
description: "*Article",
given: &articleA,
expect: articleABody,
expectError: nil,
}, {
description: "*ArticleComplete",
given: &articleComplete,
expect: articleCompleteBody,
expectError: nil,
}, {
description: "**Article",
given: &articleA,
expect: articleABody,
expectError: nil,
}, {
description: "[]Article",
given: articlesAB,
expect: articlesABBody,
expectError: nil,
}, {
description: "*[]Article",
given: &articlesAB,
expect: articlesABBody,
expectError: nil,
}, {
description: "[]Article (nonunique data)",
given: articlesAA,
expect: "",
expectError: ErrNonuniqueResource,
}, {
description: "[]*Article",
given: articlesABPtr,
expect: articlesABBody,
expectError: nil,
}, {
description: "*[]*Article",
given: articlePtrSlicePtr,
expect: articlesABBody,
expectError: nil,
}, {
description: "**[]*Article",
given: &articlePtrSlicePtr,
expect: articlesABBody,
expectError: nil,
}, {
description: "*ArticleLinked",
given: &articleALinked,
expect: articleALinkedBody,
expectError: nil,
}, {
description: "*ArticleLinkedOnlySelf",
given: &articleLinkedOnlySelf,
expect: articleLinkedOnlySelfBody,
expectError: nil,
}, {
description: "*ArticleOmitTitle (full)",
given: &articleOmitTitleFull,
expect: articleOmitTitleFullBody,
expectError: nil,
}, {
description: "*ArticleOmitTitle (partial)",
given: &articleOmitTitlePartial,
expect: articleOmitTitlePartialBody,
expectError: nil,
}, {
description: "invalid Link.Self",
given: &articleLinkedInvalidSelf,
expect: "",
expectError: &TypeError{Actual: "int", Expected: []string{"*LinkObject", "string"}},
}, {
description: "invalid Link.Related",
given: &articleLinkedInvalidRelated,
expect: "",
expectError: &TypeError{Actual: "int", Expected: []string{"*LinkObject", "string"}},
}, {
description: "invalid Link (nil Link.Self and Link.Related)",
given: &articleLinkedInvalidMissingFields,
expect: "",
expectError: ErrMissingLinkFields,
}, {
description: "invalid Link (empty Link.Self and Link.Related)",
given: &articleLinkedInvalidMissingFieldsEmptyValues,
expect: "",
expectError: ErrMissingLinkFields,
}, {
description: "invalid Link.Self.Meta",
given: &articleLinkedInvalidSelfMeta,
expect: "",
expectError: &TypeError{Actual: "string", Expected: []string{"struct", "map"}},
}, {
description: "string",
given: "a",
expect: "",
expectError: &TypeError{Actual: "string", Expected: []string{"struct", "slice"}},
}, {
description: "[]string",
given: []string{"a", "b"},
expect: "",
expectError: &TypeError{Actual: "string", Expected: []string{"struct"}},
}, {
description: "*ArticleIntID (MarshalIdentifier)",
given: &articleAIntID,
expect: articleABody,
expectError: nil,
}, {
description: "[]*ArticleIntID (MarshalIdentifier)",
given: articlesIntIDABPtr,
expect: articlesABBody,
expectError: nil,
}, {
description: "*ArticleIntIDID (fmt.Stringer)",
given: &articleAIntIDID,
expect: articleABody,
expectError: nil,
}, {
description: "[]*ArticleIntIDID (fmt.Stringer)",
given: &articlesIntIDIDABPtr,
expect: articlesABBody,
expectError: nil,
}, {
description: "*ArticleEncodingIntID (encoding.TextMarshaler)",
given: &articleAEncodingIntID,
expect: articleABody,
expectError: nil,
}, {
description: "[]*ArticleEncodinfIntID (encoding.TextMarshaler)",
given: &articlesEncodingIntIDABPtr,
expect: articlesABBody,
expectError: nil,
}, {
description: "non-string id",
given: &struct {
ID int `jsonapi:"primary,test"`
}{ID: 1},
expect: "",
expectError: ErrMarshalInvalidPrimaryField,
}, {
description: "missing primary tag",
given: &struct {
ID string `jsonapi:"attr,id"`
}{ID: "1"},
expect: "",
expectError: ErrMissingPrimaryField,
}, {
description: "ArticleWithResourceObjectMeta",
given: &articleWithResourceObjectMeta,
expect: articleWithResourceObjectMetaBody,
expectError: nil,
}, {
description: "ArticleWithoutResourceObjectMeta",
given: &articleWithoutResourceObjectMeta,
expect: articleABody,
expectError: nil,
}, {
description: "ArticleEmbedded",
given: &articleEmbedded,
expect: articleEmbeddedBody,
expectError: nil,
}, {
description: "ArticleEmbeddedPointer",
given: &articleEmbeddedPointer,
expect: articleEmbeddedBody,
expectError: nil,
}, {
description: "Error simple",
given: errorsSimpleStruct,
expect: errorsSimpleStructBody,
expectError: nil,
}, {
description: "*Error simple",
given: &errorsSimpleStruct,
expect: errorsSimpleStructBody,
expectError: nil,
}, {
description: "[]Error simple single",
given: errorsSimpleSliceSingle,
expect: errorsSimpleStructBody,
expectError: nil,
}, {
description: "[]*Error simple single",
given: errorsSimpleSliceSinglePtr,
expect: errorsSimpleStructBody,
expectError: nil,
}, {
description: "Error complex",
given: errorsComplexStruct,
expect: errorsComplexStructBody,
expectError: nil,
}, {
description: "[]Error complex many",
given: errorsComplexSliceMany,
expect: errorsComplexSliceManyBody,
expectError: nil,
}, {
description: "[]*Error complex many",
given: errorsComplexSliceManyPtr,
expect: errorsComplexSliceManyBody,
expectError: nil,
}, {
description: "Error with invalid meta",
given: errorsWithInvalidMeta,
expect: "",
expectError: &TypeError{Actual: "string", Expected: []string{"struct", "map"}},
}, {
description: "Error with link object",
given: errorsWithLinkObject,
expect: errorsWithLinkObjectBody,
expectError: nil,
}, {
description: "Error with invalid link",
given: errorsWithInvalidLink,
expect: "",
expectError: &TypeError{Actual: "int", Expected: []string{"*LinkObject", "string"}},
}, {
description: "Error with invalid Links.About.Meta",
given: errorsWithInvalidLinkMeta,
expect: "",
expectError: &TypeError{Actual: "string", Expected: []string{"struct", "map"}},
}, {
description: "Error empty",
given: Error{},
expect: `{"errors":[{}]}`,
expectError: nil,
},
}
for i, tc := range tests {
tc := tc
t.Run(fmt.Sprintf("%02d", i), func(t *testing.T) {
t.Parallel()
t.Log(tc.description)
actual, err := Marshal(tc.given)
if tc.expectError != nil {
is.EqualError(t, tc.expectError, err)
is.Nil(t, actual)
return
}
is.MustNoError(t, err)
is.EqualJSON(t, tc.expect, string(actual))
})
}
}
func TestMarshalMeta(t *testing.T) {
t.Parallel()
errorsObjectToplevelMetaBody := `{"meta":{"foo":"bar"},"errors":[{"title":"T"}]}`
tests := []struct {
description string
given any
givenMeta any
expect string
expectError error
}{
{
description: "map[string]any",
given: &articleA,
givenMeta: map[string]any{"foo": "bar"},
expect: articleAToplevelMetaBody,
expectError: nil,
}, {
description: "struct",
given: &articleA,
givenMeta: &struct {
Foo string `json:"foo"`
}{Foo: "bar"},
expect: articleAToplevelMetaBody,
expectError: nil,
}, {
description: "non-object type",
given: &articleA,
givenMeta: "foo",
expect: "",
expectError: &TypeError{Actual: "string", Expected: []string{"struct", "map"}},
}, {
description: "map[string]any errors object",
given: errorsSimpleSliceSinglePtr,
givenMeta: map[string]any{"foo": "bar"},
expect: errorsObjectToplevelMetaBody,
expectError: nil,
}, {
description: "map[string]any with nil body",
given: nil,
givenMeta: map[string]any{"foo": "bar"},
expect: articleNullWithToplevelMetaBody,
expectError: nil,
}, {
description: "map[string]any with Article (empty)",
given: Article{},
givenMeta: map[string]any{"foo": "bar"},
expect: articleNullWithToplevelMetaBody,
expectError: nil,
}, {
description: "map[string]any with body []*Article (empty)",
given: []*Article(nil),
givenMeta: map[string]any{"foo": "bar"},
expect: articleEmptyArrayWithToplevelMetaBody,
expectError: nil,
},
}
for i, tc := range tests {
tc := tc
t.Run(fmt.Sprintf("%d", i), func(t *testing.T) {
t.Parallel()
t.Log(tc.description)
actual, err := Marshal(tc.given, MarshalMeta(tc.givenMeta))
if tc.expectError != nil {
is.EqualError(t, tc.expectError, err)
is.Nil(t, actual)
return
}
is.MustNoError(t, err)
is.EqualJSON(t, tc.expect, string(actual))
})
}
}
func TestMarshalJSONAPI(t *testing.T) {
t.Parallel()
articleAJSONAPIBody := `{"data":{"id":"1","type":"articles","attributes":{"title":"A"}},"jsonapi":{"version":"1.0"}}`
articleAJSONAPIMetaBody := `{"data":{"id":"1","type":"articles","attributes":{"title":"A"}},"jsonapi":{"version":"1.0","meta":{"foo":"bar"}}}`
errorsObjectMetaBody := `{"jsonapi":{"version":"1.0","meta":{"foo":"bar"}},"errors":[{"title":"T"}]}`
tests := []struct {
description string
given any
givenJSONAPI any
expect string
expectError error
}{
{
description: "include jsonapi",
given: &articleA,
givenJSONAPI: nil,
expect: articleAJSONAPIBody,
expectError: nil,
}, {
description: "include jsonapi and meta (map)",
given: &articleA,
givenJSONAPI: map[string]any{"foo": "bar"},
expect: articleAJSONAPIMetaBody,
expectError: nil,
}, {
description: "include jsonapi and meta (struct)",
given: &articleA,
givenJSONAPI: &struct {
Foo string `json:"foo"`
}{Foo: "bar"},
expect: articleAJSONAPIMetaBody,
expectError: nil,
}, {
description: "include jsonapi and meta (non-object type)",
given: &articleA,
givenJSONAPI: "foo",
expect: "",
expectError: &TypeError{Actual: "string", Expected: []string{"struct", "map"}},
}, {
description: "include jsonapi and meta (map) errors object",
given: errorsSimpleSliceSinglePtr,
givenJSONAPI: map[string]any{"foo": "bar"},
expect: errorsObjectMetaBody,
expectError: nil,
},
}
for i, tc := range tests {
tc := tc
t.Run(fmt.Sprintf("%d", i), func(t *testing.T) {
t.Parallel()
t.Log(tc.description)
actual, err := Marshal(tc.given, MarshalJSONAPI(tc.givenJSONAPI))
if tc.expectError != nil {
is.EqualError(t, tc.expectError, err)
is.Nil(t, actual)
return
}
is.MustNoError(t, err)
is.EqualJSON(t, tc.expect, string(actual))
})
}
}
func TestMarshalLinks(t *testing.T) {
t.Parallel()
docLinksArticleABody := `{"data":{"id":"1","type":"articles","attributes":{"title":"A"}},"links":{"self":"https://example.com/articles/1"}}`
tests := []struct {
description string
given any
givenLink *Link
expect string
}{
{
description: "with link",
given: &articleA,
givenLink: &Link{Self: fmt.Sprintf("https://example.com/articles/%s", articleA.ID)},
expect: docLinksArticleABody,
}, {
description: "without link",
given: &articleA,
givenLink: nil,
expect: articleABody,
},
}
for i, tc := range tests {
tc := tc
t.Run(fmt.Sprintf("%d", i), func(t *testing.T) {
t.Parallel()
t.Log(tc.description)
actual, err := Marshal(tc.given, MarshalLinks(tc.givenLink))
is.MustNoError(t, err) // resource object errors covered in TestMarshal
is.EqualJSON(t, tc.expect, string(actual))
})
}
}
func TestMarshalFields(t *testing.T) {
t.Parallel()
articleCompleteNoInfoBody := `{"data":{"id":"1","type":"articles","attributes":{"title":"A","subtitle":"AA"}}}`
tests := []struct {
description string
setQuery func(q url.Values)
expect string
}{
{
description: "no fields filter",
setQuery: func(_ url.Values) {},
expect: articleCompleteBody,
}, {
description: "single fields filter (invalid field)",
setQuery: func(q url.Values) {
q.Set("fields[articles]", "not-a-field-in-articles")
},
expect: articleOmitTitleFullBody,
}, {
description: "single field filter",
setQuery: func(q url.Values) {
q.Set("fields[articles]", "title")
},
expect: articleABody,
}, {
description: "multiple fields filter",
setQuery: func(q url.Values) {
q.Set("fields[articles]", "title,subtitle")
},
expect: articleCompleteNoInfoBody,
},
}
for i, tc := range tests {
tc := tc
t.Run(fmt.Sprintf("%d", i), func(t *testing.T) {
t.Parallel()
t.Log(tc.description)
u, err := url.Parse("http://example.com")
is.MustNoError(t, err)
q := u.Query()
tc.setQuery(q)
u.RawQuery = q.Encode()
actual, err := Marshal(&articleComplete, MarshalFields(u.Query()))
is.MustNoError(t, err)
is.EqualJSON(t, tc.expect, string(actual))
})
}
}
func TestMarshalRelationships(t *testing.T) {
t.Parallel()
// filter relationship include data
commentArchivedQuery := url.Values{}
commentArchivedQuery.Set("fields[articles]", "title,comments")
commentArchivedQuery.Set("fields[comments]", "archived")
articleCommentsArchivedFilterBody := `{"data":{"id":"1","type":"articles","attributes":{"title":"A"},"relationships":{"comments":{"data":[{"id":"1","type":"comments"}],"links":{"self":"http://example.com/articles/1/relationships/comments","related":"http://example.com/articles/1/comments"}}}},"included":[{"id":"1","type":"comments","attributes":{"archived":true}}]}`
// articles filter is missing the relationship name
noCommentsQuery := url.Values{}
noCommentsQuery.Set("fields[articles]", "title")
noCommentsQuery.Set("fields[comments]", "archived")
articleNoCommentsFilterBody := `{"data":{"id":"1","type":"articles","attributes":{"title":"A"}},"included":[{"id":"1","type":"comments","attributes":{"archived":true}}]}`
tests := []struct {
description string
given any
marshalOptions []MarshalOption
expect string
expectError error
}{
{
description: "empty relationships with omitempty",
given: &articleRelated,
marshalOptions: nil,
expect: articleABody,
}, {
description: "empty relationships without omitempty",
given: &articleRelatedNoOmitEmpty,
marshalOptions: nil,
expect: articleRelatedNoOmitEmptyBody,
expectError: nil,
}, {
description: "with related author",
given: &articleRelatedAuthor,
marshalOptions: nil,
expect: articleRelatedAuthorBody,
expectError: nil,
}, {
description: "with related author (+meta)",
given: &articleRelatedAuthorWithMeta,
marshalOptions: nil,
expect: articleRelatedAuthorWithMetaBody,
expectError: nil,
}, {
description: "with related comments",
given: &articleRelatedComments,
marshalOptions: nil,
expect: articleRelatedCommentsBody,
expectError: nil,
}, {
description: "with related nonunique comments",
given: &articleRelatedNonuniqueComments,
marshalOptions: nil,
expect: "",
expectError: ErrNonuniqueResource,
}, {
description: "with related author and comments",
given: &articleRelatedComplete,
marshalOptions: nil,
expect: articleRelatedCompleteBody,
}, {
description: "with related comments and included comment",
given: &articleRelatedComments,
marshalOptions: []MarshalOption{MarshalInclude(&commentAWithAuthor)}, // TODO: just commentA?
expect: articleRelatedCommentsWithIncludeBody,
expectError: nil,
}, {
description: "with related comments, included comment, and included author related to comment",
given: &articleRelatedComments,
marshalOptions: []MarshalOption{MarshalInclude(&commentAWithAuthor, &authorA)},
expect: articleRelatedCommentsNestedWithIncludeBody,
expectError: nil,
}, {
description: "with related comments, included comment, and included fields archive/comment",
given: &articleRelatedCommentsArchived,
marshalOptions: []MarshalOption{MarshalInclude(&commentArchived), MarshalFields(commentArchivedQuery)},
expect: articleCommentsArchivedFilterBody,
expectError: nil,
}, {
description: "with related comments, included comment, and included filed archive",
given: &articleRelatedCommentsArchived,
marshalOptions: []MarshalOption{MarshalInclude(&commentArchived), MarshalFields(noCommentsQuery)},
expect: articleNoCommentsFilterBody,
expectError: nil,
}, {
description: "with included comment, included author, and no relationship (partial linkage)",
given: &articleA,
marshalOptions: []MarshalOption{MarshalInclude(&commentAWithAuthor, &authorA)},
expect: "",
expectError: &PartialLinkageError{[]string{"{Type: comments, ID: 1}", "{Type: author, ID: 1}"}},
}, {
description: "multiple complex with included authors and comments",
given: &articlesRelatedComplex,
marshalOptions: articlesRelatedComplexMarshalOptions,
expect: articlesRelatedComplexBody,
expectError: nil,
},
}
for i, tc := range tests {
tc := tc
t.Run(fmt.Sprintf("%d", i), func(t *testing.T) {
t.Parallel()
t.Log(tc.description)
actual, err := Marshal(tc.given, tc.marshalOptions...)
if tc.expectError != nil {
is.EqualError(t, tc.expectError, err)
is.Nil(t, actual)
return
}
is.MustNoError(t, err) // resource objects covered in TestMarshal
is.EqualJSON(t, tc.expect, string(actual))
})
}
}
func TestMarshalClientMode(t *testing.T) {
t.Parallel()
articleNoIDRelatedComplexBody := `{"data":{"type":"articles","attributes":{"title":"Bazel 101"},"relationships":{"author":{"data":{"id":"1","type":"author"},"links":{"self":"http://example.com/articles//relationships/author","related":"http://example.com/articles//author"}},"comments":{"data":[{"type":"comments"},{"type":"comments"},{"type":"comments"}],"links":{"self":"http://example.com/articles//relationships/comments","related":"http://example.com/articles//comments"}}}}}`
tests := []struct {
description string
given any
expect string
}{
{
description: "empty primary field",
given: &Article{ID: "", Title: "A"},
expect: articleANoIDBody,
},
{
description: "empty primary field with relationships",
given: &ArticleRelated{
Title: "Bazel 101",
Author: &authorA,
Comments: []*Comment{
{Body: "Why is Bazel so slow on my computerr?", Archived: true, Author: &authorBWithMeta},
{Body: "Why is Bazel so slow on my computer?", Author: &authorBWithMeta},
{Body: "Just use an Apple M1", Author: &authorA},
},
},
expect: articleNoIDRelatedComplexBody,
},
}
for i, tc := range tests {
tc := tc
t.Run(fmt.Sprintf("%02d", i), func(t *testing.T) {
t.Parallel()
t.Log(tc.description)
actual, err := Marshal(tc.given, MarshalClientMode())
is.MustNoError(t, err)
is.EqualJSON(t, tc.expect, string(actual))
})
}
}
// TestMarshalMemberNameValidation collects tests which verify that invalid member names are caught
// during marshaling, no matter where they're placed. This test does not exhaustively test every
// possible invalid name.
func TestMarshalMemberNameValidation(t *testing.T) {
t.Parallel()
tests := []struct {
description string
given any
expectError error
additionalOptions []MarshalOption
}{
{
description: "Article with valid member names",
given: &articleA,
expectError: nil,
}, {
description: "Author with invalid type name",
given: &authorWithInvalidTypeName,
expectError: &MemberNameValidationError{"aut%hor"},
}, {
description: "Author with invalid attribute name",
given: &authorWithInvalidAttributeName,
expectError: &MemberNameValidationError{"na%me"},
}, {
description: "Article with invalid resource meta member name",
given: &articleWithInvalidResourceMetaMemberName,
expectError: &MemberNameValidationError{"foo%"},
}, {
description: "Article with invalid top-level meta member name",
given: &articleA,
expectError: &MemberNameValidationError{"foo%"},
additionalOptions: []MarshalOption{MarshalMeta(map[string]any{"foo%": 2})},
}, {
description: "Article with invalid jsonapi meta member name",
given: &articleA,
expectError: &MemberNameValidationError{"foo%"},
additionalOptions: []MarshalOption{MarshalJSONAPI(map[string]any{"foo%": 1})},
}, {
description: "Article with invalid link meta member name",
given: &articleWithInvalidLinkMetaMemberName,
expectError: &MemberNameValidationError{"foo%"},
}, {
description: "Article with invalid relationship name",
given: &articleWithInvalidRelationshipName,
expectError: &MemberNameValidationError{"aut%hor"},
}, {
description: "Article with invalid relationship type name",
given: &articleWithInvalidRelationshipTypeName,
expectError: &MemberNameValidationError{"aut%hor"},
}, {
description: "Article with invalid relationship attribute name not included",
given: &articleWithInvalidRelationshipAttributeName,
expectError: nil,
}, {
description: "Article with invalid relationship attribute name included",
given: &articleWithInvalidRelationshipAttributeName,
expectError: &MemberNameValidationError{"na%me"},
additionalOptions: []MarshalOption{MarshalInclude(&authorWithInvalidAttributeName)},
}, {
description: "Articles with one invalid resource meta member name",
given: []*ArticleWithGenericMeta{
{ID: "1"}, {ID: "2", Meta: map[string]any{"foo%": 1}},
},
expectError: &MemberNameValidationError{"foo%"},
}, {
description: "Website with invalid nested relationship type name",
given: &websiteWithInvalidNestedRelationshipTypeName,
expectError: &MemberNameValidationError{"aut%hor"},
additionalOptions: []MarshalOption{
MarshalInclude(
websiteWithInvalidNestedRelationshipTypeName.Articles[0],
websiteWithInvalidNestedRelationshipTypeName.Articles[1],
websiteWithInvalidNestedRelationshipTypeName.Articles[1].Author,
),
},
},
}
for i, tc := range tests {
tc := tc
t.Run(fmt.Sprintf("%02d", i), func(t *testing.T) {
t.Parallel()
t.Log(tc.description)
opts := tc.additionalOptions
_, err := Marshal(tc.given, opts...)
is.EqualError(t, tc.expectError, err)
opts = append(opts, MarshalSetNameValidation(DisableValidation))
_, err = Marshal(tc.given, opts...)
is.MustNoError(t, err)
})
}
}
func BenchmarkMarshal(b *testing.B) {
benchmarks := []struct {
name string
given any
opts []MarshalOption
}{
{
name: "ArticleSimple",
given: articleA,
opts: nil,
}, {
name: "ArticleSimpleWithToplevelMeta",
given: articleA,
opts: []MarshalOption{
MarshalMeta(map[string]any{"foo": "bar"}),
},
}, {
name: "ArticleComplex",
given: articleRelatedComments,
opts: []MarshalOption{
MarshalInclude(&commentAWithAuthor, &authorA),
},
}, {
name: "ArticleComplexDisableNameValidation",
given: articleRelatedComments,
opts: []MarshalOption{
MarshalInclude(&commentAWithAuthor, &authorA),
MarshalSetNameValidation(DisableValidation),
},
}, {
name: "ArticlesComplex",
given: articlesRelatedComplex,
opts: articlesRelatedComplexMarshalOptions,
}, {
name: "ArticlesComplexDisableNameValidation",
given: articlesRelatedComplex,
opts: append(
[]MarshalOption{MarshalSetNameValidation(DisableValidation)},
articlesRelatedComplexMarshalOptions...,
),
},
}
for _, bm := range benchmarks {
bm := bm
b.Run(bm.name, func(b *testing.B) {
b.ReportAllocs()
for n := 0; n < b.N; n++ {
_, _ = Marshal(bm.given, bm.opts...)
}
})
}
}