Debian Codegraph @

encode_std_marshaler_test.go

raw
1 package json_test
2
3 import (
4 "bytes"
5 stdjson "encoding/json"
6 "errors"
7 "log/slog"
8 "math/big"
9 "net"
10 "net/netip"
11 "regexp"
12 "testing"
13 "time"
14
15 "github.com/goccy/go-json"
16 )
17
18 // The outputs of the marshalers of the types of the standard library are written by their appending methods: they
19 // must be what the marshalers return, for every kind of value, in every place, and the errors must be the ones of
20 // the marshalers.
21 func TestEncodeStdMarshalers(t *testing.T) {
22 tokyo := time.FixedZone("JST", 9*60*60)
23 times := []time.Time{
24 {},
25 time.Date(2026, 9, 28, 1, 2, 3, 0, time.UTC),
26 time.Date(2026, 9, 28, 1, 2, 3, 456789000, time.UTC),
27 time.Date(2026, 9, 28, 1, 2, 3, 1, tokyo),
28 time.Date(1, 1, 1, 0, 0, 0, 0, time.FixedZone("", -(3*60*60+30*60))),
29 time.Date(9999, 12, 31, 23, 59, 59, 999999999, time.UTC),
30 time.Date(2026, 9, 28, 1, 2, 3, 0, time.Local),
31 time.Unix(1790000000, 5).In(time.FixedZone("", 59*60)),
32 }
33 type fields struct {
34 T time.Time `json:"t"`
35 P *time.Time `json:"p"`
36 N *time.Time `json:"n"`
37 O time.Time `json:"o,omitempty"`
38 S []time.Time `json:"s"`
39 M map[time.Time]string `json:"m"`
40 MP map[string]*time.Time
41 I any
42 }
43 for _, tm := range times {
44 tm := tm
45 values := []any{
46 tm, &tm, []time.Time{tm, tm},
47 fields{T: tm, P: &tm, O: tm, S: []time.Time{tm}, M: map[time.Time]string{tm: "v"}, MP: map[string]*time.Time{"a": &tm, "b": nil}, I: tm},
48 map[time.Time]int{tm: 1, tm.Add(-time.Second): 2},
49 }
50 for _, v := range values {
51 want, err := stdjson.Marshal(v)
52 if err != nil {
53 t.Fatal(err)
54 }
55 for _, opts := range [][]json.EncodeOptionFunc{nil, {json.DisableHTMLEscape()}, {json.Colorize(&json.ColorScheme{})}} {
56 got, err := json.MarshalWithOption(v, opts...)
57 if err != nil || string(got) != string(want) {
58 t.Fatalf("%v:\n got %s %v\nwant %s", v, got, err, want)
59 }
60 }
61 wantIndent, _ := stdjson.MarshalIndent(v, "", " ")
62 got, err := json.MarshalIndent(v, "", " ")
63 if err != nil || string(got) != string(wantIndent) {
64 t.Fatalf("%v with indent:\n got %s %v\nwant %s", v, got, err, wantIndent)
65 }
66 }
67 }
68 // a year which RFC 3339 can't have is the error of the marshaler.
69 for _, tm := range []time.Time{time.Date(10000, 1, 1, 0, 0, 0, 0, time.UTC), time.Date(-1, 1, 1, 0, 0, 0, 0, time.UTC)} {
70 _, wantErr := tm.MarshalJSON()
71 _, textErr := tm.MarshalText()
72 for _, v := range []any{tm, &tm, struct{ T time.Time }{tm}, map[time.Time]int{tm: 1}} {
73 _, err := json.Marshal(v)
74 var marshalerErr *json.MarshalerError
75 if !errors.As(err, &marshalerErr) {
76 t.Fatalf("%v: expected a MarshalerError but got %v", v, err)
77 }
78 if inner := marshalerErr.Unwrap(); inner.Error() != wantErr.Error() && inner.Error() != textErr.Error() {
79 t.Fatalf("%v: expected the error of the marshaler but got %v", v, inner)
80 }
81 }
82 }
83 }
84
85 // checkStdEncoding checks that the values encode as encoding/json encodes them, with and without the escape of
86 // HTML and with indent, by the plain VMs and the colored ones.
87 func checkStdEncoding(t *testing.T, values ...any) {
88 t.Helper()
89 for _, v := range values {
90 want, wantErr := stdjson.Marshal(v)
91 var unescaped bytes.Buffer
92 enc := stdjson.NewEncoder(&unescaped)
93 enc.SetEscapeHTML(false)
94 _ = enc.Encode(v)
95 for i, opts := range [][]json.EncodeOptionFunc{nil, {json.DisableHTMLEscape()}, {json.Colorize(&json.ColorScheme{})}} {
96 want := want
97 if i == 1 && wantErr == nil {
98 want = bytes.TrimSuffix(unescaped.Bytes(), []byte("\n"))
99 }
100 got, err := json.MarshalWithOption(v, opts...)
101 if (err != nil) != (wantErr != nil) || string(got) != string(want) {
102 t.Fatalf("%#v ( options %d ):\n got %s %v\nwant %s %v", v, i, got, err, want, wantErr)
103 }
104 }
105 wantIndent, _ := stdjson.MarshalIndent(v, "", " ")
106 got, err := json.MarshalIndent(v, "", " ")
107 if (err != nil) != (wantErr != nil) || string(got) != string(wantIndent) {
108 t.Fatalf("%#v with indent:\n got %s %v\nwant %s %v", v, got, err, wantIndent, wantErr)
109 }
110 }
111 }
112
113 // The other types of the standard library: the outputs of MarshalJSON are not checked, and the texts are
114 // appended by AppendText.
115 func TestEncodeStdMarshalersOfOtherPackages(t *testing.T) {
116 huge, _ := new(big.Int).SetString("-123456789012345678901234567890", 10)
117 var levelVar slog.LevelVar
118 levelVar.Set(slog.LevelWarn + 2)
119 type fields struct {
120 Int *big.Int
121 NilInt *big.Int
122 Float *big.Float
123 Rat *big.Rat
124 Level slog.Level
125 LevelVar *slog.LevelVar
126 Addr netip.Addr
127 Zero netip.Addr
128 Port netip.AddrPort
129 Prefix netip.Prefix
130 IP net.IP
131 NilIP net.IP
132 Regexp *regexp.Regexp
133 Levels map[slog.Level]int
134 Addrs map[netip.Addr]string
135 Any any
136 }
137 v := fields{
138 Int: huge, Float: big.NewFloat(1.5e300), Rat: big.NewRat(-3, 7), Level: slog.LevelDebug - 1, LevelVar: &levelVar,
139 Addr: netip.MustParseAddr("fe80::1%eth0"), Port: netip.MustParseAddrPort("[::1]:8080"),
140 Prefix: netip.MustParsePrefix("10.0.0.0/8"), IP: net.ParseIP("192.0.2.1"), Regexp: regexp.MustCompile(`a<b>&c"\d+`),
141 Levels: map[slog.Level]int{slog.LevelInfo: 1, slog.LevelError: 2},
142 Addrs: map[netip.Addr]string{netip.MustParseAddr("::1"): "a", netip.MustParseAddr("127.0.0.1"): "b"}, Any: huge,
143 }
144 checkStdEncoding(t, v, &v, huge, big.NewInt(0), slog.LevelInfo, netip.Addr{}, net.IP{}, []*big.Int{huge, nil})
145 // an IP of an invalid length is the error of MarshalText.
146 if _, err := json.Marshal(net.IP{1, 2, 3}); err == nil {
147 t.Fatal("expected the error of MarshalText")
148 }
149 }
150
151 // userTime has the MarshalJSON of time.Time overridden: it is a type of the user, whose output is checked.
152 type userTime struct{ time.Time }
153
154 func (userTime) MarshalJSON() ([]byte, error) { return []byte(`{"a":`), nil }
155
156 func TestEncodeUserMarshalerIsChecked(t *testing.T) {
157 if _, err := json.Marshal(struct{ T userTime }{}); err == nil {
158 t.Fatal("expected an error for the invalid output of the marshaler of a type of the user")
159 }
160 }
161
162 // Types which embed a type of the standard library, and have its marshalers only by embedding it: their outputs
163 // are the ones of the embedded values, and are written as those are.
164 type (
165 embeddedTime struct{ time.Time }
166 embeddedTimePointer struct{ *time.Time }
167 embeddedTimeAfter struct {
168 N int
169 time.Time
170 }
171 embeddedTimeNested struct {
172 S string
173 embeddedTimeAfter
174 }
175 // embeddedThroughPointer embeds a pointer to a type which embeds time.Time.
176 embeddedThroughPointer struct{ *embeddedTime }
177 embeddedAddr struct{ netip.Addr }
178 embeddedInt struct{ *big.Int }
179 )
180
181 func TestEncodeEmbeddedStdMarshalers(t *testing.T) {
182 tm := time.Date(2026, 9, 28, 1, 2, 3, 456789000, time.FixedZone("", 9*60*60))
183 type fields struct {
184 T embeddedTime
185 TP *embeddedTime
186 TN *embeddedTime
187 P embeddedTimePointer
188 A embeddedTimeAfter
189 Nst embeddedTimeNested
190 EP embeddedThroughPointer
191 EPP *embeddedThroughPointer
192 Ad embeddedAddr
193 Int embeddedInt
194 M map[embeddedAddr]embeddedTime
195 S []embeddedTimeNested
196 Any any
197 }
198 v := fields{
199 T: embeddedTime{tm}, TP: &embeddedTime{tm}, P: embeddedTimePointer{&tm}, A: embeddedTimeAfter{1, tm},
200 Nst: embeddedTimeNested{"s", embeddedTimeAfter{2, tm}}, EP: embeddedThroughPointer{&embeddedTime{tm}},
201 EPP: &embeddedThroughPointer{&embeddedTime{tm}}, Ad: embeddedAddr{netip.MustParseAddr("fe80::1%eth0")},
202 Int: embeddedInt{big.NewInt(-12)}, M: map[embeddedAddr]embeddedTime{{netip.MustParseAddr("::1")}: {tm}},
203 S: []embeddedTimeNested{{"a", embeddedTimeAfter{3, tm}}}, Any: embeddedTimeAfter{4, tm},
204 }
205 checkStdEncoding(t, v, &v, embeddedTime{tm}, &embeddedTime{tm}, embeddedTimeNested{}, embeddedAddr{},
206 embeddedThroughPointer{&embeddedTime{tm}}, &embeddedThroughPointer{&embeddedTime{tm}})
207 // the error of the marshaler of the embedded value is the one of the call.
208 late := time.Date(10000, 1, 1, 0, 0, 0, 0, time.UTC)
209 for _, v := range []any{embeddedTime{late}, embeddedTimeNested{"s", embeddedTimeAfter{1, late}}, embeddedTimePointer{&late},
210 embeddedThroughPointer{&embeddedTime{late}}} {
211 var marshalerErr *json.MarshalerError
212 if _, err := json.Marshal(v); !errors.As(err, &marshalerErr) {
213 t.Fatalf("%v: expected a MarshalerError but got %v", v, err)
214 }
215 }
216 // a type which declares the method on top of the embedded one is checked ( see userTime ).
217 if _, err := json.Marshal(struct{ T struct{ userTime } }{}); err == nil {
218 t.Fatal("expected an error for the invalid output of the marshaler of a type of the user")
219 }
220 }
221
222 func BenchmarkEncodeTime(b *testing.B) {
223 type event struct {
224 Created, Updated, Closed time.Time
225 Due *time.Time
226 }
227 now := time.Date(2026, 9, 28, 1, 2, 3, 456789000, time.UTC)
228 v := &event{Created: now, Updated: now, Closed: now, Due: &now}
229 b.ReportAllocs()
230 for i := 0; i < b.N; i++ {
231 if _, err := json.Marshal(v); err != nil {
232 b.Fatal(err)
233 }
234 }
235 }
236
237 // BenchmarkEncodeEmbeddedTime encodes times of a type which embeds time.Time, as go-github's Timestamp does.
238 func BenchmarkEncodeEmbeddedTime(b *testing.B) {
239 type event struct {
240 Created, Updated, Closed embeddedTime
241 Due *embeddedTime
242 }
243 now := embeddedTime{time.Date(2026, 9, 28, 1, 2, 3, 456789000, time.UTC)}
244 v := &event{Created: now, Updated: now, Closed: now, Due: &now}
245 b.ReportAllocs()
246 for i := 0; i < b.N; i++ {
247 if _, err := json.Marshal(v); err != nil {
248 b.Fatal(err)
249 }
250 }
251 }
252
253 func BenchmarkEncodeStdMarshalers(b *testing.B) {
254 type record struct {
255 Amount *big.Int
256 Level slog.Level
257 Addr netip.Addr
258 Prefix netip.Prefix
259 IP net.IP
260 }
261 v := &record{Amount: big.NewInt(1234567890123), Level: slog.LevelWarn, Addr: netip.MustParseAddr("2001:db8::1"),
262 Prefix: netip.MustParsePrefix("192.168.0.0/16"), IP: net.ParseIP("192.0.2.1")}
263 b.ReportAllocs()
264 for i := 0; i < b.N; i++ {
265 if _, err := json.Marshal(v); err != nil {
266 b.Fatal(err)
267 }
268 }
269 }