k8s.io/kubernetes@v1.29.3/test/e2e/framework/flake_reporting_util.go (about) 1 /* 2 Copyright 2018 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 framework 18 19 import ( 20 "bytes" 21 "fmt" 22 "sync" 23 ) 24 25 // FlakeReport is a struct for managing the flake report. 26 type FlakeReport struct { 27 lock sync.RWMutex 28 Flakes []string `json:"flakes"` 29 FlakeCount int `json:"flakeCount"` 30 } 31 32 // NewFlakeReport returns a new flake report. 33 func NewFlakeReport() *FlakeReport { 34 return &FlakeReport{ 35 Flakes: []string{}, 36 } 37 } 38 39 func buildDescription(optionalDescription ...interface{}) string { 40 switch len(optionalDescription) { 41 case 0: 42 return "" 43 default: 44 return fmt.Sprintf(optionalDescription[0].(string), optionalDescription[1:]...) 45 } 46 } 47 48 // RecordFlakeIfError records the error (if non-nil) as a flake along with an optional description. 49 // This can be used as a replacement of framework.ExpectNoError() for non-critical errors that can 50 // be considered as 'flakes' to avoid causing failures in tests. 51 func (f *FlakeReport) RecordFlakeIfError(err error, optionalDescription ...interface{}) { 52 if err == nil { 53 return 54 } 55 msg := fmt.Sprintf("Unexpected error occurred: %v", err) 56 desc := buildDescription(optionalDescription...) 57 if desc != "" { 58 msg = fmt.Sprintf("%v (Description: %v)", msg, desc) 59 } 60 Logf(msg) 61 f.lock.Lock() 62 defer f.lock.Unlock() 63 f.Flakes = append(f.Flakes, msg) 64 f.FlakeCount++ 65 } 66 67 // GetFlakeCount returns the flake count. 68 func (f *FlakeReport) GetFlakeCount() int { 69 f.lock.RLock() 70 defer f.lock.RUnlock() 71 return f.FlakeCount 72 } 73 74 // PrintHumanReadable returns string of flake report. 75 func (f *FlakeReport) PrintHumanReadable() string { 76 f.lock.RLock() 77 defer f.lock.RUnlock() 78 buf := bytes.Buffer{} 79 buf.WriteString(fmt.Sprintf("FlakeCount: %v\n", f.FlakeCount)) 80 buf.WriteString("Flakes:\n") 81 for _, flake := range f.Flakes { 82 buf.WriteString(fmt.Sprintf("%v\n", flake)) 83 } 84 return buf.String() 85 } 86 87 // PrintJSON returns the summary of frake report with JSON format. 88 func (f *FlakeReport) PrintJSON() string { 89 f.lock.RLock() 90 defer f.lock.RUnlock() 91 return PrettyPrintJSON(f) 92 } 93 94 // SummaryKind returns the summary of flake report. 95 func (f *FlakeReport) SummaryKind() string { 96 return "FlakeReport" 97 }