github.com/zppinho/prow@v0.0.0-20240510014325-1738badeb017/pkg/pjutil/tot_test.go (about) 1 /* 2 Copyright 2017 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 pjutil 18 19 import ( 20 "fmt" 21 "net/http" 22 "net/http/httptest" 23 "testing" 24 "time" 25 ) 26 27 type responseVendor struct { 28 codes []int 29 data []string 30 31 position int 32 } 33 34 func (r *responseVendor) next() (int, string) { 35 code := r.codes[r.position] 36 datum := r.data[r.position] 37 38 r.position = r.position + 1 39 if r.position == len(r.codes) { 40 r.position = 0 41 } 42 43 return code, datum 44 } 45 46 func parrotServer(codes []int, data []string) *httptest.Server { 47 vendor := responseVendor{ 48 codes: codes, 49 data: data, 50 } 51 52 return httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { 53 code, datum := vendor.next() 54 w.WriteHeader(code) 55 fmt.Fprint(w, datum) 56 })) 57 } 58 59 func TestGetBuildID(t *testing.T) { 60 oldSleep := sleep 61 sleep = func(time.Duration) {} 62 defer func() { sleep = oldSleep }() 63 64 var testCases = []struct { 65 name string 66 codes []int 67 data []string 68 expected string 69 expectedErr bool 70 }{ 71 { 72 name: "all good", 73 codes: []int{200}, 74 data: []string{"yay"}, 75 expected: "yay", 76 expectedErr: false, 77 }, 78 { 79 name: "fail then success", 80 codes: []int{500, 200}, 81 data: []string{"boo", "yay"}, 82 expected: "yay", 83 expectedErr: false, 84 }, 85 { 86 name: "fail", 87 codes: []int{500}, 88 data: []string{"boo"}, 89 expected: "boo", 90 expectedErr: true, 91 }, 92 } 93 94 for _, testCase := range testCases { 95 totServ := parrotServer(testCase.codes, testCase.data) 96 97 actual, actualErr := GetBuildID("dummy", totServ.URL) 98 if testCase.expectedErr && actualErr == nil { 99 t.Errorf("%s: expected an error but got none", testCase.name) 100 } else if !testCase.expectedErr && actualErr != nil { 101 t.Errorf("%s: expected no error but got one: %v", testCase.name, actualErr) 102 } else if !testCase.expectedErr && actual != testCase.expected { 103 t.Errorf("%s: expected response %v but got: %v", testCase.name, testCase.expected, actual) 104 } 105 106 totServ.Close() 107 } 108 }