context.go 846 B

1234567891011121314151617181920212223242526272829303132333435363738394041
  1. package testutils
  2. import "testing"
  3. // Logger is used to log non-fatal messages during tests.
  4. type Logger interface {
  5. Logf(format string, args ...any)
  6. }
  7. var _ Logger = (*testing.T)(nil)
  8. // SetupTestOSContext joins the current goroutine to a new network namespace,
  9. // and returns its associated teardown function.
  10. //
  11. // Example usage:
  12. //
  13. // defer SetupTestOSContext(t)()
  14. func SetupTestOSContext(t *testing.T) func() {
  15. c := SetupTestOSContextEx(t)
  16. return func() { c.Cleanup(t) }
  17. }
  18. // Go starts running fn in a new goroutine inside the test OS context.
  19. func (c *OSContext) Go(t *testing.T, fn func()) {
  20. t.Helper()
  21. errCh := make(chan error, 1)
  22. go func() {
  23. teardown, err := c.Set()
  24. if err != nil {
  25. errCh <- err
  26. return
  27. }
  28. defer teardown(t)
  29. close(errCh)
  30. fn()
  31. }()
  32. if err := <-errCh; err != nil {
  33. t.Fatalf("%+v", err)
  34. }
  35. }