Debian Codegraph @

decode_skip_grammar_test.go

raw
1 package json_test
2
3 import (
4 stdjson "encoding/json"
5 "errors"
6 "io"
7 "math/rand"
8 "reflect"
9 "strings"
10 "testing"
11 "unicode/utf8"
12
13 json "github.com/goccy/go-json"
14 )
15
16 // randomSkippedValue returns a random JSON value with white spaces, escapes and long strings anywhere, of up to
17 // depth levels.
18 func randomSkippedValue(r *rand.Rand, depth int) string {
19 space := func() string {
20 return []string{"", "", " ", "\n\t", " ", "\r\n "}[r.Intn(6)]
21 }
22 switch k := r.Intn(10); {
23 case depth > 0 && k < 2:
24 var b strings.Builder
25 b.WriteString("{" + space())
26 for i, n := 0, r.Intn(5); i < n; i++ {
27 if i > 0 {
28 b.WriteString("," + space())
29 }
30 b.WriteString(randomSkippedString(r) + space() + ":" + space() + randomSkippedValue(r, depth-1) + space())
31 }
32 return b.String() + "}"
33 case depth > 0 && k < 4:
34 var b strings.Builder
35 b.WriteString("[" + space())
36 for i, n := 0, r.Intn(5); i < n; i++ {
37 if i > 0 {
38 b.WriteString("," + space())
39 }
40 b.WriteString(randomSkippedValue(r, depth-1) + space())
41 }
42 return b.String() + "]"
43 case k < 6:
44 return randomSkippedString(r)
45 case k < 8:
46 return []string{"0", "-1", "12.5e-3", "1E+9", "99999999999999999999", "-0.0"}[r.Intn(6)]
47 }
48 return []string{"true", "false", "null"}[r.Intn(3)]
49 }
50
51 func randomSkippedString(r *rand.Rand) string {
52 var b strings.Builder
53 b.WriteByte('"')
54 for i, n := 0, r.Intn(90); i < n; i++ {
55 switch k := r.Intn(20); {
56 case k == 0:
57 b.WriteString([]string{`\"`, `\\`, `\/`, `\n`, `é`, `😀`, `\\\"`}[r.Intn(7)])
58 case k == 1:
59 b.WriteString([]string{"é", "あ", "{", "]", ":", ","}[r.Intn(6)])
60 default:
61 b.WriteByte(byte('a' + r.Intn(26)))
62 }
63 }
64 b.WriteByte('"')
65 return b.String()
66 }
67
68 // mutate changes a byte of s: it replaces, deletes or inserts one.
69 func mutate(r *rand.Rand, s string) string {
70 if s == "" {
71 return s
72 }
73 i := r.Intn(len(s))
74 chars := []byte(`{}[]:,"\ 0-1e.tfnx` + "\x00\x01")
75 c := chars[r.Intn(len(chars))]
76 switch r.Intn(3) {
77 case 0:
78 return s[:i] + string(c) + s[i+1:]
79 case 1:
80 return s[:i] + s[i+1:]
81 }
82 return s[:i] + string(c) + s[i:]
83 }
84
85 func TestSkipGrammar(t *testing.T) {
86 // A value which is skipped, as the one of a key which matches no field, is checked by the grammar of JSON as
87 // encoding/json checks it: long values, which span blocks, escapes and white spaces anywhere, and values made
88 // not valid by a change of a byte.
89 r := rand.New(rand.NewSource(1))
90 for i := 0; i < 20000; i++ {
91 v := randomSkippedValue(r, 1+r.Intn(4))
92 if r.Intn(2) == 0 {
93 v = mutate(r, v)
94 }
95 doc := `{"skip":` + v + `,"X":1}`
96 var got struct{ X int }
97 err := json.Unmarshal([]byte(doc), &got)
98 if want := stdjson.Valid([]byte(doc)); (err == nil) != want {
99 t.Fatalf("%q: got error %v, valid by encoding/json %v", doc, err, want)
100 }
101 if err == nil && got.X != 1 {
102 t.Fatalf("%q: decoded X %d", doc, got.X)
103 }
104 }
105 }
106
107 func TestSyntaxErrorMessages(t *testing.T) {
108 // A syntax error is the first one of the input, with the message and the offset of encoding/json, wherever it
109 // is: in a value which is decoded, in one which is skipped, or after the value.
110 r := rand.New(rand.NewSource(5))
111 for i := 0; i < 20000; i++ {
112 doc := mutate(r, `{"skip":`+randomSkippedValue(r, 1+r.Intn(3))+`,"X":`+randomSkippedValue(r, 1+r.Intn(3))+`}`)
113 for _, newValue := range []func() any{
114 func() any { return new(any) },
115 func() any { return new(struct{ X any }) },
116 } {
117 want := stdjson.Unmarshal([]byte(doc), newValue())
118 var wantSyntax *stdjson.SyntaxError
119 if !errors.As(want, &wantSyntax) {
120 continue
121 }
122 got := json.Unmarshal([]byte(doc), newValue())
123 var gotSyntax *json.SyntaxError
124 if !errors.As(got, &gotSyntax) || gotSyntax.Error() != wantSyntax.Error() || gotSyntax.Offset != wantSyntax.Offset {
125 t.Fatalf("%q:\n got %v ( %#v )\nwant %v at %d", doc, got, got, want, wantSyntax.Offset)
126 }
127 }
128 }
129 }
130
131 func TestStreamSyntaxErrorMessages(t *testing.T) {
132 // A syntax error of a value of a stream is the first one of the value, with the message and the offset in the
133 // whole input of encoding/json, and is returned by every Decode after it. The values before it are decoded,
134 // and the strings with escapes among them, which are decoded out of the buffer, keep their input.
135 docs := []string{
136 "1.,", "1. ", "1.", "-", "-a", "tru", "tru ", "truex", "nul,", `"abc`, `"a\q"`, "\"a\x00\"", "[1,2", `{"a":1`,
137 `{"a":[1}`, `[1 2]`, `{"a" 1}`, `{"a":1,}`, "1 2 [", "1 2 x", `"a" "b\`, "\x01", `[1,2]]`, "[01]", "01",
138 }
139 r := rand.New(rand.NewSource(7))
140 for i := 0; i < 10000; i++ {
141 docs = append(docs, randomSkippedValue(r, 1+r.Intn(3))+"\n"+`{"a\"b":"c\nd","X":`+randomSkippedValue(r, 1+r.Intn(3))+`}`+" "+
142 mutate(r, `{"skip":`+randomSkippedValue(r, 1+r.Intn(3))+`,"X":`+randomSkippedValue(r, 1+r.Intn(3))+`}`))
143 }
144 for _, doc := range docs {
145 for _, newValue := range []func() any{
146 func() any { return new(any) },
147 func() any { return new(struct{ X any }) },
148 } {
149 gd := json.NewDecoder(strings.NewReader(doc))
150 sd := stdjson.NewDecoder(strings.NewReader(doc))
151 for n := 0; ; n++ {
152 gotValue, wantValue := newValue(), newValue()
153 got, want := gd.Decode(gotValue), sd.Decode(wantValue)
154 if want == io.EOF || want == io.ErrUnexpectedEOF {
155 if got != want {
156 t.Fatalf("%q: value %d: got %v, want %v", doc, n, got, want)
157 }
158 break
159 }
160 var wantSyntax *stdjson.SyntaxError
161 if !errors.As(want, &wantSyntax) {
162 if want != nil {
163 break
164 }
165 if got != nil {
166 t.Fatalf("%q: value %d: got %v, want nil", doc, n, got)
167 }
168 if !reflect.DeepEqual(gotValue, wantValue) {
169 t.Fatalf("%q: value %d: got %#v, want %#v", doc, n, gotValue, wantValue)
170 }
171 continue
172 }
173 var gotSyntax *json.SyntaxError
174 if !errors.As(got, &gotSyntax) || gotSyntax.Error() != wantSyntax.Error() || gotSyntax.Offset != wantSyntax.Offset {
175 t.Fatalf("%q: value %d:\n got %v ( %#v )\nwant %v at %d", doc, n, got, got, want, wantSyntax.Offset)
176 }
177 if again := gd.Decode(newValue()); again == nil || again.Error() != got.Error() {
178 t.Fatalf("%q: Decode after %v = %v, want the same error", doc, got, again)
179 }
180 break
181 }
182 }
183 }
184 }
185
186 func TestTokenStreamRandom(t *testing.T) {
187 // Token, Decode and More in any order read a stream as encoding/json of the Go version does: the tokens, the
188 // values, the errors with their messages and offsets, and InputOffset. go-json reads the input by parts, so
189 // that the values and the tokens which the reads cut are read too.
190 stdDecoder := func(doc string) tokenDecoder {
191 return stdjson.NewDecoder(strings.NewReader(doc))
192 }
193 goDecoder := func(doc string) tokenDecoder {
194 return json.NewDecoder(strings.NewReader(doc))
195 }
196 r := rand.New(rand.NewSource(11))
197 for i := 0; i < 5000; i++ {
198 doc := randomSkippedValue(r, 1+r.Intn(3))
199 if r.Intn(3) == 0 {
200 doc += " " + randomSkippedValue(r, 1+r.Intn(2))
201 }
202 if r.Intn(2) == 0 {
203 doc = mutate(r, doc)
204 }
205 // encoding/json of Go 1.27 reads its input by parts, and reports a rune or a \u escape which a part cuts by
206 // the bytes of the part, where go-json reports the whole one: the runes are ASCII, and there is no \u
207 doc = strings.Map(func(c rune) rune {
208 if c >= utf8.RuneSelf {
209 return 'x'
210 }
211 return c
212 }, doc)
213 if strings.Contains(doc, `\u`) {
214 continue
215 }
216 pattern := make([]byte, 1+r.Intn(4))
217 for j := range pattern {
218 pattern[j] = "tdm"[r.Intn(3)]
219 }
220 want := streamTokens(doc, string(pattern), stdDecoder)
221 got := streamTokens(doc, string(pattern), goDecoder)
222 if got != want {
223 t.Fatalf("%q by %q:\n got %q\nwant %q", doc, pattern, got, want)
224 }
225 }
226 }