moby/libnetwork/testutils/context.go
Cory Snider 9a0953a0a0 libnet/testutils: spawn goroutines in test OS ctxs
There are a handful of libnetwork tests which need to have multiple
concurrent goroutines inside the same test OS context (network
namespace), including some platform-agnostic tests. Provide test
utilities for spawning goroutines inside an OS context and
setting/restoring an existing goroutine's OS context to abstract away
platform differences and so that each test does not need to reinvent the
wheel.

Signed-off-by: Cory Snider <csnider@mirantis.com>
2022-11-08 17:55:25 -05:00

41 lines
846 B
Go

package testutils
import "testing"
// Logger is used to log non-fatal messages during tests.
type Logger interface {
Logf(format string, args ...any)
}
var _ Logger = (*testing.T)(nil)
// SetupTestOSContext joins the current goroutine to a new network namespace,
// and returns its associated teardown function.
//
// Example usage:
//
// defer SetupTestOSContext(t)()
func SetupTestOSContext(t *testing.T) func() {
c := SetupTestOSContextEx(t)
return func() { c.Cleanup(t) }
}
// Go starts running fn in a new goroutine inside the test OS context.
func (c *OSContext) Go(t *testing.T, fn func()) {
t.Helper()
errCh := make(chan error, 1)
go func() {
teardown, err := c.Set()
if err != nil {
errCh <- err
return
}
defer teardown(t)
close(errCh)
fn()
}()
if err := <-errCh; err != nil {
t.Fatalf("%+v", err)
}
}