1
// Copyright Istio Authors.
3
// Licensed under the Apache License, Version 2.0 (the "License");
4
// you may not use this file except in compliance with the License.
5
// You may obtain a copy of the License at
7
// http://www.apache.org/licenses/LICENSE-2.0
9
// Unless required by applicable law or agreed to in writing, software
10
// distributed under the License is distributed on an "AS IS" BASIS,
11
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
// See the License for the specific language governing permissions and
13
// limitations under the License.
25
"istio.io/istio/pkg/log"
29
_ Failer = &testing.T{}
30
_ Failer = &testing.B{}
31
_ Failer = &errorWrapper{}
34
// Failer is an interface to be provided to test functions of the form XXXOrFail. This is a
35
// substitute for testing.TB, which cannot be implemented outside of the testing
37
type Failer interface {
41
Fatalf(format string, args ...any)
43
Logf(format string, args ...any)
50
// Fuzzer abstracts *testing.F
51
type Fuzzer interface {
56
// errorWrapper is a Failer that can be used to just extract an `error`. This allows mixing
57
// functions that take in a Failer and those that take an error.
58
// The function must be called within a goroutine, or calls to Fatal will try to terminate the outer
59
// test context, which will cause the test to panic. The Wrap function handles this automatically
60
type errorWrapper struct {
66
// Wrap executes a function with a fake Failer, and returns an error if the test failed. This allows
67
// calling functions that take a Failer and using them with functions that expect an error, or
68
// allowing calling functions that would cause a test to immediately fail to instead return an error.
69
// Wrap handles Cleanup() and short-circuiting of Fatal() just like the real testing.T.
70
func Wrap(f func(t Failer)) error {
71
done := make(chan struct{})
78
return w.ToErrorCleanup()
81
// ToErrorCleanup returns any errors encountered and executes any cleanup actions
82
func (e *errorWrapper) ToErrorCleanup() error {
91
func (e *errorWrapper) Fail() {
92
e.Fatal("fail called")
95
func (e *errorWrapper) FailNow() {
96
e.Fatal("fail now called")
99
func (e *errorWrapper) Fatal(args ...any) {
103
e.failed = errors.New(fmt.Sprint(args...))
108
func (e *errorWrapper) Fatalf(format string, args ...any) {
109
e.Fatal(fmt.Sprintf(format, args...))
112
func (e *errorWrapper) Helper() {
115
func (e *errorWrapper) Skip(args ...any) {
119
func (e *errorWrapper) Cleanup(f func()) {
122
oldCleanup := e.cleanup
124
if oldCleanup != nil {
133
func (e *errorWrapper) Log(args ...any) {
134
log.Info(fmt.Sprint(args...))
137
func (e *errorWrapper) Logf(format string, args ...any) {
138
log.Infof(format, args...)
141
func (e *errorWrapper) TempDir() string {
142
tempDir, err := os.MkdirTemp("", "test")
145
os.RemoveAll(tempDir)