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 json string
477 query query
478 expectedFind bool
479 }{{
480 json: `{"foo": {"bar": "baz"}}`,
481 query: query{
482 SearchPath: [][]byte{[]byte("")},
483 },
484 expectedFind: false,
485 }, {
486 json: `{"foo": {"bar": "baz"}}`,
487 query: query{
488 SearchPath: [][]byte{[]byte("fool")},
489 },
490 expectedFind: false,
491 }, {
492 json: `{"foo": {"bar": "baz"}}`,
493 query: query{
494 SearchPath: [][]byte{[]byte("afoo")},
495 },
496 expectedFind: false,
497 }, {
498 json: `{"foo": {"bar": "baz"}}`,
499 query: query{
500 SearchPath: [][]byte{[]byte(""), []byte("foo")},
501 },
502 expectedFind: false,
503 }, {
504 json: `{"foo": {"bar": "baz"}}`,
505 query: query{
506 SearchPath: [][]byte{[]byte("bar"), []byte("foo")},
507 },
508 expectedFind: false,
509 }, {
510 json: `{"foo": {"bar": "foo"}}`,
511 query: query{
512 SearchPath: [][]byte{[]byte("bar"), []byte("foo")},
513 },
514 expectedFind: false,
515 }, {
516 json: `[{"foo": {"bar": "baz"}}]`,
517 query: query{
518 SearchPath: [][]byte{[]byte("foo"), []byte("bar")},
519 },
520 expectedFind: false,
521 }, {
522 json: `{"foo": {"bar": "baz"}}`,
523 query: query{
524 SearchPath: [][]byte{[]byte("foo"), []byte("bar")},
525 },
526 expectedFind: true,
527 }, {
528 json: `{"foo": {"bar": "baz"}}`,
529 query: query{
530 SearchPath: [][]byte{[]byte("foo"), []byte("bar")},
531 SearchVals: [][]byte{[]byte(`"baz"`)},
532 },
533 expectedFind: true,
534 }, {
535 json: `{"foo": {"foo": {"bar": "baz"}}}`,
536 query: query{
537 SearchPath: [][]byte{[]byte("foo"), []byte("bar")},
538 SearchVals: [][]byte{[]byte(`"baz"`)},
539 },
540 expectedFind: false,
541 }}
542
543 for _, tt := range tCases {
544 t.Run(tt.json, func(t *testing.T) {
545 p := &parserState{}
546 p.consumeAny([]byte(tt.json), []query{tt.query}, 0)
547 if tt.expectedFind != p.querySatisfied {
548 t.Errorf("expectedFind: %v, got: %v", tt.expectedFind, p.querySatisfied)
549 }
550 })
551 }
552 }
553
554 func TestConsumeObject(t *testing.T) {
555 tCases := []struct {
556 name string
557 data string
558 expected int
559 }{
560 {"empty object", `}`, 1},
561 {"object", `"a":"b"}`, 8},
562 {"panic found with fuzz", "\"\":0", 0},
563 }
564
565 p := &parserState{}
566 for _, tt := range tCases {
567 t.Run(tt.name, func(t *testing.T) {
568 got := p.consumeObject([]byte(tt.data), nil, 1)
569 if got != tt.expected {
570 t.Errorf("expected: %v, got: %v", tt.expected, got)
571 }
572 })
573 }
574 }
575
576 func TestConsumeConst(t *testing.T) {
577 tCases := []struct {
578 b string
579 cnst string
580 expect int
581 inspect int
582 }{
583 {"", "", 0, 0},
584 {"", "true", 0, 0},
585 {"true", "", 0, 0},
586 {"t", "true", 0, 1},
587 {"tr", "true", 0, 2},
588 {"tru", "true", 0, 3},
589 {"true", "true", 4, 4},
590 {"truex", "true", 4, 4},
591 }
592
593 for _, tt := range tCases {
594 p := &parserState{}
595 t.Run(tt.b+" -- "+tt.cnst, func(t *testing.T) {
596 got := p.consumeConst([]byte(tt.b), []byte(tt.cnst))
597 if got != tt.expect {
598 t.Errorf("expected: %v, got %v", tt.expect, got)
599 }
600 if p.ib != tt.inspect {
601 t.Errorf("expected to inspect: %v, got %v", tt.inspect, p.ib)
602 }
603 })
604 }
605 }
606
607 // Truncate inputs at each possible index and test if decoder parses
608 // the truncated part successfully.
609 func testTruncating(t *testing.T, jsonString string) {
610 t.Helper()
611 p := &parserState{}
612 for i := 1; i <= len(jsonString); i++ {
613 b := scan.Bytes(jsonString[:i])
614 b.TrimRWS()
615 p.reset()
616 _ = p.consumeAny(b, nil, 0)
617 if p.ib != len(b) {
618 t.Errorf("truncated positives should be fully parsed %v \n"+
619 "got: %d want: %d", string(b), p.ib, len(b))
620 }
621 }
622 }
623
624 func TestPositives(t *testing.T) {
625 for _, tt := range positives {
626 testTruncating(t, tt.json)
627 }
628 }
629
630 func TestPositivesCompacted(t *testing.T) {
631 for _, tt := range positives {
632 if !tt.stdlib {
633 continue
634 }
635 buf := &bytes.Buffer{}
636 if err := json.Compact(buf, []byte(tt.json)); err != nil {
637 t.Errorf("Compact should always be successful: %s %s", tt.json, err)
638 }
639 testTruncating(t, buf.String())
640 }
641 }
642
643 func TestPositivesIndented(t *testing.T) {
644 indents := [][2]string{
645 {"", " "},
646 {" ", " "},
647 {" ", "\t"},
648 {"\t", "\t"},
649 {"\t", " \t"},
650 {"", "\r\n"},
651 {"", " \r\n"},
652 }
653 for _, tt := range positives {
654 if !tt.stdlib {
655 continue
656 }
657 for _, indent := range indents {
658 buf := &bytes.Buffer{}
659 if err := json.Indent(buf, []byte(tt.json), indent[0], indent[1]); err != nil {
660 t.Errorf("Indent should always be successful: %s %s", tt.json, err)
661 }
662 testTruncating(t, buf.String())
663 }
664 }
665 }
666
667 func TestNegatives(t *testing.T) {
668 p := &parserState{}
669 for _, tt := range negatives {
670 t.Run(tt.name, func(t *testing.T) {
671 p.reset()
672 got := p.consumeAny([]byte(tt.json), nil, 0)
673 if got != tt.expectParse {
674 t.Errorf("unexpected parsed length got: %d want:%d", got, tt.expectParse)
675 }
676 if p.ib != tt.expectInspect {
677 t.Errorf("unexpected inspected length got: %d want:%d\nin:%s", p.ib, tt.expectInspect, tt.json)
678 }
679 })
680 }
681 }
682
683 func TestMaxRecursion(t *testing.T) {
684 tCases := []struct {
685 maxRecursion int
686 input string
687 expectParsed int
688 expectInspected int
689 }{
690 {0, `[]`, 2, 2},
691 {0, `[[[]]]`, 6, 6},
692 {0, strings.Repeat("[", 10000) + strings.Repeat("]", 10000), 20000, 20000},
693 {3, `[[[[[]]]]]`, 1, 4}, // max recursion is 3 so we need to inspect 4 opening brackets
694 }
695 for _, tt := range tCases {
696 tname := tt.input
697 if len(tname) > 10 {
698 tname = tname[:10] + "..."
699 }
700 t.Run(tname, func(t *testing.T) {
701 p := &parserState{
702 maxRecursion: tt.maxRecursion,
703 }
704 got := p.consumeAny([]byte(tt.input), nil, 0)
705 if got != tt.expectParsed {
706 t.Errorf("parsed: got: %d expected: %d", got, tt.expectParsed)
707 }
708 if p.ib != tt.expectInspected {
709 t.Errorf("inspected: got: %d expected: %d", p.ib, tt.expectInspected)
710 }
711 })
712 }
713 }
714
715 func TestStack(t *testing.T) {
716 tCases := []struct {
717 name string
718 data string
719 expected string
720 }{
721 {"empty", ` `, ""},
722 {"a string", `"abc"`, ""},
723 {"an int", `123`, ""},
724 {"true", `true`, ""},
725 {"false", `false`, ""},
726 // Input must be an incomplete JSON because the stack is popped otherwise.
727 {"arr", `[`, "["},
728 // Put a § between each segment of the stack.
729 {"arrr", `[[`, "[§["},
730 {"arrrr", `[[[`, "[§[§["},
731 {"arrr popped once", `[[[]`, "[§["},
732 {"obj", `{`, ""},
733 {"obj key", `{"abc":1`, "abc"},
734 {"obj key twice", `{"abc":{"def":1`, "abc§def"},
735 {"obj key twice but popped", `{"abc":{"def":1}`, "abc"},
736 {"obj key twice and arr", `{"abc":{"def":[`, "abc§def§["},
737 {"hacky", `{"abc":{"def[":`, "abc§def["},
738 }
739
740 join := func(bs [][]byte) string {
741 ret := make([]string, 0, len(bs))
742 for _, b := range bs {
743 ret = append(ret, string(b))
744 }
745 return strings.Join(ret, "§")
746 }
747 for _, tt := range tCases {
748 t.Run(tt.name, func(t *testing.T) {
749 p := &parserState{}
750 p.consumeAny([]byte(tt.data), []query{{}}, 0)
751 if got := join(p.currPath); got != tt.expected {
752 t.Errorf("expected: %s, got: %s", tt.expected, got)
753 }
754 })
755 }
756 }
757
758 func TestCurrPathBounded(t *testing.T) {
759 // currPath is bounded to 128.
760 count := 129
761 // input has to be an incomplete json, so that currPath does not get popped.
762 input := []byte(strings.Repeat("[", count))
763
764 for i := 0; i < 100; i++ {
765 Parse(QueryGeo, input)
766 // It's not guaranteed that p is the same parser object used by the
767 // Parse call above. Reason: go runs tests packages concurrently. If
768 // another package calls Parse in tests, that can interfere with parserPool.
769 // Running the test several times in loop mitigates that.
770 p := parserPool.Get().(*parserState)
771 if len(p.currPath) > 128 {
772 t.Errorf("expected currPath be purged if >128")
773 }
774 }
775 }
776
777 var sample = []byte(`{"type":"Feature","fruit":[{},{"dummy":"data","another field":[false,null]},true,false],"size":"Large","color":"Red"}`)
778
779 func BenchmarkParse(b *testing.B) {
780 b.ReportAllocs()
781 for b.Loop() {
782 _, _, _, query := Parse(QueryGeo, sample)
783 if !query {
784 b.Error("query should be satisfied")
785 }
786 }
787 }
788
789 func BenchmarkJSONStdlibDecoder(b *testing.B) {
790 b.ReportAllocs()
791 for b.Loop() {
792 d := json.NewDecoder(bytes.NewReader(sample))
793 for {
794 _, err := d.Token()
795 if err != nil {
796 break
797 }
798 }
799 }
800 }
801 func BenchmarkJSONOurParser(b *testing.B) {
802 b.ReportAllocs()
803 for b.Loop() {
804 p := &parserState{}
805 p.consumeAny(sample, nil, 0)
806 }
807 }
808
809 func FuzzJson(f *testing.F) {
810 for _, p := range positives {
811 f.Add([]byte(p.json), true)
812 }
813 p := &parserState{}
814 f.Fuzz(func(t *testing.T, data []byte, reset bool) {
815 if reset {
816 p.reset()
817 }
818 p.consumeString(data)
819 p.consumeNumber(data)
820 p.consumeArray(data, nil, 1)
821 p.consumeObject(data, nil, 1)
822 p.consumeAny(data, nil, 1)
823 })
824 }