github.com/go-asm/go@v1.21.1-0.20240213172139-40c5ead50c48/cmd/go/work/exec_test.go (about)

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