gunk-dev/the-valley

fuzz_test.go

source29f48ad31be9main's published tip history
1.5 KiB
1package change
2
3import (
4 "bytes"
5 "encoding/json"
6 "reflect"
7 "strings"
8 "testing"
9)
10
11// The record parser reads bytes anyone can push. Whatever they are, it
12// returns a record or an error and never panics. What it accepts is
13// a record Encode writes back unchanged, and is never something
14// encoding/json reads differently.
15func FuzzParse(f *testing.F) {
16 f.Add([]byte(record()))
17 f.Add([]byte(`{}`))
18 f.Add([]byte(`{"schema": "valley-change-record/v1", "schema": "x"}`))
19 f.Add([]byte(strings.Replace(record(), "the first", `๐Ÿ˜€`, 1)))
20 f.Add([]byte(strings.Replace(record(), `"seq": 2`, `"seq": 2e0`, 1)))
21 f.Add([]byte(record() + "{}"))
22 f.Add([]byte("[[[[[[[[[[[[[[[["))
23 f.Add([]byte("\"\\u"))
24 f.Add([]byte{0xff, '{', '}'})
25 f.Fuzz(func(t *testing.T, data []byte) {
26 r, err := Parse(data)
27 if err != nil {
28 return
29 }
30 out, err := Encode(r)
31 if err != nil {
32 t.Fatalf("a record Parse accepted cannot be encoded: %v", err)
33 }
34 again, err := Parse(out)
35 if err != nil || !reflect.DeepEqual(again, r) {
36 t.Fatalf("an encoded record read back as %+v, %v; want %+v", again, err, r)
37 }
38 // encoding/json reads what this parser accepted as the same
39 // record: none of the leniencies it has is reachable here.
40 var lenient Record
41 dec := json.NewDecoder(bytes.NewReader(data))
42 dec.DisallowUnknownFields()
43 if err := dec.Decode(&lenient); err != nil || !reflect.DeepEqual(&lenient, r) {
44 t.Fatalf("encoding/json read the record as %+v, %v; want %+v", lenient, err, r)
45 }
46 })
47}