sigs.k8s.io/prow@v0.0.0-20240503223140-c5e374dc7eb1/cmd/webhook-server/main_test.go (about) 1 /* 2 Copyright 2022 The Kubernetes Authors. 3 4 Licensed under the Apache License, Version 2.0 (the "License"); 5 you may not use this file except in compliance with the License. 6 You may obtain a copy of the License at 7 8 http://www.apache.org/licenses/LICENSE-2.0 9 10 Unless required by applicable law or agreed to in writing, software 11 distributed under the License is distributed on an "AS IS" BASIS, 12 WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 See the License for the specific language governing permissions and 14 limitations under the License. 15 */ 16 17 package main 18 19 import ( 20 "context" 21 "errors" 22 "fmt" 23 "testing" 24 ) 25 26 type secretStore struct { 27 store map[string]string 28 } 29 30 type fakeClient struct { 31 project secretStore 32 } 33 34 func newFakeClient() *fakeClient { 35 return &fakeClient{ 36 project: secretStore{ 37 store: make(map[string]string), 38 }, 39 } 40 } 41 func (f *fakeClient) CreateSecret(ctx context.Context, secretID string) error { 42 f.project.store[secretID] = "" 43 return nil 44 } 45 46 func (f *fakeClient) AddSecretVersion(ctx context.Context, secretName string, payload []byte) error { 47 f.project.store[secretName] = string(payload) 48 return nil 49 } 50 51 func (f *fakeClient) GetSecretValue(ctx context.Context, secretName string, versionName string) ([]byte, bool, error) { 52 if len(f.project.store) == 0 { 53 return nil, false, errors.New("Secret was not created!") 54 } else { 55 if val, ok := f.project.store[secretName]; ok { 56 return []byte(val), true, nil 57 } else { 58 err := fmt.Sprintf("Secret with name %s was never added", secretName) 59 return nil, false, errors.New(err) 60 } 61 } 62 } 63 64 func (f *fakeClient) CheckSecret(ctx context.Context, secretName string) (bool, error) { 65 if len(f.project.store) == 0 { 66 return false, errors.New("Secret was not created!") 67 } else { 68 if _, ok := f.project.store[secretName]; ok { 69 return true, nil 70 } else { 71 err := fmt.Sprintf("Secret with name %s was never added", secretName) 72 return false, errors.New(err) 73 } 74 } 75 } 76 77 const ( 78 secretID = "prowjob-webhook-secrets" 79 payload = "xxx123" 80 ) 81 82 func TestCreateSecrets(t *testing.T) { 83 ctx := context.Background() 84 f := newFakeClient() 85 f.CreateSecret(ctx, secretID) 86 if len(f.project.store) == 0 { 87 t.Errorf("secret was not created successfully") 88 } 89 } 90 91 func TestGetSecretValue(t *testing.T) { 92 ctx := context.Background() 93 f := newFakeClient() 94 f.AddSecretVersion(ctx, secretID, []byte(payload)) 95 res, exist, err := f.GetSecretValue(ctx, secretID, "") 96 if err != nil { 97 t.Errorf("could not get secret value %v", err) 98 } 99 if !exist { 100 t.Errorf("secret was not created") 101 } 102 if string(res) != payload { 103 t.Errorf("wrong secret obtained") 104 } 105 }