gunk-dev/the-valley

exactjson_test.go

sourcee5e09626b3e3main's published tip history
7.7 KiB
1package exactjson
2
3import (
4 "encoding/json"
5 "reflect"
6 "strings"
7 "testing"
8)
9
10// A registry-shaped document: a struct at the top, maps of structs, a
11// slice of structs, a pointer, and a field read by nobody.
12type doc struct {
13 Principals map[string]principal `json:"principals"`
14 Genesis string `json:"genesis"`
15 Derived json.RawMessage `json:"derived"`
16 Count int64 `json:"count"`
17}
18
19type principal struct {
20 Keys []key `json:"keys"`
21 Grants map[string]grant `json:"grants"`
22 Notes any `json:"notes"`
23 hidden string
24 Bare string
25}
26
27type key struct {
28 Public string `json:"public"`
29 Proof *proof `json:"proof,omitempty"`
30}
31
32type proof struct {
33 Slot string `json:"slot"`
34}
35
36type grant struct {
37 Boundary string `json:"boundary"`
38}
39
40// A document spelled exactly decodes as encoding/json decodes it. Map keys
41// are data, whatever their case, and so are the keys inside an interface
42// and a json.RawMessage. A number past a float64's range is read only by
43// the decode.
44func TestAnExactDocumentDecodesAsEncodingJSONDoes(t *testing.T) {
45 const data = `{
46 "principals": {
47 "alice": {
48 "keys": [{"public": "k1", "proof": {"slot": "s"}}, {"public": "k2"}],
49 "grants": {"push": {"boundary": "b"}, "Push": {"boundary": "B"}},
50 "notes": {"Anything": [{"goes": 1}]}
51 },
52 "Alice": {"keys": [], "grants": {}}
53 },
54 "genesis": "alice",
55 "derived": {"Grants": [1, {"x": 2}]},
56 "count": 9007199254740993
57 }`
58 var got, want doc
59 if err := Decode([]byte(data), &got); err != nil {
60 t.Fatal(err)
61 }
62 if err := json.Unmarshal([]byte(data), &want); err != nil {
63 t.Fatal(err)
64 }
65 if !reflect.DeepEqual(got, want) {
66 t.Errorf("Decode read %+v, encoding/json %+v", got, want)
67 }
68}
69
70// Every key a struct does not name exactly is refused, at every depth,
71// before anything is decoded. encoding/json would have read each of the
72// spellings below into the field it folds to, under Unicode's simple case
73// folding: ſ folds to s, and the Kelvin sign to k.
74func TestAKeyNotSpelledExactlyIsRefused(t *testing.T) {
75 for _, c := range []struct{ name, data, says string }{
76 {"a field in another case, beside the field",
77 `{"principals": {"alice": {"grants": {}, "Grants": {"push": {"boundary": "b"}}}}}`,
78 `principals["alice"] holds the key "Grants", which is its field "grants" spelled another way`},
79 {"at the top",
80 `{"genesis": "alice", "GENESIS": "mallory"}`,
81 `the document holds the key "GENESIS", which is its field "genesis" spelled another way`},
82 {"in a map's struct value",
83 `{"principals": {"alice": {"grants": {"push": {"boundary": "x", "Boundary": "b"}}}}}`,
84 `principals["alice"].grants["push"] holds the key "Boundary", which is its field "boundary" spelled another way`},
85 {"in a slice's element",
86 `{"principals": {"alice": {"keys": [{"public": "k1"}, {"public": "k2", "Public": "k3"}]}}}`,
87 `principals["alice"].keys[1] holds the key "Public", which is its field "public" spelled another way`},
88 {"behind a pointer",
89 `{"principals": {"alice": {"keys": [{"public": "k1", "proof": {"sLot": "s"}}]}}}`,
90 `principals["alice"].keys[0].proof holds the key "sLot", which is its field "slot" spelled another way`},
91 {"folded beyond ASCII",
92 `{"principals": {"alice": {"grantſ": {"push": {"boundary": "b"}}}}}`,
93 `principals["alice"] holds the key "grantſ", which is its field "grants" spelled another way`},
94 {"with the Kelvin sign",
95 "{\"principals\": {\"alice\": {\"Keys\": []}}}",
96 `principals["alice"] holds the key "` + "K" + `eys", which is its field "keys" spelled another way`},
97 {"a field no tag names",
98 `{"principals": {"alice": {"Bare": "x"}}}`,
99 `principals["alice"] holds the key "Bare", which is none of its fields`},
100 {"an unexported field",
101 `{"principals": {"alice": {"hidden": "x"}}}`,
102 `principals["alice"] holds the key "hidden", which is none of its fields`},
103 {"a field nobody declared",
104 `{"genesis": "alice", "extra": true}`,
105 `the document holds the key "extra", which is none of its fields`},
106 } {
107 var d doc
108 err := Decode([]byte(c.data), &d)
109 if err == nil || err.Error() != c.says {
110 t.Errorf("%s: Decode read %+v, %v, not %q", c.name, d, err, c.says)
111 }
112 if !reflect.DeepEqual(d, doc{}) {
113 t.Errorf("%s: a refused document decoded %+v", c.name, d)
114 }
115 }
116}
117
118// A key that appears twice in one object is refused wherever the object
119// is, a map's and a raw value's included, and however the key is escaped.
120// So is anything after the document.
121func TestAKeyTwiceOrASecondDocumentIsRefused(t *testing.T) {
122 for _, c := range []struct{ name, data, says string }{
123 {"at the top",
124 `{"principals": {}, "principals": {"mallory": {}}}`,
125 `the document holds the key "principals" twice`},
126 {"in a map",
127 `{"principals": {"alice": {}, "alice": {"grants": {"push": {"boundary": "b"}}}}}`,
128 `principals holds the key "alice" twice`},
129 {"in a struct in a map",
130 `{"principals": {"alice": {"grants": {"push": {"boundary": "x", "boundary": "b"}}}}}`,
131 `principals["alice"].grants["push"] holds the key "boundary" twice`},
132 {"escaped",
133 `{"genesis": "alice", "\u0067enesis": "mallory"}`,
134 `the document holds the key "genesis" twice`},
135 {"in a raw value",
136 `{"derived": [{"a": 1, "a": 2}]}`,
137 `derived[0] holds the key "a" twice`},
138 {"in an interface",
139 `{"principals": {"alice": {"notes": {"n": {"x": 1, "x": 2}}}}}`,
140 `principals["alice"].notes["n"] holds the key "x" twice`},
141 {"a second document",
142 `{"genesis": "alice"} {"genesis": "mallory"}`,
143 `the document holds more than one JSON value`},
144 } {
145 var d doc
146 if err := Decode([]byte(c.data), &d); err == nil || err.Error() != c.says {
147 t.Errorf("%s: Decode read %+v, %v, not %q", c.name, d, err, c.says)
148 }
149 }
150 if err := Decode([]byte(`{}`), doc{}); err == nil || !strings.Contains(err.Error(), "non-pointer") {
151 t.Errorf("Decode into a value: %v", err)
152 }
153}
154
155// Structs that embed a struct, as a value, as a pointer, and under a json
156// tag name.
157type embeds struct {
158 grant
159 Name string `json:"name"`
160}
161
162type embedsPointer struct {
163 *grant
164}
165
166type embedsTagged struct {
167 Extra `json:"extra"`
168}
169
170type Extra struct {
171 Slot string `json:"slot"`
172}
173
174// encoding/json reads the fields of an embedded struct as the embedding
175// struct's own, and Decode does not follow it there: it refuses any
176// object read into a struct that embeds one, at any depth, whatever the
177// object holds. A struct embedded under a json tag name is an ordinary
178// field.
179func TestAnEmbeddedStructIsRefused(t *testing.T) {
180 var e embeds
181 if err := json.Unmarshal([]byte(`{"boundary": "b"}`), &e); err != nil || e.Boundary != "b" {
182 t.Fatalf("encoding/json read %+v, %v", e, err)
183 }
184 for _, c := range []struct {
185 name, data, says string
186 v any
187 }{
188 {"a struct", `{"boundary": "b"}`,
189 `the document is read into exactjson.embeds, which embeds exactjson.grant, and exactjson reads no embedded struct`,
190 &embeds{}},
191 {"an empty object", `{}`,
192 `the document is read into exactjson.embeds, which embeds exactjson.grant, and exactjson reads no embedded struct`,
193 &embeds{}},
194 {"a pointer, in a map", `{"push": {"boundary": "b"}}`,
195 `["push"] is read into exactjson.embedsPointer, which embeds *exactjson.grant, and exactjson reads no embedded struct`,
196 &map[string]embedsPointer{}},
197 } {
198 if err := Decode([]byte(c.data), c.v); err == nil || err.Error() != c.says {
199 t.Errorf("%s: Decode read %+v, %v, not %q", c.name, c.v, err, c.says)
200 }
201 }
202 var tagged embedsTagged
203 if err := Decode([]byte(`{"extra": {"slot": "s"}}`), &tagged); err != nil || tagged.Slot != "s" {
204 t.Errorf("a struct embedded under a tag name: Decode read %+v, %v", tagged, err)
205 }
206 if err := Decode([]byte(`{"slot": "s"}`), &embedsTagged{}); err == nil {
207 t.Errorf("a struct embedded under a tag name: Decode read its field's key as the embedding struct's")
208 }
209}