Source file src/encoding/json/scanner_test.go

     1  // Copyright 2010 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  //go:build !goexperiment.jsonv2
     6  
     7  package json
     8  
     9  import (
    10  	"bytes"
    11  	"math"
    12  	"math/rand"
    13  	"reflect"
    14  	"strings"
    15  	"testing"
    16  )
    17  
    18  func indentNewlines(s string) string {
    19  	return strings.Join(strings.Split(s, "\n"), "\n\t")
    20  }
    21  
    22  func stripWhitespace(s string) string {
    23  	return strings.Map(func(r rune) rune {
    24  		if r == ' ' || r == '\n' || r == '\r' || r == '\t' {
    25  			return -1
    26  		}
    27  		return r
    28  	}, s)
    29  }
    30  
    31  func TestValid(t *testing.T) {
    32  	tests := []struct {
    33  		CaseName
    34  		data string
    35  		ok   bool
    36  	}{
    37  		{Name(""), `foo`, false},
    38  		{Name(""), `}{`, false},
    39  		{Name(""), `{]`, false},
    40  		{Name(""), `{}`, true},
    41  		{Name(""), `{"foo":"bar"}`, true},
    42  		{Name(""), `{"foo":"bar","bar":{"baz":["qux"]}}`, true},
    43  	}
    44  	for _, tt := range tests {
    45  		t.Run(tt.Name, func(t *testing.T) {
    46  			if ok := Valid([]byte(tt.data)); ok != tt.ok {
    47  				t.Errorf("%s: Valid(`%s`) = %v, want %v", tt.Where, tt.data, ok, tt.ok)
    48  			}
    49  		})
    50  	}
    51  }
    52  
    53  func TestCompactAndIndent(t *testing.T) {
    54  	tests := []struct {
    55  		CaseName
    56  		compact string
    57  		indent  string
    58  	}{
    59  		{Name(""), `1`, `1`},
    60  		{Name(""), `{}`, `{}`},
    61  		{Name(""), `[]`, `[]`},
    62  		{Name(""), `{"":2}`, "{\n\t\"\": 2\n}"},
    63  		{Name(""), `[3]`, "[\n\t3\n]"},
    64  		{Name(""), `[1,2,3]`, "[\n\t1,\n\t2,\n\t3\n]"},
    65  		{Name(""), `{"x":1}`, "{\n\t\"x\": 1\n}"},
    66  		{Name(""), `[true,false,null,"x",1,1.5,0,-5e+2]`, `[
    67  	true,
    68  	false,
    69  	null,
    70  	"x",
    71  	1,
    72  	1.5,
    73  	0,
    74  	-5e+2
    75  ]`},
    76  		{Name(""), "{\"\":\"<>&\u2028\u2029\"}", "{\n\t\"\": \"<>&\u2028\u2029\"\n}"}, // See golang.org/issue/34070
    77  		{Name(""), `null`, "null \n\r\t"},                                             // See golang.org/issue/13520 and golang.org/issue/74806
    78  	}
    79  	var buf bytes.Buffer
    80  	for _, tt := range tests {
    81  		t.Run(tt.Name, func(t *testing.T) {
    82  			buf.Reset()
    83  			if err := Compact(&buf, []byte(tt.compact)); err != nil {
    84  				t.Errorf("%s: Compact error: %v", tt.Where, err)
    85  			} else if got := buf.String(); got != tt.compact {
    86  				t.Errorf("%s: Compact:\n\tgot:  %s\n\twant: %s", tt.Where, indentNewlines(got), indentNewlines(tt.compact))
    87  			}
    88  
    89  			buf.Reset()
    90  			if err := Compact(&buf, []byte(tt.indent)); err != nil {
    91  				t.Errorf("%s: Compact error: %v", tt.Where, err)
    92  			} else if got := buf.String(); got != tt.compact {
    93  				t.Errorf("%s: Compact:\n\tgot:  %s\n\twant: %s", tt.Where, indentNewlines(got), indentNewlines(tt.compact))
    94  			}
    95  
    96  			buf.Reset()
    97  			if err := Indent(&buf, []byte(tt.indent), "", "\t"); err != nil {
    98  				t.Errorf("%s: Indent error: %v", tt.Where, err)
    99  			} else if got := buf.String(); got != tt.indent {
   100  				t.Errorf("%s: Compact:\n\tgot:  %s\n\twant: %s", tt.Where, indentNewlines(got), indentNewlines(tt.indent))
   101  			}
   102  
   103  			buf.Reset()
   104  			if err := Indent(&buf, []byte(tt.compact), "", "\t"); err != nil {
   105  				t.Errorf("%s: Indent error: %v", tt.Where, err)
   106  			} else if got := buf.String(); got != strings.TrimRight(tt.indent, " \n\r\t") {
   107  				t.Errorf("%s: Compact:\n\tgot:  %s\n\twant: %s", tt.Where, indentNewlines(got), indentNewlines(tt.indent))
   108  			}
   109  		})
   110  	}
   111  }
   112  
   113  func TestIndentPrefix(t *testing.T) {
   114  	tests := []struct {
   115  		CaseName
   116  		src, prefix, indent string
   117  		want                string
   118  	}{
   119  		{Name(""), "[1,[2]]", ">", "--", "[\n>--1,\n>--[\n>----2\n>--]\n>]"},
   120  		{Name(""), "[1,2]\n  ", ">", "--", "[\n>--1,\n>--2\n>]\n  "},
   121  		{Name(""), "1\n  ", ">", "", "1\n  "}, // See golang.org/issue/81547
   122  	}
   123  	for _, tt := range tests {
   124  		t.Run(tt.Name, func(t *testing.T) {
   125  			var buf bytes.Buffer
   126  			if err := Indent(&buf, []byte(tt.src), tt.prefix, tt.indent); err != nil {
   127  				t.Errorf("%s: Indent error: %v", tt.Where, err)
   128  			} else if got := buf.String(); got != tt.want {
   129  				t.Errorf("%s: Indent:\n\tgot:  %q\n\twant: %q", tt.Where, got, tt.want)
   130  			}
   131  		})
   132  	}
   133  }
   134  
   135  func TestCompactSeparators(t *testing.T) {
   136  	// U+2028 and U+2029 should be escaped inside strings.
   137  	// They should not appear outside strings.
   138  	tests := []struct {
   139  		CaseName
   140  		in, compact string
   141  	}{
   142  		{Name(""), "{\"\u2028\": 1}", "{\"\u2028\":1}"},
   143  		{Name(""), "{\"\u2029\" :2}", "{\"\u2029\":2}"},
   144  	}
   145  	for _, tt := range tests {
   146  		t.Run(tt.Name, func(t *testing.T) {
   147  			var buf bytes.Buffer
   148  			if err := Compact(&buf, []byte(tt.in)); err != nil {
   149  				t.Errorf("%s: Compact error: %v", tt.Where, err)
   150  			} else if got := buf.String(); got != tt.compact {
   151  				t.Errorf("%s: Compact:\n\tgot:  %s\n\twant: %s", tt.Where, indentNewlines(got), indentNewlines(tt.compact))
   152  			}
   153  		})
   154  	}
   155  }
   156  
   157  // Tests of a large random structure.
   158  
   159  func TestCompactBig(t *testing.T) {
   160  	initBig()
   161  	var buf bytes.Buffer
   162  	if err := Compact(&buf, jsonBig); err != nil {
   163  		t.Fatalf("Compact error: %v", err)
   164  	}
   165  	b := buf.Bytes()
   166  	if !bytes.Equal(b, jsonBig) {
   167  		t.Error("Compact:")
   168  		diff(t, b, jsonBig)
   169  		return
   170  	}
   171  }
   172  
   173  func TestIndentBig(t *testing.T) {
   174  	t.Parallel()
   175  	initBig()
   176  	var buf bytes.Buffer
   177  	if err := Indent(&buf, jsonBig, "", "\t"); err != nil {
   178  		t.Fatalf("Indent error: %v", err)
   179  	}
   180  	b := buf.Bytes()
   181  	if len(b) == len(jsonBig) {
   182  		// jsonBig is compact (no unnecessary spaces);
   183  		// indenting should make it bigger
   184  		t.Fatalf("Indent did not expand the input")
   185  	}
   186  
   187  	// should be idempotent
   188  	var buf1 bytes.Buffer
   189  	if err := Indent(&buf1, b, "", "\t"); err != nil {
   190  		t.Fatalf("Indent error: %v", err)
   191  	}
   192  	b1 := buf1.Bytes()
   193  	if !bytes.Equal(b1, b) {
   194  		t.Error("Indent(Indent(jsonBig)) != Indent(jsonBig):")
   195  		diff(t, b1, b)
   196  		return
   197  	}
   198  
   199  	// should get back to original
   200  	buf1.Reset()
   201  	if err := Compact(&buf1, b); err != nil {
   202  		t.Fatalf("Compact error: %v", err)
   203  	}
   204  	b1 = buf1.Bytes()
   205  	if !bytes.Equal(b1, jsonBig) {
   206  		t.Error("Compact(Indent(jsonBig)) != jsonBig:")
   207  		diff(t, b1, jsonBig)
   208  		return
   209  	}
   210  }
   211  
   212  func TestIndentErrors(t *testing.T) {
   213  	tests := []struct {
   214  		CaseName
   215  		in  string
   216  		err error
   217  	}{
   218  		{Name(""), `{"X": "foo", "Y"}`, &SyntaxError{"invalid character '}' after object key", len64(`{"X": "foo", "Y"}`)}},
   219  		{Name(""), `{"X": "foo" "Y": "bar"}`, &SyntaxError{"invalid character '\"' after object key:value pair", len64(`{"X": "foo" "`)}},
   220  	}
   221  	for _, tt := range tests {
   222  		t.Run(tt.Name, func(t *testing.T) {
   223  			slice := make([]uint8, 0)
   224  			buf := bytes.NewBuffer(slice)
   225  			if err := Indent(buf, []uint8(tt.in), "", ""); err != nil {
   226  				if !reflect.DeepEqual(err, tt.err) {
   227  					t.Fatalf("%s: Indent error:\n\tgot:  %v\n\twant: %v", tt.Where, err, tt.err)
   228  				}
   229  			}
   230  		})
   231  	}
   232  }
   233  
   234  func diff(t *testing.T, a, b []byte) {
   235  	t.Helper()
   236  	for i := 0; ; i++ {
   237  		if i >= len(a) || i >= len(b) || a[i] != b[i] {
   238  			j := i - 10
   239  			if j < 0 {
   240  				j = 0
   241  			}
   242  			t.Errorf("diverge at %d: «%s» vs «%s»", i, trim(a[j:]), trim(b[j:]))
   243  			return
   244  		}
   245  	}
   246  }
   247  
   248  func trim(b []byte) []byte {
   249  	return b[:min(len(b), 20)]
   250  }
   251  
   252  // Generate a random JSON object.
   253  
   254  var jsonBig []byte
   255  
   256  func initBig() {
   257  	n := 10000
   258  	if testing.Short() {
   259  		n = 100
   260  	}
   261  	b, err := Marshal(genValue(n))
   262  	if err != nil {
   263  		panic(err)
   264  	}
   265  	jsonBig = b
   266  }
   267  
   268  func genValue(n int) any {
   269  	if n > 1 {
   270  		switch rand.Intn(2) {
   271  		case 0:
   272  			return genArray(n)
   273  		case 1:
   274  			return genMap(n)
   275  		}
   276  	}
   277  	switch rand.Intn(3) {
   278  	case 0:
   279  		return rand.Intn(2) == 0
   280  	case 1:
   281  		return rand.NormFloat64()
   282  	case 2:
   283  		return genString(30)
   284  	}
   285  	panic("unreachable")
   286  }
   287  
   288  func genString(stddev float64) string {
   289  	n := int(math.Abs(rand.NormFloat64()*stddev + stddev/2))
   290  	c := make([]rune, n)
   291  	for i := range c {
   292  		f := math.Abs(rand.NormFloat64()*64 + 32)
   293  		if f > 0x10ffff {
   294  			f = 0x10ffff
   295  		}
   296  		c[i] = rune(f)
   297  	}
   298  	return string(c)
   299  }
   300  
   301  func genArray(n int) []any {
   302  	f := int(math.Abs(rand.NormFloat64()) * math.Min(10, float64(n/2)))
   303  	if f > n {
   304  		f = n
   305  	}
   306  	if f < 1 {
   307  		f = 1
   308  	}
   309  	x := make([]any, f)
   310  	for i := range x {
   311  		x[i] = genValue(((i+1)*n)/f - (i*n)/f)
   312  	}
   313  	return x
   314  }
   315  
   316  func genMap(n int) map[string]any {
   317  	f := int(math.Abs(rand.NormFloat64()) * math.Min(10, float64(n/2)))
   318  	if f > n {
   319  		f = n
   320  	}
   321  	if n > 0 && f == 0 {
   322  		f = 1
   323  	}
   324  	x := make(map[string]any)
   325  	for i := 0; i < f; i++ {
   326  		x[genString(10)] = genValue(((i+1)*n)/f - (i*n)/f)
   327  	}
   328  	return x
   329  }
   330  

View as plain text