Debian Codegraph @

landlock/lltest/lltest.go

raw
1 // Package lltest has helpers for Landlock-enabled tests.
2 package lltest
3
4 import (
5 "errors"
6 "fmt"
7 "os"
8 "os/exec"
9 "regexp"
10 "strings"
11 "testing"
12
13 "github.com/landlock-lsm/go-landlock/landlock/internal"
14 )
15
16 // RunInSubprocess runs the given test function in a subprocess
17 // and forwards its output.
18 func RunInSubprocess(t *testing.T, f func()) {
19 t.Helper()
20
21 if IsRunningInSubprocess() {
22 f()
23 return
24 }
25
26 args := append(os.Args[1:], "-test.run="+regexp.QuoteMeta(t.Name())+"$")
27
28 // Make sure that the parent process cleans up the actual TempDir.
29 // If the child process uses t.TempDir(), it'll create it in $TMPDIR.
30 t.Setenv("TMPDIR", t.TempDir())
31
32 t.Setenv("IS_SUBPROCESS", "yes")
33 buf, err := exec.Command(os.Args[0], args...).Output()
34
35 var exitErr *exec.ExitError
36 if err != nil && !errors.As(err, &exitErr) {
37 t.Fatalf("Could not execute test in subprocess: %v", err)
38 }
39
40 for l := range strings.SplitSeq(string(buf), "\n") {
41 if l == "FAIL" {
42 defer func() { t.Error("Test failed in subprocess") }()
43 continue
44 }
45 if strings.HasPrefix(l, "--- SKIP") {
46 defer func() { t.Skip("Test skipped in subprocess") }()
47 continue
48 }
49 if strings.HasPrefix(l, "===") || strings.HasPrefix(l, "---") || l == "PASS" || l == "" {
50 continue
51 }
52 fmt.Println(l)
53 }
54 }
55
56 // TempDir is a replacement for t.TempDir() to be used in Landlock tests.
57 // If we were using t.TempDir(), the test framework would try to remove it
58 // after the test, even in Landlocked subprocess tests where this fails.
59 //
60 // TODO: It would be nicer if all tests could just use t.TempDir()
61 // without the test framework trying to delete these later in the subprocesses.
62 func TempDir(t testing.TB) string {
63 t.Helper()
64
65 if IsRunningInSubprocess() {
66 dir, err := os.MkdirTemp("", "LandlockTestTempDir")
67 if err != nil {
68 t.Fatalf("os.MkdirTemp: %v", err)
69 }
70 return dir
71 }
72 return t.TempDir()
73 }
74
75 func abiVersion() (int, error) {
76 return internal.DetectedABIVersion(), nil
77 }
78
79 // RequireABI skips the test if the kernel does not provide the given ABI version.
80 func RequireABI(t testing.TB, want int) {
81 t.Helper()
82
83 if v, err := abiVersion(); err != nil || v < want {
84 t.Skipf("Requires Landlock >= V%v, got V%v (err=%v)", want, v, err)
85 }
86 }
87
88 func IsRunningInSubprocess() bool {
89 return os.Getenv("IS_SUBPROCESS") != ""
90 }