test_linux.go 792 B

12345678910111213141516171819202122232425262728293031323334353637
  1. package osl
  2. import (
  3. "runtime"
  4. "syscall"
  5. "testing"
  6. )
  7. // SetupTestOSContext joins a new network namespace, and returns its associated
  8. // teardown function.
  9. //
  10. // Example usage:
  11. //
  12. // defer SetupTestOSContext(t)()
  13. //
  14. func SetupTestOSContext(t *testing.T) func() {
  15. runtime.LockOSThread()
  16. if err := syscall.Unshare(syscall.CLONE_NEWNET); err != nil {
  17. t.Fatalf("Failed to enter netns: %v", err)
  18. }
  19. fd, err := syscall.Open("/proc/self/ns/net", syscall.O_RDONLY, 0)
  20. if err != nil {
  21. t.Fatal("Failed to open netns file")
  22. }
  23. // Since we are switching to a new test namespace make
  24. // sure to re-initialize initNs context
  25. nsInit()
  26. return func() {
  27. if err := syscall.Close(fd); err != nil {
  28. t.Logf("Warning: netns closing failed (%v)", err)
  29. }
  30. runtime.UnlockOSThread()
  31. }
  32. }