github.com/oam-dev/cluster-gateway@v1.9.0/pkg/util/cert/secret_test.go (about) 1 package cert 2 3 import ( 4 "context" 5 "strings" 6 "testing" 7 8 "github.com/stretchr/testify/assert" 9 corev1 "k8s.io/api/core/v1" 10 metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" 11 "k8s.io/apimachinery/pkg/runtime" 12 "k8s.io/client-go/kubernetes/fake" 13 ) 14 15 func TestCopySecret(t *testing.T) { 16 cases := []struct { 17 name string 18 sourceNamespace string 19 sourceName string 20 targetNamespace string 21 targetName string 22 source *corev1.Secret 23 existing *corev1.Secret 24 expected *corev1.Secret 25 errAssert func(err error) bool 26 }{ 27 { 28 name: "target should be created", 29 sourceNamespace: "ns1", 30 sourceName: "s1", 31 targetNamespace: "ns2", 32 targetName: "s2", 33 source: newSecret("ns1", "s1", map[string][]byte{ 34 "k1": []byte("v1"), 35 }), 36 existing: nil, 37 expected: newSecret("ns2", "s2", map[string][]byte{ 38 "k1": []byte("v1"), 39 }), 40 }, 41 { 42 name: "diff should be reconciled", 43 sourceNamespace: "ns1", 44 sourceName: "s1", 45 targetNamespace: "ns2", 46 targetName: "s2", 47 source: newSecret("ns1", "s1", map[string][]byte{ 48 "k1": []byte("v1"), 49 }), 50 existing: newSecret("ns2", "s2", map[string][]byte{ 51 "k1": []byte("v2"), 52 }), 53 expected: newSecret("ns2", "s2", map[string][]byte{ 54 "k1": []byte("v1"), 55 }), 56 }, 57 { 58 name: "extra content should be kept", 59 sourceNamespace: "ns1", 60 sourceName: "s1", 61 targetNamespace: "ns2", 62 targetName: "s2", 63 source: newSecret("ns1", "s1", map[string][]byte{ 64 "k1": []byte("v1"), 65 }), 66 existing: newSecret("ns2", "s2", map[string][]byte{ 67 "k1": []byte("v1"), 68 "k2": []byte("v2"), 69 }), 70 expected: newSecret("ns2", "s2", map[string][]byte{ 71 "k1": []byte("v1"), 72 "k2": []byte("v2"), 73 }), 74 }, 75 { 76 name: "no source should error", 77 sourceNamespace: "ns1", 78 sourceName: "s1", 79 targetNamespace: "ns2", 80 targetName: "s2", 81 errAssert: func(err error) bool { 82 return strings.HasPrefix(err.Error(), "failed getting source secret") 83 }, 84 }, 85 } 86 for _, c := range cases { 87 t.Run(c.name, func(t *testing.T) { 88 objs := []runtime.Object{} 89 if c.source != nil { 90 objs = append(objs, c.source) 91 } 92 if c.existing != nil { 93 objs = append(objs, c.existing) 94 } 95 client := fake.NewSimpleClientset(objs...) 96 err := CopySecret(client, c.sourceNamespace, c.sourceName, c.targetNamespace, c.targetName) 97 if c.errAssert != nil { 98 assert.True(t, c.errAssert(err)) 99 return 100 } 101 assert.NoError(t, err) 102 actual, err := client.CoreV1().Secrets(c.targetNamespace). 103 Get(context.TODO(), c.targetName, metav1.GetOptions{}) 104 assert.NoError(t, err) 105 assert.Equal(t, c.expected, actual) 106 }) 107 } 108 } 109 110 func newSecret(namespace, name string, data map[string][]byte) *corev1.Secret { 111 return &corev1.Secret{ 112 ObjectMeta: metav1.ObjectMeta{ 113 Namespace: namespace, 114 Name: name, 115 }, 116 Data: data, 117 } 118 }