-
Notifications
You must be signed in to change notification settings - Fork 3
/
env.go
81 lines (73 loc) · 1.88 KB
/
env.go
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
package testutil
import (
"context"
"k8s.io/client-go/rest"
"path/filepath"
"sigs.k8s.io/controller-runtime/pkg/envtest"
"sync"
)
type TestEnvironment struct {
Cfg *rest.Config
TestEnv *envtest.Environment
Ctx context.Context
Cancel context.CancelFunc
}
var (
envInstance *TestEnvironment
once sync.Once
)
func getSingletonInstance() *TestEnvironment {
once.Do(func() {
envInstance = &TestEnvironment{}
envInstance.TestEnv = &envtest.Environment{
CRDDirectoryPaths: []string{filepath.Join("..", "..", "config", "crd", "bases"),
filepath.Join("..", "testconfig")},
ErrorIfCRDPathMissing: true,
}
cfg, err := envInstance.TestEnv.Start()
if err != nil {
panic(err)
}
envInstance.Cfg = cfg
envInstance.Ctx, envInstance.Cancel = context.WithCancel(context.TODO())
})
return envInstance
}
func SetupSingletonEnvironment() (*rest.Config, context.Context, context.CancelFunc) {
envInstance := getSingletonInstance()
return envInstance.Cfg, envInstance.Ctx, envInstance.Cancel
}
func TeardownSingletonEnvironment() error {
envInstance := getSingletonInstance()
if envInstance.TestEnv != nil {
err := envInstance.TestEnv.Stop()
if err != nil {
return err
}
}
return nil
}
func SetupEnvironment() *TestEnvironment {
testEnvInstance := &TestEnvironment{}
testEnvInstance.TestEnv = &envtest.Environment{
CRDDirectoryPaths: []string{filepath.Join("..", "..", "config", "crd", "bases"),
filepath.Join("..", "testconfig")},
ErrorIfCRDPathMissing: true,
}
cfg, err := testEnvInstance.TestEnv.Start()
if err != nil {
panic(err)
}
testEnvInstance.Cfg = cfg
testEnvInstance.Ctx, testEnvInstance.Cancel = context.WithCancel(context.TODO())
return testEnvInstance
}
func TeardownEnvironment(envInstance *TestEnvironment) error {
if envInstance.TestEnv != nil {
err := envInstance.TestEnv.Stop()
if err != nil {
return err
}
}
return nil
}