...
1
16
17 package testing
18
19 import (
20 "fmt"
21 "strings"
22 "testing"
23
24 "github.com/stretchr/testify/require"
25
26 "k8s.io/client-go/features"
27 )
28
29 func TestDriveInitDefaultFeatureGates(t *testing.T) {
30 featureGates := features.FeatureGates()
31 assertFunctionPanicsWithMessage(t, func() { featureGates.Enabled("FakeFeatureGate") }, "features.FeatureGates().Enabled", fmt.Sprintf("feature %q is not registered in FeatureGate", "FakeFeatureGate"))
32
33 fakeFeatureGates := &alwaysEnabledFakeGates{}
34 require.True(t, fakeFeatureGates.Enabled("FakeFeatureGate"))
35
36 features.ReplaceFeatureGates(fakeFeatureGates)
37 featureGates = features.FeatureGates()
38
39 assertFeatureGatesType(t, featureGates)
40 require.True(t, featureGates.Enabled("FakeFeatureGate"))
41 }
42
43 type alwaysEnabledFakeGates struct{}
44
45 func (f *alwaysEnabledFakeGates) Enabled(features.Feature) bool {
46 return true
47 }
48
49 func assertFeatureGatesType(t *testing.T, fg features.Gates) {
50 _, ok := fg.(*alwaysEnabledFakeGates)
51 if !ok {
52 t.Fatalf("passed features.FeatureGates() is NOT of type *alwaysEnabledFakeGates, it is of type = %T", fg)
53 }
54 }
55
56 func assertFunctionPanicsWithMessage(t *testing.T, f func(), fName, errMessage string) {
57 didPanic, panicMessage := didFunctionPanic(f)
58 if !didPanic {
59 t.Fatalf("function %q did not panicked", fName)
60 }
61
62 panicError, ok := panicMessage.(error)
63 if !ok || !strings.Contains(panicError.Error(), errMessage) {
64 t.Fatalf("func %q should panic with error message:\t%#v\n\tPanic value:\t%#v\n", fName, errMessage, panicMessage)
65 }
66 }
67
68 func didFunctionPanic(f func()) (didPanic bool, panicMessage interface{}) {
69 didPanic = true
70
71 defer func() {
72 panicMessage = recover()
73 }()
74
75 f()
76 didPanic = false
77
78 return
79 }
80
View as plain text