From b6ace7d51bf18cd44105290b9e810af0fbcf2930 Mon Sep 17 00:00:00 2001 From: Tim Hockin Date: Fri, 14 Jul 2017 21:19:16 +0200 Subject: [PATCH] Add a fuzz test for non-JSON input --- unmarshal_input_test.go | 72 +++++++++++++++++++++++++++++++++++++++++ 1 file changed, 72 insertions(+) create mode 100644 unmarshal_input_test.go diff --git a/unmarshal_input_test.go b/unmarshal_input_test.go new file mode 100644 index 0000000..9d7b99c --- /dev/null +++ b/unmarshal_input_test.go @@ -0,0 +1,72 @@ +package jsoniter + +import ( + "encoding/json" + "reflect" + "testing" + + fuzz "github.com/google/gofuzz" +) + +func Test_NilInput(t *testing.T) { + var jb []byte // nil + var out string + err := Unmarshal(jb, &out) + if err == nil { + t.Errorf("Expected error") + } +} + +func Test_EmptyInput(t *testing.T) { + jb := []byte("") + var out string + err := Unmarshal(jb, &out) + if err == nil { + t.Errorf("Expected error") + } +} + +func Test_RandomInput_Bytes(t *testing.T) { + fz := fuzz.New().NilChance(0) + for i := 0; i < 10000; i++ { + var jb []byte + fz.Fuzz(&jb) + testRandomInput(t, jb) + } +} + +func Test_RandomInput_String(t *testing.T) { + fz := fuzz.New().NilChance(0) + for i := 0; i < 10000; i++ { + var js string + fz.Fuzz(&js) + jb := []byte(js) + testRandomInput(t, jb) + } +} + +func testRandomInput(t *testing.T, jb []byte) { + var outString string + testRandomInputTo(t, jb, &outString) + + var outInt int + testRandomInputTo(t, jb, &outInt) + + var outStruct struct{} + testRandomInputTo(t, jb, &outStruct) + + var outSlice []string + testRandomInputTo(t, jb, &outSlice) +} + +func testRandomInputTo(t *testing.T, jb []byte, out interface{}) { + err := Unmarshal(jb, out) + if err == nil { + // Cross-check stdlib to see if we just happened to fuzz a legit value. + err := json.Unmarshal(jb, out) + if err != nil { + t.Fatalf("Expected error unmarshaling as %s:\nas string: %q\nas bytes: %v", + reflect.TypeOf(out).Elem().Kind(), string(jb), jb) + } + } +}