Debian Codegraph @

pkg/internal/third_party/go-json-experiment/json/jsontext/state_test.go

raw
1 // Copyright 2020 The Go Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style
3 // license that can be found in the LICENSE file.
4
5 package jsontext
6
7 import (
8 "fmt"
9 "slices"
10 "strings"
11 "testing"
12 "unicode/utf8"
13 )
14
15 func TestPointer(t *testing.T) {
16 tests := []struct {
17 in Pointer
18 wantParent Pointer
19 wantLast string
20 wantTokens []string
21 wantValid bool
22 }{
23 {"", "", "", nil, true},
24 {"a", "", "a", []string{"a"}, false},
25 {"~", "", "~", []string{"~"}, false},
26 {"/a", "", "a", []string{"a"}, true},
27 {"/foo/bar", "/foo", "bar", []string{"foo", "bar"}, true},
28 {"///", "//", "", []string{"", "", ""}, true},
29 {"/~0~1", "", "~/", []string{"~/"}, true},
30 {"/\xde\xad\xbe\xef", "", "\xde\xad\xbe\xef", []string{"\xde\xad\xbe\xef"}, false},
31 }
32 for _, tt := range tests {
33 if got := tt.in.Parent(); got != tt.wantParent {
34 t.Errorf("Pointer(%q).Parent = %q, want %q", tt.in, got, tt.wantParent)
35 }
36 if got := tt.in.LastToken(); got != tt.wantLast {
37 t.Errorf("Pointer(%q).Last = %q, want %q", tt.in, got, tt.wantLast)
38 }
39 if strings.HasPrefix(string(tt.in), "/") {
40 wantRoundtrip := tt.in
41 if !utf8.ValidString(string(wantRoundtrip)) {
42 // Replace bytes of invalid UTF-8 with Unicode replacement character.
43 wantRoundtrip = Pointer([]rune(wantRoundtrip))
44 }
45 if got := tt.in.Parent().AppendToken(tt.in.LastToken()); got != wantRoundtrip {
46 t.Errorf("Pointer(%q).Parent().AppendToken(LastToken()) = %q, want %q", tt.in, got, tt.in)
47 }
48 in := tt.in
49 for {
50 if (in + "x").Contains(tt.in) {
51 t.Errorf("Pointer(%q).Contains(%q) = true, want false", in+"x", tt.in)
52 }
53 if !in.Contains(tt.in) {
54 t.Errorf("Pointer(%q).Contains(%q) = false, want true", in, tt.in)
55 }
56 if in == in.Parent() {
57 break
58 }
59 in = in.Parent()
60 }
61 }
62 if got := slices.Collect(tt.in.Tokens()); !slices.Equal(got, tt.wantTokens) {
63 t.Errorf("Pointer(%q).Tokens = %q, want %q", tt.in, got, tt.wantTokens)
64 }
65 if got := tt.in.IsValid(); got != tt.wantValid {
66 t.Errorf("Pointer(%q).IsValid = %v, want %v", tt.in, got, tt.wantValid)
67 }
68 }
69 }
70
71 func TestStateMachine(t *testing.T) {
72 // To test a state machine, we pass an ordered sequence of operations and
73 // check whether the current state is as expected.
74 // The operation type is a union type of various possible operations,
75 // which either call mutating methods on the state machine or
76 // call accessor methods on state machine and verify the results.
77 type operation any
78 type (
79 // stackLengths checks the results of stateEntry.length accessors.
80 stackLengths []int64
81
82 // appendTokens is sequence of token kinds to append where
83 // none of them are expected to fail.
84 //
85 // For example: `[nft]` is equivalent to the following sequence:
86 //
87 // pushArray()
88 // appendLiteral()
89 // appendString()
90 // appendNumber()
91 // popArray()
92 //
93 appendTokens string
94
95 // appendToken is a single token kind to append with the expected error.
96 appendToken struct {
97 kind Kind
98 want error
99 }
100
101 // needDelim checks the result of the needDelim accessor.
102 needDelim struct {
103 next Kind
104 want byte
105 }
106 )
107
108 // Each entry is a sequence of tokens to pass to the state machine.
109 tests := []struct {
110 label string
111 ops []operation
112 }{{
113 "TopLevelValues",
114 []operation{
115 stackLengths{0},
116 needDelim{'n', 0},
117 appendTokens(`nft`),
118 stackLengths{3},
119 needDelim{'"', 0},
120 appendTokens(`"0[]{}`),
121 stackLengths{7},
122 },
123 }, {
124 "ArrayValues",
125 []operation{
126 stackLengths{0},
127 needDelim{'[', 0},
128 appendTokens(`[`),
129 stackLengths{1, 0},
130 needDelim{'n', 0},
131 appendTokens(`nft`),
132 stackLengths{1, 3},
133 needDelim{'"', ','},
134 appendTokens(`"0[]{}`),
135 stackLengths{1, 7},
136 needDelim{']', 0},
137 appendTokens(`]`),
138 stackLengths{1},
139 },
140 }, {
141 "ObjectValues",
142 []operation{
143 stackLengths{0},
144 needDelim{'{', 0},
145 appendTokens(`{`),
146 stackLengths{1, 0},
147 needDelim{'"', 0},
148 appendTokens(`"`),
149 stackLengths{1, 1},
150 needDelim{'n', ':'},
151 appendTokens(`n`),
152 stackLengths{1, 2},
153 needDelim{'"', ','},
154 appendTokens(`"f"t`),
155 stackLengths{1, 6},
156 appendTokens(`"""0"[]"{}`),
157 stackLengths{1, 14},
158 needDelim{'}', 0},
159 appendTokens(`}`),
160 stackLengths{1},
161 },
162 }, {
163 "ObjectCardinality",
164 []operation{
165 appendTokens(`{`),
166
167 // Appending any kind other than string for object name is an error.
168 appendToken{'n', ErrNonStringName},
169 appendToken{'f', ErrNonStringName},
170 appendToken{'t', ErrNonStringName},
171 appendToken{'0', ErrNonStringName},
172 appendToken{'{', ErrNonStringName},
173 appendToken{'[', ErrNonStringName},
174 appendTokens(`"`),
175
176 // Appending '}' without first appending any value is an error.
177 appendToken{'}', errMissingValue},
178 appendTokens(`"`),
179
180 appendTokens(`}`),
181 },
182 }, {
183 "MismatchingDelims",
184 []operation{
185 appendToken{'}', errMismatchDelim}, // appending '}' without preceding '{'
186 appendTokens(`[[{`),
187 appendToken{']', errMismatchDelim}, // appending ']' that mismatches preceding '{'
188 appendTokens(`}]`),
189 appendToken{'}', errMismatchDelim}, // appending '}' that mismatches preceding '['
190 appendTokens(`]`),
191 appendToken{']', errMismatchDelim}, // appending ']' without preceding '['
192 },
193 }}
194
195 for _, tt := range tests {
196 t.Run(tt.label, func(t *testing.T) {
197 // Flatten appendTokens to sequence of appendToken entries.
198 var ops []operation
199 for _, op := range tt.ops {
200 if toks, ok := op.(appendTokens); ok {
201 for _, k := range []byte(toks) {
202 ops = append(ops, appendToken{Kind(k), nil})
203 }
204 continue
205 }
206 ops = append(ops, op)
207 }
208
209 // Append each token to the state machine and check the output.
210 var state stateMachine
211 state.reset()
212 var sequence []Kind
213 for _, op := range ops {
214 switch op := op.(type) {
215 case stackLengths:
216 var got []int64
217 for i := range state.Depth() {
218 e := state.index(i)
219 got = append(got, e.Length())
220 }
221 want := []int64(op)
222 if !slices.Equal(got, want) {
223 t.Fatalf("%s: stack lengths mismatch:\ngot %v\nwant %v", sequence, got, want)
224 }
225 case appendToken:
226 got := state.append(op.kind)
227 if !equalError(got, op.want) {
228 t.Fatalf("%s: append('%c') = %v, want %v", sequence, op.kind, got, op.want)
229 }
230 if got == nil {
231 sequence = append(sequence, op.kind)
232 }
233 case needDelim:
234 if got := state.needDelim(op.next); got != op.want {
235 t.Fatalf("%s: needDelim('%c') = '%c', want '%c'", sequence, op.next, got, op.want)
236 }
237 default:
238 panic(fmt.Sprintf("unknown operation: %T", op))
239 }
240 }
241 })
242 }
243 }
244
245 // append is a thin wrapper over the other append, pop, or push methods
246 // based on the token kind.
247 func (s *stateMachine) append(k Kind) error {
248 switch k {
249 case 'n', 'f', 't':
250 return s.appendLiteral()
251 case '"':
252 return s.appendString()
253 case '0':
254 return s.appendNumber()
255 case '{':
256 return s.pushObject()
257 case '}':
258 return s.popObject()
259 case '[':
260 return s.pushArray()
261 case ']':
262 return s.popArray()
263 default:
264 panic(fmt.Sprintf("invalid token kind: '%c'", k))
265 }
266 }
267
268 func TestObjectNamespace(t *testing.T) {
269 type operation any
270 type (
271 insert struct {
272 name string
273 wantInserted bool
274 }
275 removeLast struct{}
276 )
277
278 // Sequence of insert operations to perform (order matters).
279 ops := []operation{
280 insert{`""`, true},
281 removeLast{},
282 insert{`""`, true},
283 insert{`""`, false},
284
285 // Test insertion of the same name with different formatting.
286 insert{`"alpha"`, true},
287 insert{`"ALPHA"`, true}, // case-sensitive matching
288 insert{`"alpha"`, false},
289 insert{`"\u0061\u006c\u0070\u0068\u0061"`, false}, // unescapes to "alpha"
290 removeLast{}, // removes "ALPHA"
291 insert{`"alpha"`, false},
292 removeLast{}, // removes "alpha"
293 insert{`"alpha"`, true},
294 removeLast{},
295
296 // Bulk insert simple names.
297 insert{`"alpha"`, true},
298 insert{`"bravo"`, true},
299 insert{`"charlie"`, true},
300 insert{`"delta"`, true},
301 insert{`"echo"`, true},
302 insert{`"foxtrot"`, true},
303 insert{`"golf"`, true},
304 insert{`"hotel"`, true},
305 insert{`"india"`, true},
306 insert{`"juliet"`, true},
307 insert{`"kilo"`, true},
308 insert{`"lima"`, true},
309 insert{`"mike"`, true},
310 insert{`"november"`, true},
311 insert{`"oscar"`, true},
312 insert{`"papa"`, true},
313 insert{`"quebec"`, true},
314 insert{`"romeo"`, true},
315 insert{`"sierra"`, true},
316 insert{`"tango"`, true},
317 insert{`"uniform"`, true},
318 insert{`"victor"`, true},
319 insert{`"whiskey"`, true},
320 insert{`"xray"`, true},
321 insert{`"yankee"`, true},
322 insert{`"zulu"`, true},
323
324 // Test insertion of invalid UTF-8.
325 insert{`"` + "\ufffd" + `"`, true},
326 insert{`"` + "\ufffd" + `"`, false},
327 insert{`"\ufffd"`, false}, // unescapes to Unicode replacement character
328 insert{`"\uFFFD"`, false}, // unescapes to Unicode replacement character
329 insert{`"` + "\xff" + `"`, false}, // mangles as Unicode replacement character
330 removeLast{},
331 insert{`"` + "\ufffd" + `"`, true},
332
333 // Test insertion of unicode characters.
334 insert{`"☺☻☹"`, true},
335 insert{`"☺☻☹"`, false},
336 removeLast{},
337 insert{`"☺☻☹"`, true},
338 }
339
340 // Execute the sequence of operations twice:
341 // 1) on a fresh namespace and 2) on a namespace that has been reset.
342 var ns objectNamespace
343 wantNames := []string{}
344 for _, reset := range []bool{false, true} {
345 if reset {
346 ns.reset()
347 wantNames = nil
348 }
349
350 // Execute the operations and ensure the state is consistent.
351 for i, op := range ops {
352 switch op := op.(type) {
353 case insert:
354 gotInserted := ns.insertQuoted([]byte(op.name), false)
355 if gotInserted != op.wantInserted {
356 t.Fatalf("%d: objectNamespace{%v}.insert(%v) = %v, want %v", i, strings.Join(wantNames, " "), op.name, gotInserted, op.wantInserted)
357 }
358 if gotInserted {
359 b, _ := AppendUnquote(nil, []byte(op.name))
360 wantNames = append(wantNames, string(b))
361 }
362 case removeLast:
363 ns.removeLast()
364 wantNames = wantNames[:len(wantNames)-1]
365 default:
366 panic(fmt.Sprintf("unknown operation: %T", op))
367 }
368
369 // Check that the namespace is consistent.
370 gotNames := []string{}
371 for i := range ns.length() {
372 gotNames = append(gotNames, string(ns.getUnquoted(i)))
373 }
374 if !slices.Equal(gotNames, wantNames) {
375 t.Fatalf("%d: objectNamespace = {%v}, want {%v}", i, strings.Join(gotNames, " "), strings.Join(wantNames, " "))
376 }
377 }
378
379 // Verify that we have not switched to using a Go map.
380 if ns.mapNames != nil {
381 t.Errorf("objectNamespace.mapNames = non-nil, want nil")
382 }
383
384 // Insert a large number of names.
385 for i := range 64 {
386 ns.InsertUnquoted([]byte(fmt.Sprintf(`name%d`, i)))
387 }
388
389 // Verify that we did switch to using a Go map.
390 if ns.mapNames == nil {
391 t.Errorf("objectNamespace.mapNames = nil, want non-nil")
392 }
393 }
394 }