testenv.go 1.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  1. // Copyright (c) Tailscale Inc & AUTHORS
  2. // SPDX-License-Identifier: BSD-3-Clause
  3. // Package testenv provides utility functions for tests. It does not depend on
  4. // the `testing` package to allow usage in non-test code.
  5. package testenv
  6. import (
  7. "context"
  8. "flag"
  9. "tailscale.com/types/lazy"
  10. )
  11. var lazyInTest lazy.SyncValue[bool]
  12. // InTest reports whether the current binary is a test binary.
  13. func InTest() bool {
  14. return lazyInTest.Get(func() bool {
  15. return flag.Lookup("test.v") != nil
  16. })
  17. }
  18. // TB is testing.TB, to avoid importing "testing" in non-test code.
  19. type TB interface {
  20. Cleanup(func())
  21. Error(args ...any)
  22. Errorf(format string, args ...any)
  23. Fail()
  24. FailNow()
  25. Failed() bool
  26. Fatal(args ...any)
  27. Fatalf(format string, args ...any)
  28. Helper()
  29. Log(args ...any)
  30. Logf(format string, args ...any)
  31. Name() string
  32. Setenv(key, value string)
  33. Chdir(dir string)
  34. Skip(args ...any)
  35. SkipNow()
  36. Skipf(format string, args ...any)
  37. Skipped() bool
  38. TempDir() string
  39. Context() context.Context
  40. }
  41. // InParallelTest reports whether t is running as a parallel test.
  42. //
  43. // Use of this function taints t such that its Parallel method (assuming t is an
  44. // actual *testing.T) will panic if called after this function.
  45. func InParallelTest(t TB) (isParallel bool) {
  46. defer func() {
  47. if r := recover(); r != nil {
  48. isParallel = true
  49. }
  50. }()
  51. t.Chdir(".") // panics in a t.Parallel test
  52. return false
  53. }
  54. // AssertInTest panics if called outside of a test binary.
  55. func AssertInTest() {
  56. if !InTest() {
  57. panic("func called outside of test binary")
  58. }
  59. }