test_utils.go 942 B

1234567891011121314151617181920212223242526272829303132333435363738394041
  1. package netutils
  2. import (
  3. "flag"
  4. "runtime"
  5. "syscall"
  6. "testing"
  7. )
  8. var runningInContainer = flag.Bool("incontainer", false, "Indicates if the test is running in a container")
  9. // IsRunningInContainer returns whether the test is running inside a container.
  10. func IsRunningInContainer() bool {
  11. return (*runningInContainer)
  12. }
  13. // SetupTestNetNS joins a new network namespace, and returns its associated
  14. // teardown function.
  15. //
  16. // Example usage:
  17. //
  18. // defer SetupTestNetNS(t)()
  19. //
  20. func SetupTestNetNS(t *testing.T) func() {
  21. runtime.LockOSThread()
  22. if err := syscall.Unshare(syscall.CLONE_NEWNET); err != nil {
  23. t.Fatalf("Failed to enter netns: %v", err)
  24. }
  25. fd, err := syscall.Open("/proc/self/ns/net", syscall.O_RDONLY, 0)
  26. if err != nil {
  27. t.Fatal("Failed to open netns file")
  28. }
  29. return func() {
  30. if err := syscall.Close(fd); err != nil {
  31. t.Logf("Warning: netns closing failed (%v)", err)
  32. }
  33. runtime.UnlockOSThread()
  34. }
  35. }