aboutsummaryrefslogtreecommitdiffhomepage
path: root/test/sandbox/assert.go
blob: 3a7b31ed3f895295e43e839eecd4082d8b36a115 (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
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
package sandbox

import (
	"encoding/json"
	"io/fs"
	"log"
	"os"
)

var (
	assert     = log.New(os.Stderr, "sandbox: ", 0)
	printfFunc = assert.Printf
	fatalfFunc = assert.Fatalf
)

func printf(format string, v ...any) { printfFunc(format, v...) }
func fatalf(format string, v ...any) { fatalfFunc(format, v...) }

func mustDecode(wantFile string, v any) {
	if f, err := os.Open(wantFile); err != nil {
		fatalf("cannot open %q: %v", wantFile, err)
	} else if err = json.NewDecoder(f).Decode(v); err != nil {
		fatalf("cannot decode %q: %v", wantFile, err)
	} else if err = f.Close(); err != nil {
		fatalf("cannot close %q: %v", wantFile, err)
	}
}

func MustAssertMounts(name, hostMountsFile, wantFile string) {
	hostMounts := make([]*Mntent, 0, 128)
	if err := IterMounts(hostMountsFile, func(e *Mntent) {
		hostMounts = append(hostMounts, e)
	}); err != nil {
		fatalf("cannot parse host mounts: %v", err)
	}

	var want []Mntent
	mustDecode(wantFile, &want)

	for i := range want {
		if want[i].Opts == "host_passthrough" {
			for _, ent := range hostMounts {
				if want[i].FSName == ent.FSName && want[i].Type == ent.Type {
					// special case for tmpfs bind mounts
					if want[i].FSName == "tmpfs" && want[i].Dir != ent.Dir {
						continue
					}

					want[i].Opts = ent.Opts
					goto out
				}
			}
			fatalf("host passthrough missing %q", want[i].FSName)
		out:
		}
	}

	i := 0
	if err := IterMounts(name, func(e *Mntent) {
		if i == len(want) {
			fatalf("got more than %d entries", i)
		}
		if !e.Is(&want[i]) {
			fatalf("entry %d\n got: %s\nwant: %s", i,
				e, &want[i])
		}

		printf("%s", e)
		i++
	}); err != nil {
		fatalf("cannot iterate mounts: %v", err)
	}
}

func MustAssertFS(e fs.FS, wantFile string) {
	var want *FS
	mustDecode(wantFile, &want)
	if want == nil {
		fatalf("invalid payload")
	}

	if err := want.Compare(".", e); err != nil {
		fatalf("%v", err)
	}
}

func MustAssertSeccomp() {
	if TrySyscalls() != nil {
		os.Exit(1)
	}
}