Black Lives Matter. Support the Equal Justice Initiative.

Source file src/cmd/go/internal/work/exec_test.go

Documentation: cmd/go/internal/work

     1  // Copyright 2011 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 work
     6  
     7  import (
     8  	"bytes"
     9  	"cmd/internal/objabi"
    10  	"fmt"
    11  	"math/rand"
    12  	"testing"
    13  	"time"
    14  	"unicode/utf8"
    15  )
    16  
    17  func TestEncodeArgs(t *testing.T) {
    18  	t.Parallel()
    19  	tests := []struct {
    20  		arg, want string
    21  	}{
    22  		{"", ""},
    23  		{"hello", "hello"},
    24  		{"hello\n", "hello\\n"},
    25  		{"hello\\", "hello\\\\"},
    26  		{"hello\nthere", "hello\\nthere"},
    27  		{"\\\n", "\\\\\\n"},
    28  	}
    29  	for _, test := range tests {
    30  		if got := encodeArg(test.arg); got != test.want {
    31  			t.Errorf("encodeArg(%q) = %q, want %q", test.arg, got, test.want)
    32  		}
    33  	}
    34  }
    35  
    36  func TestEncodeDecode(t *testing.T) {
    37  	t.Parallel()
    38  	tests := []string{
    39  		"",
    40  		"hello",
    41  		"hello\\there",
    42  		"hello\nthere",
    43  		"hello 中国",
    44  		"hello \n中\\国",
    45  	}
    46  	for _, arg := range tests {
    47  		if got := objabi.DecodeArg(encodeArg(arg)); got != arg {
    48  			t.Errorf("objabi.DecodeArg(encodeArg(%q)) = %q", arg, got)
    49  		}
    50  	}
    51  }
    52  
    53  func TestEncodeDecodeFuzz(t *testing.T) {
    54  	if testing.Short() {
    55  		t.Skip("fuzz test is slow")
    56  	}
    57  	t.Parallel()
    58  
    59  	nRunes := ArgLengthForResponseFile + 100
    60  	rBuffer := make([]rune, nRunes)
    61  	buf := bytes.NewBuffer([]byte(string(rBuffer)))
    62  
    63  	seed := time.Now().UnixNano()
    64  	t.Logf("rand seed: %v", seed)
    65  	rng := rand.New(rand.NewSource(seed))
    66  
    67  	for i := 0; i < 50; i++ {
    68  		// Generate a random string of runes.
    69  		buf.Reset()
    70  		for buf.Len() < ArgLengthForResponseFile+1 {
    71  			var r rune
    72  			for {
    73  				r = rune(rng.Intn(utf8.MaxRune + 1))
    74  				if utf8.ValidRune(r) {
    75  					break
    76  				}
    77  			}
    78  			fmt.Fprintf(buf, "%c", r)
    79  		}
    80  		arg := buf.String()
    81  
    82  		if got := objabi.DecodeArg(encodeArg(arg)); got != arg {
    83  			t.Errorf("[%d] objabi.DecodeArg(encodeArg(%q)) = %q [seed: %v]", i, arg, got, seed)
    84  		}
    85  	}
    86  }
    87  

View as plain text