Debian Codegraph @

internal/json/parser_test.go

raw symbols SCIP
1 package json
2
3 import (
4 "bytes"
5 "encoding/json"
6 "strings"
7 "testing"
8
9 "github.com/gabriel-vasile/mimetype/internal/scan"
10 )
11
12 // These samples come from https://github.com/nst/JSONTestSuite.
13 var positives = []struct {
14 json string
15 stdlib bool
16 }{
17 {`[[] ]`, true},
18 {`[]`, true},
19 {`[""]`, true},
20 {`["a"]`, true},
21 {`[false]`, true},
22 {`[null, 1, "1", {}]`, true},
23 {`[null]`, true},
24 {`[1
25 ]`, true},
26 {` [1]`, true},
27 {`[1,null,null,null,2]`, true},
28 {`[2] `, true},
29 {`[0e+1]`, true},
30 {`[0e1]`, true},
31 {`[ 4]`, true},
32 {`[-0.000000000000000000000000000000000000000000000000000000000000000000000000000001]
33 `, true},
34 {`[20e1]`, true},
35 {`[123e65]`, true},
36 {`[-0]`, true},
37 {`[-123]`, true},
38 {`[-1]`, true},
39 {`[-0]`, true},
40 {`[1E22]`, true},
41 {`[1E-2]`, true},
42 {`[1E+2]`, true},
43 {`[123e45]`, true},
44 {`[123.456e78]`, true},
45 {`[1e-2]`, true},
46 {`[1e+2]`, true},
47 {`[123]`, true},
48 {`[123.456789]`, true},
49 {`{"asd":"sdf"}`, true},
50 {`{"a":"b","a":"b"}`, true},
51 {`{"a":"b","a":"c"}`, true},
52 {`{}`, true},
53 {`{"":0}`, true},
54 {`{"foo\u0000bar": 42}`, true},
55 {`{ "min": -1.0e+28, "max": 1.0e+28 }`, true},
56 {`{"asd":"sdf", "dfg":"fgh"}`, true},
57 {`{"x":[{"id": "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"}], "id": "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"}`, true},
58 {`{"a":[]}`, true},
59 {`{"title":"\u041f\u043e\u043b\u0442\u043e\u0440\u0430 \u0417\u0435\u043c\u043b\u0435\u043a\u043e\u043f\u0430" }`, true},
60 {`{
61 "a": "b"
62 }`, true},
63 {`["\u0060\u012a\u12AB"]`, true},
64 {`["\uD801\udc37"]`, true},
65 {`["\ud83d\ude39\ud83d\udc8d"]`, true},
66 {`["\"\\\/\b\f\n\r\t"]`, true},
67 {`["\\u0000"]`, true},
68 {`["\""]`, true},
69 {`["a/*b*/c/*d//e"]`, true},
70 {`["\\a"]`, true},
71 {`["\\n"]`, true},
72 {`["\u0012"]`, true},
73 {`["\uFFFF"]`, true},
74 {`["asd"]`, true},
75 {`[ "asd"]`, true},
76 {`["\uDBFF\uDFFF"]`, true},
77 {`["new\u00A0line"]`, true},
78 {`["􏿿"]`, true},
79 {`["￿"]`, true},
80 {`["\u0000"]`, true},
81 {`["\u002c"]`, true},
82 {`["π"]`, true},
83 {`["𛿿"]`, true},
84 {`["asd "]`, true},
85 {`" "`, true},
86 {`["\uD834\uDd1e"]`, true},
87 {`["\u0821"]`, true},
88 {`["\u0123"]`, true},
89 {`["
"]`, true},
90 {`["
"]`, true},
91 {`["new\u000Aline"]`, true},
92 {`["\u0061\u30af\u30EA\u30b9"]`, true},
93 {`[""]`, true},
94 {`["⍂㈴⍂"]`, true},
95 {`["\u005C"]`, true},
96 {`["\u0022"]`, true},
97 {`["\uA66D"]`, true},
98 {`["\uDBFF\uDFFE"]`, true},
99 {`["\uD83F\uDFFE"]`, true},
100 {`["\u200B"]`, true},
101 {`["\u2064"]`, true},
102 {`["\uFDD0"]`, true},
103 {`["\uFFFE"]`, true},
104 {`["€𝄞"]`, true},
105 {`["aa"]`, true},
106 {`false`, true},
107 {`42`, true},
108 {`-0.1`, true},
109 {`null`, true},
110 {`"asd"`, true},
111 {`true`, true},
112 {`""`, true},
113 {`["a"]
114 `, true},
115 {`[true]`, true},
116 {` [] `, true},
117
118 // Bug: following samples are invalid JSONs but they are parsed successfully.
119 {` `, false},
120 {`["",]`, false},
121 {`[1,]`, false},
122 {`[-01]`, false},
123 {`[-2.]`, false},
124 {`[.2e-3]`, false},
125 {`[0.e1]`, false},
126 {`[2.e+3]`, false},
127 {`[2.e-3]`, false},
128 {`[2.e3]`, false},
129 {`[-012]`, false},
130 {`[-.123]`, false},
131 {`[1.]`, false},
132 {`[.123]`, false},
133 {`[012]`, false},
134 {`{"�":"0",}`, false},
135 {`{"id":0,}`, false},
136 {`"`, false},
137 {`["new
138 line"]`, false},
139 {`[" "]`, false},
140 {`[`, false},
141 {`[[`, false},
142 {`{`, false},
143 }
144
145 var negatives = []struct {
146 name string
147 json string
148 expectParse int
149 expectInspect int
150 }{
151 {"array_1_true_without_comma", `[1 true]`, 1, 3},
152 {"array_a_invalid_utf8", `[a�]`, 1, 1},
153 {"array_colon_instead_of_comma", `["": 1]`, 1, 3},
154 {"array_comma_after_close", `[""],`, 4, 4},
155 {"array_comma_and_number", `[,1]`, 1, 1},
156 {"array_double_comma", `[1,,2]`, 1, 3},
157 {"array_double_extra_comma", `["x",,]`, 1, 5},
158 {"array_extra_close", `["x"]]`, 5, 5},
159 {"array_incomplete_invalid_value", `[x`, 1, 1},
160 {"array_incomplete", `["x"`, 1, 4},
161 {"array_inner_array_no_comma", `[3[4]]`, 1, 2},
162 {"array_invalid_utf8", `[�]`, 1, 1},
163 {"array_items_separated_by_semicolon", `[1:2]`, 1, 2},
164 {"array_just_comma", `[,]`, 1, 1},
165 {"array_just_minus", `[-]`, 1, 2},
166 {"array_missing_value", `[ , ""]`, 1, 4},
167 {"array_newlines_unclosed", `["a",
168 4
169 ,1,`, 1, 11},
170 {"array_number_and_several_commas", `[1,,]`, 1, 3},
171 {"array_spaces_vertical_tab_formfeed", "\x5b\x22\x0b\x61\x22\x5c\x66\x5d", 1, 5},
172 {"array_star_inside", `[*]`, 1, 1},
173 {"array_unclosed", `[""`, 1, 3},
174 {"array_unclosed_trailing_comma", `[1,`, 1, 3},
175 {"array_unclosed_with_new_lines", "\x5b\x31\x2c\x0a\x31\x0a\x2c\x31", 1, 8},
176 {"array_unclosed_with_object_inside", `[{}`, 1, 3},
177 {"incomplete_false", `[fals]`, 1, 5},
178 {"incomplete_null", `[nul]`, 1, 4},
179 {"incomplete_true", `[tru]`, 1, 4},
180 {"multidigit_number_then_00", "\x31\x32\x33\x00", 3, 3},
181 {"number_0.1.2", `[0.1.2]`, 1, 4},
182 {"number_0.3e+", `[0.3e+]`, 1, 6},
183 {"number_0.3e", `[0.3e]`, 1, 5},
184 {"number_0_capital_E+", `[0E+]`, 1, 4},
185 {"number_0_capital_E", `[0E]`, 1, 3},
186 {"number_0e+", `[0e+]`, 1, 4},
187 {"number_0e", `[0e]`, 1, 3},
188 {"number_1_000", `[1 000.0]`, 1, 3},
189 {"number_1.0e+", `[1.0e+]`, 1, 6},
190 {"number_1.0e-", `[1.0e-]`, 1, 6},
191 {"number_1.0e", `[1.0e]`, 1, 5},
192 {"number_-1.0.", `[-1.0.]`, 1, 5},
193 {"number_1eE2", `[1eE2]`, 1, 3},
194 {"number_+1", `[+1]`, 1, 1},
195 {"number_.-1", `[.-1]`, 1, 2},
196 {"number_9.e+", `[9.e+]`, 1, 5},
197 {"number_expression", `[1+2]`, 1, 2},
198 {"number_hex_1_digit", `[0x1]`, 1, 2},
199 {"number_hex_2_digits", `[0x42]`, 1, 2},
200 {"number_infinity", `[Infinity]`, 1, 1},
201 {"number_+Inf", `[+Inf]`, 1, 1},
202 {"number_Inf", `[Inf]`, 1, 1},
203 {"number_invalid+-", `[0e+-1]`, 1, 4},
204 {"number_invalid-negative-real", `[-123.123foo]`, 1, 9},
205 {"number_invalid-utf-8-in-bigger-int", `[123�]`, 1, 4},
206 {"number_invalid-utf-8-in-exponent", `[1e1�]`, 1, 4},
207 {"number_invalid-utf-8-in-int", "\x5b\x30\xe5\x5d\x0a", 1, 2},
208 {"number_++", `[++1234]`, 1, 1},
209 {"number_minus_infinity", `[-Infinity]`, 1, 2},
210 {"number_minus_sign_with_trailing_garbage", `[-foo]`, 1, 2},
211 {"number_minus_space_1", `[- 1]`, 1, 2},
212 {"number_-NaN", `[-NaN]`, 1, 2},
213 {"number_NaN", `[NaN]`, 1, 1},
214 {"number_neg_with_garbage_at_end", `[-1x]`, 1, 3},
215 {"number_real_garbage_after_e", `[1ea]`, 1, 3},
216 {"number_real_with_invalid_utf8_after_e", `[1e�]`, 1, 3},
217 {"number_U+FF11_fullwidth_digit_one", `[1]`, 1, 1},
218 {"number_with_alpha_char", `[1.8011670033376514H-308]`, 1, 19},
219 {"number_with_alpha", `[1.2a-3]`, 1, 4},
220 {"object_bad_value", `["x", truth]`, 1, 9},
221 {"object_bracket_key", "\x7b\x5b\x3a\x20\x22\x78\x22\x7d\x0a", 1, 1},
222 {"object_comma_instead_of_colon", `{"x", null}`, 1, 4},
223 {"object_double_colon", `{"x"::"b"}`, 1, 5},
224 {"object_emoji", `{🇨🇭}`, 1, 1},
225 {"object_garbage_at_end", `{"a":"a" 123}`, 1, 9},
226 {"object_key_with_single_quotes", `{key: 'value'}`, 1, 1},
227 {"object_missing_colon", `{"a" b}`, 1, 5},
228 {"object_missing_key", `{:"b"}`, 1, 1},
229 {"object_missing_semicolon", `{"a" "b"}`, 1, 5},
230 {"object_missing_value", `{"a":`, 1, 5},
231 {"object_no-colon", `{"a"`, 1, 4},
232 {"object_non_string_key_but_huge_number_instead", `{9999E9999:1}`, 1, 1},
233 {"object_non_string_key", `{1:1}`, 1, 1},
234 {"object_repeated_null_null", `{null:null,null:null}`, 1, 1},
235 {"object_several_trailing_commas", `{"id":0,,,,,}`, 1, 8},
236 {"object_single_quote", `{'a':0}`, 1, 1},
237 {"object_trailing_comment", `{"a":"b"}/**/`, 9, 9},
238 {"object_trailing_comment_open", `{"a":"b"}/**//`, 9, 9},
239 {"object_trailing_comment_slash_open_incomplete", `{"a":"b"}/`, 9, 9},
240 {"object_trailing_comment_slash_open", `{"a":"b"}//`, 9, 9},
241 {"object_two_commas_in_a_row", `{"a":"b",,"c":"d"}`, 1, 9},
242 {"object_unquoted_key", `{a: "b"}`, 1, 1},
243 {"object_unterminated-value", `{"a":"a`, 1, 7},
244 {"object_with_single_string", `{ "foo" : "bar", "a" }`, 1, 21},
245 {"object_with_trailing_garbage", `{"a":"b"}#`, 9, 9},
246 {"single_space", ` `, 0, 1},
247 {"string_1_surrogate_then_escape", `["\uD800\"]`, 1, 11},
248 {"string_1_surrogate_then_escape_u1", `["\uD800\u1"]`, 1, 11},
249 {"string_1_surrogate_then_escape_u1x", `["\uD800\u1x"]`, 1, 11},
250 {"string_1_surrogate_then_escape_u", `["\uD800\u"]`, 1, 10},
251 {"string_accentuated_char_no_quotes", `[é]`, 1, 1},
252 {"string_backslash_00", "\x5b\x22\x5c\x00\x22\x5d", 1, 3},
253 {"string_escaped_backslash_bad", `["\\\"]`, 1, 7},
254 {"string_escaped_ctrl_char_tab", "\x5b\x22\x5c\x09\x22\x5d", 1, 3},
255 {"string_escaped_emoji", `["\🌀"]`, 1, 3},
256 {"string_escape_x", `["\x00"]`, 1, 3},
257 {"string_incomplete_escaped_character", `["\u00A"]`, 1, 7},
258 {"string_incomplete_escape", `["\"]`, 1, 5},
259 {"string_incomplete_surrogate_escape_invalid", `["\uD800\uD800\x"]`, 1, 15},
260 {"string_incomplete_surrogate", `["\uD834\uDd"]`, 1, 12},
261 {"string_invalid_backslash_esc", `["\a"]`, 1, 3},
262 {"string_invalid_unicode_escape", `["\uqqqq"]`, 1, 4},
263 {"string_invalid_utf8_after_escape", `["\�"]`, 1, 3},
264 {"string_invalid-utf-8-in-escape", `["\u�"]`, 1, 4},
265 {"string_leading_uescaped_thinspace", `[\u0020"asd"]`, 1, 1},
266 {"string_no_quotes_with_bad_escape", `[\n]`, 1, 1},
267 {"string_single_quote", `['single quote']`, 1, 1},
268 {"string_single_string_no_double_quotes", `abc`, 0, 0},
269 {"string_start_escape_unclosed", `["\`, 1, 3},
270 {"string_unicode_CapitalU", `"\UA66D"`, 1, 2},
271 {"string_with_trailing_garbage", `""x`, 2, 2},
272 {"structure_angle_bracket_.", `<.>`, 0, 0},
273 {"structure_angle_bracket_null", `[<null>]`, 1, 1},
274 {"structure_array_trailing_garbage", `[1]x`, 3, 3},
275 {"structure_array_with_extra_array_close", `[1]]`, 3, 3},
276 {"structure_array_with_unclosed_string", `["asd]`, 1, 6},
277 {"structure_ascii-unicode-identifier", `aå`, 0, 0},
278 {"structure_capitalized_True", `[True]`, 1, 1},
279 {"structure_close_unopened_array", `1]`, 1, 1},
280 {"structure_comma_instead_of_closing_brace", `{"x": true,`, 1, 11},
281 {"structure_double_array", `[][]`, 2, 2},
282 {"structure_end_array", `]`, 0, 0},
283 {"structure_incomplete_UTF8_BOM", `�{}`, 0, 0},
284 {"structure_lone-invalid-utf-8", `�`, 0, 0},
285 {"structure_null-byte-outside-string", "\x5b\x00\x5d", 1, 1},
286 {"structure_number_with_trailing_garbage", `2@`, 1, 1},
287 {"structure_object_followed_by_closing_object", `{}}`, 2, 2},
288 {"structure_object_unclosed_no_value", `{"":`, 1, 4},
289 {"structure_object_with_comment", `{"a":/*comment*/"b"}`, 1, 5},
290 {"structure_object_with_trailing_garbage", `{"a": true} "x"`, 12, 12},
291 {"structure_open_array_apostrophe", `['`, 1, 1},
292 {"structure_open_array_comma", `[,`, 1, 1},
293 {"structure_open_array_open_object", `[{`, 1, 2},
294 {"structure_open_array_open_string", `["a`, 1, 3},
295 {"structure_open_array_string", `["a"`, 1, 4},
296 {"structure_open_object_close_array", `{]`, 1, 1},
297 {"structure_open_object_comma", `{,`, 1, 1},
298 {"structure_open_object_open_array", `{[`, 1, 1},
299 {"structure_open_object_open_string", `{"a`, 1, 3},
300 {"structure_open_object_string_with_apostrophes", `{'a'`, 1, 1},
301 {"structure_open_open", `["\{["\{["\{["\{`, 1, 3},
302 {"structure_single_eacute", `�`, 0, 0},
303 {"structure_single_star", `*`, 0, 0},
304 {"structure_trailing_#", `{"a":"b"}#{}`, 9, 9},
305 {"structure_U+2060_word_joined", "\x5b\xe2\x81\xa0\x5d", 1, 1},
306 {"structure_uescaped_LF_before_string", `[\u000A""]`, 1, 1},
307 {"structure_unclosed_array", `[1`, 1, 2},
308 {"structure_unclosed_array_partial_null", `[ false, nul`, 1, 12},
309 {"structure_unclosed_array_unfinished_false", `[ true, fals`, 1, 12},
310 {"structure_unclosed_array_unfinished_true", `[ false, tru`, 1, 12},
311 {"structure_unclosed_object", `{"asd":"asd"`, 1, 12},
312 {"structure_unicode-identifier", `å`, 0, 0},
313 {"structure_UTF8_BOM_no_data", "\xef\xbb\xbf", 0, 0},
314 {"structure_whitespace_formfeed", "\x5b\x0c\x5d", 1, 1},
315 {"structure_whitespace_U+2060_word_joiner", "\x5b\xe2\x81\xa0\x5d", 1, 1},
316 }
317
318 func TestConsumeString(t *testing.T) {
319 tCases := []struct {
320 name string
321 data string
322 expected int
323 }{
324 {"ascii string", `foo"`, 4},
325 {"utf-8 string one char", `ß"`, 3},
326 {"utf-8 string multiple chars", `ßßßß"`, 9},
327 {"empty string", ``, 0},
328 {"non-ending ascii string", `a`, 0},
329 {"non-ending utf-8 string", `ß`, 0},
330 {"escaped ascii string", "\\b a\"", 5},
331 {"escaped utf-8 string", "\\b ß\"", 6},
332 }
333
334 for _, tt := range tCases {
335 t.Run(tt.name, func(t *testing.T) {
336 p := &parserState{}
337 got := p.consumeString([]byte(tt.data))
338 if got != tt.expected {
339 t.Errorf("expected: %v, got: %v", tt.expected, got)
340 }
341 })
342 }
343 }
344
345 func TestConsumeNumber(t *testing.T) {
346 tCases := []struct {
347 data string
348 expected int
349 }{
350 {`123`, 3},
351 {`123.1`, 5},
352 {`123.`, 4},
353 {`.123`, 4},
354 {`.`, 0},
355 {`..`, 0},
356 {`e`, 0},
357 {`1e1`, 3},
358 {`1.1e1`, 5},
359 {`.1e1`, 4},
360 {"", 0},
361 {`"NaN"`, 0},
362 {`"Infinity"`, 0},
363 {`"-Infinity"`, 0},
364 {".0", 2},
365 {"0", 1},
366 {"-0", 2},
367 {"+0", 0},
368 {"1", 1},
369 {"-1", 2},
370 {"00", 2},
371 {"-00", 3},
372 {"01", 2},
373 {"-01", 3},
374 {"0i", 1},
375 {"-0i", 2},
376 {"0f", 1},
377 {"-0f", 2},
378 {"9876543210", 10},
379 {"-9876543210", 11},
380 {"9876543210x", 10},
381 {"-9876543210x", 11},
382 {" 9876543210", 0},
383 {"- 9876543210", 0},
384 {strings.Repeat("9876543210", 1000), 10000},
385 {"-" + strings.Repeat("9876543210", 1000), 1 + 10000},
386 {"0.", 2},
387 {"-0.", 3},
388 {"0e", 0},
389 {"-0e", 0},
390 {"0E", 0},
391 {"-0E", 0},
392 {"0.0", 3},
393 {"-0.0", 4},
394 {"0e0", 3},
395 {"-0e0", 4},
396 {"0E0", 3},
397 {"-0E0", 4},
398 {"0.0123456789", 12},
399 {"-0.0123456789", 13},
400 {"1.f", 2},
401 {"-1.f", 3},
402 {"1.e", 0},
403 {"-1.e", 0},
404 {"1e0", 3},
405 {"-1e0", 4},
406 {"1E0", 3},
407 {"-1E0", 4},
408 {"1Ex", 0},
409 {"-1Ex", 0},
410 {"1e-0", 4},
411 {"-1e-0", 5},
412 {"1e+0", 4},
413 {"-1e+0", 5},
414 {"1E-0", 4},
415 {"-1E-0", 5},
416 {"1E+0", 4},
417 {"-1E+0", 5},
418 {"1E+00500", 8},
419 {"-1E+00500", 9},
420 {"1E+00500x", 8},
421 {"-1E+00500x", 9},
422 {"9876543210.0123456789e+01234589x", 31},
423 {"-9876543210.0123456789e+01234589x", 32},
424 {"1_000_000", 1},
425 {"0x12ef", 1},
426 {"0x1p-2", 1},
427 }
428
429 p := &parserState{}
430 for _, tt := range tCases {
431 tname := tt.data
432 if len(tname) > 10 {
433 tname = tname[:10] + "..."
434 }
435 t.Run(tname, func(t *testing.T) {
436 got := p.consumeNumber([]byte(tt.data))
437 if got != tt.expected {
438 t.Errorf("expected: %v, got: %v", tt.expected, got)
439 }
440 })
441 }
442 }
443
444 func TestConsumeArray(t *testing.T) {
445 tCases := []struct {
446 name string
447 data string
448 expected int
449 }{
450 {"empty array", `]`, 1},
451 {"empty array spaces", ` ]`, 2},
452 {"one int array", `1]`, 2},
453 {"one int array spaces", ` 1 ]`, 4},
454 {"two ints array", `1,2]`, 4},
455 {"two ints array spaces", ` 1 , 2 ]`, 8},
456 {"everything array", `[], {}, true, false, null, 1, "abc"]`, 36},
457 {"everything array v2", `[1,2,3], {"a":"b"}, true, false, null, 1, "abc"]`, 48},
458 {"escaped \"", `"\""]`, 5},
459 {"hex", `"\uA66D"]`, 9},
460 {"unfinished string", `"\uFFF`, 0},
461 }
462
463 p := &parserState{}
464 for _, tt := range tCases {
465 t.Run(tt.name, func(t *testing.T) {
466 got := p.consumeArray([]byte(tt.data), nil, 1)
467 if got != tt.expected {
468 t.Errorf("expected: %v, got: %v", tt.expected, got)
469 }
470 })
471 }
472 }
473
474 func TestQueryObject(t *testing.T) {
475 tCases := []struct {
476 name string
477 json string
478 query query
479 expectedFind bool
480 }{{
481 name: "empty path",
482 json: `{"foo": {"bar": "baz"}}`,
483 query: query{
484 SearchPath: [][]byte{[]byte("")},
485 },
486 expectedFind: false,
487 }, {
488 name: "path not matching after",
489 json: `{"foo": {"bar": "baz"}}`,
490 query: query{
491 SearchPath: [][]byte{[]byte("fool")},
492 },
493 expectedFind: false,
494 }, {
495 name: "path not matching before",
496 json: `{"foo": {"bar": "baz"}}`,
497 query: query{
498 SearchPath: [][]byte{[]byte("afoo")},
499 },
500 expectedFind: false,
501 }, {
502 name: "empty segment followed by valid segment",
503 json: `{"foo": {"bar": "baz"}}`,
504 query: query{
505 SearchPath: [][]byte{[]byte(""), []byte("foo")},
506 },
507 expectedFind: false,
508 }, {
509 name: "inversed segments",
510 json: `{"foo": {"bar": "baz"}}`,
511 query: query{
512 SearchPath: [][]byte{[]byte("bar"), []byte("foo")},
513 },
514 expectedFind: false,
515 }, {
516 name: "foo is value, not path",
517 json: `{"foo": {"bar": "foo"}}`,
518 query: query{
519 SearchPath: [][]byte{[]byte("bar"), []byte("foo")},
520 },
521 expectedFind: false,
522 }, {
523 name: "not matching because it's array",
524 json: `[{"foo": {"bar": "baz"}}]`,
525 query: query{
526 SearchPath: [][]byte{[]byte("foo"), []byte("bar")},
527 },
528 expectedFind: false,
529 }, {
530 name: "match without value",
531 json: `{"foo": {"bar": "baz"}}`,
532 query: query{
533 SearchPath: [][]byte{[]byte("foo"), []byte("bar")},
534 },
535 expectedFind: true,
536 }, {
537 name: "match with value",
538 json: `{"foo": {"bar": "baz"}}`,
539 query: query{
540 SearchPath: [][]byte{[]byte("foo"), []byte("bar")},
541 SearchVals: [][]byte{[]byte(`"baz"`)},
542 },
543 expectedFind: true,
544 }, {
545 name: "no match because path is offset with one foo",
546 json: `{"foo": {"foo": {"bar": "baz"}}}`,
547 query: query{
548 SearchPath: [][]byte{[]byte("foo"), []byte("bar")},
549 SearchVals: [][]byte{[]byte(`"baz"`)},
550 },
551 expectedFind: false,
552 }}
553
554 for _, tt := range tCases {
555 t.Run(tt.name, func(t *testing.T) {
556 p := &parserState{}
557 p.consumeAny([]byte(tt.json), []query{tt.query}, 0)
558 if tt.expectedFind != p.querySatisfied {
559 t.Errorf("expectedFind: %v, got: %v", tt.expectedFind, p.querySatisfied)
560 }
561 })
562 }
563 }
564
565 func TestConsumeObject(t *testing.T) {
566 tCases := []struct {
567 name string
568 data string
569 expected int
570 }{
571 {"empty object", `}`, 1},
572 {"object", `"a":"b"}`, 8},
573 {"panic found with fuzz", "\"\":0", 0},
574 }
575
576 p := &parserState{}
577 for _, tt := range tCases {
578 t.Run(tt.name, func(t *testing.T) {
579 got := p.consumeObject([]byte(tt.data), nil, 1)
580 if got != tt.expected {
581 t.Errorf("expected: %v, got: %v", tt.expected, got)
582 }
583 })
584 }
585 }
586
587 func TestConsumeConst(t *testing.T) {
588 tCases := []struct {
589 b string
590 cnst string
591 expect int
592 inspect int
593 }{
594 {"", "", 0, 0},
595 {"", "true", 0, 0},
596 {"true", "", 0, 0},
597 {"t", "true", 0, 1},
598 {"tr", "true", 0, 2},
599 {"tru", "true", 0, 3},
600 {"true", "true", 4, 4},
601 {"truex", "true", 4, 4},
602 }
603
604 for _, tt := range tCases {
605 p := &parserState{}
606 t.Run(tt.b+" -- "+tt.cnst, func(t *testing.T) {
607 got := p.consumeConst([]byte(tt.b), []byte(tt.cnst))
608 if got != tt.expect {
609 t.Errorf("expected: %v, got %v", tt.expect, got)
610 }
611 if p.ib != tt.inspect {
612 t.Errorf("expected to inspect: %v, got %v", tt.inspect, p.ib)
613 }
614 })
615 }
616 }
617
618 // Truncate inputs at each possible index and test if decoder parses
619 // the truncated part successfully.
620 func testTruncating(t *testing.T, jsonString string) {
621 t.Helper()
622 p := &parserState{}
623 for i := 1; i <= len(jsonString); i++ {
624 b := scan.Bytes(jsonString[:i])
625 b.TrimRWS()
626 p.reset()
627 _ = p.consumeAny(b, nil, 0)
628 if p.ib != len(b) {
629 t.Errorf("truncated positives should be fully parsed %v \n"+
630 "got: %d want: %d", string(b), p.ib, len(b))
631 }
632 }
633 }
634
635 func TestPositives(t *testing.T) {
636 for _, tt := range positives {
637 testTruncating(t, tt.json)
638 }
639 }
640
641 func TestPositivesCompacted(t *testing.T) {
642 for _, tt := range positives {
643 if !tt.stdlib {
644 continue
645 }
646 buf := &bytes.Buffer{}
647 if err := json.Compact(buf, []byte(tt.json)); err != nil {
648 t.Errorf("Compact should always be successful: %s %s", tt.json, err)
649 }
650 testTruncating(t, buf.String())
651 }
652 }
653
654 func TestPositivesIndented(t *testing.T) {
655 indents := [][2]string{
656 {"", " "},
657 {" ", " "},
658 {" ", "\t"},
659 {"\t", "\t"},
660 {"\t", " \t"},
661 {"", "\r\n"},
662 {"", " \r\n"},
663 }
664 for _, tt := range positives {
665 if !tt.stdlib {
666 continue
667 }
668 for _, indent := range indents {
669 buf := &bytes.Buffer{}
670 if err := json.Indent(buf, []byte(tt.json), indent[0], indent[1]); err != nil {
671 t.Errorf("Indent should always be successful: %s %s", tt.json, err)
672 }
673 testTruncating(t, buf.String())
674 }
675 }
676 }
677
678 func TestNegatives(t *testing.T) {
679 p := &parserState{}
680 for _, tt := range negatives {
681 t.Run(tt.name, func(t *testing.T) {
682 p.reset()
683 got := p.consumeAny([]byte(tt.json), nil, 0)
684 if got != tt.expectParse {
685 t.Errorf("unexpected parsed length got: %d want:%d", got, tt.expectParse)
686 }
687 if p.ib != tt.expectInspect {
688 t.Errorf("unexpected inspected length got: %d want:%d\nin:%s", p.ib, tt.expectInspect, tt.json)
689 }
690 })
691 }
692 }
693
694 func TestMaxRecursion(t *testing.T) {
695 tCases := []struct {
696 maxRecursion int
697 input string
698 expectParsed int
699 expectInspected int
700 }{
701 {0, `[]`, 2, 2},
702 {0, `[[[]]]`, 6, 6},
703 {0, strings.Repeat("[", 10000) + strings.Repeat("]", 10000), 20000, 20000},
704 {3, `[[[[[]]]]]`, 1, 4}, // max recursion is 3 so we need to inspect 4 opening brackets
705 }
706 for _, tt := range tCases {
707 tname := tt.input
708 if len(tname) > 10 {
709 tname = tname[:10] + "..."
710 }
711 t.Run(tname, func(t *testing.T) {
712 p := &parserState{
713 maxRecursion: tt.maxRecursion,
714 }
715 got := p.consumeAny([]byte(tt.input), nil, 0)
716 if got != tt.expectParsed {
717 t.Errorf("parsed: got: %d expected: %d", got, tt.expectParsed)
718 }
719 if p.ib != tt.expectInspected {
720 t.Errorf("inspected: got: %d expected: %d", p.ib, tt.expectInspected)
721 }
722 })
723 }
724 }
725
726 func TestStack(t *testing.T) {
727 tCases := []struct {
728 name string
729 data string
730 expected string
731 }{
732 {"empty", ` `, ""},
733 {"a string", `"abc"`, ""},
734 {"an int", `123`, ""},
735 {"true", `true`, ""},
736 {"false", `false`, ""},
737 // Input must be an incomplete JSON because the stack is popped otherwise.
738 {"arr", `[`, "["},
739 // Put a § between each segment of the stack.
740 {"arrr", `[[`, "[§["},
741 {"arrrr", `[[[`, "[§[§["},
742 {"arrr popped once", `[[[]`, "[§["},
743 {"obj", `{`, ""},
744 {"obj key", `{"abc":1`, "abc"},
745 {"obj key twice", `{"abc":{"def":1`, "abc§def"},
746 {"obj key twice but popped", `{"abc":{"def":1}`, "abc"},
747 {"obj key twice and arr", `{"abc":{"def":[`, "abc§def§["},
748 {"hacky", `{"abc":{"def[":`, "abc§def["},
749 }
750
751 join := func(bs [][]byte) string {
752 ret := make([]string, 0, len(bs))
753 for _, b := range bs {
754 ret = append(ret, string(b))
755 }
756 return strings.Join(ret, "§")
757 }
758 for _, tt := range tCases {
759 t.Run(tt.name, func(t *testing.T) {
760 p := &parserState{}
761 p.consumeAny([]byte(tt.data), []query{{}}, 0)
762 if got := join(p.currPath); got != tt.expected {
763 t.Errorf("expected: %s, got: %s", tt.expected, got)
764 }
765 })
766 }
767 }
768
769 func TestCurrPathBounded(t *testing.T) {
770 // currPath is bounded to 128.
771 count := 129
772 // input has to be an incomplete json, so that currPath does not get popped.
773 input := []byte(strings.Repeat("[", count))
774
775 for i := 0; i < 100; i++ {
776 Parse(QueryGeo, input)
777 // It's not guaranteed that p is the same parser object used by the
778 // Parse call above. Reason: go runs tests packages concurrently. If
779 // another package calls Parse in tests, that can interfere with parserPool.
780 // Running the test several times in loop mitigates that.
781 p := parserPool.Get().(*parserState)
782 if len(p.currPath) > 128 {
783 t.Errorf("expected currPath be purged if >128")
784 }
785 }
786 }
787
788 var sample = []byte(`{"type":"Feature","fruit":[{},{"dummy":"data","another field":[false,null]},true,false],"size":"Large","color":"Red"}`)
789
790 func BenchmarkParse(b *testing.B) {
791 b.ReportAllocs()
792 for b.Loop() {
793 _, _, _, query := Parse(QueryGeo, sample)
794 if !query {
795 b.Error("query should be satisfied")
796 }
797 }
798 }
799
800 func BenchmarkJSONStdlibDecoder(b *testing.B) {
801 b.ReportAllocs()
802 for b.Loop() {
803 d := json.NewDecoder(bytes.NewReader(sample))
804 for {
805 _, err := d.Token()
806 if err != nil {
807 break
808 }
809 }
810 }
811 }
812 func BenchmarkJSONOurParser(b *testing.B) {
813 b.ReportAllocs()
814 for b.Loop() {
815 p := &parserState{}
816 p.consumeAny(sample, nil, 0)
817 }
818 }
819
820 func FuzzJson(f *testing.F) {
821 for _, p := range positives {
822 f.Add([]byte(p.json), true)
823 }
824 queryTypes := []string{QueryNone, QueryGeo, QueryHAR, QueryGLTF, QueryCDX}
825 p := &parserState{}
826 f.Fuzz(func(t *testing.T, data []byte, reset bool) {
827 if reset {
828 p.reset()
829 }
830 p.consumeString(data)
831 p.consumeNumber(data)
832 p.consumeArray(data, nil, 1)
833 p.consumeObject(data, nil, 1)
834 p.consumeAny(data, nil, 1)
835 // Exercise the query matching logic through the public entry point.
836 for _, q := range queryTypes {
837 Parse(q, data)
838 }
839 })
840 }