diff options
author | Ian Lance Taylor <iant@golang.org> | 2023-03-08 16:16:59 -0800 |
---|---|---|
committer | Gopher Robot <gobot@golang.org> | 2023-03-13 21:58:46 +0000 |
commit | 7f38067acb738c43d870400dd648662d31456f5f (patch) | |
tree | 025b7a15e03a78e9e7de73150f7b1099a878b46c /src/testing/testing_test.go | |
parent | e8543a6fa6e68a9d35178a5bbb71812cfbc2ba05 (diff) | |
download | go-git-7f38067acb738c43d870400dd648662d31456f5f.tar.gz |
testing: add Testing function
The Testing function reports whether the program is a test created
by "go test".
Fixes #52600
Change-Id: Ie0fff7c7dfdfdf997c18b4b6112632600b327cc8
Reviewed-on: https://go-review.googlesource.com/c/go/+/475496
Run-TryBot: Ian Lance Taylor <iant@golang.org>
TryBot-Result: Gopher Robot <gobot@golang.org>
Reviewed-by: Bryan Mills <bcmills@google.com>
Reviewed-by: Ian Lance Taylor <iant@google.com>
Auto-Submit: Ian Lance Taylor <iant@google.com>
Diffstat (limited to 'src/testing/testing_test.go')
-rw-r--r-- | src/testing/testing_test.go | 61 |
1 files changed, 61 insertions, 0 deletions
diff --git a/src/testing/testing_test.go b/src/testing/testing_test.go index 3616f04d5f..5e9268779f 100644 --- a/src/testing/testing_test.go +++ b/src/testing/testing_test.go @@ -5,6 +5,8 @@ package testing_test import ( + "bytes" + "internal/testenv" "os" "path/filepath" "testing" @@ -232,3 +234,62 @@ func TestSetenvWithParallelGrandParentBeforeSetenv(t *testing.T) { }) }) } + +// testingTrueInInit is part of TestTesting. +var testingTrueInInit = false + +// testingTrueInPackageVarInit is part of TestTesting. +var testingTrueInPackageVarInit = testing.Testing() + +// init is part of TestTesting. +func init() { + if testing.Testing() { + testingTrueInInit = true + } +} + +var testingProg = ` +package main + +import ( + "fmt" + "testing" +) + +func main() { + fmt.Println(testing.Testing()) +} +` + +func TestTesting(t *testing.T) { + if !testing.Testing() { + t.Errorf("testing.Testing() == %t, want %t", testing.Testing(), true) + } + if !testingTrueInInit { + t.Errorf("testing.Testing() called by init function == %t, want %t", testingTrueInInit, true) + } + if !testingTrueInPackageVarInit { + t.Errorf("testing.Testing() variable initialized as %t, want %t", testingTrueInPackageVarInit, true) + } + + if testing.Short() { + t.Skip("skipping building a binary in short mode") + } + testenv.MustHaveGoRun(t) + + fn := filepath.Join(t.TempDir(), "x.go") + if err := os.WriteFile(fn, []byte(testingProg), 0644); err != nil { + t.Fatal(err) + } + + cmd := testenv.Command(t, testenv.GoToolPath(t), "run", fn) + out, err := cmd.CombinedOutput() + if err != nil { + t.Fatalf("%v failed: %v\n%s", cmd, err, out) + } + + s := string(bytes.TrimSpace(out)) + if s != "false" { + t.Errorf("in non-test testing.Test() returned %q, want %q", s, "false") + } +} |