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

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

View as plain text