github.com/pwn-term/docker@v0.0.0-20210616085119-6e977cce2565/libnetwork/testutils/context_unix.go (about) 1 // +build linux freebsd 2 3 package testutils 4 5 import ( 6 "os" 7 "runtime" 8 "syscall" 9 "testing" 10 11 "github.com/docker/libnetwork/ns" 12 ) 13 14 // SetupTestOSContext joins a new network namespace, and returns its associated 15 // teardown function. 16 // 17 // Example usage: 18 // 19 // defer SetupTestOSContext(t)() 20 // 21 func SetupTestOSContext(t *testing.T) func() { 22 runtime.LockOSThread() 23 if err := syscall.Unshare(syscall.CLONE_NEWNET); err != nil { 24 t.Fatalf("Failed to enter netns: %v", err) 25 } 26 27 fd, err := syscall.Open("/proc/self/ns/net", syscall.O_RDONLY, 0) 28 if err != nil { 29 t.Fatal("Failed to open netns file") 30 } 31 32 // Since we are switching to a new test namespace make 33 // sure to re-initialize initNs context 34 ns.Init() 35 36 runtime.LockOSThread() 37 38 return func() { 39 if err := syscall.Close(fd); err != nil { 40 t.Logf("Warning: netns closing failed (%v)", err) 41 } 42 runtime.UnlockOSThread() 43 } 44 } 45 46 // RunningOnCircleCI returns true if being executed on libnetwork Circle CI setup 47 func RunningOnCircleCI() bool { 48 return os.Getenv("CIRCLECI") != "" 49 }