context.go 699 B

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