...

Source file src/cmd/dist/testjson_test.go

Documentation: cmd/dist

     1  // Copyright 2023 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 main
     6  
     7  import (
     8  	"strings"
     9  	"testing"
    10  )
    11  
    12  func TestJSONFilterRewritePackage(t *testing.T) {
    13  	const in = `{"Package":"abc"}
    14  {"Field1":"1","Package":"abc","Field3":"3"}
    15  {"Package":123}
    16  {}
    17  {"Package":"abc","Unexpected":[null,true,false,99999999999999999999]}
    18  `
    19  	want := strings.ReplaceAll(in, `"Package":"abc"`, `"Package":"abc:variant"`)
    20  
    21  	checkJSONFilter(t, in, want)
    22  }
    23  
    24  func TestJSONFilterMalformed(t *testing.T) {
    25  	const in = `unexpected text
    26  {"Package":"abc"}
    27  more text
    28  {"Package":"abc"}trailing text
    29  {not json}
    30  no newline`
    31  	const want = `unexpected text
    32  {"Package":"abc:variant"}
    33  more text
    34  {"Package":"abc:variant"}trailing text
    35  {not json}
    36  no newline`
    37  	checkJSONFilter(t, in, want)
    38  }
    39  
    40  func TestJSONFilterBoundaries(t *testing.T) {
    41  	const in = `{"Package":"abc"}
    42  {"Package":"def"}
    43  {"Package":"ghi"}
    44  `
    45  	want := strings.ReplaceAll(in, `"}`, `:variant"}`)
    46  
    47  	// Write one bytes at a time.
    48  	t.Run("bytes", func(t *testing.T) {
    49  		checkJSONFilterWith(t, want, func(f *testJSONFilter) {
    50  			for i := 0; i < len(in); i++ {
    51  				f.Write([]byte{in[i]})
    52  			}
    53  		})
    54  	})
    55  	// Write a block containing a whole line bordered by two partial lines.
    56  	t.Run("bytes", func(t *testing.T) {
    57  		checkJSONFilterWith(t, want, func(f *testJSONFilter) {
    58  			const b1 = 5
    59  			const b2 = len(in) - 5
    60  			f.Write([]byte(in[:b1]))
    61  			f.Write([]byte(in[b1:b2]))
    62  			f.Write([]byte(in[b2:]))
    63  		})
    64  	})
    65  }
    66  
    67  func checkJSONFilter(t *testing.T, in, want string) {
    68  	t.Helper()
    69  	checkJSONFilterWith(t, want, func(f *testJSONFilter) {
    70  		f.Write([]byte(in))
    71  	})
    72  }
    73  
    74  func checkJSONFilterWith(t *testing.T, want string, write func(*testJSONFilter)) {
    75  	t.Helper()
    76  
    77  	out := new(strings.Builder)
    78  	f := &testJSONFilter{w: out, variant: "variant"}
    79  	write(f)
    80  	f.Flush()
    81  	got := out.String()
    82  	if want != got {
    83  		t.Errorf("want:\n%s\ngot:\n%s", want, got)
    84  	}
    85  }
    86  

View as plain text