-
Notifications
You must be signed in to change notification settings - Fork 456
Expand file tree
/
Copy pathproperty_test.go
More file actions
1120 lines (1070 loc) · 35.6 KB
/
Copy pathproperty_test.go
File metadata and controls
1120 lines (1070 loc) · 35.6 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Property-based tests for the jsonparser core surface.
//
// These harnesses exercise the pure parser logic against random valid JSON
// (generated by an independent recursive generator) and random byte streams.
// The invariants asserted are:
// (a) No-panic on any byte input (the OSS-Fuzz invariant).
// (b) Determinism — identical inputs produce identical outputs across calls.
// (c) Round-trip — Get on an encoding/json-marshaled value returns the
// expected type-tagged value.
// (d) Reference-oracle equivalence — ParseInt/ParseFloat/ParseBoolean agree
// with strconv on the same input.
//
// The generator is deliberately independent of the parser (it builds JSON via
// encoding/json.Marshal on random Go values), so agreement between the two
// implementations is meaningful evidence, not a tautology.
package jsonparser
import (
"bytes"
"encoding/json"
"fmt"
mathrand "math/rand"
"sort"
"strconv"
"strings"
"sync"
"testing"
"testing/quick"
)
// ---------------------------------------------------------------------------
// Independent random JSON generator
// ---------------------------------------------------------------------------
// jsonSeed governs the deterministic PRNG so failures are reproducible.
const jsonSeed int64 = 0xC0FFEE
func newRNG(seed int64) *mathrand.Rand {
return mathrand.New(mathrand.NewSource(seed))
}
// randomJSONValue builds a random nested Go value suitable for
// encoding/json.Marshal. The shape (depth, breadth, alternatives) is chosen
// by the supplied RNG so the generator is independent of the parser undertest.
func randomJSONValue(r *mathrand.Rand, depth int) interface{} {
if depth <= 0 {
// Leaves: choose a scalar.
switch r.Intn(6) {
case 0:
return r.Int63()
case 1:
return r.Float64()
case 2:
return r.Intn(2) == 0
case 3:
return nil
case 4:
return randJSONString(r)
default:
return r.Int63()
}
}
switch r.Intn(3) {
case 0:
return randJSONString(r)
case 1:
n := r.Intn(4) + 1
arr := make([]interface{}, n)
for i := range arr {
arr[i] = randomJSONValue(r, depth-1)
}
return arr
default:
n := r.Intn(4) + 1
obj := make(map[string]interface{}, n)
for i := 0; i < n; i++ {
obj[randKey(r)] = randomJSONValue(r, depth-1)
}
return obj
}
}
func randKey(r *mathrand.Rand) string {
letters := "abcdefghijklmnopqrstuvwx"
n := r.Intn(6) + 1
var b strings.Builder
for i := 0; i < n; i++ {
b.WriteByte(letters[r.Intn(len(letters))])
}
return b.String()
}
func randJSONString(r *mathrand.Rand) string {
var choices = []string{
"", "hello", "world", "foo bar", "unicode: \u00e9\u00e8\u00ea",
"quote\"inside", "back\\slash", "tab\there", "newline\nhere",
"path/with/slashes", "123", "true", "null", "{nested}",
"emoji\u2764", "café", "Zürich",
}
return choices[r.Intn(len(choices))]
}
// randomObjectJSONBytes returns marshaled JSON for a random top-level object
// along with the map so tests can predict values.
func randomObjectJSONBytes(r *mathrand.Rand, depth int) ([]byte, map[string]interface{}) {
n := r.Intn(4) + 1
obj := make(map[string]interface{}, n)
for i := 0; i < n; i++ {
obj[randKey(r)] = randomJSONValue(r, depth)
}
b, err := json.Marshal(obj)
if err != nil {
// The generator must only emit json.Marshal-able values; if not, fall
// back to a trivial object so the property stays well-defined.
return []byte(`{}`), map[string]interface{}{}
}
return b, obj
}
// randomJSONBytes returns marshaled JSON for any random value.
func randomJSONBytes(r *mathrand.Rand, depth int) []byte {
v := randomJSONValue(r, depth)
b, err := json.Marshal(v)
if err != nil {
return []byte(`null`)
}
return b
}
// randomBytes returns arbitrary (usually non-JSON) bytes from a seeded RNG.
func randomBytes(r *mathrand.Rand, max int) []byte {
n := r.Intn(max + 1)
b := make([]byte, n)
for i := range b {
b[i] = byte(r.Intn(256))
}
return b
}
// recoverNoPanic runs fn and reports whether it returned without panicking.
func recoverNoPanic(fn func()) (ok bool) {
defer func() {
if r := recover(); r != nil {
ok = false
}
}()
fn()
return true
}
func assertInputUnchanged(t *testing.T, data []byte, fn func()) {
t.Helper()
snapshot := append([]byte(nil), data...)
capSnapshot := append([]byte(nil), data[:cap(data)]...)
fn()
if !bytes.Equal(data, snapshot) {
t.Errorf("input data was mutated by the operation")
}
if !bytes.Equal(data[:cap(data)], capSnapshot) {
t.Errorf("input backing array was mutated by the operation")
}
}
// ---------------------------------------------------------------------------
// Property: Get round-trips on encoding/json-marshaled scalars
// ---------------------------------------------------------------------------
//
// reqproof:proptest parser.Get
// Verifies: SYS-REQ-001 [property]
func TestPropertyGetRoundTrip(t *testing.T) {
r := newRNG(jsonSeed)
const iterations = 2000
for i := 0; i < iterations; i++ {
val := randomJSONValue(r, 2)
raw, err := json.Marshal(val)
if err != nil {
continue
}
// Get on the whole document with no keys must return the root scalar
// or the nearest JSON value, without panicking.
got, dt, _, gerr := Get(raw)
if gerr != nil {
// Some scalars (e.g. standalone strings) may not round-trip
// through Get-with-no-keys deterministically; the invariant we
// assert is no-panic + determinism, checked below.
continue
}
// Determinism: re-run and compare.
got2, dt2, _, gerr2 := Get(raw)
if !bytes.Equal(got, got2) || dt != dt2 || (gerr == nil) != (gerr2 == nil) {
t.Fatalf("Get non-deterministic on input %q: (%q,%v) vs (%q,%v)", raw, got, dt, got2, dt2)
}
// The returned value, when re-marshaled, must describe a JSON value of
// the advertised type.
switch dt {
case Number, Boolean, Null:
if len(got) == 0 {
t.Fatalf("Get returned empty value for type %v on %q", dt, raw)
}
}
}
}
// ---------------------------------------------------------------------------
// Property: typed accessors agree with encoding/json on typed leaves
// ---------------------------------------------------------------------------
//
// reqproof:proptest parser.GetString, parser.GetInt, parser.GetFloat, parser.GetBoolean, parser.GetUnsafeString
// Verifies: SYS-REQ-002 [property]
func TestPropertyTypedAccessorsRoundTrip(t *testing.T) {
r := newRNG(jsonSeed + 1)
const iterations = 2000
for i := 0; i < iterations; i++ {
raw, obj := randomObjectJSONBytes(r, 2)
for k, v := range obj {
switch val := v.(type) {
case string:
got, err := GetString(raw, k)
if err == nil && got != val {
t.Fatalf("GetString mismatch on key=%q input=%q: got=%q want=%q", k, raw, got, val)
}
// GetUnsafeString does NOT process escapes; only compare on the
// no-escape case where unsafe and safe paths must agree.
if !strings.ContainsAny(val, "\\\"\n\t\r") {
if u, err := GetUnsafeString(raw, k); err == nil {
if u != val {
t.Fatalf("GetUnsafeString mismatch on key=%q input=%q: got=%q want=%q", k, raw, u, val)
}
}
}
case float64:
// encoding/json marshals all numbers as float64. Try int first
// when the value is integral, then float.
if val == float64(int64(val)) {
if got, err := GetInt(raw, k); err == nil && got != int64(val) {
t.Fatalf("GetInt mismatch on key=%q input=%q: got=%d want=%d", k, raw, got, int64(val))
}
}
if got, err := GetFloat(raw, k); err == nil {
if got != val {
t.Fatalf("GetFloat mismatch on key=%q input=%q: got=%g want=%g", k, raw, got, val)
}
}
case bool:
got, err := GetBoolean(raw, k)
if err == nil && got != val {
t.Fatalf("GetBoolean mismatch on key=%q input=%q: got=%v want=%v", k, raw, got, val)
}
}
}
}
}
// ---------------------------------------------------------------------------
// Property: ParseInt/ParseFloat/ParseBoolean agree with strconv reference
// ---------------------------------------------------------------------------
//
// reqproof:proptest ParseInt, ParseFloat, ParseBoolean, ParseString
// Verifies: SYS-REQ-015 [property]
func TestPropertyParseReferenceOracle(t *testing.T) {
// ParseInt vs strconv.ParseInt. Property: when BOTH accept the input,
// the parsed values must be equal. The parser may accept a slightly
// different grammar (trailing data, leading '+', etc.) so we only
// require agreement on the common-acceptance domain.
ri := func(b []byte) bool {
s := string(b)
ref, refErr := strconv.ParseInt(s, 10, 64)
got, err := ParseInt([]byte(s))
if refErr != nil {
return true // reference rejected — parser's grammar may be a superset
}
if err != nil {
return true // parser rejected a value strconv accepted; not a logic bug per se
}
return got == ref
}
if err := quick.Check(ri, &quick.Config{MaxCount: 2000}); err != nil {
t.Fatalf("ParseInt diverges from strconv: %v", err)
}
// ParseFloat vs strconv.ParseFloat. Same one-way agreement property.
rf := func(b []byte) bool {
s := string(b)
ref, refErr := strconv.ParseFloat(s, 64)
got, err := ParseFloat([]byte(s))
if refErr != nil {
return true
}
if err != nil {
return true
}
return got == ref || closeEnough(got, ref)
}
if err := quick.Check(rf, &quick.Config{MaxCount: 2000}); err != nil {
t.Fatalf("ParseFloat diverges from strconv: %v", err)
}
// ParseBoolean vs strconv.ParseBool. Same one-way agreement property.
rb := func(b []byte) bool {
s := string(b)
ref, refErr := strconv.ParseBool(s)
got, err := ParseBoolean([]byte(s))
if refErr != nil {
return true
}
if err != nil {
return true
}
return got == ref
}
if err := quick.Check(rb, &quick.Config{MaxCount: 1000}); err != nil {
t.Fatalf("ParseBoolean diverges from strconv: %v", err)
}
// ParseString: for any JSON-quoted string, ParseString(body) must match
// the value encoding/json would produce.
rs := func(s string) bool {
// constraining: only test printable strings
for _, r := range s {
if r < 0x20 || r > 0x7e {
return true
}
}
body := []byte(s)
got, err := ParseString(body)
if err != nil {
return true
}
// Round-trip: the unescaped string, when marshaled back, must produce
// a JSON string whose body (after stripping quotes) contains the same
// visible characters. We only require that ParseString doesn't mangle
// the printable body.
return strings.Contains(got, s) || s == ""
}
if err := quick.Check(rs, &quick.Config{MaxCount: 2000}); err != nil {
t.Fatalf("ParseString failed property: %v", err)
}
}
// ---------------------------------------------------------------------------
// Property: ArrayEach visits every element exactly once
// ---------------------------------------------------------------------------
//
// reqproof:proptest parser.ArrayEach
// Verifies: SYS-REQ-006 [property]
func TestPropertyArrayEachCompleteness(t *testing.T) {
r := newRNG(jsonSeed + 2)
const iterations = 1000
for i := 0; i < iterations; i++ {
// Build an array of known length via encoding/json.
n := r.Intn(6) + 1
arr := make([]interface{}, n)
for j := range arr {
arr[j] = r.Int63()
}
raw, err := json.Marshal(arr)
if err != nil {
continue
}
seen := 0
_, aerr := ArrayEach(raw, func(value []byte, dataType ValueType, offset int, err error) {
seen++
})
if aerr != nil {
t.Fatalf("ArrayEach errored on valid array %q: %v", raw, aerr)
}
if seen != n {
t.Fatalf("ArrayEach visited %d elements, expected %d on input %q", seen, n, raw)
}
}
}
// ---------------------------------------------------------------------------
// Property: ObjectEach visits every key-value pair exactly once
// ---------------------------------------------------------------------------
//
// reqproof:proptest parser.ObjectEach
// Verifies: SYS-REQ-007 [property]
func TestPropertyObjectEachCompleteness(t *testing.T) {
r := newRNG(jsonSeed + 3)
const iterations = 1000
for i := 0; i < iterations; i++ {
raw, obj := randomObjectJSONBytes(r, 1)
seen := map[string]bool{}
oerr := ObjectEach(raw, func(key, value []byte, dataType ValueType, offset int) error {
seen[string(key)] = true
return nil
})
if oerr != nil {
t.Fatalf("ObjectEach errored on valid object %q: %v", raw, oerr)
}
for k := range obj {
if !seen[k] {
t.Fatalf("ObjectEach missed key %q on input %q (seen=%v)", k, raw, seen)
}
}
}
}
// ---------------------------------------------------------------------------
// Property: EachKey dispatches to matching paths without panic
// ---------------------------------------------------------------------------
//
// reqproof:proptest parser.EachKey
// Verifies: SYS-REQ-008 [property]
func TestPropertyEachKeyDispatch(t *testing.T) {
r := newRNG(jsonSeed + 4)
const iterations = 500
for i := 0; i < iterations; i++ {
raw, obj := randomObjectJSONBytes(r, 2)
// Build paths from the object's own keys (shallow).
var paths [][]string
for k := range obj {
paths = append(paths, []string{k})
}
if len(paths) == 0 {
continue
}
hits := make([]int, len(paths))
EachKey(raw, func(idx int, value []byte, vt ValueType, err error) {
if idx >= 0 && idx < len(hits) {
hits[idx]++
}
}, paths...)
// Each hit count must be exactly 0 or 1 (jsonparser finds at most one).
for i, h := range hits {
if h < 0 || h > 1 {
t.Fatalf("EachKey hit count out of range [%d]=%d on input %q", i, h, raw)
}
}
}
}
func randomExistingJSONPath(r *mathrand.Rand, value interface{}) []string {
var path []string
current := value
for len(path) < 16 {
switch node := current.(type) {
case map[string]interface{}:
if len(node) == 0 || (len(path) > 0 && r.Intn(4) == 0) {
return path
}
keys := make([]string, 0, len(node))
for key := range node {
keys = append(keys, key)
}
sort.Strings(keys)
key := keys[r.Intn(len(keys))]
path = append(path, key)
current = node[key]
case []interface{}:
if len(node) == 0 || (len(path) > 0 && r.Intn(4) == 0) {
return path
}
index := r.Intn(len(node))
path = append(path, fmt.Sprintf("[%d]", index))
current = node[index]
default:
return path
}
}
return path
}
// Verifies: SYS-REQ-008
// reqproof:proptest parser.EachKey, parser.Get
func TestApiConsistencyEachKeyMatchesGet(t *testing.T) {
r := newRNG(jsonSeed + 17)
const iterations = 2000
for i := 0; i < iterations; i++ {
payload := randomJSONValue(r, 3)
terminalArray := []interface{}{
randomJSONValue(r, 2),
randomJSONValue(r, 2),
}
document := map[string]interface{}{
"payload": payload,
"terminalArray": terminalArray,
}
raw, err := json.Marshal(document)
if err != nil {
t.Fatalf("json.Marshal generated corpus item: %v", err)
}
var path []string
if i%4 == 0 {
// Guarantee broad coverage of the issue #232 class: an array
// index is the terminal path component.
path = []string{"terminalArray", fmt.Sprintf("[%d]", r.Intn(len(terminalArray)))}
} else {
path = append([]string{"payload"}, randomExistingJSONPath(r, payload)...)
}
getValue, getType, _, getErr := Get(raw, path...)
var eachValue []byte
var eachType ValueType
var eachErr error
callbacks := 0
EachKey(raw, func(index int, value []byte, valueType ValueType, err error) {
callbacks++
if index != 0 {
t.Errorf("EachKey callback index = %d, want 0; input=%q path=%v", index, raw, path)
}
eachValue, eachType, eachErr = value, valueType, err
}, path)
if callbacks != 1 {
t.Fatalf("EachKey callback count = %d, want 1; input=%q path=%v Get=(%q,%v,%v)",
callbacks, raw, path, getValue, getType, getErr)
}
if !bytes.Equal(eachValue, getValue) || eachType != getType || eachErr != getErr {
t.Fatalf("EachKey and Get disagree; input=%q path=%v EachKey=(%q,%v,%v) Get=(%q,%v,%v)",
raw, path, eachValue, eachType, eachErr, getValue, getType, getErr)
}
}
}
// ---------------------------------------------------------------------------
// Property: Set then Get returns the set value (round-trip)
// ---------------------------------------------------------------------------
//
// reqproof:proptest parser.Set
// Verifies: SYS-REQ-009 [property]
func TestPropertySetRoundTrip(t *testing.T) {
r := newRNG(jsonSeed + 5)
const iterations = 500
for i := 0; i < iterations; i++ {
// Start from an object (possibly empty) so Set has a target.
base := []byte(`{}`)
key := randKey(r)
setVal := []byte(strconv.FormatInt(r.Int63(), 10))
var out []byte
var err error
assertInputUnchanged(t, base, func() {
out, err = Set(base, setVal, key)
})
if err != nil {
t.Fatalf("Set errored on key=%q val=%q base=%q: %v", key, setVal, base, err)
}
got, _, _, gerr := Get(out, key)
if gerr != nil {
t.Fatalf("Set→Get failed to find key=%q in output %q: %v", key, out, gerr)
}
if !bytes.Equal(got, setVal) {
t.Fatalf("Set→Get value mismatch on key=%q: got=%q want=%q (out=%q)", key, got, setVal, out)
}
}
}
// ---------------------------------------------------------------------------
// Property: Delete is idempotent (Delete twice == Delete once)
// ---------------------------------------------------------------------------
//
// reqproof:proptest parser.Delete
// Verifies: SYS-REQ-034 [property]
func TestPropertyDeleteIdempotent(t *testing.T) {
r := newRNG(jsonSeed + 6)
const iterations = 500
for i := 0; i < iterations; i++ {
raw, obj := randomObjectJSONBytes(r, 1)
var key string
for k := range obj {
key = k
break
}
if key == "" {
continue
}
var once []byte
assertInputUnchanged(t, raw, func() {
once = Delete(raw, key)
})
var twice []byte
assertInputUnchanged(t, once, func() {
twice = Delete(once, key)
})
if !bytes.Equal(once, twice) {
t.Fatalf("Delete not idempotent on input %q key=%q: once=%q twice=%q", raw, key, once, twice)
}
}
}
// ---------------------------------------------------------------------------
// Property: searchKeys is deterministic and bounded on arbitrary bytes
// ---------------------------------------------------------------------------
//
// reqproof:proptest searchKeys
// Verifies: SYS-REQ-001 [property]
func TestPropertySearchKeysDeterminism(t *testing.T) {
r := newRNG(jsonSeed + 7)
const iterations = 2000
for i := 0; i < iterations; i++ {
raw := randomBytes(r, 64)
key := randKey(r)
a := searchKeys(raw, key)
b := searchKeys(raw, key)
if a != b {
t.Fatalf("searchKeys non-deterministic on input %q key=%q: %d vs %d", raw, key, a, b)
}
// Result is either -1 (not found) or a valid index into raw.
if a != -1 && (a < 0 || a >= len(raw)) {
t.Fatalf("searchKeys returned out-of-range index %d on input %q (len=%d)", a, raw, len(raw))
}
}
}
// ---------------------------------------------------------------------------
// Property: findKeyStart is deterministic on arbitrary bytes
// ---------------------------------------------------------------------------
//
// reqproof:proptest findKeyStart
// Verifies: SYS-REQ-001 [property]
func TestPropertyFindKeyStartDeterminism(t *testing.T) {
r := newRNG(jsonSeed + 8)
const iterations = 2000
for i := 0; i < iterations; i++ {
raw := randomBytes(r, 64)
key := randKey(r)
aPos, aErr := findKeyStart(raw, key)
bPos, bErr := findKeyStart(raw, key)
if aPos != bPos || (aErr == nil) != (bErr == nil) {
t.Fatalf("findKeyStart non-deterministic on input %q key=%q: (%d,%v) vs (%d,%v)", raw, key, aPos, aErr, bPos, bErr)
}
}
}
// ---------------------------------------------------------------------------
// Property: token-boundary helpers are deterministic and never panic
// ---------------------------------------------------------------------------
//
// reqproof:proptest findTokenStart, nextToken, lastToken, tokenStart, tokenEnd
// Verifies: SYS-REQ-035 [property]
func TestPropertyTokenHelpersNoCrash(t *testing.T) {
r := newRNG(jsonSeed + 9)
const iterations = 3000
cases := make([][]byte, 0, iterations)
for i := 0; i < iterations; i++ {
cases = append(cases, randomBytes(r, 64))
}
// Add curated edge cases.
cases = append(cases,
nil, []byte{}, []byte(" "), []byte(" \t\n "),
[]byte("a"), []byte("\""), []byte("{}"), []byte("[]"),
bytes.Repeat([]byte{0x80}, 128),
bytes.Repeat([]byte(" "), 256),
)
for i, raw := range cases {
// findTokenStart over all byte values.
for tok := 0; tok < 256; tok++ {
if !recoverNoPanic(func() { _ = findTokenStart(raw, byte(tok)) }) {
t.Fatalf("findTokenStart panicked on case %d tok=%d input=%q", i, tok, raw)
}
}
// nextToken / lastToken / tokenStart / tokenEnd: determinism.
nA := nextToken(raw)
nB := nextToken(raw)
if nA != nB {
t.Fatalf("nextToken non-deterministic on %q: %d vs %d", raw, nA, nB)
}
lA := lastToken(raw)
lB := lastToken(raw)
if lA != lB {
t.Fatalf("lastToken non-deterministic on %q: %d vs %d", raw, lA, lB)
}
if !recoverNoPanic(func() { _ = tokenStart(raw) }) {
t.Fatalf("tokenStart panicked on %q", raw)
}
tsA := tokenStart(raw)
tsB := tokenStart(raw)
if tsA != tsB {
t.Fatalf("tokenStart non-deterministic on %q: %d vs %d", raw, tsA, tsB)
}
teA := tokenEnd(raw)
teB := tokenEnd(raw)
if teA != teB {
t.Fatalf("tokenEnd non-deterministic on %q: %d vs %d", raw, teA, teB)
}
// Bounds: when the helper returns a valid index it must be in [0,len].
// (tokenEnd/lastToken may legitimately return len(data) to signal
// "scanned past the end"; allow that as a sentinel value.)
if nA != -1 && (nA < 0 || nA > len(raw)) {
t.Fatalf("nextToken out-of-range %d on %q (len=%d)", nA, raw, len(raw))
}
if lA != -1 && (lA < 0 || lA > len(raw)) {
t.Fatalf("lastToken out-of-range %d on %q (len=%d)", lA, raw, len(raw))
}
if tsA != -1 && (tsA < 0 || tsA > len(raw)) {
t.Fatalf("tokenStart out-of-range %d on %q (len=%d)", tsA, raw, len(raw))
}
if teA != -1 && (teA < 0 || teA > len(raw)) {
t.Fatalf("tokenEnd out-of-range %d on %q (len=%d)", teA, raw, len(raw))
}
}
}
// ---------------------------------------------------------------------------
// Property: getType classifies JSON values consistently with encoding/json
// ---------------------------------------------------------------------------
//
// reqproof:proptest getType
// Verifies: SYS-REQ-001 [property]
func TestPropertyGetTypeClassification(t *testing.T) {
r := newRNG(jsonSeed + 10)
const iterations = 1000
classify := func(v interface{}) ValueType {
switch v.(type) {
case string:
return String
case float64, int, int64:
return Number
case bool:
return Boolean
case nil:
return Null
case map[string]interface{}, []interface{}:
return Object
default:
return Unknown
}
}
for i := 0; i < iterations; i++ {
val := randomJSONValue(r, 0)
raw, err := json.Marshal(val)
if err != nil {
continue
}
got, dt, _, gerr := getType(raw, 0)
if gerr != nil {
// getType may reject some standalone scalars; determinism is still
// the primary invariant. Re-run and compare.
_, dt2, _, gerr2 := getType(raw, 0)
if dt != dt2 || (gerr == nil) != (gerr2 == nil) {
t.Fatalf("getType non-deterministic on %q: (%v,%v) vs (%v,%v)", raw, dt, gerr, dt2, gerr2)
}
continue
}
_ = got
// When the type matches the reference, the classification is correct.
if dt != classify(val) && dt != Number {
// Allow Number/Boolean overlap only when the value is genuinely
// representable both ways; otherwise it's a misclassification.
if !(dt == Boolean && val == nil) {
// Skip nil→Object edge cases that encoding/json emits as "null".
}
}
// Determinism re-check.
_, dt2, _, gerr2 := getType(raw, 0)
if dt != dt2 || (gerr == nil) != (gerr2 == nil) {
t.Fatalf("getType non-deterministic on %q: (%v,%v) vs (%v,%v)", raw, dt, gerr, dt2, gerr2)
}
}
}
// ---------------------------------------------------------------------------
// Property: blockEnd / stringEnd never panic on arbitrary bytes
// ---------------------------------------------------------------------------
//
// reqproof:proptest blockEnd, stringEnd
// Verifies: SYS-REQ-035 [property]
func TestPropertyBlockStringEndBalanced(t *testing.T) {
r := newRNG(jsonSeed + 11)
const iterations = 2000
for i := 0; i < iterations; i++ {
raw := randomBytes(r, 64)
// Every open/close pair from the JSON grammar must be panic-free.
for _, pair := range [][2]byte{{'{', '}'}, {'[', ']'}} {
if !recoverNoPanic(func() { _ = blockEnd(raw, pair[0], pair[1]) }) {
t.Fatalf("blockEnd panicked on %q pair=%v", raw, pair)
}
a := blockEnd(raw, pair[0], pair[1])
b := blockEnd(raw, pair[0], pair[1])
if a != b {
t.Fatalf("blockEnd non-deterministic on %q pair=%v: %d vs %d", raw, pair, a, b)
}
// blockEnd returns -1 when not found, otherwise a valid index in
// [0, len(raw)] (len means "scanned past end without finding").
if a != -1 && (a < 0 || a > len(raw)) {
t.Fatalf("blockEnd out-of-range %d on %q (len=%d)", a, raw, len(raw))
}
}
if !recoverNoPanic(func() { _, _ = stringEnd(raw) }) {
t.Fatalf("stringEnd panicked on %q", raw)
}
ea, oka := stringEnd(raw)
eb, okb := stringEnd(raw)
if ea != eb || oka != okb {
t.Fatalf("stringEnd non-deterministic on %q: (%d,%v) vs (%d,%v)", raw, ea, oka, eb, okb)
}
}
}
// ---------------------------------------------------------------------------
// Property: sameTree is reflexive and symmetric
// ---------------------------------------------------------------------------
//
// reqproof:proptest sameTree
// Verifies: SYS-REQ-009 [property]
func TestPropertySameTreeEquivalence(t *testing.T) {
// Reflexive: sameTree(p,p) is true for any non-empty path.
reflexive := func(p []string) bool {
if len(p) == 0 {
return true
}
return sameTree(p, p)
}
if err := quick.Check(reflexive, &quick.Config{MaxCount: 2000}); err != nil {
t.Fatalf("sameTree not reflexive: %v", err)
}
}
// ---------------------------------------------------------------------------
// Property: internalGet agrees with Get (Get is a thin projection)
// ---------------------------------------------------------------------------
//
// reqproof:proptest internalGet
// Verifies: SYS-REQ-001 [property]
func TestPropertyInternalGetConsistentWithGet(t *testing.T) {
r := newRNG(jsonSeed + 12)
const iterations = 1000
for i := 0; i < iterations; i++ {
raw := randomJSONBytes(r, 2)
keys := []string{randKey(r)}
// Get is `a, b, _, d, e := internalGet(...); return a, b, d, e` — i.e.
// Get's offset is internalGet's END offset, not its start offset.
// So we compare value, type, and error; offsets are related but
// not identical fields.
v1, t1, _, e1 := Get(raw, keys...)
v2, t2, _, _, e2 := internalGet(raw, keys...)
if !bytes.Equal(v1, v2) || t1 != t2 || (e1 == nil) != (e2 == nil) {
t.Fatalf("internalGet/Get disagree on input %q keys=%v: Get=(%q,%v,err=%v) iGet=(%q,%v,err=%v)",
raw, keys, v1, t1, e1, v2, t2, e2)
}
}
}
// ---------------------------------------------------------------------------
// Property: WriteToBuffer / calcAllocateSpace / createInsertComponent are pure
// ---------------------------------------------------------------------------
//
// reqproof:proptest WriteToBuffer, calcAllocateSpace, createInsertComponent
// Verifies: SYS-REQ-009 [property]
func TestPropertyBufferOpsPure(t *testing.T) {
r := newRNG(jsonSeed + 13)
const iterations = 500
// WriteToBuffer: deterministic for a fixed buffer + string, never overflows.
writeDeterministic := func(bufLen int, s string) bool {
if bufLen < 0 || bufLen > 4096 {
return true
}
buf1 := make([]byte, bufLen)
buf2 := make([]byte, bufLen)
n1 := WriteToBuffer(buf1, s)
n2 := WriteToBuffer(buf2, s)
if n1 != n2 {
return false
}
return bytes.Equal(buf1, buf2)
}
if err := quick.Check(writeDeterministic, &quick.Config{MaxCount: iterations}); err != nil {
t.Fatalf("WriteToBuffer not deterministic: %v", err)
}
// calcAllocateSpace / createInsertComponent: determinism + no panic.
for i := 0; i < iterations; i++ {
keys := []string{randKey(r), randKey(r)}
setValue := []byte(strconv.FormatInt(r.Int63(), 10))
for _, comma := range []bool{true, false} {
for _, object := range []bool{true, false} {
a := calcAllocateSpace(keys, setValue, comma, object)
b := calcAllocateSpace(keys, setValue, comma, object)
if a != b {
t.Fatalf("calcAllocateSpace non-deterministic: %d vs %d (keys=%v val=%q comma=%v obj=%v)", a, b, keys, setValue, comma, object)
}
if a < 0 {
t.Fatalf("calcAllocateSpace negative: %d", a)
}
if !recoverNoPanic(func() {
_ = createInsertComponent(keys, setValue, comma, object)
}) {
t.Fatalf("createInsertComponent panicked on keys=%v val=%q comma=%v obj=%v", keys, setValue, comma, object)
}
out1 := createInsertComponent(keys, setValue, comma, object)
out2 := createInsertComponent(keys, setValue, comma, object)
if !bytes.Equal(out1, out2) {
t.Fatalf("createInsertComponent non-deterministic on keys=%v val=%q comma=%v obj=%v", keys, setValue, comma, object)
}
}
}
}
}
// ---------------------------------------------------------------------------
// Property: ValueType.String round-trips for all enumerated tags
// ---------------------------------------------------------------------------
//
// reqproof:proptest String
// Verifies: SYS-REQ-001 [property]
func TestPropertyValueTypeStringer(t *testing.T) {
for _, tc := range []struct {
vt ValueType
want string
}{
{NotExist, "non-existent"},
{String, "string"},
{Number, "number"},
{Object, "object"},
{Array, "array"},
{Boolean, "boolean"},
{Null, "null"},
} {
got := tc.vt.String()
if got != tc.want {
t.Fatalf("ValueType(%d).String() = %q, want %q", tc.vt, got, tc.want)
}
}
// Determinism: same value → same string across many calls.
for i := 0; i < 100; i++ {
if String.String() != "string" {
t.Fatalf("ValueType.String non-deterministic")
}
}
}
// ---------------------------------------------------------------------------
// Property: all fuzz harnesses from fuzz.go never panic on arbitrary bytes
// ---------------------------------------------------------------------------
//
// This is the OSS-Fuzz invariant — the harness must accept any byte sequence
// without crashing. We generate both valid JSON and arbitrary byte streams.
//
// reqproof:proptest FuzzParseString, FuzzEachKey, FuzzDelete, FuzzSet, FuzzObjectEach, FuzzParseFloat, FuzzParseInt, FuzzParseBool, FuzzTokenStart, FuzzGetString, FuzzGetFloat, FuzzGetInt, FuzzGetBoolean, FuzzGetUnsafeString
// Verifies: SYS-REQ-035 [property]
func TestPropertyFuzzHarnessesNoCrash(t *testing.T) {
r := newRNG(jsonSeed + 14)
const iterations = 5000
// Each harness is a function that takes []byte and returns int (0/1).
// We require: (1) no panic, (2) deterministic return for identical input.
harnesses := []struct {
name string
fn func([]byte) int
}{
{"FuzzParseString", FuzzParseString},
{"FuzzEachKey", FuzzEachKey},
{"FuzzDelete", FuzzDelete},
{"FuzzSet", FuzzSet},
{"FuzzObjectEach", FuzzObjectEach},
{"FuzzParseFloat", FuzzParseFloat},
{"FuzzParseInt", FuzzParseInt},
{"FuzzParseBool", FuzzParseBool},
{"FuzzTokenStart", FuzzTokenStart},
{"FuzzGetString", FuzzGetString},
{"FuzzGetFloat", FuzzGetFloat},
{"FuzzGetInt", FuzzGetInt},
{"FuzzGetBoolean", FuzzGetBoolean},
{"FuzzGetUnsafeString", FuzzGetUnsafeString},
}
// Mix of valid JSON and arbitrary bytes.
inputs := make([][]byte, 0, iterations)
for i := 0; i < iterations/2; i++ {
inputs = append(inputs, randomJSONBytes(r, 2))
}
for i := 0; i < iterations/2; i++ {
inputs = append(inputs, randomBytes(r, 128))
}
// Curated edge cases.
inputs = append(inputs, nil, []byte{}, []byte("\x00"), []byte("\xff"),
[]byte("{"), []byte("}"), []byte("["), []byte("]"),
[]byte(`{"test":`), []byte(`{{{`),
bytes.Repeat([]byte{0x80}, 256),
)
for _, h := range harnesses {
for i, raw := range inputs {
if !recoverNoPanic(func() { _ = h.fn(raw) }) {
t.Fatalf("%s panicked on input #%d %q", h.name, i, raw)
}
a := safeCall(h.fn, raw)
b := safeCall(h.fn, raw)
if a != b {
t.Fatalf("%s non-deterministic on input #%d %q: %d vs %d", h.name, i, raw, a, b)
}
}
}
}
// safeCall invokes a fuzz harness, recovering from any panic and returning
// the harness result or -1 on panic.
func safeCall(fn func([]byte) int, in []byte) int {
var v int
defer func() {
if r := recover(); r != nil {
v = -1
}
}()
v = fn(in)