Source file src/encoding/json/fuzz_test.go

     1  // Copyright 2021 The Go Authors. All rights reserved.
     2  // Use of this source code is governed by a BSD-style
     3  // license that can be found in the LICENSE file.
     4  
     5  package json
     6  
     7  import (
     8  	"bytes"
     9  	"io"
    10  	"testing"
    11  )
    12  
    13  func FuzzUnmarshalJSON(f *testing.F) {
    14  	f.Add([]byte(`{
    15  "object": {
    16  	"slice": [
    17  		1,
    18  		2.0,
    19  		"3",
    20  		[4],
    21  		{5: {}}
    22  	]
    23  },
    24  "slice": [[]],
    25  "string": ":)",
    26  "int": 1e5,
    27  "float": 3e-9"
    28  }`))
    29  
    30  	f.Fuzz(func(t *testing.T, b []byte) {
    31  		for _, typ := range []func() interface{}{
    32  			func() interface{} { return new(interface{}) },
    33  			func() interface{} { return new(map[string]interface{}) },
    34  			func() interface{} { return new([]interface{}) },
    35  		} {
    36  			i := typ()
    37  			if err := Unmarshal(b, i); err != nil {
    38  				return
    39  			}
    40  
    41  			encoded, err := Marshal(i)
    42  			if err != nil {
    43  				t.Fatalf("failed to marshal: %s", err)
    44  			}
    45  
    46  			if err := Unmarshal(encoded, i); err != nil {
    47  				t.Fatalf("failed to roundtrip: %s", err)
    48  			}
    49  		}
    50  	})
    51  }
    52  
    53  func FuzzDecoderToken(f *testing.F) {
    54  	f.Add([]byte(`{
    55  "object": {
    56  	"slice": [
    57  		1,
    58  		2.0,
    59  		"3",
    60  		[4],
    61  		{5: {}}
    62  	]
    63  },
    64  "slice": [[]],
    65  "string": ":)",
    66  "int": 1e5,
    67  "float": 3e-9"
    68  }`))
    69  
    70  	f.Fuzz(func(t *testing.T, b []byte) {
    71  		r := bytes.NewReader(b)
    72  		d := NewDecoder(r)
    73  		for {
    74  			_, err := d.Token()
    75  			if err != nil {
    76  				if err == io.EOF {
    77  					break
    78  				}
    79  				return
    80  			}
    81  		}
    82  	})
    83  }
    84  

View as plain text