Debian Codegraph @

test_helpers_test.go

raw symbols SCIP
1 package zfs_test
2
3 import (
4 "fmt"
5 "io/ioutil"
6 "math"
7 "os"
8 "path/filepath"
9 "reflect"
10 "runtime"
11 "testing"
12 "time"
13
14 "github.com/mistifyio/go-zfs/v3"
15 )
16
17 func sleep(delay int) {
18 time.Sleep(time.Duration(delay) * time.Second)
19 }
20
21 func pow2(x int) int64 {
22 return int64(math.Pow(2, float64(x)))
23 }
24
25 // https://github.com/benbjohnson/testing
26 // assert fails the test if the condition is false.
27 func _assert(t *testing.T, condition bool, msg string, v ...interface{}) {
28 t.Helper()
29
30 if !condition {
31 _, file, line, _ := runtime.Caller(2)
32 t.Logf("\033[31m%s:%d: "+msg+"\033[39m\n\n", append([]interface{}{filepath.Base(file), line}, v...)...)
33 t.FailNow()
34 }
35 }
36
37 func assert(t *testing.T, condition bool, msg string, v ...interface{}) {
38 t.Helper()
39 _assert(t, condition, msg, v...)
40 }
41
42 // ok fails the test if an err is not nil.
43 func ok(t *testing.T, err error) {
44 t.Helper()
45 _assert(t, err == nil, "unexpected error: %v", err)
46 }
47
48 // nok fails the test if an err is nil.
49 func nok(t *testing.T, err error) {
50 t.Helper()
51 _assert(t, err != nil, "expected error, got nil")
52 }
53
54 // equals fails the test if exp is not equal to act.
55 func equals(t *testing.T, exp, act interface{}) {
56 t.Helper()
57 _assert(t, reflect.DeepEqual(exp, act), "exp: %#v\n\ngot: %#v", exp, act)
58 }
59
60 type cleanUpFunc func()
61
62 func (f cleanUpFunc) cleanUp() {
63 f()
64 }
65
66 // do something like Restorer in github.com/packethost/pkg/internal/testenv/clearer.go
67 func setupZPool(t *testing.T) cleanUpFunc {
68 t.Helper()
69
70 d, err := ioutil.TempDir("/tmp/", "zfs-test-*")
71 ok(t, err)
72
73 var skipRemoveAll bool
74 defer func() {
75 if !skipRemoveAll {
76 t.Logf("cleaning up")
77 os.RemoveAll(d)
78 }
79 }()
80
81 tempfiles := make([]string, 3)
82 for i := range tempfiles {
83 f, err := ioutil.TempFile(d, fmt.Sprintf("loop%d", i))
84 ok(t, err)
85
86 ok(t, f.Truncate(pow2(30)))
87
88 f.Close()
89 tempfiles[i] = f.Name()
90 }
91
92 pool, err := zfs.CreateZpool("test", nil, tempfiles...)
93 ok(t, err)
94
95 skipRemoveAll = true
96 return func() {
97 ok(t, pool.Destroy())
98 os.RemoveAll(d)
99 }
100 }