netnsutils

package
v0.0.0-...-076c976 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Jun 14, 2024 License: Apache-2.0 Imports: 12 Imported by: 0

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func AssertSocketSameNetNS

func AssertSocketSameNetNS(t testing.TB, conn syscall.Conn)

AssertSocketSameNetNS makes a best-effort attempt to assert that conn is in the same network namespace as the current goroutine's thread.

func SetupTestOSContext

func SetupTestOSContext(t *testing.T) func()

SetupTestOSContext joins the current goroutine to a new network namespace, and returns its associated teardown function.

Example usage:

defer SetupTestOSContext(t)()

Types

type OSContext

type OSContext struct {
	// contains filtered or unexported fields
}

OSContext is a handle to a test OS context.

func SetupTestOSContextEx

func SetupTestOSContextEx(t *testing.T) *OSContext

SetupTestOSContextEx joins the current goroutine to a new network namespace.

Compared to SetupTestOSContext, this function allows goroutines to be spawned which are associated with the same OS context via the returned OSContext value.

Example usage:

c := SetupTestOSContext(t)
defer c.Cleanup(t)

func (*OSContext) Cleanup

func (c *OSContext) Cleanup(t *testing.T)

Cleanup tears down the OS context. It must be called from the same goroutine as the SetupTestOSContextEx call which returned c.

Explicit cleanup is required as (*testing.T).Cleanup() makes no guarantees about which goroutine the cleanup functions are invoked on.

func (*OSContext) Go

func (c *OSContext) Go(t *testing.T, fn func())

Go starts running fn in a new goroutine inside the test OS context.

func (*OSContext) Set

func (c *OSContext) Set() (func(testutils.Logger), error)

Set sets the OS context of the calling goroutine to c and returns a teardown function to restore the calling goroutine's OS context and release resources. The teardown function accepts an optional Logger argument.

This is a lower-level interface which is less ergonomic than c.Go() but more composable with other goroutine-spawning utilities such as sync.WaitGroup or golang.org/x/sync/errgroup.Group.

Example usage:

func TestFoo(t *testing.T) {
	osctx := testutils.SetupTestOSContextEx(t)
	defer osctx.Cleanup(t)
	var eg errgroup.Group
	eg.Go(func() error {
		teardown, err := osctx.Set()
		if err != nil {
			return err
		}
		defer teardown(t)
		// ...
	})
	if err := eg.Wait(); err != nil {
		t.Fatalf("%+v", err)
	}
}

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL