Source file src/testing/flag_test.go

     1  // Copyright 2022 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 testing_test
     6  
     7  import (
     8  	"flag"
     9  	"internal/testenv"
    10  	"os"
    11  	"os/exec"
    12  	"testing"
    13  )
    14  
    15  var testFlagArg = flag.String("test_flag_arg", "", "TestFlag: passing -v option")
    16  
    17  const flagTestEnv = "GO_WANT_FLAG_HELPER_PROCESS"
    18  
    19  func TestFlag(t *testing.T) {
    20  	if os.Getenv(flagTestEnv) == "1" {
    21  		testFlagHelper(t)
    22  		return
    23  	}
    24  
    25  	testenv.MustHaveExec(t)
    26  
    27  	for _, flag := range []string{"", "-test.v", "-test.v=test2json"} {
    28  		t.Run(flag, func(t *testing.T) {
    29  			t.Parallel()
    30  			cmd := exec.Command(testenv.Executable(t), "-test.run=^TestFlag$", "-test_flag_arg="+flag)
    31  			if flag != "" {
    32  				cmd.Args = append(cmd.Args, flag)
    33  			}
    34  			cmd.Env = append(cmd.Environ(), flagTestEnv+"=1")
    35  			b, err := cmd.CombinedOutput()
    36  			if len(b) > 0 {
    37  				// When we set -test.v=test2json, we need to escape the ^V control
    38  				// character used for JSON framing so that the JSON parser doesn't
    39  				// misinterpret the subprocess output as output from the parent test.
    40  				t.Logf("%q", b)
    41  			}
    42  			if err != nil {
    43  				t.Error(err)
    44  			}
    45  		})
    46  	}
    47  }
    48  
    49  // testFlagHelper is called by the TestFlagHelper subprocess.
    50  func testFlagHelper(t *testing.T) {
    51  	f := flag.Lookup("test.v")
    52  	if f == nil {
    53  		t.Fatal(`flag.Lookup("test.v") failed`)
    54  	}
    55  
    56  	bf, ok := f.Value.(interface{ IsBoolFlag() bool })
    57  	if !ok {
    58  		t.Errorf("test.v flag (type %T) does not have IsBoolFlag method", f)
    59  	} else if !bf.IsBoolFlag() {
    60  		t.Error("test.v IsBoolFlag() returned false")
    61  	}
    62  
    63  	gf, ok := f.Value.(flag.Getter)
    64  	if !ok {
    65  		t.Fatalf("test.v flag (type %T) does not have Get method", f)
    66  	}
    67  	v := gf.Get()
    68  
    69  	var want any
    70  	switch *testFlagArg {
    71  	case "":
    72  		want = false
    73  	case "-test.v":
    74  		want = true
    75  	case "-test.v=test2json":
    76  		want = "test2json"
    77  	default:
    78  		t.Fatalf("unexpected test_flag_arg %q", *testFlagArg)
    79  	}
    80  
    81  	if v != want {
    82  		t.Errorf("test.v is %v want %v", v, want)
    83  	}
    84  }
    85  

View as plain text