Debian Codegraph @

encode_nil_text_marshaler_test.go

raw
1 package json_test
2
3 import (
4 stdjson "encoding/json"
5 "testing"
6
7 "github.com/goccy/go-json"
8 )
9
10 // A nil pointer to a TextMarshaler is null as a value, wherever the value is, and "" as the key of a map,
11 // as encoding/json writes them, whether MarshalText has a value receiver or a pointer receiver.
12
13 type nilTextValue struct{ S string }
14
15 func (v nilTextValue) MarshalText() ([]byte, error) { return []byte(v.S), nil }
16
17 type nilTextPointer struct{ S string }
18
19 func (v *nilTextPointer) MarshalText() ([]byte, error) { return []byte(v.S), nil }
20
21 func TestEncodeNilTextMarshaler(t *testing.T) {
22 values := []any{
23 []*nilTextValue{nil, {"x"}},
24 []*nilTextPointer{nil, {"x"}},
25 [2]*nilTextValue{},
26 [2]*nilTextPointer{},
27 []**nilTextValue{nil},
28 map[string]*nilTextValue{"a": nil, "b": {"x"}},
29 map[string]*nilTextPointer{"a": nil, "b": {"x"}},
30 map[*nilTextValue]int{nil: 1, {"x"}: 2},
31 map[*nilTextPointer]int{nil: 1, {"x"}: 2},
32 map[*nilTextValue]*nilTextValue{nil: nil},
33 map[*nilTextPointer]*nilTextPointer{nil: nil},
34 map[*nilTextValue][]*nilTextValue{nil: {nil}},
35 map[string]any{"a": (*nilTextValue)(nil), "b": (*nilTextPointer)(nil)},
36 struct {
37 A *nilTextValue
38 B *nilTextPointer
39 C []*nilTextValue
40 D map[string]*nilTextPointer
41 }{C: []*nilTextValue{nil}, D: map[string]*nilTextPointer{"d": nil}},
42 }
43 for _, v := range values {
44 want, err := stdjson.Marshal(v)
45 if err != nil {
46 t.Fatal(err)
47 }
48 got, err := json.Marshal(v)
49 if err != nil {
50 t.Fatalf("%T: %v", v, err)
51 }
52 if string(got) != string(want) {
53 t.Errorf("%T: got %s, want %s", v, got, want)
54 }
55 wantIndent, err := stdjson.MarshalIndent(v, "", " ")
56 if err != nil {
57 t.Fatal(err)
58 }
59 gotIndent, err := json.MarshalIndent(v, "", " ")
60 if err != nil {
61 t.Fatalf("%T: %v", v, err)
62 }
63 if string(gotIndent) != string(wantIndent) {
64 t.Errorf("%T: indent: got %s, want %s", v, gotIndent, wantIndent)
65 }
66 }
67 }