gunk-dev/the-valley

exactjson_test.go

sourced9c8073fd613main's published tip history
13.3 KiB
1package exactjson
2
3import (
4 "bytes"
5 "encoding/json"
6 "errors"
7 "fmt"
8 "io"
9 "reflect"
10 "runtime"
11 "strings"
12 "testing"
13)
14
15// A registry-shaped document: a struct at the top, maps of structs, a
16// slice of structs, a pointer, and a field read by nobody.
17type doc struct {
18 Principals map[string]principal `json:"principals"`
19 Genesis string `json:"genesis"`
20 Derived json.RawMessage `json:"derived"`
21 Count int64 `json:"count"`
22}
23
24type principal struct {
25 Keys []key `json:"keys"`
26 Grants map[string]grant `json:"grants"`
27 Notes any `json:"notes"`
28 hidden string
29 Bare string
30}
31
32type key struct {
33 Public string `json:"public"`
34 Proof *proof `json:"proof,omitempty"`
35}
36
37type proof struct {
38 Slot string `json:"slot"`
39}
40
41type grant struct {
42 Boundary string `json:"boundary"`
43}
44
45// A document spelled exactly decodes as encoding/json decodes it. Map keys
46// are data, whatever their case, and so are the keys inside an interface
47// and a json.RawMessage. A number past a float64's range is read only by
48// the decode.
49func TestAnExactDocumentDecodesAsEncodingJSONDoes(t *testing.T) {
50 const data = `{
51 "principals": {
52 "alice": {
53 "keys": [{"public": "k1", "proof": {"slot": "s"}}, {"public": "k2"}],
54 "grants": {"push": {"boundary": "b"}, "Push": {"boundary": "B"}},
55 "notes": {"Anything": [{"goes": 1}]}
56 },
57 "Alice": {"keys": [], "grants": {}}
58 },
59 "genesis": "alice",
60 "derived": {"Grants": [1, {"x": 2}]},
61 "count": 9007199254740993
62 }`
63 var got, want doc
64 if err := Decode([]byte(data), &got); err != nil {
65 t.Fatal(err)
66 }
67 if err := json.Unmarshal([]byte(data), &want); err != nil {
68 t.Fatal(err)
69 }
70 if !reflect.DeepEqual(got, want) {
71 t.Errorf("Decode read %+v, encoding/json %+v", got, want)
72 }
73}
74
75// Every key a struct does not name exactly is refused, at every depth,
76// before anything is decoded. encoding/json would have read each of the
77// spellings below into the field it folds to, under Unicode's simple case
78// folding: ſ folds to s, and the Kelvin sign to k.
79func TestAKeyNotSpelledExactlyIsRefused(t *testing.T) {
80 for _, c := range []struct{ name, data, says string }{
81 {"a field in another case, beside the field",
82 `{"principals": {"alice": {"grants": {}, "Grants": {"push": {"boundary": "b"}}}}}`,
83 `principals["alice"] holds the key "Grants", which is its field "grants" spelled another way`},
84 {"at the top",
85 `{"genesis": "alice", "GENESIS": "mallory"}`,
86 `the document holds the key "GENESIS", which is its field "genesis" spelled another way`},
87 {"in a map's struct value",
88 `{"principals": {"alice": {"grants": {"push": {"boundary": "x", "Boundary": "b"}}}}}`,
89 `principals["alice"].grants["push"] holds the key "Boundary", which is its field "boundary" spelled another way`},
90 {"in a slice's element",
91 `{"principals": {"alice": {"keys": [{"public": "k1"}, {"public": "k2", "Public": "k3"}]}}}`,
92 `principals["alice"].keys[1] holds the key "Public", which is its field "public" spelled another way`},
93 {"behind a pointer",
94 `{"principals": {"alice": {"keys": [{"public": "k1", "proof": {"sLot": "s"}}]}}}`,
95 `principals["alice"].keys[0].proof holds the key "sLot", which is its field "slot" spelled another way`},
96 {"folded beyond ASCII",
97 `{"principals": {"alice": {"grantſ": {"push": {"boundary": "b"}}}}}`,
98 `principals["alice"] holds the key "grantſ", which is its field "grants" spelled another way`},
99 {"with the Kelvin sign",
100 "{\"principals\": {\"alice\": {\"Keys\": []}}}",
101 `principals["alice"] holds the key "` + "K" + `eys", which is its field "keys" spelled another way`},
102 {"a field no tag names",
103 `{"principals": {"alice": {"Bare": "x"}}}`,
104 `principals["alice"] holds the key "Bare", which is none of its fields`},
105 {"an unexported field",
106 `{"principals": {"alice": {"hidden": "x"}}}`,
107 `principals["alice"] holds the key "hidden", which is none of its fields`},
108 {"a field nobody declared",
109 `{"genesis": "alice", "extra": true}`,
110 `the document holds the key "extra", which is none of its fields`},
111 } {
112 var d doc
113 err := Decode([]byte(c.data), &d)
114 if err == nil || err.Error() != c.says {
115 t.Errorf("%s: Decode read %+v, %v, not %q", c.name, d, err, c.says)
116 }
117 if !reflect.DeepEqual(d, doc{}) {
118 t.Errorf("%s: a refused document decoded %+v", c.name, d)
119 }
120 }
121}
122
123// A key that appears twice in one object is refused wherever the object
124// is, a map's and a raw value's included, and however the key is escaped.
125// So is anything after the document.
126func TestAKeyTwiceOrASecondDocumentIsRefused(t *testing.T) {
127 for _, c := range []struct{ name, data, says string }{
128 {"at the top",
129 `{"principals": {}, "principals": {"mallory": {}}}`,
130 `the document holds the key "principals" twice`},
131 {"in a map",
132 `{"principals": {"alice": {}, "alice": {"grants": {"push": {"boundary": "b"}}}}}`,
133 `principals holds the key "alice" twice`},
134 {"in a struct in a map",
135 `{"principals": {"alice": {"grants": {"push": {"boundary": "x", "boundary": "b"}}}}}`,
136 `principals["alice"].grants["push"] holds the key "boundary" twice`},
137 {"escaped",
138 `{"genesis": "alice", "\u0067enesis": "mallory"}`,
139 `the document holds the key "genesis" twice`},
140 {"in a raw value",
141 `{"derived": [{"a": 1, "a": 2}]}`,
142 `derived[0] holds the key "a" twice`},
143 {"in an interface",
144 `{"principals": {"alice": {"notes": {"n": {"x": 1, "x": 2}}}}}`,
145 `principals["alice"].notes["n"] holds the key "x" twice`},
146 {"a second document",
147 `{"genesis": "alice"} {"genesis": "mallory"}`,
148 `the document holds more than one JSON value`},
149 } {
150 var d doc
151 if err := Decode([]byte(c.data), &d); err == nil || err.Error() != c.says {
152 t.Errorf("%s: Decode read %+v, %v, not %q", c.name, d, err, c.says)
153 }
154 }
155 if err := Decode([]byte(`{}`), doc{}); err == nil || !strings.Contains(err.Error(), "non-pointer") {
156 t.Errorf("Decode into a value: %v", err)
157 }
158}
159
160// Structs that embed a struct, as a value, as a pointer, and under a json
161// tag name.
162type embeds struct {
163 grant
164 Name string `json:"name"`
165}
166
167type embedsPointer struct {
168 *grant
169}
170
171type embedsTagged struct {
172 Extra `json:"extra"`
173}
174
175type Extra struct {
176 Slot string `json:"slot"`
177}
178
179// encoding/json reads the fields of an embedded struct as the embedding
180// struct's own, and Decode does not follow it there: it refuses any
181// object read into a struct that embeds one, at any depth, whatever the
182// object holds. A struct embedded under a json tag name is an ordinary
183// field.
184func TestAnEmbeddedStructIsRefused(t *testing.T) {
185 var e embeds
186 if err := json.Unmarshal([]byte(`{"boundary": "b"}`), &e); err != nil || e.Boundary != "b" {
187 t.Fatalf("encoding/json read %+v, %v", e, err)
188 }
189 for _, c := range []struct {
190 name, data, says string
191 v any
192 }{
193 {"a struct", `{"boundary": "b"}`,
194 `the document is read into exactjson.embeds, which embeds exactjson.grant, and exactjson reads no embedded struct`,
195 &embeds{}},
196 {"an empty object", `{}`,
197 `the document is read into exactjson.embeds, which embeds exactjson.grant, and exactjson reads no embedded struct`,
198 &embeds{}},
199 {"a pointer, in a map", `{"push": {"boundary": "b"}}`,
200 `["push"] is read into exactjson.embedsPointer, which embeds *exactjson.grant, and exactjson reads no embedded struct`,
201 &map[string]embedsPointer{}},
202 } {
203 if err := Decode([]byte(c.data), c.v); err == nil || err.Error() != c.says {
204 t.Errorf("%s: Decode read %+v, %v, not %q", c.name, c.v, err, c.says)
205 }
206 }
207 var tagged embedsTagged
208 if err := Decode([]byte(`{"extra": {"slot": "s"}}`), &tagged); err != nil || tagged.Slot != "s" {
209 t.Errorf("a struct embedded under a tag name: Decode read %+v, %v", tagged, err)
210 }
211 if err := Decode([]byte(`{"slot": "s"}`), &embedsTagged{}); err == nil {
212 t.Errorf("a struct embedded under a tag name: Decode read its field's key as the embedding struct's")
213 }
214}
215
216// An array or object read into a type that holds none is refused where it
217// is, before anything inside it is read. encoding/json would refuse each
218// of these too, but only after reading the whole document.
219func TestAContainerOfTheWrongKindIsRefused(t *testing.T) {
220 for _, c := range []struct{ name, data, says string }{
221 {"an array for the document",
222 `[{"genesis": "alice"}]`,
223 `the document is an array, where an object belongs`},
224 {"an array for a map",
225 `{"principals": [{"keys": []}]}`,
226 `principals is an array, where an object belongs`},
227 {"an object for a string",
228 `{"genesis": {"Genesis": "alice"}}`,
229 `genesis is an object, where a string belongs`},
230 {"an object for a slice",
231 `{"principals": {"alice": {"keys": {"public": "k1"}}}}`,
232 `principals["alice"].keys is an object, where an array belongs`},
233 {"an array for a number",
234 `{"count": [1]}`,
235 `count is an array, where a whole number belongs`},
236 {"an array behind a pointer",
237 `{"principals": {"alice": {"keys": [{"public": "k1", "proof": []}]}}}`,
238 `principals["alice"].keys[0].proof is an array, where an object belongs`},
239 } {
240 var d doc
241 if err := Decode([]byte(c.data), &d); err == nil || err.Error() != c.says {
242 t.Errorf("%s: Decode read %+v, %v, not %q", c.name, d, err, c.says)
243 }
244 if err := json.Unmarshal([]byte(c.data), &doc{}); err == nil {
245 t.Errorf("%s: encoding/json reads the document", c.name)
246 }
247 }
248}
249
250// A value of the wrong kind where a string, a number, a boolean or the
251// document belongs is refused saying what was written and what belongs
252// there, in words. No Go type is named, so the text stays the same when a
253// type is renamed or moved.
254func TestAValueOfTheWrongKindIsRefusedInWords(t *testing.T) {
255 for _, c := range []struct{ name, data, says string }{
256 {"a number for a string", `{"genesis": 1}`, `genesis is a number, where a string belongs`},
257 {"a boolean for a string", `{"principals": {"alice": {"keys": [{"public": true}]}}}`,
258 `principals["alice"].keys[0].public is a boolean, where a string belongs`},
259 {"a string for a number", `{"count": "1"}`, `count is a string, where a whole number belongs`},
260 {"a fraction for a whole number", `{"count": 1.5}`, `count is the number 1.5, where a whole number belongs`},
261 {"a string for the document", `"alice"`, `the document is a string, where an object belongs`},
262 } {
263 var d doc
264 err := Decode([]byte(c.data), &d)
265 if err == nil || err.Error() != c.says {
266 t.Errorf("%s: Decode read %+v, %v, not %q", c.name, d, err, c.says)
267 }
268 var mismatch *json.UnmarshalTypeError
269 if !errors.As(err, &mismatch) {
270 t.Errorf("%s: encoding/json's error is not beneath %v", c.name, err)
271 }
272 }
273}
274
275// Arrays and objects may nest MaxDepth deep, counting the document's own,
276// and no deeper. Only a raw value or an interface nests freely enough to
277// reach the bound.
278func TestNestingPastMaxDepthIsRefused(t *testing.T) {
279 nested := func(depth int) string {
280 return `{"derived": ` + strings.Repeat("[", depth-1) + strings.Repeat("]", depth-1) + `}`
281 }
282 var d doc
283 if err := Decode([]byte(nested(MaxDepth)), &d); err != nil {
284 t.Errorf("a document %d deep: %v", MaxDepth, err)
285 }
286 says := fmt.Sprintf("the document nests arrays and objects more than %d deep", MaxDepth)
287 if err := Decode([]byte(nested(MaxDepth+1)), &d); err == nil || err.Error() != says {
288 t.Errorf("a document %d deep: Decode read %v, not %q", MaxDepth+1, err, says)
289 }
290 var v any
291 if err := Decode([]byte(strings.Repeat(`{"a":`, MaxDepth)+"1"+strings.Repeat("}", MaxDepth)), &v); err != nil {
292 t.Errorf("objects %d deep in an interface: %v", MaxDepth, err)
293 }
294 if err := Decode([]byte(strings.Repeat(`{"a":`, MaxDepth+1)+"1"+strings.Repeat("}", MaxDepth+1)), &v); err == nil || err.Error() != says {
295 t.Errorf("objects %d deep in an interface: Decode read %v, not %q", MaxDepth+1, err, says)
296 }
297}
298
299// counted counts the bytes read from r.
300type counted struct {
301 r io.Reader
302 n int
303}
304
305func (c *counted) Read(p []byte) (int, error) {
306 n, err := c.r.Read(p)
307 c.n += n
308 return n, err
309}
310
311// A million brackets around null is refused at the first bracket the type
312// cannot hold, or at the bracket past MaxDepth, whichever comes first.
313// The check reads no further than that, and what it holds while it reads
314// grows with the depth it reaches, not with the document.
315func TestDeepBracketsAreRefusedEarly(t *testing.T) {
316 const n = 1 << 20
317 brackets := strings.Repeat("[", n) + "null" + strings.Repeat("]", n)
318 deep := fmt.Sprintf("the document nests arrays and objects more than %d deep", MaxDepth)
319 for _, c := range []struct {
320 name, data, says string
321 v any
322 }{
323 {"a struct", brackets,
324 `the document is an array, where an object belongs`, &doc{}},
325 {"a slice of structs", brackets,
326 `[0] is an array, where an object belongs`, &[]doc{}},
327 {"an interface", brackets, deep, new(any)},
328 {"a raw value", brackets, deep, &json.RawMessage{}},
329 {"a raw value in a struct", `{"derived": ` + brackets + `}`, deep, &doc{}},
330 } {
331 in := []byte(c.data)
332 r := &counted{r: bytes.NewReader(in)}
333 if err := Check(json.NewDecoder(r), reflect.TypeOf(c.v)); err == nil || err.Error() != c.says {
334 t.Errorf("%s: Check read %v, not %q", c.name, err, c.says)
335 }
336 if r.n > 64<<10 {
337 t.Errorf("%s: Check read %d bytes of %d", c.name, r.n, len(in))
338 }
339 var before, after runtime.MemStats
340 runtime.ReadMemStats(&before)
341 if err := Decode(in, c.v); err == nil || err.Error() != c.says {
342 t.Errorf("%s: Decode read %v, not %q", c.name, err, c.says)
343 }
344 runtime.ReadMemStats(&after)
345 if grew := after.TotalAlloc - before.TotalAlloc; grew > 1<<20 {
346 t.Errorf("%s: Decode allocated %d bytes", c.name, grew)
347 }
348 }
349}