-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathencode_test.go
More file actions
1869 lines (1667 loc) · 45.8 KB
/
Copy pathencode_test.go
File metadata and controls
1869 lines (1667 loc) · 45.8 KB
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 jsonc
import (
"bytes"
"context"
"encoding/json"
"errors"
"math"
"math/big"
"path/filepath"
"strconv"
"strings"
"testing"
"time"
)
// ---------------------------------------------------------------------------
// Scalars
// ---------------------------------------------------------------------------
func TestEncodeNil(t *testing.T) {
out, err := Marshal(nil)
if err != nil {
t.Fatal(err)
}
if string(out) != "null" {
t.Errorf("got %q", out)
}
}
func TestEncodeBool(t *testing.T) {
out, err := Marshal(true)
if err != nil {
t.Fatal(err)
}
if string(out) != "true" {
t.Errorf("got %q", out)
}
}
func TestEncodeInt(t *testing.T) {
out, err := Marshal(42)
if err != nil {
t.Fatal(err)
}
if string(out) != "42" {
t.Errorf("got %q", out)
}
}
func TestEncodeUint(t *testing.T) {
out, err := Marshal(uint64(1 << 63))
if err != nil {
t.Fatal(err)
}
if string(out) != "9223372036854775808" {
t.Errorf("got %q", out)
}
}
func TestEncodeFloat(t *testing.T) {
cases := []struct {
in float64
want string
}{
{0, "0"},
{1.5, "1.5"},
{-3.14, "-3.14"},
{1e-7, "1e-7"},
{1e21, "1e+21"},
}
for _, c := range cases {
out, err := Marshal(c.in)
if err != nil {
t.Fatal(err)
}
if string(out) != c.want {
t.Errorf("for %v got %q want %q", c.in, out, c.want)
}
}
}
func TestEncodeFloatInfRejected(t *testing.T) {
_, err := Marshal(math.Inf(1))
if !errors.Is(err, ErrUnsupportedValue) {
t.Errorf("expected ErrUnsupportedValue, got %v", err)
}
}
func TestEncodeFloatNaNRejected(t *testing.T) {
_, err := Marshal(math.NaN())
if !errors.Is(err, ErrUnsupportedValue) {
t.Errorf("expected ErrUnsupportedValue, got %v", err)
}
}
func TestEncodeString(t *testing.T) {
out, err := Marshal("hello")
if err != nil {
t.Fatal(err)
}
if string(out) != `"hello"` {
t.Errorf("got %q", out)
}
}
func TestEncodeStringEscapes(t *testing.T) {
out, err := Marshal("a\nb\tc\"d\\e")
if err != nil {
t.Fatal(err)
}
if string(out) != `"a\nb\tc\"d\\e"` {
t.Errorf("got %q", out)
}
}
func TestEncodeStringHTMLDefault(t *testing.T) {
// Default: no HTML escaping (differs from stdlib).
out, err := Marshal("<script>")
if err != nil {
t.Fatal(err)
}
if string(out) != `"<script>"` {
t.Errorf("got %q", out)
}
}
func TestEncodeStringHTMLOptIn(t *testing.T) {
out, err := MarshalWithOptions("<&>", WithEscapeHTML(true))
if err != nil {
t.Fatal(err)
}
if bytes.ContainsAny(out, "<&>") {
t.Errorf("expected escaped output, got %q", out)
}
if !strings.Contains(string(out), "\\u003c") {
t.Errorf("expected \\u003c in output, got %q", out)
}
}
// ---------------------------------------------------------------------------
// Slices and arrays
// ---------------------------------------------------------------------------
func TestEncodeSlice(t *testing.T) {
out, err := Marshal([]int{1, 2, 3})
if err != nil {
t.Fatal(err)
}
if string(out) != "[1, 2, 3]" {
t.Errorf("got %q", out)
}
}
func TestEncodeSliceNil(t *testing.T) {
var s []int
out, err := Marshal(s)
if err != nil {
t.Fatal(err)
}
if string(out) != "null" {
t.Errorf("got %q", out)
}
}
func TestEncodeSliceEmpty(t *testing.T) {
out, err := Marshal([]int{})
if err != nil {
t.Fatal(err)
}
if string(out) != "[]" {
t.Errorf("got %q", out)
}
}
func TestEncodeArray(t *testing.T) {
out, err := Marshal([3]int{1, 2, 3})
if err != nil {
t.Fatal(err)
}
if string(out) != "[1, 2, 3]" {
t.Errorf("got %q", out)
}
}
func TestEncodeBytesAsBase64(t *testing.T) {
out, err := Marshal([]byte("hello"))
if err != nil {
t.Fatal(err)
}
if string(out) != `"aGVsbG8="` {
t.Errorf("got %q", out)
}
}
// ---------------------------------------------------------------------------
// Maps
// ---------------------------------------------------------------------------
func TestEncodeMapStringKey(t *testing.T) {
out, err := Marshal(map[string]int{"b": 2, "a": 1, "c": 3})
if err != nil {
t.Fatal(err)
}
// Default = lexicographic.
if string(out) != `{"a": 1, "b": 2, "c": 3}` {
t.Errorf("got %q", out)
}
}
func TestEncodeMapNil(t *testing.T) {
var m map[string]int
out, err := Marshal(m)
if err != nil {
t.Fatal(err)
}
if string(out) != "null" {
t.Errorf("got %q", out)
}
}
func TestEncodeMapIntKey(t *testing.T) {
out, err := Marshal(map[int]string{2: "b", 1: "a"})
if err != nil {
t.Fatal(err)
}
if string(out) != `{"1": "a", "2": "b"}` {
t.Errorf("got %q", out)
}
}
type colorKey int
func (c colorKey) MarshalText() ([]byte, error) {
return []byte(map[colorKey]string{1: "red", 2: "blue"}[c]), nil
}
func TestEncodeMapTextMarshalerKey(t *testing.T) {
out, err := Marshal(map[colorKey]int{1: 100, 2: 200})
if err != nil {
t.Fatal(err)
}
if string(out) != `{"blue": 200, "red": 100}` {
t.Errorf("got %q", out)
}
}
func TestEncodeMapSlice(t *testing.T) {
ms := MapSlice{
{Key: "first", Value: 1},
{Key: "second", Value: "two"},
{Key: "third", Value: true},
}
out, err := Marshal(ms)
if err != nil {
t.Fatal(err)
}
if string(out) != `{"first": 1, "second": "two", "third": true}` {
t.Errorf("got %q", out)
}
}
// ---------------------------------------------------------------------------
// Structs
// ---------------------------------------------------------------------------
type basicStruct struct {
Name string `json:"name"`
Age int `json:"age"`
}
func TestEncodeStruct(t *testing.T) {
// Struct fields are emitted in declaration order, matching encoding/json.
out, err := Marshal(basicStruct{Name: "alice", Age: 30})
if err != nil {
t.Fatal(err)
}
if string(out) != `{"name": "alice", "age": 30}` {
t.Errorf("got %q", out)
}
}
type omitStruct struct {
A string `json:"a,omitempty"`
B int `json:"b,omitempty"`
C bool `json:"c,omitempty"`
}
func TestEncodeStructOmitEmpty(t *testing.T) {
out, err := Marshal(omitStruct{A: "set"})
if err != nil {
t.Fatal(err)
}
if string(out) != `{"a": "set"}` {
t.Errorf("got %q", out)
}
}
type omitZeroStruct struct {
A int `jsonc:"a,omitzero"`
B int `jsonc:"b,omitzero"`
}
func TestEncodeStructOmitZero(t *testing.T) {
out, err := Marshal(omitZeroStruct{A: 5})
if err != nil {
t.Fatal(err)
}
if string(out) != `{"a": 5}` {
t.Errorf("got %q", out)
}
}
type stringTagStruct struct {
N int `json:"n,string"`
B bool `json:"b,string"`
}
func TestEncodeStructAsString(t *testing.T) {
out, err := Marshal(stringTagStruct{N: 42, B: true})
if err != nil {
t.Fatal(err)
}
if string(out) != `{"n": "42", "b": "true"}` {
t.Errorf("got %q", out)
}
}
type embeddedInner struct {
X int `json:"x"`
Y int `json:"y"`
}
type embeddedOuter struct {
embeddedInner
Z int `json:"z"`
}
func TestEncodeStructEmbedded(t *testing.T) {
out, err := Marshal(embeddedOuter{embeddedInner: embeddedInner{X: 1, Y: 2}, Z: 3})
if err != nil {
t.Fatal(err)
}
if string(out) != `{"x": 1, "y": 2, "z": 3}` {
t.Errorf("got %q", out)
}
}
type skippedStruct struct {
Public string `json:"public"`
Skipped string `json:"-"`
}
func TestEncodeStructSkipDash(t *testing.T) {
out, err := Marshal(skippedStruct{Public: "yes", Skipped: "no"})
if err != nil {
t.Fatal(err)
}
if string(out) != `{"public": "yes"}` {
t.Errorf("got %q", out)
}
}
// ---------------------------------------------------------------------------
// Indent and trailing comma
// ---------------------------------------------------------------------------
func TestEncodeIndent(t *testing.T) {
out, err := MarshalIndent(map[string]int{"a": 1, "b": 2}, " ")
if err != nil {
t.Fatal(err)
}
want := "{\n \"a\": 1,\n \"b\": 2\n}"
if string(out) != want {
t.Errorf("got %q\nwant %q", out, want)
}
}
func TestEncodeIndentTrailingComma(t *testing.T) {
out, err := MarshalWithOptions(
map[string]int{"a": 1},
WithIndent(" "),
WithTrailingComma(true),
)
if err != nil {
t.Fatal(err)
}
want := "{\n \"a\": 1,\n}"
if string(out) != want {
t.Errorf("got %q\nwant %q", out, want)
}
}
func TestEncodeStrictJSONOutputDropsTrailingComma(t *testing.T) {
out, err := MarshalWithOptions(
map[string]int{"a": 1},
WithIndent(" "),
WithTrailingComma(true),
WithStrictJSONOutput(true),
)
if err != nil {
t.Fatal(err)
}
if strings.Contains(string(out), ",\n}") {
t.Errorf("strict-JSON output should drop trailing comma: %s", out)
}
}
// ---------------------------------------------------------------------------
// Special types
// ---------------------------------------------------------------------------
func TestEncodeTime(t *testing.T) {
ts := time.Date(2024, 1, 15, 10, 30, 0, 0, time.UTC)
out, err := Marshal(ts)
if err != nil {
t.Fatal(err)
}
if string(out) != `"2024-01-15T10:30:00Z"` {
t.Errorf("got %q", out)
}
}
func TestEncodeDurationDefaultIsInt64(t *testing.T) {
d := 1500 * time.Millisecond
out, err := Marshal(d)
if err != nil {
t.Fatal(err)
}
if string(out) != "1500000000" {
t.Errorf("got %q", out)
}
}
func TestEncodeDurationAsString(t *testing.T) {
d := 1500 * time.Millisecond
out, err := MarshalWithOptions(d, WithDurationAsString(true))
if err != nil {
t.Fatal(err)
}
if string(out) != `"1.5s"` {
t.Errorf("got %q", out)
}
}
func TestEncodeBigInt(t *testing.T) {
bi := new(big.Int)
bi.SetString("12345678901234567890123456789012345", 10)
out, err := Marshal(bi)
if err != nil {
t.Fatal(err)
}
if string(out) != "12345678901234567890123456789012345" {
t.Errorf("got %q", out)
}
}
func TestEncodeBigFloat(t *testing.T) {
bf, _, err := big.ParseFloat("3.14", 10, 53, big.ToNearestEven)
if err != nil {
t.Fatal(err)
}
out, err := Marshal(bf)
if err != nil {
t.Fatal(err)
}
if !strings.HasPrefix(string(out), "3.14") {
t.Errorf("got %q", out)
}
}
func TestEncodeJSONNumber(t *testing.T) {
n := json.Number("3.14159")
out, err := Marshal(n)
if err != nil {
t.Fatal(err)
}
if string(out) != "3.14159" {
t.Errorf("got %q", out)
}
}
func TestEncodeRawValue(t *testing.T) {
r := RawValue(`{"a": 1, /* preserved */ "b": 2}`)
out, err := Marshal(r)
if err != nil {
t.Fatal(err)
}
if string(out) != string(r) {
t.Errorf("RawValue should pass through verbatim. got %q", out)
}
}
func TestEncodeRawValueStrictDropsComments(t *testing.T) {
r := RawValue(`{"a": 1, /* dropped */ "b": 2,}`)
out, err := MarshalWithOptions(r, WithStrictJSONOutput(true))
if err != nil {
t.Fatal(err)
}
if strings.Contains(string(out), "/*") {
t.Errorf("strict output should drop comments: %s", out)
}
}
func TestEncodeRawMessage(t *testing.T) {
r := json.RawMessage(`{"x":1}`)
out, err := Marshal(r)
if err != nil {
t.Fatal(err)
}
if string(out) != `{"x":1}` {
t.Errorf("got %q", out)
}
}
// ---------------------------------------------------------------------------
// Marshaler interfaces
// ---------------------------------------------------------------------------
type customMarshaler struct {
Tag string
}
func (c customMarshaler) MarshalJSONC() ([]byte, error) {
return []byte(`"custom:` + c.Tag + `"`), nil
}
func TestEncodeMarshaler(t *testing.T) {
out, err := Marshal(customMarshaler{Tag: "foo"})
if err != nil {
t.Fatal(err)
}
if string(out) != `"custom:foo"` {
t.Errorf("got %q", out)
}
}
type ctxMarshaler struct {
Tag string
}
func (c ctxMarshaler) MarshalJSONC(_ context.Context) ([]byte, error) {
return []byte(`"ctx:` + c.Tag + `"`), nil
}
func TestEncodeMarshalerContext(t *testing.T) {
var buf strings.Builder
enc := NewEncoder(&buf)
if err := enc.Encode(ctxMarshaler{Tag: "x"}); err != nil {
t.Fatal(err)
}
if !strings.Contains(buf.String(), `"ctx:x"`) {
t.Errorf("got %q", buf.String())
}
}
type stdMarshaler struct {
Tag string
}
func (s stdMarshaler) MarshalJSON() ([]byte, error) {
return []byte(`"std:` + s.Tag + `"`), nil
}
func TestEncodeStdlibMarshaler(t *testing.T) {
out, err := Marshal(stdMarshaler{Tag: "y"})
if err != nil {
t.Fatal(err)
}
if string(out) != `"std:y"` {
t.Errorf("got %q", out)
}
}
type textMarshalerType struct {
Value string
}
func (tm textMarshalerType) MarshalText() ([]byte, error) {
return []byte("txt:" + tm.Value), nil
}
func TestEncodeTextMarshaler(t *testing.T) {
out, err := Marshal(textMarshalerType{Value: "z"})
if err != nil {
t.Fatal(err)
}
if string(out) != `"txt:z"` {
t.Errorf("got %q", out)
}
}
// ---------------------------------------------------------------------------
// Custom marshalers via WithCustomMarshaler
// ---------------------------------------------------------------------------
type plainStruct struct {
A int
}
func TestEncodeCustomMarshaler(t *testing.T) {
opt := WithCustomMarshaler(func(p plainStruct) ([]byte, error) {
return []byte(`"plain"`), nil
})
out, err := MarshalWithOptions(plainStruct{A: 1}, opt)
if err != nil {
t.Fatal(err)
}
if string(out) != `"plain"` {
t.Errorf("got %q", out)
}
}
// ---------------------------------------------------------------------------
// Pointers and cycles
// ---------------------------------------------------------------------------
func TestEncodePointerNil(t *testing.T) {
var p *int
out, err := Marshal(p)
if err != nil {
t.Fatal(err)
}
if string(out) != "null" {
t.Errorf("got %q", out)
}
}
func TestEncodePointerValue(t *testing.T) {
x := 5
out, err := Marshal(&x)
if err != nil {
t.Fatal(err)
}
if string(out) != "5" {
t.Errorf("got %q", out)
}
}
type cyclic struct {
Self *cyclic
}
func TestEncodeCycleDetected(t *testing.T) {
c := &cyclic{}
c.Self = c
_, err := Marshal(c)
if !errors.Is(err, ErrUnsupportedValue) {
t.Errorf("expected ErrUnsupportedValue, got %v", err)
}
}
// ---------------------------------------------------------------------------
// Encoder streaming
// ---------------------------------------------------------------------------
func TestEncoderEncode(t *testing.T) {
var buf strings.Builder
enc := NewEncoder(&buf)
if err := enc.Encode(map[string]int{"a": 1}); err != nil {
t.Fatal(err)
}
if buf.String() != `{"a": 1}`+"\n" {
t.Errorf("got %q", buf.String())
}
}
func TestEncoderMultiple(t *testing.T) {
var buf strings.Builder
enc := NewEncoder(&buf)
for i := range 3 {
if err := enc.Encode(i); err != nil {
t.Fatal(err)
}
}
if buf.String() != "0\n1\n2\n" {
t.Errorf("got %q", buf.String())
}
}
func TestEncoderSetIndent(t *testing.T) {
var buf strings.Builder
enc := NewEncoder(&buf)
enc.SetIndent("\t")
if err := enc.Encode([]int{1, 2}); err != nil {
t.Fatal(err)
}
if !strings.Contains(buf.String(), "\t1") {
t.Errorf("expected tab indent: %q", buf.String())
}
}
func TestEncoderSetEscapeHTML(t *testing.T) {
var buf strings.Builder
enc := NewEncoder(&buf)
enc.SetEscapeHTML(true)
if err := enc.Encode("<x>"); err != nil {
t.Fatal(err)
}
if strings.ContainsAny(buf.String(), "<>") {
t.Errorf("expected escaped output, got %q", buf.String())
}
if !strings.Contains(buf.String(), "\\u003c") {
t.Errorf("expected \\u003c, got %q", buf.String())
}
}
func TestEncoderSetContext(t *testing.T) {
var buf strings.Builder
enc := NewEncoder(&buf)
type ctxKey struct{}
ctx := context.WithValue(context.Background(), ctxKey{}, "v")
enc.SetContext(ctx)
if err := enc.Encode("x"); err != nil {
t.Fatal(err)
}
}
// ---------------------------------------------------------------------------
// Round trip through Unmarshal
// ---------------------------------------------------------------------------
func TestEncodeRoundTrip(t *testing.T) {
type Inner struct {
Tags []string `json:"tags"`
}
type Outer struct {
Name string `json:"name"`
Count int `json:"count"`
Inner Inner `json:"inner"`
}
in := Outer{Name: "x", Count: 7, Inner: Inner{Tags: []string{"a", "b"}}}
out, err := Marshal(in)
if err != nil {
t.Fatal(err)
}
var got Outer
if err := Unmarshal(out, &got); err != nil {
t.Fatal(err)
}
if got.Name != in.Name || got.Count != in.Count || len(got.Inner.Tags) != 2 {
t.Errorf("round-trip mismatch: %+v vs %+v", got, in)
}
}
// ---------------------------------------------------------------------------
// Unsupported types
// ---------------------------------------------------------------------------
func TestEncodeUnsupportedChan(t *testing.T) {
ch := make(chan int)
_, err := Marshal(ch)
if !errors.Is(err, ErrUnsupportedValue) {
t.Errorf("expected ErrUnsupportedValue, got %v", err)
}
}
func TestEncodeUnsupportedFunc(t *testing.T) {
_, err := Marshal(func() {})
if !errors.Is(err, ErrUnsupportedValue) {
t.Errorf("expected ErrUnsupportedValue, got %v", err)
}
}
// ---------------------------------------------------------------------------
// WithComment(map[string][]Comment) — path-keyed comment injection
// ---------------------------------------------------------------------------
type withCommentServer struct {
Port int `json:"port"`
Host string `json:"host"`
}
type withCommentRoot struct {
Server withCommentServer `json:"server"`
Tags []string `json:"tags"`
}
func TestEncodeWithCommentHead(t *testing.T) {
v := withCommentServer{Port: 8080, Host: "localhost"}
out, err := MarshalWithOptions(v,
WithIndent(" "),
WithComment(map[string][]Comment{
"port": {{Position: HeadCommentPos, Text: "the listening port"}},
}),
)
if err != nil {
t.Fatal(err)
}
want := "{\n // the listening port\n \"port\": 8080,\n \"host\": \"localhost\"\n}"
if string(out) != want {
t.Errorf("got %q\nwant %q", out, want)
}
}
func TestEncodeWithCommentLine(t *testing.T) {
v := withCommentServer{Port: 8080, Host: "localhost"}
out, err := MarshalWithOptions(v,
WithIndent(" "),
WithComment(map[string][]Comment{
"port": {{Position: LineCommentPos, Text: "default"}},
}),
)
if err != nil {
t.Fatal(err)
}
if !strings.Contains(string(out), `"port": 8080, // default`) {
t.Errorf("expected line comment after value, got %q", out)
}
}
func TestEncodeWithCommentFootMid(t *testing.T) {
// Foot comment on a non-last field appears between members.
v := withCommentServer{Port: 8080, Host: "localhost"}
out, err := MarshalWithOptions(v,
WithIndent(" "),
WithComment(map[string][]Comment{
"port": {{Position: FootCommentPos, Text: "end of port section"}},
}),
)
if err != nil {
t.Fatal(err)
}
want := "{\n \"port\": 8080,\n // end of port section\n \"host\": \"localhost\"\n}"
if string(out) != want {
t.Errorf("got %q\nwant %q", out, want)
}
}
func TestEncodeWithCommentFootLast(t *testing.T) {
// Foot comment on the last field appears before the closing brace,
// without an extra blank line.
v := withCommentServer{Port: 8080, Host: "localhost"}
out, err := MarshalWithOptions(v,
WithIndent(" "),
WithComment(map[string][]Comment{
"host": {{Position: FootCommentPos, Text: "trailing"}},
}),
)
if err != nil {
t.Fatal(err)
}
want := "{\n \"port\": 8080,\n \"host\": \"localhost\"\n // trailing\n}"
if string(out) != want {
t.Errorf("got %q\nwant %q", out, want)
}
}
func TestEncodeWithCommentNestedPath(t *testing.T) {
v := withCommentRoot{
Server: withCommentServer{Port: 8080, Host: "localhost"},
Tags: []string{"a"},
}
out, err := MarshalWithOptions(v,
WithIndent(" "),
WithComment(map[string][]Comment{
"server.port": {{Position: HeadCommentPos, Text: "nested head"}},
}),
)
if err != nil {
t.Fatal(err)
}
if !strings.Contains(string(out), " // nested head\n \"port\": 8080") {
t.Errorf("expected nested head comment, got:\n%s", out)
}
}
func TestEncodeWithCommentArrayIndex(t *testing.T) {
v := withCommentRoot{
Server: withCommentServer{Port: 1, Host: "h"},
Tags: []string{"first", "second", "third"},
}
out, err := MarshalWithOptions(v,
WithIndent(" "),
WithComment(map[string][]Comment{
"tags[1]": {{Position: HeadCommentPos, Text: "the middle one"}},
}),
)
if err != nil {
t.Fatal(err)
}
if !strings.Contains(string(out), "// the middle one\n \"second\"") {
t.Errorf("expected head comment on tags[1], got:\n%s", out)
}
}
func TestEncodeWithCommentMultiplePerPath(t *testing.T) {
v := withCommentServer{Port: 8080, Host: "localhost"}
out, err := MarshalWithOptions(v,
WithIndent(" "),
WithComment(map[string][]Comment{
"port": {
{Position: HeadCommentPos, Text: "first head"},
{Position: HeadCommentPos, Text: "second head"},
{Position: LineCommentPos, Text: "inline"},
},
}),
)
if err != nil {
t.Fatal(err)
}
s := string(out)
if !strings.Contains(s, "// first head") || !strings.Contains(s, "// second head") {
t.Errorf("expected both head comments, got:\n%s", s)
}
if !strings.Contains(s, "// inline") {
t.Errorf("expected inline comment, got:\n%s", s)
}
}
func TestEncodeWithCommentDroppedInCompact(t *testing.T) {
// No indent → compact mode → comments must be dropped.
v := withCommentServer{Port: 8080, Host: "localhost"}
out, err := MarshalWithOptions(v,
WithComment(map[string][]Comment{
"port": {{Position: HeadCommentPos, Text: "should not appear"}},
}),
)
if err != nil {
t.Fatal(err)
}
if strings.Contains(string(out), "should not appear") {
t.Errorf("compact mode should drop comments, got: %s", out)
}
if strings.Contains(string(out), "//") {
t.Errorf("compact mode should drop comments, got: %s", out)
}
}
func TestEncodeWithCommentDroppedInStrictOutput(t *testing.T) {
v := withCommentServer{Port: 8080, Host: "localhost"}
out, err := MarshalWithOptions(v,
WithIndent(" "),
WithStrictJSONOutput(true),
WithComment(map[string][]Comment{
"port": {{Position: HeadCommentPos, Text: "should not appear"}},
}),
)
if err != nil {
t.Fatal(err)
}
if strings.Contains(string(out), "should not appear") {
t.Errorf("strict-JSON output should drop comments, got: %s", out)
}
}
func TestEncodeWithCommentMap(t *testing.T) {
// Same path-lookup logic must work for native maps.
v := map[string]int{"a": 1, "b": 2}
out, err := MarshalWithOptions(v,
WithIndent(" "),
WithComment(map[string][]Comment{
"a": {{Position: HeadCommentPos, Text: "first"}},
}),
)
if err != nil {
t.Fatal(err)
}
if !strings.Contains(string(out), "// first\n \"a\"") {
t.Errorf("expected head comment on map key 'a', got:\n%s", out)
}
}
func TestEncodeWithCommentMapSlice(t *testing.T) {
// MapSlice should also honor path lookups by key string.
v := MapSlice{
{Key: "x", Value: 1},
{Key: "y", Value: 2},
}
out, err := MarshalWithOptions(v,
WithIndent(" "),
WithComment(map[string][]Comment{
"x": {{Position: LineCommentPos, Text: "the x"}},
}),
)
if err != nil {
t.Fatal(err)
}
if !strings.Contains(string(out), `"x": 1, // the x`) {
t.Errorf("expected line comment on MapSlice key 'x', got:\n%s", out)
}
}
func TestEncodeWithCommentMultilineHeadText(t *testing.T) {
// Multi-line text in a head comment should produce multiple // lines.
v := withCommentServer{Port: 8080, Host: "localhost"}
out, err := MarshalWithOptions(v,
WithIndent(" "),
WithComment(map[string][]Comment{
"port": {{Position: HeadCommentPos, Text: "line one\nline two"}},
}),
)
if err != nil {
t.Fatal(err)
}
s := string(out)
if !strings.Contains(s, "// line one\n // line two\n \"port\"") {
t.Errorf("expected two-line head comment, got:\n%s", s)
}
}