Debian Codegraph @

encode_reported_issues_test.go

raw
1 package json_test
2
3 // The cases of the reported issues of the encoder, by the number of the issue: each builds the value the issue
4 // describes, encodes it and compares the result byte for byte with encoding/json, unless the issue is about
5 // what encoding/json cannot express ( noted inline ). They are the regression tests of those reports.
6
7 import (
8 "bytes"
9 "context"
10 stdjson "encoding/json"
11 "fmt"
12 "testing"
13 "time"
14
15 "github.com/goccy/go-json"
16 )
17
18 // issueRecover turns a panic inside the encoder into a test failure
19 // instead of killing the whole test binary.
20 func issueRecover(t *testing.T) {
21 t.Helper()
22 if r := recover(); r != nil {
23 t.Errorf("panic: %v", r)
24 }
25 }
26
27 // issueCompare encodes v with both libraries and reports any difference.
28 func issueCompare(t *testing.T, name string, v any) {
29 t.Helper()
30 want, wantErr := stdjson.Marshal(v)
31 got, gotErr := json.Marshal(v)
32 if (wantErr == nil) != (gotErr == nil) {
33 t.Errorf("%s: error mismatch: encoding/json=%v go-json=%v", name, wantErr, gotErr)
34 return
35 }
36 if !bytes.Equal(want, got) {
37 t.Errorf("%s:\n encoding/json: %s\n go-json: %s", name, want, got)
38 }
39 }
40
41 // issueCompareIndent is issueCompare for MarshalIndent.
42 func issueCompareIndent(t *testing.T, name string, v any, prefix, indent string) {
43 t.Helper()
44 want, wantErr := stdjson.MarshalIndent(v, prefix, indent)
45 got, gotErr := json.MarshalIndent(v, prefix, indent)
46 if (wantErr == nil) != (gotErr == nil) {
47 t.Errorf("%s: error mismatch: encoding/json=%v go-json=%v", name, wantErr, gotErr)
48 return
49 }
50 if !bytes.Equal(want, got) {
51 t.Errorf("%s:\n encoding/json: %s\n go-json: %s", name, want, got)
52 }
53 }
54
55 // issueCompareEncoder is issueCompare for the streaming Encoder.
56 func issueCompareEncoder(t *testing.T, name string, v any) {
57 t.Helper()
58 var want, got bytes.Buffer
59 wantErr := stdjson.NewEncoder(&want).Encode(v)
60 gotErr := json.NewEncoder(&got).Encode(v)
61 if (wantErr == nil) != (gotErr == nil) {
62 t.Errorf("%s: error mismatch: encoding/json=%v go-json=%v", name, wantErr, gotErr)
63 return
64 }
65 if !bytes.Equal(want.Bytes(), got.Bytes()) {
66 t.Errorf("%s:\n encoding/json: %q\n go-json: %q", name, want.String(), got.String())
67 }
68 }
69
70 // ---------------------------------------------------------------- 401
71
72 type issue401Set map[string]struct{}
73
74 func (s issue401Set) MarshalJSON() ([]byte, error) {
75 if s == nil {
76 return []byte("null"), nil
77 }
78 if len(s) == 0 {
79 return []byte("[]"), nil
80 }
81 // The issue iterates the map; a single key keeps the output deterministic.
82 b := []byte{'['}
83 for symbol := range s {
84 b = append(b, '"')
85 b = append(b, symbol...)
86 b = append(b, '"', ',')
87 }
88 b[len(b)-1] = ']'
89 return b, nil
90 }
91
92 type issue401PanicType map[uint64]struct{}
93
94 func (w issue401PanicType) MarshalJSON() ([]byte, error) {
95 _ = w[1]
96 return []byte{'1'}, nil
97 }
98
99 func TestIssue401(t *testing.T) {
100 defer issueRecover(t)
101 issueCompare(t, "map of custom map with MarshalJSON", map[string]issue401Set{"foo": {"bar": {}}})
102 issueCompare(t, "map[int] of map type reading itself in MarshalJSON", map[int]issue401PanicType{1: {15124: struct{}{}}})
103 }
104
105 // ---------------------------------------------------------------- 418
106
107 type issue418Embedding struct{}
108
109 func (n *issue418Embedding) MarshalJSON() ([]byte, error) {
110 return []byte(`"this is MarshalJSON"`), nil
111 }
112
113 type issue418Parent struct {
114 issue418Embedding
115 }
116
117 type issue418PtrParent struct{}
118
119 func (n *issue418PtrParent) MarshalJSON() ([]byte, error) {
120 return []byte(`"this is MarshalJSON"`), nil
121 }
122
123 func TestIssue418(t *testing.T) {
124 defer issueRecover(t)
125 x := &issue418Parent{}
126 issueCompareEncoder(t, "pointer-receiver MarshalJSON on embedded value, **Parent", &x)
127 y := &issue418PtrParent{}
128 issueCompareEncoder(t, "pointer-receiver MarshalJSON on the struct, **Parent", &y)
129 }
130
131 // ---------------------------------------------------------------- 449
132
133 func TestIssue449(t *testing.T) {
134 defer issueRecover(t)
135 var key any = "x"
136 obj := map[any]any{key: "xxxxx"}
137 // encoding/json refuses map[interface{}]T as well (UnsupportedTypeError),
138 // so the expected outcome is "both return an error".
139 _, wantErr := stdjson.Marshal(obj)
140 _, gotErr := json.Marshal(obj)
141 if (wantErr == nil) != (gotErr == nil) {
142 t.Errorf("error mismatch: encoding/json=%v go-json=%v", wantErr, gotErr)
143 }
144 }
145
146 // ---------------------------------------------------------------- 450
147
148 type issue450Embedded struct {
149 Embedded string `json:"Embedded"`
150 Other int `json:"Other"`
151 }
152
153 type issue450Struct struct {
154 issue450Embedded
155 Name string `json:"Name"`
156 }
157
158 func TestIssue450(t *testing.T) {
159 defer issueRecover(t)
160 // The issue uses a type literally named Embedded embedding a field named
161 // Embedded; the local type name has to differ, so the embedded field is
162 // named after the local type and the inner field keeps the issue's name.
163 type Embedded struct {
164 Embedded string `json:"Embedded"`
165 Other int `json:"Other"`
166 }
167 type Struct struct {
168 Embedded
169 Name string `json:"Name"`
170 }
171 issueCompare(t, "embedded struct whose field has the same name (local types)",
172 Struct{Embedded: Embedded{Embedded: "inside", Other: 111}, Name: "outside"})
173 issueCompare(t, "embedded struct whose field has the same name (file scope)",
174 issue450Struct{issue450Embedded: issue450Embedded{Embedded: "inside", Other: 111}, Name: "outside"})
175 }
176
177 // ---------------------------------------------------------------- 458
178
179 type issue458Empty [0]int
180
181 func (issue458Empty) MarshalJSON() ([]byte, error) { return []byte(`"empty-array"`), nil }
182
183 type issue458Two [2]int
184
185 func (issue458Two) MarshalJSON() ([]byte, error) { return []byte(`"two-array"`), nil }
186
187 type issue458Holder struct {
188 E issue458Empty `json:"e,omitempty"`
189 P *issue458Empty `json:"p,omitempty"`
190 T issue458Two `json:"t,omitempty"`
191 }
192
193 func TestIssue458(t *testing.T) {
194 defer issueRecover(t)
195 issueCompare(t, "omitempty on array types with MarshalJSON", issue458Holder{})
196 issueCompare(t, "omitempty on array types with MarshalJSON, pointer set", issue458Holder{P: &issue458Empty{}})
197 }
198
199 // ---------------------------------------------------------------- 460
200
201 type Issue460B struct {
202 Bar string `json:"bar"`
203 }
204
205 type issue460A struct {
206 Foo string `json:"foo"`
207 *Issue460B `json:",inline,omitempty"`
208 }
209
210 type issue460AOmitOnly struct {
211 Foo string `json:"foo"`
212 *Issue460B `json:",omitempty"`
213 }
214
215 func TestIssue460(t *testing.T) {
216 defer issueRecover(t)
217 issueCompare(t, "embedded pointer with inline,omitempty", issue460A{Foo: "fff", Issue460B: &Issue460B{Bar: "bbb"}})
218 issueCompare(t, "embedded pointer with inline,omitempty, nil", issue460A{Foo: "fff"})
219 issueCompare(t, "embedded pointer with omitempty", issue460AOmitOnly{Foo: "fff", Issue460B: &Issue460B{Bar: "bbb"}})
220 issueCompare(t, "embedded pointer with omitempty, nil", issue460AOmitOnly{Foo: "fff"})
221 }
222
223 // ---------------------------------------------------------------- 468
224
225 type issue468Outer struct {
226 *Issue468Inner
227 }
228
229 type Issue468Inner struct {
230 Inner *Issue468Inner `json:"inner"`
231 }
232
233 func TestIssue468(t *testing.T) {
234 defer issueRecover(t)
235 issueCompare(t, "embedded pointer to a recursive struct, nil", &issue468Outer{})
236 issueCompare(t, "embedded pointer to a recursive struct, set",
237 &issue468Outer{Issue468Inner: &Issue468Inner{Inner: &Issue468Inner{}}})
238 }
239
240 // ---------------------------------------------------------------- 486
241
242 type issue486Structure struct {
243 Id int `json:"id"`
244 *issue486Structure
245 }
246
247 type issue486AlternativeStructure struct {
248 Id int `json:"id"`
249 *Issue486Structure2
250 }
251
252 type Issue486Structure2 struct {
253 Id int `json:"id"`
254 Alternative issue486AlternativeStructure `json:"alternative"`
255 }
256
257 func TestIssue486(t *testing.T) {
258 defer issueRecover(t)
259 issueCompare(t, "struct embedding a nil pointer to itself", issue486Structure{Id: 99})
260 issueCompare(t, "struct embedding a nil pointer to the enclosing struct",
261 Issue486Structure2{Id: 99, Alternative: issue486AlternativeStructure{Id: 123}})
262 }
263
264 // ---------------------------------------------------------------- 488
265
266 type issue488StringAlias string
267
268 func (d *issue488StringAlias) MarshalJSON() ([]byte, error) {
269 return []byte(fmt.Sprintf("\"%s\"", *d)), nil
270 }
271
272 type issue488WithOmit struct {
273 A issue488StringAlias `json:"a,omitempty"`
274 }
275
276 func TestIssue488(t *testing.T) {
277 defer issueRecover(t)
278 var v issue488WithOmit
279 issueCompare(t, "omitempty on a type with pointer-receiver MarshalJSON, empty", &v)
280 v.A = "x"
281 issueCompare(t, "omitempty on a type with pointer-receiver MarshalJSON, set", &v)
282 }
283
284 // ---------------------------------------------------------------- 499
285
286 type issue499Foo struct{}
287
288 type issue499CtxKey struct{}
289
290 func (issue499Foo) MarshalJSON(ctx context.Context) ([]byte, error) {
291 if ctx != nil {
292 if val := ctx.Value(issue499CtxKey{}); val != nil {
293 return []byte(`"` + val.(string) + `"`), nil
294 }
295 }
296 return []byte(`"foo"`), nil
297 }
298
299 func TestIssue499(t *testing.T) {
300 defer issueRecover(t)
301 // MarshalerContext is a go-json extension, so encoding/json cannot serve
302 // as the oracle; the test asserts what the issue asks for: the context
303 // of a MarshalContext call must not leak into a following Marshal call.
304 foo := issue499Foo{}
305 ctx := context.WithValue(context.Background(), issue499CtxKey{}, "bar")
306 out, err := json.MarshalContext(ctx, foo)
307 if err != nil {
308 t.Fatal(err)
309 }
310 if string(out) != `"bar"` {
311 t.Errorf(`MarshalContext: expected "bar", got %s`, out)
312 }
313 for i := 0; i < 8; i++ {
314 out, err = json.Marshal(foo)
315 if err != nil {
316 t.Fatal(err)
317 }
318 if string(out) != `"foo"` {
319 t.Errorf(`Marshal after MarshalContext: expected "foo", got %s (leaked context)`, out)
320 return
321 }
322 }
323 }
324
325 // ---------------------------------------------------------------- 503
326
327 type issue503RootInt struct {
328 Child *issue503ChildInt `json:"c,omitempty"`
329 }
330
331 type issue503ChildInt struct {
332 Value int `json:"v"`
333 }
334
335 type issue503RootBool struct {
336 Child *issue503ChildBool `json:"c,omitempty"`
337 }
338
339 type issue503ChildBool struct {
340 Value bool `json:"v"`
341 }
342
343 type issue503RootString struct {
344 Child *issue503ChildString `json:"c,omitempty"`
345 }
346
347 type issue503ChildString struct {
348 Value string `json:"v"`
349 }
350
351 func TestIssue503(t *testing.T) {
352 defer issueRecover(t)
353 issueCompare(t, "omitempty pointer to struct whose first field is 0", issue503RootInt{Child: &issue503ChildInt{Value: 0}})
354 issueCompare(t, "omitempty pointer to struct whose first field is 1", issue503RootInt{Child: &issue503ChildInt{Value: 1}})
355 issueCompare(t, "omitempty pointer to struct whose first field is false", issue503RootBool{Child: &issue503ChildBool{Value: false}})
356 issueCompare(t, "omitempty pointer to struct whose first field is true", issue503RootBool{Child: &issue503ChildBool{Value: true}})
357 issueCompare(t, `omitempty pointer to struct whose first field is ""`, issue503RootString{Child: &issue503ChildString{Value: ""}})
358 issueCompare(t, `omitempty pointer to struct whose first field is "a"`, issue503RootString{Child: &issue503ChildString{Value: "a"}})
359 }
360
361 // ---------------------------------------------------------------- 507
362
363 type issue507Config struct {
364 Steps []struct {
365 Config stdjson.RawMessage `json:"config"`
366 }
367 }
368
369 func TestIssue507(t *testing.T) {
370 defer issueRecover(t)
371 // The issue's raw data holds a literal U+2028 before the "<".
372 rawData := []byte("{\"steps\": [{\"config\":{\"message\": \"Fail \u2028<\"}}]}")
373 var v issue507Config
374 if err := stdjson.Unmarshal(rawData, &v); err != nil {
375 t.Fatal(err)
376 }
377 issueCompare(t, "RawMessage with U+2028 and < (HTML escape + compaction)", v)
378
379 // The same content through go-json's own RawMessage type.
380 type config struct {
381 Steps []struct {
382 Config json.RawMessage `json:"config"`
383 }
384 }
385 var v2 config
386 if err := stdjson.Unmarshal(rawData, &v2); err != nil {
387 t.Fatal(err)
388 }
389 issueCompare(t, "go-json RawMessage with U+2028 and <", v2)
390 }
391
392 // ---------------------------------------------------------------- 512
393
394 type issue512Common struct {
395 Domains []string `json:"domains,omitempty" binding:"required,gte=1,lte=3,unique,dive,required"`
396 }
397
398 type issue512App struct {
399 ID uint `json:"id,omitempty"`
400 Type string `json:"type,omitempty"`
401 issue512Common
402 }
403
404 type issue512Data struct {
405 issue512App
406 }
407
408 type issue512AppGetResponse struct {
409 TotalCount int `json:"totalCount"`
410 Data []issue512Data `json:"data,omitempty"`
411 }
412
413 type issue512App2 struct {
414 issue512Common
415 ID uint `json:"id,omitempty"`
416 Type string `json:"type,omitempty"`
417 }
418
419 type issue512Data2 struct {
420 issue512App2
421 }
422
423 type issue512AppGetResponse2 struct {
424 TotalCount int `json:"totalCount"`
425 Data []issue512Data2 `json:"data,omitempty"`
426 }
427
428 func TestIssue512(t *testing.T) {
429 defer issueRecover(t)
430 resp := issue512AppGetResponse{TotalCount: 1, Data: make([]issue512Data, 1)}
431 resp.Data[0] = issue512Data{issue512App: issue512App{ID: 1, Type: "custom"}}
432 issueCompare(t, "doubly embedded struct, omitempty slice last", resp)
433
434 resp2 := issue512AppGetResponse2{TotalCount: 1, Data: make([]issue512Data2, 1)}
435 resp2.Data[0] = issue512Data2{issue512App2: issue512App2{ID: 1, Type: "custom"}}
436 issueCompare(t, "doubly embedded struct, omitempty slice first", resp2)
437 }
438
439 // ---------------------------------------------------------------- 513
440
441 type Issue513Customer struct {
442 TKID string `gorm:"primarykey;not null;type:varchar(255);"`
443 IDs []*Issue513IDMapping `gorm:"foreignKey:TKID;"`
444 }
445
446 type Issue513IDMapping struct {
447 TKID string `gorm:"comment:TKID;index:idx_tk_id;not null;type:varchar(255);"`
448 Customer *Issue513Customer
449 }
450
451 func TestIssue513(t *testing.T) {
452 defer issueRecover(t)
453 type MyCustomer struct {
454 Issue513Customer
455 MyField string
456 }
457 list := []MyCustomer{{Issue513Customer: Issue513Customer{TKID: "1"}, MyField: "111"}}
458 issueCompare(t, "slice of struct embedding a mutually recursive struct", list)
459 issueCompare(t, "the embedded struct alone", list[0].Issue513Customer)
460 }
461
462 // ---------------------------------------------------------------- 519
463
464 type issue519Body struct {
465 Payload *issue519Detail `json:"p,omitempty"`
466 }
467
468 type issue519Detail struct {
469 I issue519Item `json:"i"`
470 }
471
472 type issue519Item struct {
473 A string `json:"a"`
474 B string `json:"b,omitempty"`
475 }
476
477 func TestIssue519(t *testing.T) {
478 defer issueRecover(t)
479 issueCompare(t, "omitempty pointer to struct holding a struct with omitempty string",
480 issue519Body{Payload: &issue519Detail{I: issue519Item{A: "a", B: "b"}}})
481 }
482
483 // ---------------------------------------------------------------- 523
484
485 func TestIssue523(t *testing.T) {
486 defer issueRecover(t)
487 issueCompare(t, "[]*time.Time{nil}", []*time.Time{nil})
488 now := time.Date(2024, 1, 2, 3, 4, 5, 0, time.UTC)
489 issueCompare(t, "[]*time.Time{nil, &t}", []*time.Time{nil, &now})
490 }
491
492 // ---------------------------------------------------------------- 526
493
494 type issue526CondFn byte
495 type issue526Args map[string]any
496
497 type issue526Rule struct {
498 Id int `json:"id"`
499 Disabled bool `json:"disabled,omitempty"`
500 Name string `json:"name,omitempty"`
501 Condition issue526Condition `json:"condition,omitempty"`
502 }
503
504 type issue526Condition struct {
505 Id int `json:"-"`
506 Fn issue526CondFn `json:"fn,omitempty"`
507 Args issue526Args `json:"args,omitempty"`
508 Nested []issue526Condition `json:"nested,omitempty"`
509 }
510
511 func TestIssue526(t *testing.T) {
512 defer issueRecover(t)
513 rule := issue526Rule{
514 Condition: issue526Condition{
515 Nested: []issue526Condition{{Args: issue526Args{"Value": 111}}},
516 },
517 }
518 issueCompare(t, `recursive struct with a json:"-" field and omitempty map`, rule)
519 }
520
521 // ---------------------------------------------------------------- 537
522
523 // issue537List mirrors github.com/kaptinlin/jsonschema.List (the package is
524 // not available here): a recursive struct with two omitempty maps.
525 type issue537List struct {
526 Valid bool `json:"valid"`
527 EvaluationPath string `json:"evaluationPath"`
528 SchemaLocation string `json:"schemaLocation"`
529 InstanceLocation string `json:"instanceLocation"`
530 Annotations map[string]any `json:"annotations,omitempty"`
531 Errors map[string]string `json:"errors,omitempty"`
532 Details []issue537List `json:"details,omitempty"`
533 }
534
535 const issue537Payload = `{
536 "valid": false,
537 "evaluationPath": "",
538 "schemaLocation": "",
539 "instanceLocation": "",
540 "annotations": {
541 "description": "Blueprint type prototype\n\nThis is just a brief example of a common blueprint structure. Just few fields\nwere selected to demonstrate the JSON schema."
542 },
543 "errors": {
544 "properties": "Properties 'registration', 'network' do not match their schemas",
545 "required": "Required properties 'registration', 'network' are missing"
546 },
547 "details": [
548 {
549 "valid": false,
550 "evaluationPath": "/properties/registration",
551 "schemaLocation": "https://github.com/lzap/common-blueprint-example/blueprint#/properties/registration",
552 "instanceLocation": "/registration",
553 "annotations": {
554 "description": "Registration details"
555 },
556 "errors": {
557 "type": "Value is null but should be object"
558 }
559 },
560 {
561 "valid": false,
562 "evaluationPath": "/properties/network",
563 "schemaLocation": "https://github.com/lzap/common-blueprint-example/blueprint#/properties/network",
564 "instanceLocation": "/network",
565 "annotations": {
566 "description": "Networking details"
567 },
568 "errors": {
569 "type": "Value is null but should be object"
570 }
571 },
572 {
573 "valid": true,
574 "evaluationPath": "/properties/name",
575 "schemaLocation": "https://github.com/lzap/common-blueprint-example/blueprint#/properties/name",
576 "instanceLocation": "/name",
577 "annotations": {
578 "description": "Name of the blueprint"
579 }
580 }
581 ]
582 }`
583
584 func TestIssue537(t *testing.T) {
585 defer issueRecover(t)
586 var list issue537List
587 if err := stdjson.Unmarshal([]byte(issue537Payload), &list); err != nil {
588 t.Fatal(err)
589 }
590 issueCompareIndent(t, "MarshalIndent of a recursive struct with omitempty maps (jsonschema.List shape)", list, "", " ")
591 issueCompare(t, "Marshal of the same value", list)
592 }
593
594 // ---------------------------------------------------------------- 541
595
596 type issue541BotRetPtrID struct {
597 Id *string `json:"id"`
598 Name string `json:"name"`
599 }
600
601 type issue541RetPtr struct {
602 Bot *issue541BotRetPtrID `json:"bot"`
603 }
604
605 type issue541BotRet struct {
606 Id string `json:"id"`
607 Name string `json:"name"`
608 }
609
610 type issue541Ret struct {
611 Bot issue541BotRet `json:"bot"`
612 }
613
614 func TestIssue541(t *testing.T) {
615 defer issueRecover(t)
616 // The issue only shows the types (panic in appendNormalizedHTMLString);
617 // the values are reconstructed: nil / set pointer, empty / filled strings.
618 id := "id-1"
619 issueCompare(t, "pointer struct field, nil", issue541RetPtr{})
620 issueCompare(t, "pointer struct field, set, nil id", issue541RetPtr{Bot: &issue541BotRetPtrID{Name: "n"}})
621 issueCompare(t, "pointer struct field, set, id set", issue541RetPtr{Bot: &issue541BotRetPtrID{Id: &id, Name: "n"}})
622 issueCompare(t, "value struct field, zero", issue541Ret{})
623 issueCompare(t, "value struct field, set", issue541Ret{Bot: issue541BotRet{Id: "id", Name: "n"}})
624 issueCompare(t, "pointer to the anonymous struct", &issue541Ret{Bot: issue541BotRet{Id: "id", Name: "n"}})
625 }
626
627 // ---------------------------------------------------------------- 543
628
629 type issue543Map map[string]struct{}
630
631 type issue543MapMap map[string]issue543Map
632
633 func (m issue543Map) MarshalJSON() ([]byte, error) {
634 keys := make([]string, 0, len(m))
635 for k := range m {
636 keys = append(keys, k)
637 }
638 return stdjson.Marshal(keys)
639 }
640
641 func TestIssue543(t *testing.T) {
642 defer issueRecover(t)
643 issueCompare(t, "map of map type with MarshalJSON", issue543MapMap{"test": issue543Map{"test": {}}})
644 }
645
646 // ---------------------------------------------------------------- 546
647
648 type issue546Device struct {
649 Alerts [][]any
650 Items []issue546Device
651 ID int64
652 }
653
654 const issue546Data = `
655 {
656 "items": [
657 {
658 "alerts": [[2]],
659 "id": 2
660 }
661 ],
662 "id": 1
663 }
664 `
665
666 func TestIssue546(t *testing.T) {
667 defer issueRecover(t)
668 var d issue546Device
669 if err := stdjson.Unmarshal([]byte(issue546Data), &d); err != nil {
670 t.Fatal(err)
671 }
672 issueCompare(t, "recursive struct with [][]any first", d)
673 }
674
675 // ---------------------------------------------------------------- 552
676
677 type issue552DBObject struct {
678 ID int64 `json:"id,omitempty"`
679 }
680
681 type Issue552Item struct {
682 issue552DBObject
683 }
684
685 type issue552Request struct {
686 *Issue552Item
687 }
688
689 type issue552StudyLabel struct {
690 HasPartList bool `json:"has_part_list"`
691 PartItems []*issue552ResLabel `json:"part_items"`
692 ResourceItems []*issue552Resource `json:"resource_items"`
693 }
694
695 type issue552Resource struct {
696 Name string `json:"name"`
697 }
698
699 type issue552ResLabel struct {
700 ClassId int `json:"class_id"`
701 ClassName string `json:"class_name"`
702 PercentRate int `json:"percent_rate"`
703 IsCompleted bool `json:"is_completed"`
704
705 issue552StudyLabel
706 }
707
708 func TestIssue552(t *testing.T) {
709 defer issueRecover(t)
710 var req issue552Request
711 if err := stdjson.Unmarshal([]byte(`{"id": 1}`), &req); err != nil {
712 t.Fatal(err)
713 }
714 issueCompareEncoder(t, "embedded pointer to struct embedding a struct with omitempty int", req)
715 issueCompare(t, "same value through Marshal", req)
716
717 label := &issue552ResLabel{
718 ClassId: 150301,
719 ClassName: "PreA1",
720 issue552StudyLabel: issue552StudyLabel{
721 PartItems: []*issue552ResLabel{},
722 ResourceItems: []*issue552Resource{{Name: "r"}},
723 },
724 }
725 issueCompare(t, "embedded recursive struct after plain fields", label)
726 issueCompare(t, "slice of the same", []*issue552ResLabel{label, {issue552StudyLabel: issue552StudyLabel{PartItems: []*issue552ResLabel{label}}}})
727 }
728
729 // ---------------------------------------------------------------- 554
730
731 type issue554Grandpa struct{ issue554Father }
732
733 type issue554Father struct {
734 issue554Son
735 A []string `json:"a,omitempty"`
736 }
737
738 type issue554Son struct {
739 B string `json:"b"`
740 C string `json:"c"`
741 }
742
743 func TestIssue554(t *testing.T) {
744 defer issueRecover(t)
745 issueCompare(t, "doubly embedded struct, empty slice with omitempty last", &issue554Grandpa{})
746 issueCompare(t, "same by value", issue554Grandpa{})
747 }
748
749 // ---------------------------------------------------------------- 559
750
751 type issue559Node struct {
752 Label string `json:"label"`
753 Value string `json:"value"`
754 Meta map[string]any `json:"meta,omitempty"`
755 Children []issue559Node `json:"children,omitempty"`
756 }
757
758 func TestIssue559(t *testing.T) {
759 defer issueRecover(t)
760 tree := []issue559Node{
761 {
762 Label: "Parent",
763 Value: "p1",
764 Meta: map[string]any{"code": "parent", "desc": "Parent node"},
765 Children: []issue559Node{
766 {
767 Label: "Child1",
768 Value: "c1",
769 Meta: map[string]any{"code": "child1", "desc": "First child"},
770 },
771 },
772 },
773 }
774 issueCompare(t, "recursive struct with map[string]any in parent and child", tree)
775 }
776
777 // ---------------------------------------------------------------- 576
778
779 type issue576ErrWithOmitempty struct {
780 Error string `json:"error,omitempty"`
781 }
782
783 type issue576MyResult struct {
784 issue576ErrWithOmitempty
785 Data string `json:"data"`
786 }
787
788 type issue576Result struct {
789 issue576MyResult
790 }
791
792 type issue576ErrWithoutOmitempty struct {
793 Error string `json:"error"`
794 }
795
796 type issue576MyResult2 struct {
797 issue576ErrWithoutOmitempty
798 Data string `json:"data"`
799 }
800
801 type issue576Result2 struct {
802 issue576MyResult2
803 }
804
805 func TestIssue576(t *testing.T) {
806 defer issueRecover(t)
807 issueCompare(t, "doubly embedded struct whose first field is omitempty and empty",
808 issue576Result{issue576MyResult{Data: "hi"}})
809 issueCompare(t, "doubly embedded struct whose first field is not omitempty",
810 issue576Result2{issue576MyResult2{Data: "hi"}})
811 }
812
813 // ---------------------------------------------------------------- 581
814
815 type issue581Reason struct {
816 Code string `json:"reasonCode,omitempty"`
817 }
818
819 type issue581Cov struct {
820 Type string `json:"type"`
821 }
822
823 type issue581Inner struct {
824 issue581Cov
825 R *issue581Reason `json:"reason,omitempty"`
826 }
827
828 type issue581Outer struct {
829 issue581Inner
830 }
831
832 func TestIssue581(t *testing.T) {
833 defer issueRecover(t)
834 issueCompare(t, "embedded struct with embedded value struct followed by omitempty nil pointer", issue581Outer{})
835 issueCompare(t, "same with the pointer set", issue581Outer{issue581Inner{R: &issue581Reason{Code: "c"}}})
836 }