github.com/cloudwego/kitex@v0.9.0/internal/test/assert.go (about)

     1  /*
     2   * Copyright 2021 CloudWeGo 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 test
    18  
    19  import "reflect"
    20  
    21  // testingTB is a subset of common methods between *testing.T and *testing.B.
    22  type testingTB interface {
    23  	Fatal(args ...interface{})
    24  	Fatalf(format string, args ...interface{})
    25  	Helper()
    26  }
    27  
    28  // Assert asserts cond is true, otherwise fails the test.
    29  func Assert(t testingTB, cond bool, val ...interface{}) {
    30  	t.Helper()
    31  	if !cond {
    32  		if len(val) > 0 {
    33  			val = append([]interface{}{"assertion failed:"}, val...)
    34  			t.Fatal(val...)
    35  		} else {
    36  			t.Fatal("assertion failed")
    37  		}
    38  	}
    39  }
    40  
    41  // Assertf asserts cond is true, otherwise fails the test.
    42  func Assertf(t testingTB, cond bool, format string, val ...interface{}) {
    43  	t.Helper()
    44  	if !cond {
    45  		t.Fatalf(format, val...)
    46  	}
    47  }
    48  
    49  // DeepEqual asserts a and b are deep equal, otherwise fails the test.
    50  func DeepEqual(t testingTB, a, b interface{}) {
    51  	t.Helper()
    52  	if !reflect.DeepEqual(a, b) {
    53  		t.Fatalf("assertion failed: %v != %v", a, b)
    54  	}
    55  }
    56  
    57  // Panic asserts fn should panic and recover it, otherwise fails the test.
    58  func Panic(t testingTB, fn func()) {
    59  	t.Helper()
    60  	defer func() {
    61  		if err := recover(); err == nil {
    62  			t.Fatal("assertion failed: did not panic")
    63  		}
    64  	}()
    65  	fn()
    66  }
    67  
    68  // PanicAt asserts fn should panic and recover it, otherwise fails the test. The expect function can be provided to do further examination of the error.
    69  func PanicAt(t testingTB, fn func(), expect func(err interface{}) bool) {
    70  	t.Helper()
    71  	defer func() {
    72  		if err := recover(); err == nil {
    73  			t.Fatal("assertion failed: did not panic")
    74  		} else {
    75  			if expect != nil && !expect(err) {
    76  				t.Fatal("assertion failed: panic but not expected")
    77  			}
    78  		}
    79  	}()
    80  	fn()
    81  }