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