/
context.go
75 lines (59 loc) · 2.29 KB
/
context.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
package testcontext
import (
"context"
"github.com/kyma-project/api-gateway/apis/operator/v1alpha1"
"testing"
"github.com/pkg/errors"
"sigs.k8s.io/controller-runtime/pkg/client"
)
// apiGatewayCrCtxKey is the key used to store the ApiGatewayCR used by a scenario in the context.Context.
type apiGatewayCrCtxKey struct{}
func GetApiGatewayCRsFromContext(ctx context.Context) ([]*v1alpha1.APIGateway, bool) {
v, ok := ctx.Value(apiGatewayCrCtxKey{}).([]*v1alpha1.APIGateway)
return v, ok
}
func AddApiGatewayCRIntoContext(ctx context.Context, apiGateway *v1alpha1.APIGateway) context.Context {
apiGateways, ok := GetApiGatewayCRsFromContext(ctx)
if !ok {
apiGateways = []*v1alpha1.APIGateway{}
}
apiGateways = append(apiGateways, apiGateway)
return context.WithValue(ctx, apiGatewayCrCtxKey{}, apiGateways)
}
// createdTestObjectsCtxKey is the key used to store the test resources created during tests in the context.Context.
type createdTestObjectsCtxKey struct{}
func GetCreatedTestObjectsFromContext(ctx context.Context) ([]client.Object, bool) {
v, ok := ctx.Value(createdTestObjectsCtxKey{}).([]client.Object)
return v, ok
}
func AddCreatedTestObjectInContext(ctx context.Context, object client.Object) context.Context {
objects, ok := GetCreatedTestObjectsFromContext(ctx)
if !ok {
objects = []client.Object{}
}
objects = append(objects, object)
return context.WithValue(ctx, createdTestObjectsCtxKey{}, objects)
}
// k8sClientCtxKey is the key used to store the k8sClient used during tests in the context.Context.
type k8sClientCtxKey struct{}
func GetK8sClientFromContext(ctx context.Context) (client.Client, error) {
v, ok := ctx.Value(k8sClientCtxKey{}).(client.Client)
if !ok {
return v, errors.New("k8sClient not found in context")
}
return v, nil
}
func SetK8sClientInContext(ctx context.Context, k8sClient client.Client) context.Context {
return context.WithValue(ctx, k8sClientCtxKey{}, k8sClient)
}
type testingContextKey struct{}
func GetTestingFromContext(ctx context.Context) (*testing.T, error) {
v, ok := ctx.Value(testingContextKey{}).(*testing.T)
if !ok {
return v, errors.New("testing.T not found in context")
}
return v, nil
}
func SetTestingInContext(ctx context.Context, testing *testing.T) context.Context {
return context.WithValue(ctx, testingContextKey{}, testing)
}