summaryrefslogtreecommitdiff
path: root/libnetwork/testutils/context.go
blob: 16f25bbd5f27a02c7d72697fdfeb28f1988c2f74 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
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)
	}
}