forked from ebhomengo/niki
1
0
Fork 0
niki/vendor/github.com/stretchr/testify/assert/assertions.go

3539 lines
61 KiB
Go
Raw Normal View History

2024-04-26 19:30:35 +00:00
package assert
import (
"bufio"
"bytes"
"encoding/json"
"errors"
"fmt"
"math"
"os"
"reflect"
"regexp"
"runtime"
"runtime/debug"
"strings"
"time"
"unicode"
"unicode/utf8"
"github.com/davecgh/go-spew/spew"
"github.com/pmezard/go-difflib/difflib"
2024-05-14 13:07:09 +00:00
"gopkg.in/yaml.v3"
2024-04-26 19:30:35 +00:00
)
//go:generate sh -c "cd ../_codegen && go build && cd - && ../_codegen/_codegen -output-package=assert -template=assertion_format.go.tmpl"
// TestingT is an interface wrapper around *testing.T
2024-04-26 19:30:35 +00:00
type TestingT interface {
Errorf(format string, args ...interface{})
}
// ComparisonAssertionFunc is a common function prototype when comparing two values. Can be useful
2024-04-26 19:30:35 +00:00
// for table driven tests.
2024-04-26 19:30:35 +00:00
type ComparisonAssertionFunc func(TestingT, interface{}, interface{}, ...interface{}) bool
// ValueAssertionFunc is a common function prototype when validating a single value. Can be useful
2024-04-26 19:30:35 +00:00
// for table driven tests.
2024-04-26 19:30:35 +00:00
type ValueAssertionFunc func(TestingT, interface{}, ...interface{}) bool
// BoolAssertionFunc is a common function prototype when validating a bool value. Can be useful
2024-04-26 19:30:35 +00:00
// for table driven tests.
2024-04-26 19:30:35 +00:00
type BoolAssertionFunc func(TestingT, bool, ...interface{}) bool
// ErrorAssertionFunc is a common function prototype when validating an error value. Can be useful
2024-04-26 19:30:35 +00:00
// for table driven tests.
2024-04-26 19:30:35 +00:00
type ErrorAssertionFunc func(TestingT, error, ...interface{}) bool
// Comparison is a custom function that returns true on success and false on failure
2024-04-26 19:30:35 +00:00
type Comparison func() (success bool)
/*
2024-04-26 19:30:35 +00:00
Helper functions
2024-04-26 19:30:35 +00:00
*/
// ObjectsAreEqual determines if two objects are considered equal.
2024-04-26 19:30:35 +00:00
//
2024-04-26 19:30:35 +00:00
// This function does no assertion of any kind.
2024-04-26 19:30:35 +00:00
func ObjectsAreEqual(expected, actual interface{}) bool {
2024-04-26 19:30:35 +00:00
if expected == nil || actual == nil {
2024-04-26 19:30:35 +00:00
return expected == actual
2024-04-26 19:30:35 +00:00
}
exp, ok := expected.([]byte)
2024-04-26 19:30:35 +00:00
if !ok {
2024-04-26 19:30:35 +00:00
return reflect.DeepEqual(expected, actual)
2024-04-26 19:30:35 +00:00
}
act, ok := actual.([]byte)
2024-04-26 19:30:35 +00:00
if !ok {
2024-04-26 19:30:35 +00:00
return false
2024-04-26 19:30:35 +00:00
}
2024-04-26 19:30:35 +00:00
if exp == nil || act == nil {
2024-04-26 19:30:35 +00:00
return exp == nil && act == nil
2024-04-26 19:30:35 +00:00
}
2024-04-26 19:30:35 +00:00
return bytes.Equal(exp, act)
2024-04-26 19:30:35 +00:00
}
// copyExportedFields iterates downward through nested data structures and creates a copy
2024-04-26 19:30:35 +00:00
// that only contains the exported struct fields.
2024-04-26 19:30:35 +00:00
func copyExportedFields(expected interface{}) interface{} {
2024-04-26 19:30:35 +00:00
if isNil(expected) {
2024-04-26 19:30:35 +00:00
return expected
2024-04-26 19:30:35 +00:00
}
expectedType := reflect.TypeOf(expected)
2024-04-26 19:30:35 +00:00
expectedKind := expectedType.Kind()
2024-04-26 19:30:35 +00:00
expectedValue := reflect.ValueOf(expected)
switch expectedKind {
2024-04-26 19:30:35 +00:00
case reflect.Struct:
2024-04-26 19:30:35 +00:00
result := reflect.New(expectedType).Elem()
2024-04-26 19:30:35 +00:00
for i := 0; i < expectedType.NumField(); i++ {
2024-04-26 19:30:35 +00:00
field := expectedType.Field(i)
2024-04-26 19:30:35 +00:00
isExported := field.IsExported()
2024-04-26 19:30:35 +00:00
if isExported {
2024-04-26 19:30:35 +00:00
fieldValue := expectedValue.Field(i)
2024-04-26 19:30:35 +00:00
if isNil(fieldValue) || isNil(fieldValue.Interface()) {
2024-04-26 19:30:35 +00:00
continue
2024-04-26 19:30:35 +00:00
}
2024-04-26 19:30:35 +00:00
newValue := copyExportedFields(fieldValue.Interface())
2024-04-26 19:30:35 +00:00
result.Field(i).Set(reflect.ValueOf(newValue))
2024-04-26 19:30:35 +00:00
}
2024-04-26 19:30:35 +00:00
}
2024-04-26 19:30:35 +00:00
return result.Interface()
case reflect.Ptr:
2024-04-26 19:30:35 +00:00
result := reflect.New(expectedType.Elem())
2024-04-26 19:30:35 +00:00
unexportedRemoved := copyExportedFields(expectedValue.Elem().Interface())
2024-04-26 19:30:35 +00:00
result.Elem().Set(reflect.ValueOf(unexportedRemoved))
2024-04-26 19:30:35 +00:00
return result.Interface()
case reflect.Array, reflect.Slice:
2024-05-14 13:07:09 +00:00
var result reflect.Value
2024-05-14 13:07:09 +00:00
if expectedKind == reflect.Array {
2024-05-14 13:07:09 +00:00
result = reflect.New(reflect.ArrayOf(expectedValue.Len(), expectedType.Elem())).Elem()
2024-05-14 13:07:09 +00:00
} else {
2024-05-14 13:07:09 +00:00
result = reflect.MakeSlice(expectedType, expectedValue.Len(), expectedValue.Len())
2024-05-14 13:07:09 +00:00
}
2024-04-26 19:30:35 +00:00
for i := 0; i < expectedValue.Len(); i++ {
2024-04-26 19:30:35 +00:00
index := expectedValue.Index(i)
2024-04-26 19:30:35 +00:00
if isNil(index) {
2024-04-26 19:30:35 +00:00
continue
2024-04-26 19:30:35 +00:00
}
2024-04-26 19:30:35 +00:00
unexportedRemoved := copyExportedFields(index.Interface())
2024-04-26 19:30:35 +00:00
result.Index(i).Set(reflect.ValueOf(unexportedRemoved))
2024-04-26 19:30:35 +00:00
}
2024-04-26 19:30:35 +00:00
return result.Interface()
case reflect.Map:
2024-04-26 19:30:35 +00:00
result := reflect.MakeMap(expectedType)
2024-04-26 19:30:35 +00:00
for _, k := range expectedValue.MapKeys() {
2024-04-26 19:30:35 +00:00
index := expectedValue.MapIndex(k)
2024-04-26 19:30:35 +00:00
unexportedRemoved := copyExportedFields(index.Interface())
2024-04-26 19:30:35 +00:00
result.SetMapIndex(k, reflect.ValueOf(unexportedRemoved))
2024-04-26 19:30:35 +00:00
}
2024-04-26 19:30:35 +00:00
return result.Interface()
default:
2024-04-26 19:30:35 +00:00
return expected
2024-04-26 19:30:35 +00:00
}
2024-04-26 19:30:35 +00:00
}
// ObjectsExportedFieldsAreEqual determines if the exported (public) fields of two objects are
2024-04-26 19:30:35 +00:00
// considered equal. This comparison of only exported fields is applied recursively to nested data
2024-04-26 19:30:35 +00:00
// structures.
2024-04-26 19:30:35 +00:00
//
2024-04-26 19:30:35 +00:00
// This function does no assertion of any kind.
2024-05-14 13:07:09 +00:00
//
2024-05-14 13:07:09 +00:00
// Deprecated: Use [EqualExportedValues] instead.
2024-04-26 19:30:35 +00:00
func ObjectsExportedFieldsAreEqual(expected, actual interface{}) bool {
2024-04-26 19:30:35 +00:00
expectedCleaned := copyExportedFields(expected)
2024-04-26 19:30:35 +00:00
actualCleaned := copyExportedFields(actual)
2024-04-26 19:30:35 +00:00
return ObjectsAreEqualValues(expectedCleaned, actualCleaned)
2024-04-26 19:30:35 +00:00
}
// ObjectsAreEqualValues gets whether two objects are equal, or if their
2024-04-26 19:30:35 +00:00
// values are equal.
2024-04-26 19:30:35 +00:00
func ObjectsAreEqualValues(expected, actual interface{}) bool {
2024-04-26 19:30:35 +00:00
if ObjectsAreEqual(expected, actual) {
2024-04-26 19:30:35 +00:00
return true
2024-04-26 19:30:35 +00:00
}
2024-05-14 13:07:09 +00:00
expectedValue := reflect.ValueOf(expected)
2024-05-14 13:07:09 +00:00
actualValue := reflect.ValueOf(actual)
2024-05-14 13:07:09 +00:00
if !expectedValue.IsValid() || !actualValue.IsValid() {
2024-04-26 19:30:35 +00:00
return false
2024-04-26 19:30:35 +00:00
}
2024-05-14 13:07:09 +00:00
expectedType := expectedValue.Type()
2024-05-14 13:07:09 +00:00
actualType := actualValue.Type()
2024-05-14 13:07:09 +00:00
if !expectedType.ConvertibleTo(actualType) {
2024-05-14 13:07:09 +00:00
return false
2024-05-14 13:07:09 +00:00
}
if !isNumericType(expectedType) || !isNumericType(actualType) {
2024-04-26 19:30:35 +00:00
// Attempt comparison after type conversion
2024-05-14 13:07:09 +00:00
return reflect.DeepEqual(
2024-05-14 13:07:09 +00:00
expectedValue.Convert(actualType).Interface(), actual,
)
2024-04-26 19:30:35 +00:00
}
2024-05-14 13:07:09 +00:00
// If BOTH values are numeric, there are chances of false positives due
2024-05-14 13:07:09 +00:00
// to overflow or underflow. So, we need to make sure to always convert
2024-05-14 13:07:09 +00:00
// the smaller type to a larger type before comparing.
2024-05-14 13:07:09 +00:00
if expectedType.Size() >= actualType.Size() {
2024-05-14 13:07:09 +00:00
return actualValue.Convert(expectedType).Interface() == expected
2024-05-14 13:07:09 +00:00
}
return expectedValue.Convert(actualType).Interface() == actual
2024-05-14 13:07:09 +00:00
}
// isNumericType returns true if the type is one of:
2024-05-14 13:07:09 +00:00
// int, int8, int16, int32, int64, uint, uint8, uint16, uint32, uint64,
2024-05-14 13:07:09 +00:00
// float32, float64, complex64, complex128
2024-05-14 13:07:09 +00:00
func isNumericType(t reflect.Type) bool {
2024-05-14 13:07:09 +00:00
return t.Kind() >= reflect.Int && t.Kind() <= reflect.Complex128
2024-04-26 19:30:35 +00:00
}
/* CallerInfo is necessary because the assert functions use the testing object
2024-04-26 19:30:35 +00:00
internally, causing it to print the file:line of the assert method, rather than where
2024-04-26 19:30:35 +00:00
the problem actually occurred in calling code.*/
// CallerInfo returns an array of strings containing the file and line number
2024-04-26 19:30:35 +00:00
// of each stack frame leading from the current test to the assert call that
2024-04-26 19:30:35 +00:00
// failed.
2024-04-26 19:30:35 +00:00
func CallerInfo() []string {
var pc uintptr
2024-04-26 19:30:35 +00:00
var ok bool
2024-04-26 19:30:35 +00:00
var file string
2024-04-26 19:30:35 +00:00
var line int
2024-04-26 19:30:35 +00:00
var name string
callers := []string{}
2024-04-26 19:30:35 +00:00
for i := 0; ; i++ {
2024-04-26 19:30:35 +00:00
pc, file, line, ok = runtime.Caller(i)
2024-04-26 19:30:35 +00:00
if !ok {
2024-04-26 19:30:35 +00:00
// The breaks below failed to terminate the loop, and we ran off the
2024-04-26 19:30:35 +00:00
// end of the call stack.
2024-04-26 19:30:35 +00:00
break
2024-04-26 19:30:35 +00:00
}
// This is a huge edge case, but it will panic if this is the case, see #180
2024-04-26 19:30:35 +00:00
if file == "<autogenerated>" {
2024-04-26 19:30:35 +00:00
break
2024-04-26 19:30:35 +00:00
}
f := runtime.FuncForPC(pc)
2024-04-26 19:30:35 +00:00
if f == nil {
2024-04-26 19:30:35 +00:00
break
2024-04-26 19:30:35 +00:00
}
2024-04-26 19:30:35 +00:00
name = f.Name()
// testing.tRunner is the standard library function that calls
2024-04-26 19:30:35 +00:00
// tests. Subtests are called directly by tRunner, without going through
2024-04-26 19:30:35 +00:00
// the Test/Benchmark/Example function that contains the t.Run calls, so
2024-04-26 19:30:35 +00:00
// with subtests we should break when we hit tRunner, without adding it
2024-04-26 19:30:35 +00:00
// to the list of callers.
2024-04-26 19:30:35 +00:00
if name == "testing.tRunner" {
2024-04-26 19:30:35 +00:00
break
2024-04-26 19:30:35 +00:00
}
parts := strings.Split(file, "/")
2024-04-26 19:30:35 +00:00
if len(parts) > 1 {
2024-04-26 19:30:35 +00:00
filename := parts[len(parts)-1]
2024-04-26 19:30:35 +00:00
dir := parts[len(parts)-2]
2024-04-26 19:30:35 +00:00
if (dir != "assert" && dir != "mock" && dir != "require") || filename == "mock_test.go" {
2024-04-26 19:30:35 +00:00
callers = append(callers, fmt.Sprintf("%s:%d", file, line))
2024-04-26 19:30:35 +00:00
}
2024-04-26 19:30:35 +00:00
}
// Drop the package
2024-04-26 19:30:35 +00:00
segments := strings.Split(name, ".")
2024-04-26 19:30:35 +00:00
name = segments[len(segments)-1]
2024-04-26 19:30:35 +00:00
if isTest(name, "Test") ||
2024-04-26 19:30:35 +00:00
isTest(name, "Benchmark") ||
2024-04-26 19:30:35 +00:00
isTest(name, "Example") {
2024-04-26 19:30:35 +00:00
break
2024-04-26 19:30:35 +00:00
}
2024-04-26 19:30:35 +00:00
}
return callers
2024-04-26 19:30:35 +00:00
}
// Stolen from the `go test` tool.
2024-04-26 19:30:35 +00:00
// isTest tells whether name looks like a test (or benchmark, according to prefix).
2024-04-26 19:30:35 +00:00
// It is a Test (say) if there is a character after Test that is not a lower-case letter.
2024-04-26 19:30:35 +00:00
// We don't want TesticularCancer.
2024-04-26 19:30:35 +00:00
func isTest(name, prefix string) bool {
2024-04-26 19:30:35 +00:00
if !strings.HasPrefix(name, prefix) {
2024-04-26 19:30:35 +00:00
return false
2024-04-26 19:30:35 +00:00
}
2024-04-26 19:30:35 +00:00
if len(name) == len(prefix) { // "Test" is ok
2024-04-26 19:30:35 +00:00
return true
2024-04-26 19:30:35 +00:00
}
2024-04-26 19:30:35 +00:00
r, _ := utf8.DecodeRuneInString(name[len(prefix):])
2024-04-26 19:30:35 +00:00
return !unicode.IsLower(r)
2024-04-26 19:30:35 +00:00
}
func messageFromMsgAndArgs(msgAndArgs ...interface{}) string {
2024-04-26 19:30:35 +00:00
if len(msgAndArgs) == 0 || msgAndArgs == nil {
2024-04-26 19:30:35 +00:00
return ""
2024-04-26 19:30:35 +00:00
}
2024-04-26 19:30:35 +00:00
if len(msgAndArgs) == 1 {
2024-04-26 19:30:35 +00:00
msg := msgAndArgs[0]
2024-04-26 19:30:35 +00:00
if msgAsStr, ok := msg.(string); ok {
2024-04-26 19:30:35 +00:00
return msgAsStr
2024-04-26 19:30:35 +00:00
}
2024-04-26 19:30:35 +00:00
return fmt.Sprintf("%+v", msg)
2024-04-26 19:30:35 +00:00
}
2024-04-26 19:30:35 +00:00
if len(msgAndArgs) > 1 {
2024-04-26 19:30:35 +00:00
return fmt.Sprintf(msgAndArgs[0].(string), msgAndArgs[1:]...)
2024-04-26 19:30:35 +00:00
}
2024-04-26 19:30:35 +00:00
return ""
2024-04-26 19:30:35 +00:00
}
// Aligns the provided message so that all lines after the first line start at the same location as the first line.
2024-04-26 19:30:35 +00:00
// Assumes that the first line starts at the correct location (after carriage return, tab, label, spacer and tab).
2024-05-14 13:07:09 +00:00
// The longestLabelLen parameter specifies the length of the longest label in the output (required because this is the
2024-04-26 19:30:35 +00:00
// basis on which the alignment occurs).
2024-04-26 19:30:35 +00:00
func indentMessageLines(message string, longestLabelLen int) string {
2024-04-26 19:30:35 +00:00
outBuf := new(bytes.Buffer)
for i, scanner := 0, bufio.NewScanner(strings.NewReader(message)); scanner.Scan(); i++ {
2024-04-26 19:30:35 +00:00
// no need to align first line because it starts at the correct location (after the label)
2024-04-26 19:30:35 +00:00
if i != 0 {
2024-04-26 19:30:35 +00:00
// append alignLen+1 spaces to align with "{{longestLabel}}:" before adding tab
2024-04-26 19:30:35 +00:00
outBuf.WriteString("\n\t" + strings.Repeat(" ", longestLabelLen+1) + "\t")
2024-04-26 19:30:35 +00:00
}
2024-04-26 19:30:35 +00:00
outBuf.WriteString(scanner.Text())
2024-04-26 19:30:35 +00:00
}
return outBuf.String()
2024-04-26 19:30:35 +00:00
}
type failNower interface {
FailNow()
}
// FailNow fails test
2024-04-26 19:30:35 +00:00
func FailNow(t TestingT, failureMessage string, msgAndArgs ...interface{}) bool {
2024-04-26 19:30:35 +00:00
if h, ok := t.(tHelper); ok {
2024-04-26 19:30:35 +00:00
h.Helper()
2024-04-26 19:30:35 +00:00
}
2024-04-26 19:30:35 +00:00
Fail(t, failureMessage, msgAndArgs...)
// We cannot extend TestingT with FailNow() and
2024-04-26 19:30:35 +00:00
// maintain backwards compatibility, so we fallback
2024-04-26 19:30:35 +00:00
// to panicking when FailNow is not available in
2024-04-26 19:30:35 +00:00
// TestingT.
2024-04-26 19:30:35 +00:00
// See issue #263
if t, ok := t.(failNower); ok {
2024-04-26 19:30:35 +00:00
t.FailNow()
2024-04-26 19:30:35 +00:00
} else {
2024-04-26 19:30:35 +00:00
panic("test failed and t is missing `FailNow()`")
2024-04-26 19:30:35 +00:00
}
2024-04-26 19:30:35 +00:00
return false
2024-04-26 19:30:35 +00:00
}
// Fail reports a failure through
2024-04-26 19:30:35 +00:00
func Fail(t TestingT, failureMessage string, msgAndArgs ...interface{}) bool {
2024-04-26 19:30:35 +00:00
if h, ok := t.(tHelper); ok {
2024-04-26 19:30:35 +00:00
h.Helper()
2024-04-26 19:30:35 +00:00
}
2024-04-26 19:30:35 +00:00
content := []labeledContent{
2024-04-26 19:30:35 +00:00
{"Error Trace", strings.Join(CallerInfo(), "\n\t\t\t")},
2024-04-26 19:30:35 +00:00
{"Error", failureMessage},
}
// Add test name if the Go version supports it
2024-04-26 19:30:35 +00:00
if n, ok := t.(interface {
Name() string
}); ok {
2024-04-26 19:30:35 +00:00
content = append(content, labeledContent{"Test", n.Name()})
2024-04-26 19:30:35 +00:00
}
message := messageFromMsgAndArgs(msgAndArgs...)
2024-04-26 19:30:35 +00:00
if len(message) > 0 {
2024-04-26 19:30:35 +00:00
content = append(content, labeledContent{"Messages", message})
2024-04-26 19:30:35 +00:00
}
t.Errorf("\n%s", ""+labeledOutput(content...))
return false
2024-04-26 19:30:35 +00:00
}
type labeledContent struct {
label string
2024-04-26 19:30:35 +00:00
content string
}
// labeledOutput returns a string consisting of the provided labeledContent. Each labeled output is appended in the following manner:
2024-04-26 19:30:35 +00:00
//
2024-04-26 19:30:35 +00:00
// \t{{label}}:{{align_spaces}}\t{{content}}\n
2024-04-26 19:30:35 +00:00
//
2024-04-26 19:30:35 +00:00
// The initial carriage return is required to undo/erase any padding added by testing.T.Errorf. The "\t{{label}}:" is for the label.
2024-04-26 19:30:35 +00:00
// If a label is shorter than the longest label provided, padding spaces are added to make all the labels match in length. Once this
2024-04-26 19:30:35 +00:00
// alignment is achieved, "\t{{content}}\n" is added for the output.
2024-04-26 19:30:35 +00:00
//
2024-04-26 19:30:35 +00:00
// If the content of the labeledOutput contains line breaks, the subsequent lines are aligned so that they start at the same location as the first line.
2024-04-26 19:30:35 +00:00
func labeledOutput(content ...labeledContent) string {
2024-04-26 19:30:35 +00:00
longestLabel := 0
2024-04-26 19:30:35 +00:00
for _, v := range content {
2024-04-26 19:30:35 +00:00
if len(v.label) > longestLabel {
2024-04-26 19:30:35 +00:00
longestLabel = len(v.label)
2024-04-26 19:30:35 +00:00
}
2024-04-26 19:30:35 +00:00
}
2024-04-26 19:30:35 +00:00
var output string
2024-04-26 19:30:35 +00:00
for _, v := range content {
2024-04-26 19:30:35 +00:00
output += "\t" + v.label + ":" + strings.Repeat(" ", longestLabel-len(v.label)) + "\t" + indentMessageLines(v.content, longestLabel) + "\n"
2024-04-26 19:30:35 +00:00
}
2024-04-26 19:30:35 +00:00
return output
2024-04-26 19:30:35 +00:00
}
// Implements asserts that an object is implemented by the specified interface.
2024-04-26 19:30:35 +00:00
//
2024-04-26 19:30:35 +00:00
// assert.Implements(t, (*MyInterface)(nil), new(MyObject))
2024-04-26 19:30:35 +00:00
func Implements(t TestingT, interfaceObject interface{}, object interface{}, msgAndArgs ...interface{}) bool {
2024-04-26 19:30:35 +00:00
if h, ok := t.(tHelper); ok {
2024-04-26 19:30:35 +00:00
h.Helper()
2024-04-26 19:30:35 +00:00
}
2024-04-26 19:30:35 +00:00
interfaceType := reflect.TypeOf(interfaceObject).Elem()
if object == nil {
2024-04-26 19:30:35 +00:00
return Fail(t, fmt.Sprintf("Cannot check if nil implements %v", interfaceType), msgAndArgs...)
2024-04-26 19:30:35 +00:00
}
2024-04-26 19:30:35 +00:00
if !reflect.TypeOf(object).Implements(interfaceType) {
2024-04-26 19:30:35 +00:00
return Fail(t, fmt.Sprintf("%T must implement %v", object, interfaceType), msgAndArgs...)
2024-04-26 19:30:35 +00:00
}
return true
2024-04-26 19:30:35 +00:00
}
2024-05-14 13:07:09 +00:00
// NotImplements asserts that an object does not implement the specified interface.
2024-05-14 13:07:09 +00:00
//
2024-05-14 13:07:09 +00:00
// assert.NotImplements(t, (*MyInterface)(nil), new(MyObject))
2024-05-14 13:07:09 +00:00
func NotImplements(t TestingT, interfaceObject interface{}, object interface{}, msgAndArgs ...interface{}) bool {
2024-05-14 13:07:09 +00:00
if h, ok := t.(tHelper); ok {
2024-05-14 13:07:09 +00:00
h.Helper()
2024-05-14 13:07:09 +00:00
}
2024-05-14 13:07:09 +00:00
interfaceType := reflect.TypeOf(interfaceObject).Elem()
if object == nil {
2024-05-14 13:07:09 +00:00
return Fail(t, fmt.Sprintf("Cannot check if nil does not implement %v", interfaceType), msgAndArgs...)
2024-05-14 13:07:09 +00:00
}
2024-05-14 13:07:09 +00:00
if reflect.TypeOf(object).Implements(interfaceType) {
2024-05-14 13:07:09 +00:00
return Fail(t, fmt.Sprintf("%T implements %v", object, interfaceType), msgAndArgs...)
2024-05-14 13:07:09 +00:00
}
return true
2024-05-14 13:07:09 +00:00
}
2024-04-26 19:30:35 +00:00
// IsType asserts that the specified objects are of the same type.
2024-04-26 19:30:35 +00:00
func IsType(t TestingT, expectedType interface{}, object interface{}, msgAndArgs ...interface{}) bool {
2024-04-26 19:30:35 +00:00
if h, ok := t.(tHelper); ok {
2024-04-26 19:30:35 +00:00
h.Helper()
2024-04-26 19:30:35 +00:00
}
if !ObjectsAreEqual(reflect.TypeOf(object), reflect.TypeOf(expectedType)) {
2024-04-26 19:30:35 +00:00
return Fail(t, fmt.Sprintf("Object expected to be of type %v, but was %v", reflect.TypeOf(expectedType), reflect.TypeOf(object)), msgAndArgs...)
2024-04-26 19:30:35 +00:00
}
return true
2024-04-26 19:30:35 +00:00
}
// Equal asserts that two objects are equal.
2024-04-26 19:30:35 +00:00
//
2024-04-26 19:30:35 +00:00
// assert.Equal(t, 123, 123)
2024-04-26 19:30:35 +00:00
//
2024-04-26 19:30:35 +00:00
// Pointer variable equality is determined based on the equality of the
2024-04-26 19:30:35 +00:00
// referenced values (as opposed to the memory addresses). Function equality
2024-04-26 19:30:35 +00:00
// cannot be determined and will always fail.
2024-04-26 19:30:35 +00:00
func Equal(t TestingT, expected, actual interface{}, msgAndArgs ...interface{}) bool {
2024-04-26 19:30:35 +00:00
if h, ok := t.(tHelper); ok {
2024-04-26 19:30:35 +00:00
h.Helper()
2024-04-26 19:30:35 +00:00
}
2024-04-26 19:30:35 +00:00
if err := validateEqualArgs(expected, actual); err != nil {
2024-04-26 19:30:35 +00:00
return Fail(t, fmt.Sprintf("Invalid operation: %#v == %#v (%s)",
2024-04-26 19:30:35 +00:00
expected, actual, err), msgAndArgs...)
2024-04-26 19:30:35 +00:00
}
if !ObjectsAreEqual(expected, actual) {
2024-04-26 19:30:35 +00:00
diff := diff(expected, actual)
2024-04-26 19:30:35 +00:00
expected, actual = formatUnequalValues(expected, actual)
2024-04-26 19:30:35 +00:00
return Fail(t, fmt.Sprintf("Not equal: \n"+
2024-04-26 19:30:35 +00:00
"expected: %s\n"+
2024-04-26 19:30:35 +00:00
"actual : %s%s", expected, actual, diff), msgAndArgs...)
2024-04-26 19:30:35 +00:00
}
return true
}
// validateEqualArgs checks whether provided arguments can be safely used in the
2024-04-26 19:30:35 +00:00
// Equal/NotEqual functions.
2024-04-26 19:30:35 +00:00
func validateEqualArgs(expected, actual interface{}) error {
2024-04-26 19:30:35 +00:00
if expected == nil && actual == nil {
2024-04-26 19:30:35 +00:00
return nil
2024-04-26 19:30:35 +00:00
}
if isFunction(expected) || isFunction(actual) {
2024-04-26 19:30:35 +00:00
return errors.New("cannot take func type as argument")
2024-04-26 19:30:35 +00:00
}
2024-04-26 19:30:35 +00:00
return nil
2024-04-26 19:30:35 +00:00
}
// Same asserts that two pointers reference the same object.
2024-04-26 19:30:35 +00:00
//
2024-04-26 19:30:35 +00:00
// assert.Same(t, ptr1, ptr2)
2024-04-26 19:30:35 +00:00
//
2024-04-26 19:30:35 +00:00
// Both arguments must be pointer variables. Pointer variable sameness is
2024-04-26 19:30:35 +00:00
// determined based on the equality of both type and value.
2024-04-26 19:30:35 +00:00
func Same(t TestingT, expected, actual interface{}, msgAndArgs ...interface{}) bool {
2024-04-26 19:30:35 +00:00
if h, ok := t.(tHelper); ok {
2024-04-26 19:30:35 +00:00
h.Helper()
2024-04-26 19:30:35 +00:00
}
if !samePointers(expected, actual) {
2024-04-26 19:30:35 +00:00
return Fail(t, fmt.Sprintf("Not same: \n"+
2024-04-26 19:30:35 +00:00
"expected: %p %#v\n"+
2024-04-26 19:30:35 +00:00
"actual : %p %#v", expected, expected, actual, actual), msgAndArgs...)
2024-04-26 19:30:35 +00:00
}
return true
2024-04-26 19:30:35 +00:00
}
// NotSame asserts that two pointers do not reference the same object.
2024-04-26 19:30:35 +00:00
//
2024-04-26 19:30:35 +00:00
// assert.NotSame(t, ptr1, ptr2)
2024-04-26 19:30:35 +00:00
//
2024-04-26 19:30:35 +00:00
// Both arguments must be pointer variables. Pointer variable sameness is
2024-04-26 19:30:35 +00:00
// determined based on the equality of both type and value.
2024-04-26 19:30:35 +00:00
func NotSame(t TestingT, expected, actual interface{}, msgAndArgs ...interface{}) bool {
2024-04-26 19:30:35 +00:00
if h, ok := t.(tHelper); ok {
2024-04-26 19:30:35 +00:00
h.Helper()
2024-04-26 19:30:35 +00:00
}
if samePointers(expected, actual) {
2024-04-26 19:30:35 +00:00
return Fail(t, fmt.Sprintf(
2024-04-26 19:30:35 +00:00
"Expected and actual point to the same object: %p %#v",
2024-04-26 19:30:35 +00:00
expected, expected), msgAndArgs...)
2024-04-26 19:30:35 +00:00
}
2024-04-26 19:30:35 +00:00
return true
2024-04-26 19:30:35 +00:00
}
// samePointers compares two generic interface objects and returns whether
2024-04-26 19:30:35 +00:00
// they point to the same object
2024-04-26 19:30:35 +00:00
func samePointers(first, second interface{}) bool {
2024-04-26 19:30:35 +00:00
firstPtr, secondPtr := reflect.ValueOf(first), reflect.ValueOf(second)
2024-04-26 19:30:35 +00:00
if firstPtr.Kind() != reflect.Ptr || secondPtr.Kind() != reflect.Ptr {
2024-04-26 19:30:35 +00:00
return false
2024-04-26 19:30:35 +00:00
}
firstType, secondType := reflect.TypeOf(first), reflect.TypeOf(second)
2024-04-26 19:30:35 +00:00
if firstType != secondType {
2024-04-26 19:30:35 +00:00
return false
2024-04-26 19:30:35 +00:00
}
// compare pointer addresses
2024-04-26 19:30:35 +00:00
return first == second
2024-04-26 19:30:35 +00:00
}
// formatUnequalValues takes two values of arbitrary types and returns string
2024-04-26 19:30:35 +00:00
// representations appropriate to be presented to the user.
2024-04-26 19:30:35 +00:00
//
2024-04-26 19:30:35 +00:00
// If the values are not of like type, the returned strings will be prefixed
2024-05-14 13:07:09 +00:00
// with the type name, and the value will be enclosed in parentheses similar
2024-04-26 19:30:35 +00:00
// to a type conversion in the Go grammar.
2024-04-26 19:30:35 +00:00
func formatUnequalValues(expected, actual interface{}) (e string, a string) {
2024-04-26 19:30:35 +00:00
if reflect.TypeOf(expected) != reflect.TypeOf(actual) {
2024-04-26 19:30:35 +00:00
return fmt.Sprintf("%T(%s)", expected, truncatingFormat(expected)),
2024-04-26 19:30:35 +00:00
fmt.Sprintf("%T(%s)", actual, truncatingFormat(actual))
2024-04-26 19:30:35 +00:00
}
2024-04-26 19:30:35 +00:00
switch expected.(type) {
2024-04-26 19:30:35 +00:00
case time.Duration:
2024-04-26 19:30:35 +00:00
return fmt.Sprintf("%v", expected), fmt.Sprintf("%v", actual)
2024-04-26 19:30:35 +00:00
}
2024-04-26 19:30:35 +00:00
return truncatingFormat(expected), truncatingFormat(actual)
2024-04-26 19:30:35 +00:00
}
// truncatingFormat formats the data and truncates it if it's too long.
2024-04-26 19:30:35 +00:00
//
2024-04-26 19:30:35 +00:00
// This helps keep formatted error messages lines from exceeding the
2024-04-26 19:30:35 +00:00
// bufio.MaxScanTokenSize max line length that the go testing framework imposes.
2024-04-26 19:30:35 +00:00
func truncatingFormat(data interface{}) string {
2024-04-26 19:30:35 +00:00
value := fmt.Sprintf("%#v", data)
2024-04-26 19:30:35 +00:00
max := bufio.MaxScanTokenSize - 100 // Give us some space the type info too if needed.
2024-04-26 19:30:35 +00:00
if len(value) > max {
2024-04-26 19:30:35 +00:00
value = value[0:max] + "<... truncated>"
2024-04-26 19:30:35 +00:00
}
2024-04-26 19:30:35 +00:00
return value
2024-04-26 19:30:35 +00:00
}
2024-05-14 13:07:09 +00:00
// EqualValues asserts that two objects are equal or convertible to the same types
2024-04-26 19:30:35 +00:00
// and equal.
2024-04-26 19:30:35 +00:00
//
2024-04-26 19:30:35 +00:00
// assert.EqualValues(t, uint32(123), int32(123))
2024-04-26 19:30:35 +00:00
func EqualValues(t TestingT, expected, actual interface{}, msgAndArgs ...interface{}) bool {
2024-04-26 19:30:35 +00:00
if h, ok := t.(tHelper); ok {
2024-04-26 19:30:35 +00:00
h.Helper()
2024-04-26 19:30:35 +00:00
}
if !ObjectsAreEqualValues(expected, actual) {
2024-04-26 19:30:35 +00:00
diff := diff(expected, actual)
2024-04-26 19:30:35 +00:00
expected, actual = formatUnequalValues(expected, actual)
2024-04-26 19:30:35 +00:00
return Fail(t, fmt.Sprintf("Not equal: \n"+
2024-04-26 19:30:35 +00:00
"expected: %s\n"+
2024-04-26 19:30:35 +00:00
"actual : %s%s", expected, actual, diff), msgAndArgs...)
2024-04-26 19:30:35 +00:00
}
return true
}
// EqualExportedValues asserts that the types of two objects are equal and their public
2024-04-26 19:30:35 +00:00
// fields are also equal. This is useful for comparing structs that have private fields
2024-04-26 19:30:35 +00:00
// that could potentially differ.
2024-04-26 19:30:35 +00:00
//
2024-04-26 19:30:35 +00:00
// type S struct {
2024-04-26 19:30:35 +00:00
// Exported int
2024-04-26 19:30:35 +00:00
// notExported int
2024-04-26 19:30:35 +00:00
// }
2024-04-26 19:30:35 +00:00
// assert.EqualExportedValues(t, S{1, 2}, S{1, 3}) => true
2024-04-26 19:30:35 +00:00
// assert.EqualExportedValues(t, S{1, 2}, S{2, 3}) => false
2024-04-26 19:30:35 +00:00
func EqualExportedValues(t TestingT, expected, actual interface{}, msgAndArgs ...interface{}) bool {
2024-04-26 19:30:35 +00:00
if h, ok := t.(tHelper); ok {
2024-04-26 19:30:35 +00:00
h.Helper()
2024-04-26 19:30:35 +00:00
}
aType := reflect.TypeOf(expected)
2024-04-26 19:30:35 +00:00
bType := reflect.TypeOf(actual)
if aType != bType {
2024-04-26 19:30:35 +00:00
return Fail(t, fmt.Sprintf("Types expected to match exactly\n\t%v != %v", aType, bType), msgAndArgs...)
2024-04-26 19:30:35 +00:00
}
2024-05-14 13:07:09 +00:00
if aType.Kind() == reflect.Ptr {
2024-05-14 13:07:09 +00:00
aType = aType.Elem()
2024-05-14 13:07:09 +00:00
}
2024-05-14 13:07:09 +00:00
if bType.Kind() == reflect.Ptr {
2024-05-14 13:07:09 +00:00
bType = bType.Elem()
2024-05-14 13:07:09 +00:00
}
2024-04-26 19:30:35 +00:00
if aType.Kind() != reflect.Struct {
2024-05-14 13:07:09 +00:00
return Fail(t, fmt.Sprintf("Types expected to both be struct or pointer to struct \n\t%v != %v", aType.Kind(), reflect.Struct), msgAndArgs...)
2024-04-26 19:30:35 +00:00
}
if bType.Kind() != reflect.Struct {
2024-05-14 13:07:09 +00:00
return Fail(t, fmt.Sprintf("Types expected to both be struct or pointer to struct \n\t%v != %v", bType.Kind(), reflect.Struct), msgAndArgs...)
2024-04-26 19:30:35 +00:00
}
expected = copyExportedFields(expected)
2024-04-26 19:30:35 +00:00
actual = copyExportedFields(actual)
if !ObjectsAreEqualValues(expected, actual) {
2024-04-26 19:30:35 +00:00
diff := diff(expected, actual)
2024-04-26 19:30:35 +00:00
expected, actual = formatUnequalValues(expected, actual)
2024-04-26 19:30:35 +00:00
return Fail(t, fmt.Sprintf("Not equal (comparing only exported fields): \n"+
2024-04-26 19:30:35 +00:00
"expected: %s\n"+
2024-04-26 19:30:35 +00:00
"actual : %s%s", expected, actual, diff), msgAndArgs...)
2024-04-26 19:30:35 +00:00
}
return true
2024-04-26 19:30:35 +00:00
}
// Exactly asserts that two objects are equal in value and type.
2024-04-26 19:30:35 +00:00
//
2024-04-26 19:30:35 +00:00
// assert.Exactly(t, int32(123), int64(123))
2024-04-26 19:30:35 +00:00
func Exactly(t TestingT, expected, actual interface{}, msgAndArgs ...interface{}) bool {
2024-04-26 19:30:35 +00:00
if h, ok := t.(tHelper); ok {
2024-04-26 19:30:35 +00:00
h.Helper()
2024-04-26 19:30:35 +00:00
}
aType := reflect.TypeOf(expected)
2024-04-26 19:30:35 +00:00
bType := reflect.TypeOf(actual)
if aType != bType {
2024-04-26 19:30:35 +00:00
return Fail(t, fmt.Sprintf("Types expected to match exactly\n\t%v != %v", aType, bType), msgAndArgs...)
2024-04-26 19:30:35 +00:00
}
return Equal(t, expected, actual, msgAndArgs...)
}
// NotNil asserts that the specified object is not nil.
2024-04-26 19:30:35 +00:00
//
2024-04-26 19:30:35 +00:00
// assert.NotNil(t, err)
2024-04-26 19:30:35 +00:00
func NotNil(t TestingT, object interface{}, msgAndArgs ...interface{}) bool {
2024-04-26 19:30:35 +00:00
if !isNil(object) {
2024-04-26 19:30:35 +00:00
return true
2024-04-26 19:30:35 +00:00
}
2024-04-26 19:30:35 +00:00
if h, ok := t.(tHelper); ok {
2024-04-26 19:30:35 +00:00
h.Helper()
2024-04-26 19:30:35 +00:00
}
2024-04-26 19:30:35 +00:00
return Fail(t, "Expected value not to be nil.", msgAndArgs...)
2024-04-26 19:30:35 +00:00
}
// isNil checks if a specified object is nil or not, without Failing.
2024-04-26 19:30:35 +00:00
func isNil(object interface{}) bool {
2024-04-26 19:30:35 +00:00
if object == nil {
2024-04-26 19:30:35 +00:00
return true
2024-04-26 19:30:35 +00:00
}
value := reflect.ValueOf(object)
2024-05-14 13:07:09 +00:00
switch value.Kind() {
2024-05-14 13:07:09 +00:00
case
2024-05-14 13:07:09 +00:00
reflect.Chan, reflect.Func,
2024-05-14 13:07:09 +00:00
reflect.Interface, reflect.Map,
2024-05-14 13:07:09 +00:00
reflect.Ptr, reflect.Slice, reflect.UnsafePointer:
return value.IsNil()
2024-04-26 19:30:35 +00:00
}
return false
2024-04-26 19:30:35 +00:00
}
// Nil asserts that the specified object is nil.
2024-04-26 19:30:35 +00:00
//
2024-04-26 19:30:35 +00:00
// assert.Nil(t, err)
2024-04-26 19:30:35 +00:00
func Nil(t TestingT, object interface{}, msgAndArgs ...interface{}) bool {
2024-04-26 19:30:35 +00:00
if isNil(object) {
2024-04-26 19:30:35 +00:00
return true
2024-04-26 19:30:35 +00:00
}
2024-04-26 19:30:35 +00:00
if h, ok := t.(tHelper); ok {
2024-04-26 19:30:35 +00:00
h.Helper()
2024-04-26 19:30:35 +00:00
}
2024-04-26 19:30:35 +00:00
return Fail(t, fmt.Sprintf("Expected nil, but got: %#v", object), msgAndArgs...)
2024-04-26 19:30:35 +00:00
}
// isEmpty gets whether the specified object is considered empty or not.
2024-04-26 19:30:35 +00:00
func isEmpty(object interface{}) bool {
// get nil case out of the way
2024-04-26 19:30:35 +00:00
if object == nil {
2024-04-26 19:30:35 +00:00
return true
2024-04-26 19:30:35 +00:00
}
objValue := reflect.ValueOf(object)
switch objValue.Kind() {
2024-04-26 19:30:35 +00:00
// collection types are empty when they have no element
2024-04-26 19:30:35 +00:00
case reflect.Chan, reflect.Map, reflect.Slice:
2024-04-26 19:30:35 +00:00
return objValue.Len() == 0
2024-04-26 19:30:35 +00:00
// pointers are empty if nil or if the value they point to is empty
2024-04-26 19:30:35 +00:00
case reflect.Ptr:
2024-04-26 19:30:35 +00:00
if objValue.IsNil() {
2024-04-26 19:30:35 +00:00
return true
2024-04-26 19:30:35 +00:00
}
2024-04-26 19:30:35 +00:00
deref := objValue.Elem().Interface()
2024-04-26 19:30:35 +00:00
return isEmpty(deref)
2024-04-26 19:30:35 +00:00
// for all other types, compare against the zero value
2024-04-26 19:30:35 +00:00
// array types are empty when they match their zero-initialized state
2024-04-26 19:30:35 +00:00
default:
2024-04-26 19:30:35 +00:00
zero := reflect.Zero(objValue.Type())
2024-04-26 19:30:35 +00:00
return reflect.DeepEqual(object, zero.Interface())
2024-04-26 19:30:35 +00:00
}
2024-04-26 19:30:35 +00:00
}
// Empty asserts that the specified object is empty. I.e. nil, "", false, 0 or either
2024-04-26 19:30:35 +00:00
// a slice or a channel with len == 0.
2024-04-26 19:30:35 +00:00
//
2024-04-26 19:30:35 +00:00
// assert.Empty(t, obj)
2024-04-26 19:30:35 +00:00
func Empty(t TestingT, object interface{}, msgAndArgs ...interface{}) bool {
2024-04-26 19:30:35 +00:00
pass := isEmpty(object)
2024-04-26 19:30:35 +00:00
if !pass {
2024-04-26 19:30:35 +00:00
if h, ok := t.(tHelper); ok {
2024-04-26 19:30:35 +00:00
h.Helper()
2024-04-26 19:30:35 +00:00
}
2024-04-26 19:30:35 +00:00
Fail(t, fmt.Sprintf("Should be empty, but was %v", object), msgAndArgs...)
2024-04-26 19:30:35 +00:00
}
return pass
}
// NotEmpty asserts that the specified object is NOT empty. I.e. not nil, "", false, 0 or either
2024-04-26 19:30:35 +00:00
// a slice or a channel with len == 0.
2024-04-26 19:30:35 +00:00
//
2024-04-26 19:30:35 +00:00
// if assert.NotEmpty(t, obj) {
2024-04-26 19:30:35 +00:00
// assert.Equal(t, "two", obj[1])
2024-04-26 19:30:35 +00:00
// }
2024-04-26 19:30:35 +00:00
func NotEmpty(t TestingT, object interface{}, msgAndArgs ...interface{}) bool {
2024-04-26 19:30:35 +00:00
pass := !isEmpty(object)
2024-04-26 19:30:35 +00:00
if !pass {
2024-04-26 19:30:35 +00:00
if h, ok := t.(tHelper); ok {
2024-04-26 19:30:35 +00:00
h.Helper()
2024-04-26 19:30:35 +00:00
}
2024-04-26 19:30:35 +00:00
Fail(t, fmt.Sprintf("Should NOT be empty, but was %v", object), msgAndArgs...)
2024-04-26 19:30:35 +00:00
}
return pass
}
2024-05-14 13:07:09 +00:00
// getLen tries to get the length of an object.
2024-05-14 13:07:09 +00:00
// It returns (0, false) if impossible.
2024-05-14 13:07:09 +00:00
func getLen(x interface{}) (length int, ok bool) {
2024-04-26 19:30:35 +00:00
v := reflect.ValueOf(x)
2024-04-26 19:30:35 +00:00
defer func() {
2024-05-14 13:07:09 +00:00
ok = recover() == nil
2024-04-26 19:30:35 +00:00
}()
2024-05-14 13:07:09 +00:00
return v.Len(), true
2024-04-26 19:30:35 +00:00
}
// Len asserts that the specified object has specific length.
2024-04-26 19:30:35 +00:00
// Len also fails if the object has a type that len() not accept.
2024-04-26 19:30:35 +00:00
//
2024-04-26 19:30:35 +00:00
// assert.Len(t, mySlice, 3)
2024-04-26 19:30:35 +00:00
func Len(t TestingT, object interface{}, length int, msgAndArgs ...interface{}) bool {
2024-04-26 19:30:35 +00:00
if h, ok := t.(tHelper); ok {
2024-04-26 19:30:35 +00:00
h.Helper()
2024-04-26 19:30:35 +00:00
}
2024-05-14 13:07:09 +00:00
l, ok := getLen(object)
2024-04-26 19:30:35 +00:00
if !ok {
2024-05-14 13:07:09 +00:00
return Fail(t, fmt.Sprintf("\"%v\" could not be applied builtin len()", object), msgAndArgs...)
2024-04-26 19:30:35 +00:00
}
if l != length {
2024-05-14 13:07:09 +00:00
return Fail(t, fmt.Sprintf("\"%v\" should have %d item(s), but has %d", object, length, l), msgAndArgs...)
2024-04-26 19:30:35 +00:00
}
2024-04-26 19:30:35 +00:00
return true
2024-04-26 19:30:35 +00:00
}
// True asserts that the specified value is true.
2024-04-26 19:30:35 +00:00
//
2024-04-26 19:30:35 +00:00
// assert.True(t, myBool)
2024-04-26 19:30:35 +00:00
func True(t TestingT, value bool, msgAndArgs ...interface{}) bool {
2024-04-26 19:30:35 +00:00
if !value {
2024-04-26 19:30:35 +00:00
if h, ok := t.(tHelper); ok {
2024-04-26 19:30:35 +00:00
h.Helper()
2024-04-26 19:30:35 +00:00
}
2024-04-26 19:30:35 +00:00
return Fail(t, "Should be true", msgAndArgs...)
2024-04-26 19:30:35 +00:00
}
return true
}
// False asserts that the specified value is false.
2024-04-26 19:30:35 +00:00
//
2024-04-26 19:30:35 +00:00
// assert.False(t, myBool)
2024-04-26 19:30:35 +00:00
func False(t TestingT, value bool, msgAndArgs ...interface{}) bool {
2024-04-26 19:30:35 +00:00
if value {
2024-04-26 19:30:35 +00:00
if h, ok := t.(tHelper); ok {
2024-04-26 19:30:35 +00:00
h.Helper()
2024-04-26 19:30:35 +00:00
}
2024-04-26 19:30:35 +00:00
return Fail(t, "Should be false", msgAndArgs...)
2024-04-26 19:30:35 +00:00
}
return true
}
// NotEqual asserts that the specified values are NOT equal.
2024-04-26 19:30:35 +00:00
//
2024-04-26 19:30:35 +00:00
// assert.NotEqual(t, obj1, obj2)
2024-04-26 19:30:35 +00:00
//
2024-04-26 19:30:35 +00:00
// Pointer variable equality is determined based on the equality of the
2024-04-26 19:30:35 +00:00
// referenced values (as opposed to the memory addresses).
2024-04-26 19:30:35 +00:00
func NotEqual(t TestingT, expected, actual interface{}, msgAndArgs ...interface{}) bool {
2024-04-26 19:30:35 +00:00
if h, ok := t.(tHelper); ok {
2024-04-26 19:30:35 +00:00
h.Helper()
2024-04-26 19:30:35 +00:00
}
2024-04-26 19:30:35 +00:00
if err := validateEqualArgs(expected, actual); err != nil {
2024-04-26 19:30:35 +00:00
return Fail(t, fmt.Sprintf("Invalid operation: %#v != %#v (%s)",
2024-04-26 19:30:35 +00:00
expected, actual, err), msgAndArgs...)
2024-04-26 19:30:35 +00:00
}
if ObjectsAreEqual(expected, actual) {
2024-04-26 19:30:35 +00:00
return Fail(t, fmt.Sprintf("Should not be: %#v\n", actual), msgAndArgs...)
2024-04-26 19:30:35 +00:00
}
return true
}
// NotEqualValues asserts that two objects are not equal even when converted to the same type
2024-04-26 19:30:35 +00:00
//
2024-04-26 19:30:35 +00:00
// assert.NotEqualValues(t, obj1, obj2)
2024-04-26 19:30:35 +00:00
func NotEqualValues(t TestingT, expected, actual interface{}, msgAndArgs ...interface{}) bool {
2024-04-26 19:30:35 +00:00
if h, ok := t.(tHelper); ok {
2024-04-26 19:30:35 +00:00
h.Helper()
2024-04-26 19:30:35 +00:00
}
if ObjectsAreEqualValues(expected, actual) {
2024-04-26 19:30:35 +00:00
return Fail(t, fmt.Sprintf("Should not be: %#v\n", actual), msgAndArgs...)
2024-04-26 19:30:35 +00:00
}
return true
2024-04-26 19:30:35 +00:00
}
// containsElement try loop over the list check if the list includes the element.
2024-04-26 19:30:35 +00:00
// return (false, false) if impossible.
2024-04-26 19:30:35 +00:00
// return (true, false) if element was not found.
2024-04-26 19:30:35 +00:00
// return (true, true) if element was found.
2024-04-26 19:30:35 +00:00
func containsElement(list interface{}, element interface{}) (ok, found bool) {
listValue := reflect.ValueOf(list)
2024-04-26 19:30:35 +00:00
listType := reflect.TypeOf(list)
2024-04-26 19:30:35 +00:00
if listType == nil {
2024-04-26 19:30:35 +00:00
return false, false
2024-04-26 19:30:35 +00:00
}
2024-04-26 19:30:35 +00:00
listKind := listType.Kind()
2024-04-26 19:30:35 +00:00
defer func() {
2024-04-26 19:30:35 +00:00
if e := recover(); e != nil {
2024-04-26 19:30:35 +00:00
ok = false
2024-04-26 19:30:35 +00:00
found = false
2024-04-26 19:30:35 +00:00
}
2024-04-26 19:30:35 +00:00
}()
if listKind == reflect.String {
2024-04-26 19:30:35 +00:00
elementValue := reflect.ValueOf(element)
2024-04-26 19:30:35 +00:00
return true, strings.Contains(listValue.String(), elementValue.String())
2024-04-26 19:30:35 +00:00
}
if listKind == reflect.Map {
2024-04-26 19:30:35 +00:00
mapKeys := listValue.MapKeys()
2024-04-26 19:30:35 +00:00
for i := 0; i < len(mapKeys); i++ {
2024-04-26 19:30:35 +00:00
if ObjectsAreEqual(mapKeys[i].Interface(), element) {
2024-04-26 19:30:35 +00:00
return true, true
2024-04-26 19:30:35 +00:00
}
2024-04-26 19:30:35 +00:00
}
2024-04-26 19:30:35 +00:00
return true, false
2024-04-26 19:30:35 +00:00
}
for i := 0; i < listValue.Len(); i++ {
2024-04-26 19:30:35 +00:00
if ObjectsAreEqual(listValue.Index(i).Interface(), element) {
2024-04-26 19:30:35 +00:00
return true, true
2024-04-26 19:30:35 +00:00
}
2024-04-26 19:30:35 +00:00
}
2024-04-26 19:30:35 +00:00
return true, false
}
// Contains asserts that the specified string, list(array, slice...) or map contains the
2024-04-26 19:30:35 +00:00
// specified substring or element.
2024-04-26 19:30:35 +00:00
//
2024-04-26 19:30:35 +00:00
// assert.Contains(t, "Hello World", "World")
2024-04-26 19:30:35 +00:00
// assert.Contains(t, ["Hello", "World"], "World")
2024-04-26 19:30:35 +00:00
// assert.Contains(t, {"Hello": "World"}, "Hello")
2024-04-26 19:30:35 +00:00
func Contains(t TestingT, s, contains interface{}, msgAndArgs ...interface{}) bool {
2024-04-26 19:30:35 +00:00
if h, ok := t.(tHelper); ok {
2024-04-26 19:30:35 +00:00
h.Helper()
2024-04-26 19:30:35 +00:00
}
ok, found := containsElement(s, contains)
2024-04-26 19:30:35 +00:00
if !ok {
2024-04-26 19:30:35 +00:00
return Fail(t, fmt.Sprintf("%#v could not be applied builtin len()", s), msgAndArgs...)
2024-04-26 19:30:35 +00:00
}
2024-04-26 19:30:35 +00:00
if !found {
2024-04-26 19:30:35 +00:00
return Fail(t, fmt.Sprintf("%#v does not contain %#v", s, contains), msgAndArgs...)
2024-04-26 19:30:35 +00:00
}
return true
}
// NotContains asserts that the specified string, list(array, slice...) or map does NOT contain the
2024-04-26 19:30:35 +00:00
// specified substring or element.
2024-04-26 19:30:35 +00:00
//
2024-04-26 19:30:35 +00:00
// assert.NotContains(t, "Hello World", "Earth")
2024-04-26 19:30:35 +00:00
// assert.NotContains(t, ["Hello", "World"], "Earth")
2024-04-26 19:30:35 +00:00
// assert.NotContains(t, {"Hello": "World"}, "Earth")
2024-04-26 19:30:35 +00:00
func NotContains(t TestingT, s, contains interface{}, msgAndArgs ...interface{}) bool {
2024-04-26 19:30:35 +00:00
if h, ok := t.(tHelper); ok {
2024-04-26 19:30:35 +00:00
h.Helper()
2024-04-26 19:30:35 +00:00
}
ok, found := containsElement(s, contains)
2024-04-26 19:30:35 +00:00
if !ok {
2024-04-26 19:30:35 +00:00
return Fail(t, fmt.Sprintf("%#v could not be applied builtin len()", s), msgAndArgs...)
2024-04-26 19:30:35 +00:00
}
2024-04-26 19:30:35 +00:00
if found {
2024-04-26 19:30:35 +00:00
return Fail(t, fmt.Sprintf("%#v should not contain %#v", s, contains), msgAndArgs...)
2024-04-26 19:30:35 +00:00
}
return true
}
2024-05-14 13:07:09 +00:00
// Subset asserts that the specified list(array, slice...) or map contains all
2024-05-14 13:07:09 +00:00
// elements given in the specified subset list(array, slice...) or map.
2024-04-26 19:30:35 +00:00
//
2024-05-14 13:07:09 +00:00
// assert.Subset(t, [1, 2, 3], [1, 2])
2024-05-14 13:07:09 +00:00
// assert.Subset(t, {"x": 1, "y": 2}, {"x": 1})
2024-04-26 19:30:35 +00:00
func Subset(t TestingT, list, subset interface{}, msgAndArgs ...interface{}) (ok bool) {
2024-04-26 19:30:35 +00:00
if h, ok := t.(tHelper); ok {
2024-04-26 19:30:35 +00:00
h.Helper()
2024-04-26 19:30:35 +00:00
}
2024-04-26 19:30:35 +00:00
if subset == nil {
2024-04-26 19:30:35 +00:00
return true // we consider nil to be equal to the nil set
2024-04-26 19:30:35 +00:00
}
listKind := reflect.TypeOf(list).Kind()
2024-04-26 19:30:35 +00:00
if listKind != reflect.Array && listKind != reflect.Slice && listKind != reflect.Map {
2024-04-26 19:30:35 +00:00
return Fail(t, fmt.Sprintf("%q has an unsupported type %s", list, listKind), msgAndArgs...)
2024-04-26 19:30:35 +00:00
}
subsetKind := reflect.TypeOf(subset).Kind()
2024-04-26 19:30:35 +00:00
if subsetKind != reflect.Array && subsetKind != reflect.Slice && listKind != reflect.Map {
2024-04-26 19:30:35 +00:00
return Fail(t, fmt.Sprintf("%q has an unsupported type %s", subset, subsetKind), msgAndArgs...)
2024-04-26 19:30:35 +00:00
}
if subsetKind == reflect.Map && listKind == reflect.Map {
2024-04-26 19:30:35 +00:00
subsetMap := reflect.ValueOf(subset)
2024-04-26 19:30:35 +00:00
actualMap := reflect.ValueOf(list)
for _, k := range subsetMap.MapKeys() {
2024-04-26 19:30:35 +00:00
ev := subsetMap.MapIndex(k)
2024-04-26 19:30:35 +00:00
av := actualMap.MapIndex(k)
if !av.IsValid() {
2024-04-26 19:30:35 +00:00
return Fail(t, fmt.Sprintf("%#v does not contain %#v", list, subset), msgAndArgs...)
2024-04-26 19:30:35 +00:00
}
2024-04-26 19:30:35 +00:00
if !ObjectsAreEqual(ev.Interface(), av.Interface()) {
2024-04-26 19:30:35 +00:00
return Fail(t, fmt.Sprintf("%#v does not contain %#v", list, subset), msgAndArgs...)
2024-04-26 19:30:35 +00:00
}
2024-04-26 19:30:35 +00:00
}
return true
2024-04-26 19:30:35 +00:00
}
subsetList := reflect.ValueOf(subset)
2024-04-26 19:30:35 +00:00
for i := 0; i < subsetList.Len(); i++ {
2024-04-26 19:30:35 +00:00
element := subsetList.Index(i).Interface()
2024-04-26 19:30:35 +00:00
ok, found := containsElement(list, element)
2024-04-26 19:30:35 +00:00
if !ok {
2024-04-26 19:30:35 +00:00
return Fail(t, fmt.Sprintf("%#v could not be applied builtin len()", list), msgAndArgs...)
2024-04-26 19:30:35 +00:00
}
2024-04-26 19:30:35 +00:00
if !found {
2024-04-26 19:30:35 +00:00
return Fail(t, fmt.Sprintf("%#v does not contain %#v", list, element), msgAndArgs...)
2024-04-26 19:30:35 +00:00
}
2024-04-26 19:30:35 +00:00
}
return true
2024-04-26 19:30:35 +00:00
}
2024-05-14 13:07:09 +00:00
// NotSubset asserts that the specified list(array, slice...) or map does NOT
2024-05-14 13:07:09 +00:00
// contain all elements given in the specified subset list(array, slice...) or
2024-05-14 13:07:09 +00:00
// map.
2024-04-26 19:30:35 +00:00
//
2024-05-14 13:07:09 +00:00
// assert.NotSubset(t, [1, 3, 4], [1, 2])
2024-05-14 13:07:09 +00:00
// assert.NotSubset(t, {"x": 1, "y": 2}, {"z": 3})
2024-04-26 19:30:35 +00:00
func NotSubset(t TestingT, list, subset interface{}, msgAndArgs ...interface{}) (ok bool) {
2024-04-26 19:30:35 +00:00
if h, ok := t.(tHelper); ok {
2024-04-26 19:30:35 +00:00
h.Helper()
2024-04-26 19:30:35 +00:00
}
2024-04-26 19:30:35 +00:00
if subset == nil {
2024-04-26 19:30:35 +00:00
return Fail(t, "nil is the empty set which is a subset of every set", msgAndArgs...)
2024-04-26 19:30:35 +00:00
}
listKind := reflect.TypeOf(list).Kind()
2024-04-26 19:30:35 +00:00
if listKind != reflect.Array && listKind != reflect.Slice && listKind != reflect.Map {
2024-04-26 19:30:35 +00:00
return Fail(t, fmt.Sprintf("%q has an unsupported type %s", list, listKind), msgAndArgs...)
2024-04-26 19:30:35 +00:00
}
subsetKind := reflect.TypeOf(subset).Kind()
2024-04-26 19:30:35 +00:00
if subsetKind != reflect.Array && subsetKind != reflect.Slice && listKind != reflect.Map {
2024-04-26 19:30:35 +00:00
return Fail(t, fmt.Sprintf("%q has an unsupported type %s", subset, subsetKind), msgAndArgs...)
2024-04-26 19:30:35 +00:00
}
if subsetKind == reflect.Map && listKind == reflect.Map {
2024-04-26 19:30:35 +00:00
subsetMap := reflect.ValueOf(subset)
2024-04-26 19:30:35 +00:00
actualMap := reflect.ValueOf(list)
for _, k := range subsetMap.MapKeys() {
2024-04-26 19:30:35 +00:00
ev := subsetMap.MapIndex(k)
2024-04-26 19:30:35 +00:00
av := actualMap.MapIndex(k)
if !av.IsValid() {
2024-04-26 19:30:35 +00:00
return true
2024-04-26 19:30:35 +00:00
}
2024-04-26 19:30:35 +00:00
if !ObjectsAreEqual(ev.Interface(), av.Interface()) {
2024-04-26 19:30:35 +00:00
return true
2024-04-26 19:30:35 +00:00
}
2024-04-26 19:30:35 +00:00
}
return Fail(t, fmt.Sprintf("%q is a subset of %q", subset, list), msgAndArgs...)
2024-04-26 19:30:35 +00:00
}
subsetList := reflect.ValueOf(subset)
2024-04-26 19:30:35 +00:00
for i := 0; i < subsetList.Len(); i++ {
2024-04-26 19:30:35 +00:00
element := subsetList.Index(i).Interface()
2024-04-26 19:30:35 +00:00
ok, found := containsElement(list, element)
2024-04-26 19:30:35 +00:00
if !ok {
2024-04-26 19:30:35 +00:00
return Fail(t, fmt.Sprintf("\"%s\" could not be applied builtin len()", list), msgAndArgs...)
2024-04-26 19:30:35 +00:00
}
2024-04-26 19:30:35 +00:00
if !found {
2024-04-26 19:30:35 +00:00
return true
2024-04-26 19:30:35 +00:00
}
2024-04-26 19:30:35 +00:00
}
return Fail(t, fmt.Sprintf("%q is a subset of %q", subset, list), msgAndArgs...)
2024-04-26 19:30:35 +00:00
}
// ElementsMatch asserts that the specified listA(array, slice...) is equal to specified
2024-04-26 19:30:35 +00:00
// listB(array, slice...) ignoring the order of the elements. If there are duplicate elements,
2024-04-26 19:30:35 +00:00
// the number of appearances of each of them in both lists should match.
2024-04-26 19:30:35 +00:00
//
2024-04-26 19:30:35 +00:00
// assert.ElementsMatch(t, [1, 3, 2, 3], [1, 3, 3, 2])
2024-04-26 19:30:35 +00:00
func ElementsMatch(t TestingT, listA, listB interface{}, msgAndArgs ...interface{}) (ok bool) {
2024-04-26 19:30:35 +00:00
if h, ok := t.(tHelper); ok {
2024-04-26 19:30:35 +00:00
h.Helper()
2024-04-26 19:30:35 +00:00
}
2024-04-26 19:30:35 +00:00
if isEmpty(listA) && isEmpty(listB) {
2024-04-26 19:30:35 +00:00
return true
2024-04-26 19:30:35 +00:00
}
if !isList(t, listA, msgAndArgs...) || !isList(t, listB, msgAndArgs...) {
2024-04-26 19:30:35 +00:00
return false
2024-04-26 19:30:35 +00:00
}
extraA, extraB := diffLists(listA, listB)
if len(extraA) == 0 && len(extraB) == 0 {
2024-04-26 19:30:35 +00:00
return true
2024-04-26 19:30:35 +00:00
}
return Fail(t, formatListDiff(listA, listB, extraA, extraB), msgAndArgs...)
2024-04-26 19:30:35 +00:00
}
// isList checks that the provided value is array or slice.
2024-04-26 19:30:35 +00:00
func isList(t TestingT, list interface{}, msgAndArgs ...interface{}) (ok bool) {
2024-04-26 19:30:35 +00:00
kind := reflect.TypeOf(list).Kind()
2024-04-26 19:30:35 +00:00
if kind != reflect.Array && kind != reflect.Slice {
2024-04-26 19:30:35 +00:00
return Fail(t, fmt.Sprintf("%q has an unsupported type %s, expecting array or slice", list, kind),
2024-04-26 19:30:35 +00:00
msgAndArgs...)
2024-04-26 19:30:35 +00:00
}
2024-04-26 19:30:35 +00:00
return true
2024-04-26 19:30:35 +00:00
}
// diffLists diffs two arrays/slices and returns slices of elements that are only in A and only in B.
2024-04-26 19:30:35 +00:00
// If some element is present multiple times, each instance is counted separately (e.g. if something is 2x in A and
2024-04-26 19:30:35 +00:00
// 5x in B, it will be 0x in extraA and 3x in extraB). The order of items in both lists is ignored.
2024-04-26 19:30:35 +00:00
func diffLists(listA, listB interface{}) (extraA, extraB []interface{}) {
2024-04-26 19:30:35 +00:00
aValue := reflect.ValueOf(listA)
2024-04-26 19:30:35 +00:00
bValue := reflect.ValueOf(listB)
aLen := aValue.Len()
2024-04-26 19:30:35 +00:00
bLen := bValue.Len()
// Mark indexes in bValue that we already used
2024-04-26 19:30:35 +00:00
visited := make([]bool, bLen)
2024-04-26 19:30:35 +00:00
for i := 0; i < aLen; i++ {
2024-04-26 19:30:35 +00:00
element := aValue.Index(i).Interface()
2024-04-26 19:30:35 +00:00
found := false
2024-04-26 19:30:35 +00:00
for j := 0; j < bLen; j++ {
2024-04-26 19:30:35 +00:00
if visited[j] {
2024-04-26 19:30:35 +00:00
continue
2024-04-26 19:30:35 +00:00
}
2024-04-26 19:30:35 +00:00
if ObjectsAreEqual(bValue.Index(j).Interface(), element) {
2024-04-26 19:30:35 +00:00
visited[j] = true
2024-04-26 19:30:35 +00:00
found = true
2024-04-26 19:30:35 +00:00
break
2024-04-26 19:30:35 +00:00
}
2024-04-26 19:30:35 +00:00
}
2024-04-26 19:30:35 +00:00
if !found {
2024-04-26 19:30:35 +00:00
extraA = append(extraA, element)
2024-04-26 19:30:35 +00:00
}
2024-04-26 19:30:35 +00:00
}
for j := 0; j < bLen; j++ {
2024-04-26 19:30:35 +00:00
if visited[j] {
2024-04-26 19:30:35 +00:00
continue
2024-04-26 19:30:35 +00:00
}
2024-04-26 19:30:35 +00:00
extraB = append(extraB, bValue.Index(j).Interface())
2024-04-26 19:30:35 +00:00
}
return
2024-04-26 19:30:35 +00:00
}
func formatListDiff(listA, listB interface{}, extraA, extraB []interface{}) string {
2024-04-26 19:30:35 +00:00
var msg bytes.Buffer
msg.WriteString("elements differ")
2024-04-26 19:30:35 +00:00
if len(extraA) > 0 {
2024-04-26 19:30:35 +00:00
msg.WriteString("\n\nextra elements in list A:\n")
2024-04-26 19:30:35 +00:00
msg.WriteString(spewConfig.Sdump(extraA))
2024-04-26 19:30:35 +00:00
}
2024-04-26 19:30:35 +00:00
if len(extraB) > 0 {
2024-04-26 19:30:35 +00:00
msg.WriteString("\n\nextra elements in list B:\n")
2024-04-26 19:30:35 +00:00
msg.WriteString(spewConfig.Sdump(extraB))
2024-04-26 19:30:35 +00:00
}
2024-04-26 19:30:35 +00:00
msg.WriteString("\n\nlistA:\n")
2024-04-26 19:30:35 +00:00
msg.WriteString(spewConfig.Sdump(listA))
2024-04-26 19:30:35 +00:00
msg.WriteString("\n\nlistB:\n")
2024-04-26 19:30:35 +00:00
msg.WriteString(spewConfig.Sdump(listB))
return msg.String()
2024-04-26 19:30:35 +00:00
}
// Condition uses a Comparison to assert a complex condition.
2024-04-26 19:30:35 +00:00
func Condition(t TestingT, comp Comparison, msgAndArgs ...interface{}) bool {
2024-04-26 19:30:35 +00:00
if h, ok := t.(tHelper); ok {
2024-04-26 19:30:35 +00:00
h.Helper()
2024-04-26 19:30:35 +00:00
}
2024-04-26 19:30:35 +00:00
result := comp()
2024-04-26 19:30:35 +00:00
if !result {
2024-04-26 19:30:35 +00:00
Fail(t, "Condition failed!", msgAndArgs...)
2024-04-26 19:30:35 +00:00
}
2024-04-26 19:30:35 +00:00
return result
2024-04-26 19:30:35 +00:00
}
// PanicTestFunc defines a func that should be passed to the assert.Panics and assert.NotPanics
2024-04-26 19:30:35 +00:00
// methods, and represents a simple func that takes no arguments, and returns nothing.
2024-04-26 19:30:35 +00:00
type PanicTestFunc func()
// didPanic returns true if the function passed to it panics. Otherwise, it returns false.
2024-04-26 19:30:35 +00:00
func didPanic(f PanicTestFunc) (didPanic bool, message interface{}, stack string) {
2024-04-26 19:30:35 +00:00
didPanic = true
defer func() {
2024-04-26 19:30:35 +00:00
message = recover()
2024-04-26 19:30:35 +00:00
if didPanic {
2024-04-26 19:30:35 +00:00
stack = string(debug.Stack())
2024-04-26 19:30:35 +00:00
}
2024-04-26 19:30:35 +00:00
}()
// call the target function
2024-04-26 19:30:35 +00:00
f()
2024-04-26 19:30:35 +00:00
didPanic = false
return
2024-04-26 19:30:35 +00:00
}
// Panics asserts that the code inside the specified PanicTestFunc panics.
2024-04-26 19:30:35 +00:00
//
2024-04-26 19:30:35 +00:00
// assert.Panics(t, func(){ GoCrazy() })
2024-04-26 19:30:35 +00:00
func Panics(t TestingT, f PanicTestFunc, msgAndArgs ...interface{}) bool {
2024-04-26 19:30:35 +00:00
if h, ok := t.(tHelper); ok {
2024-04-26 19:30:35 +00:00
h.Helper()
2024-04-26 19:30:35 +00:00
}
if funcDidPanic, panicValue, _ := didPanic(f); !funcDidPanic {
2024-04-26 19:30:35 +00:00
return Fail(t, fmt.Sprintf("func %#v should panic\n\tPanic value:\t%#v", f, panicValue), msgAndArgs...)
2024-04-26 19:30:35 +00:00
}
return true
2024-04-26 19:30:35 +00:00
}
// PanicsWithValue asserts that the code inside the specified PanicTestFunc panics, and that
2024-04-26 19:30:35 +00:00
// the recovered panic value equals the expected panic value.
2024-04-26 19:30:35 +00:00
//
2024-04-26 19:30:35 +00:00
// assert.PanicsWithValue(t, "crazy error", func(){ GoCrazy() })
2024-04-26 19:30:35 +00:00
func PanicsWithValue(t TestingT, expected interface{}, f PanicTestFunc, msgAndArgs ...interface{}) bool {
2024-04-26 19:30:35 +00:00
if h, ok := t.(tHelper); ok {
2024-04-26 19:30:35 +00:00
h.Helper()
2024-04-26 19:30:35 +00:00
}
funcDidPanic, panicValue, panickedStack := didPanic(f)
2024-04-26 19:30:35 +00:00
if !funcDidPanic {
2024-04-26 19:30:35 +00:00
return Fail(t, fmt.Sprintf("func %#v should panic\n\tPanic value:\t%#v", f, panicValue), msgAndArgs...)
2024-04-26 19:30:35 +00:00
}
2024-04-26 19:30:35 +00:00
if panicValue != expected {
2024-04-26 19:30:35 +00:00
return Fail(t, fmt.Sprintf("func %#v should panic with value:\t%#v\n\tPanic value:\t%#v\n\tPanic stack:\t%s", f, expected, panicValue, panickedStack), msgAndArgs...)
2024-04-26 19:30:35 +00:00
}
return true
2024-04-26 19:30:35 +00:00
}
// PanicsWithError asserts that the code inside the specified PanicTestFunc
2024-04-26 19:30:35 +00:00
// panics, and that the recovered panic value is an error that satisfies the
2024-04-26 19:30:35 +00:00
// EqualError comparison.
2024-04-26 19:30:35 +00:00
//
2024-04-26 19:30:35 +00:00
// assert.PanicsWithError(t, "crazy error", func(){ GoCrazy() })
2024-04-26 19:30:35 +00:00
func PanicsWithError(t TestingT, errString string, f PanicTestFunc, msgAndArgs ...interface{}) bool {
2024-04-26 19:30:35 +00:00
if h, ok := t.(tHelper); ok {
2024-04-26 19:30:35 +00:00
h.Helper()
2024-04-26 19:30:35 +00:00
}
funcDidPanic, panicValue, panickedStack := didPanic(f)
2024-04-26 19:30:35 +00:00
if !funcDidPanic {
2024-04-26 19:30:35 +00:00
return Fail(t, fmt.Sprintf("func %#v should panic\n\tPanic value:\t%#v", f, panicValue), msgAndArgs...)
2024-04-26 19:30:35 +00:00
}
2024-04-26 19:30:35 +00:00
panicErr, ok := panicValue.(error)
2024-04-26 19:30:35 +00:00
if !ok || panicErr.Error() != errString {
2024-04-26 19:30:35 +00:00
return Fail(t, fmt.Sprintf("func %#v should panic with error message:\t%#v\n\tPanic value:\t%#v\n\tPanic stack:\t%s", f, errString, panicValue, panickedStack), msgAndArgs...)
2024-04-26 19:30:35 +00:00
}
return true
2024-04-26 19:30:35 +00:00
}
// NotPanics asserts that the code inside the specified PanicTestFunc does NOT panic.
2024-04-26 19:30:35 +00:00
//
2024-04-26 19:30:35 +00:00
// assert.NotPanics(t, func(){ RemainCalm() })
2024-04-26 19:30:35 +00:00
func NotPanics(t TestingT, f PanicTestFunc, msgAndArgs ...interface{}) bool {
2024-04-26 19:30:35 +00:00
if h, ok := t.(tHelper); ok {
2024-04-26 19:30:35 +00:00
h.Helper()
2024-04-26 19:30:35 +00:00
}
if funcDidPanic, panicValue, panickedStack := didPanic(f); funcDidPanic {
2024-04-26 19:30:35 +00:00
return Fail(t, fmt.Sprintf("func %#v should not panic\n\tPanic value:\t%v\n\tPanic stack:\t%s", f, panicValue, panickedStack), msgAndArgs...)
2024-04-26 19:30:35 +00:00
}
return true
2024-04-26 19:30:35 +00:00
}
// WithinDuration asserts that the two times are within duration delta of each other.
2024-04-26 19:30:35 +00:00
//
2024-04-26 19:30:35 +00:00
// assert.WithinDuration(t, time.Now(), time.Now(), 10*time.Second)
2024-04-26 19:30:35 +00:00
func WithinDuration(t TestingT, expected, actual time.Time, delta time.Duration, msgAndArgs ...interface{}) bool {
2024-04-26 19:30:35 +00:00
if h, ok := t.(tHelper); ok {
2024-04-26 19:30:35 +00:00
h.Helper()
2024-04-26 19:30:35 +00:00
}
dt := expected.Sub(actual)
2024-04-26 19:30:35 +00:00
if dt < -delta || dt > delta {
2024-04-26 19:30:35 +00:00
return Fail(t, fmt.Sprintf("Max difference between %v and %v allowed is %v, but difference was %v", expected, actual, delta, dt), msgAndArgs...)
2024-04-26 19:30:35 +00:00
}
return true
2024-04-26 19:30:35 +00:00
}
// WithinRange asserts that a time is within a time range (inclusive).
2024-04-26 19:30:35 +00:00
//
2024-04-26 19:30:35 +00:00
// assert.WithinRange(t, time.Now(), time.Now().Add(-time.Second), time.Now().Add(time.Second))
2024-04-26 19:30:35 +00:00
func WithinRange(t TestingT, actual, start, end time.Time, msgAndArgs ...interface{}) bool {
2024-04-26 19:30:35 +00:00
if h, ok := t.(tHelper); ok {
2024-04-26 19:30:35 +00:00
h.Helper()
2024-04-26 19:30:35 +00:00
}
if end.Before(start) {
2024-04-26 19:30:35 +00:00
return Fail(t, "Start should be before end", msgAndArgs...)
2024-04-26 19:30:35 +00:00
}
if actual.Before(start) {
2024-04-26 19:30:35 +00:00
return Fail(t, fmt.Sprintf("Time %v expected to be in time range %v to %v, but is before the range", actual, start, end), msgAndArgs...)
2024-04-26 19:30:35 +00:00
} else if actual.After(end) {
2024-04-26 19:30:35 +00:00
return Fail(t, fmt.Sprintf("Time %v expected to be in time range %v to %v, but is after the range", actual, start, end), msgAndArgs...)
2024-04-26 19:30:35 +00:00
}
return true
2024-04-26 19:30:35 +00:00
}
func toFloat(x interface{}) (float64, bool) {
2024-04-26 19:30:35 +00:00
var xf float64
2024-04-26 19:30:35 +00:00
xok := true
switch xn := x.(type) {
2024-04-26 19:30:35 +00:00
case uint:
2024-04-26 19:30:35 +00:00
xf = float64(xn)
2024-04-26 19:30:35 +00:00
case uint8:
2024-04-26 19:30:35 +00:00
xf = float64(xn)
2024-04-26 19:30:35 +00:00
case uint16:
2024-04-26 19:30:35 +00:00
xf = float64(xn)
2024-04-26 19:30:35 +00:00
case uint32:
2024-04-26 19:30:35 +00:00
xf = float64(xn)
2024-04-26 19:30:35 +00:00
case uint64:
2024-04-26 19:30:35 +00:00
xf = float64(xn)
2024-04-26 19:30:35 +00:00
case int:
2024-04-26 19:30:35 +00:00
xf = float64(xn)
2024-04-26 19:30:35 +00:00
case int8:
2024-04-26 19:30:35 +00:00
xf = float64(xn)
2024-04-26 19:30:35 +00:00
case int16:
2024-04-26 19:30:35 +00:00
xf = float64(xn)
2024-04-26 19:30:35 +00:00
case int32:
2024-04-26 19:30:35 +00:00
xf = float64(xn)
2024-04-26 19:30:35 +00:00
case int64:
2024-04-26 19:30:35 +00:00
xf = float64(xn)
2024-04-26 19:30:35 +00:00
case float32:
2024-04-26 19:30:35 +00:00
xf = float64(xn)
2024-04-26 19:30:35 +00:00
case float64:
2024-04-26 19:30:35 +00:00
xf = xn
2024-04-26 19:30:35 +00:00
case time.Duration:
2024-04-26 19:30:35 +00:00
xf = float64(xn)
2024-04-26 19:30:35 +00:00
default:
2024-04-26 19:30:35 +00:00
xok = false
2024-04-26 19:30:35 +00:00
}
return xf, xok
2024-04-26 19:30:35 +00:00
}
// InDelta asserts that the two numerals are within delta of each other.
2024-04-26 19:30:35 +00:00
//
2024-04-26 19:30:35 +00:00
// assert.InDelta(t, math.Pi, 22/7.0, 0.01)
2024-04-26 19:30:35 +00:00
func InDelta(t TestingT, expected, actual interface{}, delta float64, msgAndArgs ...interface{}) bool {
2024-04-26 19:30:35 +00:00
if h, ok := t.(tHelper); ok {
2024-04-26 19:30:35 +00:00
h.Helper()
2024-04-26 19:30:35 +00:00
}
af, aok := toFloat(expected)
2024-04-26 19:30:35 +00:00
bf, bok := toFloat(actual)
if !aok || !bok {
2024-04-26 19:30:35 +00:00
return Fail(t, "Parameters must be numerical", msgAndArgs...)
2024-04-26 19:30:35 +00:00
}
if math.IsNaN(af) && math.IsNaN(bf) {
2024-04-26 19:30:35 +00:00
return true
2024-04-26 19:30:35 +00:00
}
if math.IsNaN(af) {
2024-04-26 19:30:35 +00:00
return Fail(t, "Expected must not be NaN", msgAndArgs...)
2024-04-26 19:30:35 +00:00
}
if math.IsNaN(bf) {
2024-04-26 19:30:35 +00:00
return Fail(t, fmt.Sprintf("Expected %v with delta %v, but was NaN", expected, delta), msgAndArgs...)
2024-04-26 19:30:35 +00:00
}
dt := af - bf
2024-04-26 19:30:35 +00:00
if dt < -delta || dt > delta {
2024-04-26 19:30:35 +00:00
return Fail(t, fmt.Sprintf("Max difference between %v and %v allowed is %v, but difference was %v", expected, actual, delta, dt), msgAndArgs...)
2024-04-26 19:30:35 +00:00
}
return true
2024-04-26 19:30:35 +00:00
}
// InDeltaSlice is the same as InDelta, except it compares two slices.
2024-04-26 19:30:35 +00:00
func InDeltaSlice(t TestingT, expected, actual interface{}, delta float64, msgAndArgs ...interface{}) bool {
2024-04-26 19:30:35 +00:00
if h, ok := t.(tHelper); ok {
2024-04-26 19:30:35 +00:00
h.Helper()
2024-04-26 19:30:35 +00:00
}
2024-04-26 19:30:35 +00:00
if expected == nil || actual == nil ||
2024-04-26 19:30:35 +00:00
reflect.TypeOf(actual).Kind() != reflect.Slice ||
2024-04-26 19:30:35 +00:00
reflect.TypeOf(expected).Kind() != reflect.Slice {
2024-04-26 19:30:35 +00:00
return Fail(t, "Parameters must be slice", msgAndArgs...)
2024-04-26 19:30:35 +00:00
}
actualSlice := reflect.ValueOf(actual)
2024-04-26 19:30:35 +00:00
expectedSlice := reflect.ValueOf(expected)
for i := 0; i < actualSlice.Len(); i++ {
2024-04-26 19:30:35 +00:00
result := InDelta(t, actualSlice.Index(i).Interface(), expectedSlice.Index(i).Interface(), delta, msgAndArgs...)
2024-04-26 19:30:35 +00:00
if !result {
2024-04-26 19:30:35 +00:00
return result
2024-04-26 19:30:35 +00:00
}
2024-04-26 19:30:35 +00:00
}
return true
2024-04-26 19:30:35 +00:00
}
// InDeltaMapValues is the same as InDelta, but it compares all values between two maps. Both maps must have exactly the same keys.
2024-04-26 19:30:35 +00:00
func InDeltaMapValues(t TestingT, expected, actual interface{}, delta float64, msgAndArgs ...interface{}) bool {
2024-04-26 19:30:35 +00:00
if h, ok := t.(tHelper); ok {
2024-04-26 19:30:35 +00:00
h.Helper()
2024-04-26 19:30:35 +00:00
}
2024-04-26 19:30:35 +00:00
if expected == nil || actual == nil ||
2024-04-26 19:30:35 +00:00
reflect.TypeOf(actual).Kind() != reflect.Map ||
2024-04-26 19:30:35 +00:00
reflect.TypeOf(expected).Kind() != reflect.Map {
2024-04-26 19:30:35 +00:00
return Fail(t, "Arguments must be maps", msgAndArgs...)
2024-04-26 19:30:35 +00:00
}
expectedMap := reflect.ValueOf(expected)
2024-04-26 19:30:35 +00:00
actualMap := reflect.ValueOf(actual)
if expectedMap.Len() != actualMap.Len() {
2024-04-26 19:30:35 +00:00
return Fail(t, "Arguments must have the same number of keys", msgAndArgs...)
2024-04-26 19:30:35 +00:00
}
for _, k := range expectedMap.MapKeys() {
2024-04-26 19:30:35 +00:00
ev := expectedMap.MapIndex(k)
2024-04-26 19:30:35 +00:00
av := actualMap.MapIndex(k)
if !ev.IsValid() {
2024-04-26 19:30:35 +00:00
return Fail(t, fmt.Sprintf("missing key %q in expected map", k), msgAndArgs...)
2024-04-26 19:30:35 +00:00
}
if !av.IsValid() {
2024-04-26 19:30:35 +00:00
return Fail(t, fmt.Sprintf("missing key %q in actual map", k), msgAndArgs...)
2024-04-26 19:30:35 +00:00
}
if !InDelta(
2024-04-26 19:30:35 +00:00
t,
2024-04-26 19:30:35 +00:00
ev.Interface(),
2024-04-26 19:30:35 +00:00
av.Interface(),
2024-04-26 19:30:35 +00:00
delta,
2024-04-26 19:30:35 +00:00
msgAndArgs...,
) {
2024-04-26 19:30:35 +00:00
return false
2024-04-26 19:30:35 +00:00
}
2024-04-26 19:30:35 +00:00
}
return true
2024-04-26 19:30:35 +00:00
}
func calcRelativeError(expected, actual interface{}) (float64, error) {
2024-04-26 19:30:35 +00:00
af, aok := toFloat(expected)
2024-04-26 19:30:35 +00:00
bf, bok := toFloat(actual)
2024-04-26 19:30:35 +00:00
if !aok || !bok {
2024-04-26 19:30:35 +00:00
return 0, fmt.Errorf("Parameters must be numerical")
2024-04-26 19:30:35 +00:00
}
2024-04-26 19:30:35 +00:00
if math.IsNaN(af) && math.IsNaN(bf) {
2024-04-26 19:30:35 +00:00
return 0, nil
2024-04-26 19:30:35 +00:00
}
2024-04-26 19:30:35 +00:00
if math.IsNaN(af) {
2024-04-26 19:30:35 +00:00
return 0, errors.New("expected value must not be NaN")
2024-04-26 19:30:35 +00:00
}
2024-04-26 19:30:35 +00:00
if af == 0 {
2024-04-26 19:30:35 +00:00
return 0, fmt.Errorf("expected value must have a value other than zero to calculate the relative error")
2024-04-26 19:30:35 +00:00
}
2024-04-26 19:30:35 +00:00
if math.IsNaN(bf) {
2024-04-26 19:30:35 +00:00
return 0, errors.New("actual value must not be NaN")
2024-04-26 19:30:35 +00:00
}
return math.Abs(af-bf) / math.Abs(af), nil
2024-04-26 19:30:35 +00:00
}
// InEpsilon asserts that expected and actual have a relative error less than epsilon
2024-04-26 19:30:35 +00:00
func InEpsilon(t TestingT, expected, actual interface{}, epsilon float64, msgAndArgs ...interface{}) bool {
2024-04-26 19:30:35 +00:00
if h, ok := t.(tHelper); ok {
2024-04-26 19:30:35 +00:00
h.Helper()
2024-04-26 19:30:35 +00:00
}
2024-04-26 19:30:35 +00:00
if math.IsNaN(epsilon) {
2024-05-14 13:07:09 +00:00
return Fail(t, "epsilon must not be NaN", msgAndArgs...)
2024-04-26 19:30:35 +00:00
}
2024-04-26 19:30:35 +00:00
actualEpsilon, err := calcRelativeError(expected, actual)
2024-04-26 19:30:35 +00:00
if err != nil {
2024-04-26 19:30:35 +00:00
return Fail(t, err.Error(), msgAndArgs...)
2024-04-26 19:30:35 +00:00
}
2024-04-26 19:30:35 +00:00
if actualEpsilon > epsilon {
2024-04-26 19:30:35 +00:00
return Fail(t, fmt.Sprintf("Relative error is too high: %#v (expected)\n"+
2024-04-26 19:30:35 +00:00
" < %#v (actual)", epsilon, actualEpsilon), msgAndArgs...)
2024-04-26 19:30:35 +00:00
}
return true
2024-04-26 19:30:35 +00:00
}
// InEpsilonSlice is the same as InEpsilon, except it compares each value from two slices.
2024-04-26 19:30:35 +00:00
func InEpsilonSlice(t TestingT, expected, actual interface{}, epsilon float64, msgAndArgs ...interface{}) bool {
2024-04-26 19:30:35 +00:00
if h, ok := t.(tHelper); ok {
2024-04-26 19:30:35 +00:00
h.Helper()
2024-04-26 19:30:35 +00:00
}
2024-05-14 13:07:09 +00:00
if expected == nil || actual == nil {
2024-04-26 19:30:35 +00:00
return Fail(t, "Parameters must be slice", msgAndArgs...)
2024-04-26 19:30:35 +00:00
}
expectedSlice := reflect.ValueOf(expected)
2024-05-14 13:07:09 +00:00
actualSlice := reflect.ValueOf(actual)
2024-04-26 19:30:35 +00:00
2024-05-14 13:07:09 +00:00
if expectedSlice.Type().Kind() != reflect.Slice {
2024-05-14 13:07:09 +00:00
return Fail(t, "Expected value must be slice", msgAndArgs...)
2024-05-14 13:07:09 +00:00
}
expectedLen := expectedSlice.Len()
2024-05-14 13:07:09 +00:00
if !IsType(t, expected, actual) || !Len(t, actual, expectedLen) {
2024-05-14 13:07:09 +00:00
return false
2024-05-14 13:07:09 +00:00
}
for i := 0; i < expectedLen; i++ {
2024-05-14 13:07:09 +00:00
if !InEpsilon(t, expectedSlice.Index(i).Interface(), actualSlice.Index(i).Interface(), epsilon, "at index %d", i) {
2024-05-14 13:07:09 +00:00
return false
2024-04-26 19:30:35 +00:00
}
2024-04-26 19:30:35 +00:00
}
return true
2024-04-26 19:30:35 +00:00
}
/*
2024-04-26 19:30:35 +00:00
Errors
2024-04-26 19:30:35 +00:00
*/
// NoError asserts that a function returned no error (i.e. `nil`).
2024-04-26 19:30:35 +00:00
//
2024-04-26 19:30:35 +00:00
// actualObj, err := SomeFunction()
2024-04-26 19:30:35 +00:00
// if assert.NoError(t, err) {
2024-04-26 19:30:35 +00:00
// assert.Equal(t, expectedObj, actualObj)
2024-04-26 19:30:35 +00:00
// }
2024-04-26 19:30:35 +00:00
func NoError(t TestingT, err error, msgAndArgs ...interface{}) bool {
2024-04-26 19:30:35 +00:00
if err != nil {
2024-04-26 19:30:35 +00:00
if h, ok := t.(tHelper); ok {
2024-04-26 19:30:35 +00:00
h.Helper()
2024-04-26 19:30:35 +00:00
}
2024-04-26 19:30:35 +00:00
return Fail(t, fmt.Sprintf("Received unexpected error:\n%+v", err), msgAndArgs...)
2024-04-26 19:30:35 +00:00
}
return true
2024-04-26 19:30:35 +00:00
}
// Error asserts that a function returned an error (i.e. not `nil`).
2024-04-26 19:30:35 +00:00
//
2024-04-26 19:30:35 +00:00
// actualObj, err := SomeFunction()
2024-04-26 19:30:35 +00:00
// if assert.Error(t, err) {
2024-04-26 19:30:35 +00:00
// assert.Equal(t, expectedError, err)
2024-04-26 19:30:35 +00:00
// }
2024-04-26 19:30:35 +00:00
func Error(t TestingT, err error, msgAndArgs ...interface{}) bool {
2024-04-26 19:30:35 +00:00
if err == nil {
2024-04-26 19:30:35 +00:00
if h, ok := t.(tHelper); ok {
2024-04-26 19:30:35 +00:00
h.Helper()
2024-04-26 19:30:35 +00:00
}
2024-04-26 19:30:35 +00:00
return Fail(t, "An error is expected but got nil.", msgAndArgs...)
2024-04-26 19:30:35 +00:00
}
return true
2024-04-26 19:30:35 +00:00
}
// EqualError asserts that a function returned an error (i.e. not `nil`)
2024-04-26 19:30:35 +00:00
// and that it is equal to the provided error.
2024-04-26 19:30:35 +00:00
//
2024-04-26 19:30:35 +00:00
// actualObj, err := SomeFunction()
2024-04-26 19:30:35 +00:00
// assert.EqualError(t, err, expectedErrorString)
2024-04-26 19:30:35 +00:00
func EqualError(t TestingT, theError error, errString string, msgAndArgs ...interface{}) bool {
2024-04-26 19:30:35 +00:00
if h, ok := t.(tHelper); ok {
2024-04-26 19:30:35 +00:00
h.Helper()
2024-04-26 19:30:35 +00:00
}
2024-04-26 19:30:35 +00:00
if !Error(t, theError, msgAndArgs...) {
2024-04-26 19:30:35 +00:00
return false
2024-04-26 19:30:35 +00:00
}
2024-04-26 19:30:35 +00:00
expected := errString
2024-04-26 19:30:35 +00:00
actual := theError.Error()
2024-04-26 19:30:35 +00:00
// don't need to use deep equals here, we know they are both strings
2024-04-26 19:30:35 +00:00
if expected != actual {
2024-04-26 19:30:35 +00:00
return Fail(t, fmt.Sprintf("Error message not equal:\n"+
2024-04-26 19:30:35 +00:00
"expected: %q\n"+
2024-04-26 19:30:35 +00:00
"actual : %q", expected, actual), msgAndArgs...)
2024-04-26 19:30:35 +00:00
}
2024-04-26 19:30:35 +00:00
return true
2024-04-26 19:30:35 +00:00
}
// ErrorContains asserts that a function returned an error (i.e. not `nil`)
2024-04-26 19:30:35 +00:00
// and that the error contains the specified substring.
2024-04-26 19:30:35 +00:00
//
2024-04-26 19:30:35 +00:00
// actualObj, err := SomeFunction()
2024-04-26 19:30:35 +00:00
// assert.ErrorContains(t, err, expectedErrorSubString)
2024-04-26 19:30:35 +00:00
func ErrorContains(t TestingT, theError error, contains string, msgAndArgs ...interface{}) bool {
2024-04-26 19:30:35 +00:00
if h, ok := t.(tHelper); ok {
2024-04-26 19:30:35 +00:00
h.Helper()
2024-04-26 19:30:35 +00:00
}
2024-04-26 19:30:35 +00:00
if !Error(t, theError, msgAndArgs...) {
2024-04-26 19:30:35 +00:00
return false
2024-04-26 19:30:35 +00:00
}
actual := theError.Error()
2024-04-26 19:30:35 +00:00
if !strings.Contains(actual, contains) {
2024-04-26 19:30:35 +00:00
return Fail(t, fmt.Sprintf("Error %#v does not contain %#v", actual, contains), msgAndArgs...)
2024-04-26 19:30:35 +00:00
}
return true
2024-04-26 19:30:35 +00:00
}
// matchRegexp return true if a specified regexp matches a string.
2024-04-26 19:30:35 +00:00
func matchRegexp(rx interface{}, str interface{}) bool {
var r *regexp.Regexp
2024-04-26 19:30:35 +00:00
if rr, ok := rx.(*regexp.Regexp); ok {
2024-04-26 19:30:35 +00:00
r = rr
2024-04-26 19:30:35 +00:00
} else {
2024-04-26 19:30:35 +00:00
r = regexp.MustCompile(fmt.Sprint(rx))
2024-04-26 19:30:35 +00:00
}
return (r.FindStringIndex(fmt.Sprint(str)) != nil)
}
// Regexp asserts that a specified regexp matches a string.
2024-04-26 19:30:35 +00:00
//
2024-04-26 19:30:35 +00:00
// assert.Regexp(t, regexp.MustCompile("start"), "it's starting")
2024-04-26 19:30:35 +00:00
// assert.Regexp(t, "start...$", "it's not starting")
2024-04-26 19:30:35 +00:00
func Regexp(t TestingT, rx interface{}, str interface{}, msgAndArgs ...interface{}) bool {
2024-04-26 19:30:35 +00:00
if h, ok := t.(tHelper); ok {
2024-04-26 19:30:35 +00:00
h.Helper()
2024-04-26 19:30:35 +00:00
}
match := matchRegexp(rx, str)
if !match {
2024-04-26 19:30:35 +00:00
Fail(t, fmt.Sprintf("Expect \"%v\" to match \"%v\"", str, rx), msgAndArgs...)
2024-04-26 19:30:35 +00:00
}
return match
2024-04-26 19:30:35 +00:00
}
// NotRegexp asserts that a specified regexp does not match a string.
2024-04-26 19:30:35 +00:00
//
2024-04-26 19:30:35 +00:00
// assert.NotRegexp(t, regexp.MustCompile("starts"), "it's starting")
2024-04-26 19:30:35 +00:00
// assert.NotRegexp(t, "^start", "it's not starting")
2024-04-26 19:30:35 +00:00
func NotRegexp(t TestingT, rx interface{}, str interface{}, msgAndArgs ...interface{}) bool {
2024-04-26 19:30:35 +00:00
if h, ok := t.(tHelper); ok {
2024-04-26 19:30:35 +00:00
h.Helper()
2024-04-26 19:30:35 +00:00
}
2024-04-26 19:30:35 +00:00
match := matchRegexp(rx, str)
if match {
2024-04-26 19:30:35 +00:00
Fail(t, fmt.Sprintf("Expect \"%v\" to NOT match \"%v\"", str, rx), msgAndArgs...)
2024-04-26 19:30:35 +00:00
}
return !match
}
// Zero asserts that i is the zero value for its type.
2024-04-26 19:30:35 +00:00
func Zero(t TestingT, i interface{}, msgAndArgs ...interface{}) bool {
2024-04-26 19:30:35 +00:00
if h, ok := t.(tHelper); ok {
2024-04-26 19:30:35 +00:00
h.Helper()
2024-04-26 19:30:35 +00:00
}
2024-04-26 19:30:35 +00:00
if i != nil && !reflect.DeepEqual(i, reflect.Zero(reflect.TypeOf(i)).Interface()) {
2024-04-26 19:30:35 +00:00
return Fail(t, fmt.Sprintf("Should be zero, but was %v", i), msgAndArgs...)
2024-04-26 19:30:35 +00:00
}
2024-04-26 19:30:35 +00:00
return true
2024-04-26 19:30:35 +00:00
}
// NotZero asserts that i is not the zero value for its type.
2024-04-26 19:30:35 +00:00
func NotZero(t TestingT, i interface{}, msgAndArgs ...interface{}) bool {
2024-04-26 19:30:35 +00:00
if h, ok := t.(tHelper); ok {
2024-04-26 19:30:35 +00:00
h.Helper()
2024-04-26 19:30:35 +00:00
}
2024-04-26 19:30:35 +00:00
if i == nil || reflect.DeepEqual(i, reflect.Zero(reflect.TypeOf(i)).Interface()) {
2024-04-26 19:30:35 +00:00
return Fail(t, fmt.Sprintf("Should not be zero, but was %v", i), msgAndArgs...)
2024-04-26 19:30:35 +00:00
}
2024-04-26 19:30:35 +00:00
return true
2024-04-26 19:30:35 +00:00
}
// FileExists checks whether a file exists in the given path. It also fails if
2024-04-26 19:30:35 +00:00
// the path points to a directory or there is an error when trying to check the file.
2024-04-26 19:30:35 +00:00
func FileExists(t TestingT, path string, msgAndArgs ...interface{}) bool {
2024-04-26 19:30:35 +00:00
if h, ok := t.(tHelper); ok {
2024-04-26 19:30:35 +00:00
h.Helper()
2024-04-26 19:30:35 +00:00
}
2024-04-26 19:30:35 +00:00
info, err := os.Lstat(path)
2024-04-26 19:30:35 +00:00
if err != nil {
2024-04-26 19:30:35 +00:00
if os.IsNotExist(err) {
2024-04-26 19:30:35 +00:00
return Fail(t, fmt.Sprintf("unable to find file %q", path), msgAndArgs...)
2024-04-26 19:30:35 +00:00
}
2024-04-26 19:30:35 +00:00
return Fail(t, fmt.Sprintf("error when running os.Lstat(%q): %s", path, err), msgAndArgs...)
2024-04-26 19:30:35 +00:00
}
2024-04-26 19:30:35 +00:00
if info.IsDir() {
2024-04-26 19:30:35 +00:00
return Fail(t, fmt.Sprintf("%q is a directory", path), msgAndArgs...)
2024-04-26 19:30:35 +00:00
}
2024-04-26 19:30:35 +00:00
return true
2024-04-26 19:30:35 +00:00
}
// NoFileExists checks whether a file does not exist in a given path. It fails
2024-04-26 19:30:35 +00:00
// if the path points to an existing _file_ only.
2024-04-26 19:30:35 +00:00
func NoFileExists(t TestingT, path string, msgAndArgs ...interface{}) bool {
2024-04-26 19:30:35 +00:00
if h, ok := t.(tHelper); ok {
2024-04-26 19:30:35 +00:00
h.Helper()
2024-04-26 19:30:35 +00:00
}
2024-04-26 19:30:35 +00:00
info, err := os.Lstat(path)
2024-04-26 19:30:35 +00:00
if err != nil {
2024-04-26 19:30:35 +00:00
return true
2024-04-26 19:30:35 +00:00
}
2024-04-26 19:30:35 +00:00
if info.IsDir() {
2024-04-26 19:30:35 +00:00
return true
2024-04-26 19:30:35 +00:00
}
2024-04-26 19:30:35 +00:00
return Fail(t, fmt.Sprintf("file %q exists", path), msgAndArgs...)
2024-04-26 19:30:35 +00:00
}
// DirExists checks whether a directory exists in the given path. It also fails
2024-04-26 19:30:35 +00:00
// if the path is a file rather a directory or there is an error checking whether it exists.
2024-04-26 19:30:35 +00:00
func DirExists(t TestingT, path string, msgAndArgs ...interface{}) bool {
2024-04-26 19:30:35 +00:00
if h, ok := t.(tHelper); ok {
2024-04-26 19:30:35 +00:00
h.Helper()
2024-04-26 19:30:35 +00:00
}
2024-04-26 19:30:35 +00:00
info, err := os.Lstat(path)
2024-04-26 19:30:35 +00:00
if err != nil {
2024-04-26 19:30:35 +00:00
if os.IsNotExist(err) {
2024-04-26 19:30:35 +00:00
return Fail(t, fmt.Sprintf("unable to find file %q", path), msgAndArgs...)
2024-04-26 19:30:35 +00:00
}
2024-04-26 19:30:35 +00:00
return Fail(t, fmt.Sprintf("error when running os.Lstat(%q): %s", path, err), msgAndArgs...)
2024-04-26 19:30:35 +00:00
}
2024-04-26 19:30:35 +00:00
if !info.IsDir() {
2024-04-26 19:30:35 +00:00
return Fail(t, fmt.Sprintf("%q is a file", path), msgAndArgs...)
2024-04-26 19:30:35 +00:00
}
2024-04-26 19:30:35 +00:00
return true
2024-04-26 19:30:35 +00:00
}
// NoDirExists checks whether a directory does not exist in the given path.
2024-04-26 19:30:35 +00:00
// It fails if the path points to an existing _directory_ only.
2024-04-26 19:30:35 +00:00
func NoDirExists(t TestingT, path string, msgAndArgs ...interface{}) bool {
2024-04-26 19:30:35 +00:00
if h, ok := t.(tHelper); ok {
2024-04-26 19:30:35 +00:00
h.Helper()
2024-04-26 19:30:35 +00:00
}
2024-04-26 19:30:35 +00:00
info, err := os.Lstat(path)
2024-04-26 19:30:35 +00:00
if err != nil {
2024-04-26 19:30:35 +00:00
if os.IsNotExist(err) {
2024-04-26 19:30:35 +00:00
return true
2024-04-26 19:30:35 +00:00
}
2024-04-26 19:30:35 +00:00
return true
2024-04-26 19:30:35 +00:00
}
2024-04-26 19:30:35 +00:00
if !info.IsDir() {
2024-04-26 19:30:35 +00:00
return true
2024-04-26 19:30:35 +00:00
}
2024-04-26 19:30:35 +00:00
return Fail(t, fmt.Sprintf("directory %q exists", path), msgAndArgs...)
2024-04-26 19:30:35 +00:00
}
// JSONEq asserts that two JSON strings are equivalent.
2024-04-26 19:30:35 +00:00
//
2024-04-26 19:30:35 +00:00
// assert.JSONEq(t, `{"hello": "world", "foo": "bar"}`, `{"foo": "bar", "hello": "world"}`)
2024-04-26 19:30:35 +00:00
func JSONEq(t TestingT, expected string, actual string, msgAndArgs ...interface{}) bool {
2024-04-26 19:30:35 +00:00
if h, ok := t.(tHelper); ok {
2024-04-26 19:30:35 +00:00
h.Helper()
2024-04-26 19:30:35 +00:00
}
2024-04-26 19:30:35 +00:00
var expectedJSONAsInterface, actualJSONAsInterface interface{}
if err := json.Unmarshal([]byte(expected), &expectedJSONAsInterface); err != nil {
2024-04-26 19:30:35 +00:00
return Fail(t, fmt.Sprintf("Expected value ('%s') is not valid json.\nJSON parsing error: '%s'", expected, err.Error()), msgAndArgs...)
2024-04-26 19:30:35 +00:00
}
if err := json.Unmarshal([]byte(actual), &actualJSONAsInterface); err != nil {
2024-04-26 19:30:35 +00:00
return Fail(t, fmt.Sprintf("Input ('%s') needs to be valid json.\nJSON parsing error: '%s'", actual, err.Error()), msgAndArgs...)
2024-04-26 19:30:35 +00:00
}
return Equal(t, expectedJSONAsInterface, actualJSONAsInterface, msgAndArgs...)
2024-04-26 19:30:35 +00:00
}
// YAMLEq asserts that two YAML strings are equivalent.
2024-04-26 19:30:35 +00:00
func YAMLEq(t TestingT, expected string, actual string, msgAndArgs ...interface{}) bool {
2024-04-26 19:30:35 +00:00
if h, ok := t.(tHelper); ok {
2024-04-26 19:30:35 +00:00
h.Helper()
2024-04-26 19:30:35 +00:00
}
2024-04-26 19:30:35 +00:00
var expectedYAMLAsInterface, actualYAMLAsInterface interface{}
if err := yaml.Unmarshal([]byte(expected), &expectedYAMLAsInterface); err != nil {
2024-04-26 19:30:35 +00:00
return Fail(t, fmt.Sprintf("Expected value ('%s') is not valid yaml.\nYAML parsing error: '%s'", expected, err.Error()), msgAndArgs...)
2024-04-26 19:30:35 +00:00
}
if err := yaml.Unmarshal([]byte(actual), &actualYAMLAsInterface); err != nil {
2024-04-26 19:30:35 +00:00
return Fail(t, fmt.Sprintf("Input ('%s') needs to be valid yaml.\nYAML error: '%s'", actual, err.Error()), msgAndArgs...)
2024-04-26 19:30:35 +00:00
}
return Equal(t, expectedYAMLAsInterface, actualYAMLAsInterface, msgAndArgs...)
2024-04-26 19:30:35 +00:00
}
func typeAndKind(v interface{}) (reflect.Type, reflect.Kind) {
2024-04-26 19:30:35 +00:00
t := reflect.TypeOf(v)
2024-04-26 19:30:35 +00:00
k := t.Kind()
if k == reflect.Ptr {
2024-04-26 19:30:35 +00:00
t = t.Elem()
2024-04-26 19:30:35 +00:00
k = t.Kind()
2024-04-26 19:30:35 +00:00
}
2024-04-26 19:30:35 +00:00
return t, k
2024-04-26 19:30:35 +00:00
}
// diff returns a diff of both values as long as both are of the same type and
2024-04-26 19:30:35 +00:00
// are a struct, map, slice, array or string. Otherwise it returns an empty string.
2024-04-26 19:30:35 +00:00
func diff(expected interface{}, actual interface{}) string {
2024-04-26 19:30:35 +00:00
if expected == nil || actual == nil {
2024-04-26 19:30:35 +00:00
return ""
2024-04-26 19:30:35 +00:00
}
et, ek := typeAndKind(expected)
2024-04-26 19:30:35 +00:00
at, _ := typeAndKind(actual)
if et != at {
2024-04-26 19:30:35 +00:00
return ""
2024-04-26 19:30:35 +00:00
}
if ek != reflect.Struct && ek != reflect.Map && ek != reflect.Slice && ek != reflect.Array && ek != reflect.String {
2024-04-26 19:30:35 +00:00
return ""
2024-04-26 19:30:35 +00:00
}
var e, a string
switch et {
2024-04-26 19:30:35 +00:00
case reflect.TypeOf(""):
2024-04-26 19:30:35 +00:00
e = reflect.ValueOf(expected).String()
2024-04-26 19:30:35 +00:00
a = reflect.ValueOf(actual).String()
2024-04-26 19:30:35 +00:00
case reflect.TypeOf(time.Time{}):
2024-04-26 19:30:35 +00:00
e = spewConfigStringerEnabled.Sdump(expected)
2024-04-26 19:30:35 +00:00
a = spewConfigStringerEnabled.Sdump(actual)
2024-04-26 19:30:35 +00:00
default:
2024-04-26 19:30:35 +00:00
e = spewConfig.Sdump(expected)
2024-04-26 19:30:35 +00:00
a = spewConfig.Sdump(actual)
2024-04-26 19:30:35 +00:00
}
diff, _ := difflib.GetUnifiedDiffString(difflib.UnifiedDiff{
A: difflib.SplitLines(e),
B: difflib.SplitLines(a),
2024-04-26 19:30:35 +00:00
FromFile: "Expected",
2024-04-26 19:30:35 +00:00
FromDate: "",
ToFile: "Actual",
ToDate: "",
Context: 1,
2024-04-26 19:30:35 +00:00
})
return "\n\nDiff:\n" + diff
2024-04-26 19:30:35 +00:00
}
func isFunction(arg interface{}) bool {
2024-04-26 19:30:35 +00:00
if arg == nil {
2024-04-26 19:30:35 +00:00
return false
2024-04-26 19:30:35 +00:00
}
2024-04-26 19:30:35 +00:00
return reflect.TypeOf(arg).Kind() == reflect.Func
2024-04-26 19:30:35 +00:00
}
var spewConfig = spew.ConfigState{
Indent: " ",
2024-04-26 19:30:35 +00:00
DisablePointerAddresses: true,
DisableCapacities: true,
SortKeys: true,
DisableMethods: true,
MaxDepth: 10,
2024-04-26 19:30:35 +00:00
}
var spewConfigStringerEnabled = spew.ConfigState{
Indent: " ",
2024-04-26 19:30:35 +00:00
DisablePointerAddresses: true,
DisableCapacities: true,
SortKeys: true,
MaxDepth: 10,
2024-04-26 19:30:35 +00:00
}
type tHelper interface {
Helper()
}
// Eventually asserts that given condition will be met in waitFor time,
2024-04-26 19:30:35 +00:00
// periodically checking target function each tick.
2024-04-26 19:30:35 +00:00
//
2024-04-26 19:30:35 +00:00
// assert.Eventually(t, func() bool { return true; }, time.Second, 10*time.Millisecond)
2024-04-26 19:30:35 +00:00
func Eventually(t TestingT, condition func() bool, waitFor time.Duration, tick time.Duration, msgAndArgs ...interface{}) bool {
2024-04-26 19:30:35 +00:00
if h, ok := t.(tHelper); ok {
2024-04-26 19:30:35 +00:00
h.Helper()
2024-04-26 19:30:35 +00:00
}
ch := make(chan bool, 1)
timer := time.NewTimer(waitFor)
2024-04-26 19:30:35 +00:00
defer timer.Stop()
ticker := time.NewTicker(tick)
2024-04-26 19:30:35 +00:00
defer ticker.Stop()
for tick := ticker.C; ; {
2024-04-26 19:30:35 +00:00
select {
2024-04-26 19:30:35 +00:00
case <-timer.C:
2024-04-26 19:30:35 +00:00
return Fail(t, "Condition never satisfied", msgAndArgs...)
2024-04-26 19:30:35 +00:00
case <-tick:
2024-04-26 19:30:35 +00:00
tick = nil
2024-04-26 19:30:35 +00:00
go func() { ch <- condition() }()
2024-04-26 19:30:35 +00:00
case v := <-ch:
2024-04-26 19:30:35 +00:00
if v {
2024-04-26 19:30:35 +00:00
return true
2024-04-26 19:30:35 +00:00
}
2024-04-26 19:30:35 +00:00
tick = ticker.C
2024-04-26 19:30:35 +00:00
}
2024-04-26 19:30:35 +00:00
}
2024-04-26 19:30:35 +00:00
}
// CollectT implements the TestingT interface and collects all errors.
2024-04-26 19:30:35 +00:00
type CollectT struct {
errors []error
}
// Errorf collects the error.
2024-04-26 19:30:35 +00:00
func (c *CollectT) Errorf(format string, args ...interface{}) {
2024-04-26 19:30:35 +00:00
c.errors = append(c.errors, fmt.Errorf(format, args...))
2024-04-26 19:30:35 +00:00
}
// FailNow panics.
2024-05-14 13:07:09 +00:00
func (*CollectT) FailNow() {
2024-04-26 19:30:35 +00:00
panic("Assertion failed")
2024-04-26 19:30:35 +00:00
}
2024-05-14 13:07:09 +00:00
// Deprecated: That was a method for internal usage that should not have been published. Now just panics.
2024-05-14 13:07:09 +00:00
func (*CollectT) Reset() {
2024-05-14 13:07:09 +00:00
panic("Reset() is deprecated")
2024-04-26 19:30:35 +00:00
}
2024-05-14 13:07:09 +00:00
// Deprecated: That was a method for internal usage that should not have been published. Now just panics.
2024-05-14 13:07:09 +00:00
func (*CollectT) Copy(TestingT) {
2024-05-14 13:07:09 +00:00
panic("Copy() is deprecated")
2024-04-26 19:30:35 +00:00
}
// EventuallyWithT asserts that given condition will be met in waitFor time,
2024-04-26 19:30:35 +00:00
// periodically checking target function each tick. In contrast to Eventually,
2024-04-26 19:30:35 +00:00
// it supplies a CollectT to the condition function, so that the condition
2024-04-26 19:30:35 +00:00
// function can use the CollectT to call other assertions.
2024-04-26 19:30:35 +00:00
// The condition is considered "met" if no errors are raised in a tick.
2024-04-26 19:30:35 +00:00
// The supplied CollectT collects all errors from one tick (if there are any).
2024-04-26 19:30:35 +00:00
// If the condition is not met before waitFor, the collected errors of
2024-04-26 19:30:35 +00:00
// the last tick are copied to t.
2024-04-26 19:30:35 +00:00
//
2024-04-26 19:30:35 +00:00
// externalValue := false
2024-04-26 19:30:35 +00:00
// go func() {
2024-04-26 19:30:35 +00:00
// time.Sleep(8*time.Second)
2024-04-26 19:30:35 +00:00
// externalValue = true
2024-04-26 19:30:35 +00:00
// }()
2024-04-26 19:30:35 +00:00
// assert.EventuallyWithT(t, func(c *assert.CollectT) {
2024-04-26 19:30:35 +00:00
// // add assertions as needed; any assertion failure will fail the current tick
2024-04-26 19:30:35 +00:00
// assert.True(c, externalValue, "expected 'externalValue' to be true")
2024-04-26 19:30:35 +00:00
// }, 1*time.Second, 10*time.Second, "external state has not changed to 'true'; still false")
2024-04-26 19:30:35 +00:00
func EventuallyWithT(t TestingT, condition func(collect *CollectT), waitFor time.Duration, tick time.Duration, msgAndArgs ...interface{}) bool {
2024-04-26 19:30:35 +00:00
if h, ok := t.(tHelper); ok {
2024-04-26 19:30:35 +00:00
h.Helper()
2024-04-26 19:30:35 +00:00
}
2024-05-14 13:07:09 +00:00
var lastFinishedTickErrs []error
2024-05-14 13:07:09 +00:00
ch := make(chan []error, 1)
2024-04-26 19:30:35 +00:00
timer := time.NewTimer(waitFor)
2024-04-26 19:30:35 +00:00
defer timer.Stop()
ticker := time.NewTicker(tick)
2024-04-26 19:30:35 +00:00
defer ticker.Stop()
for tick := ticker.C; ; {
2024-04-26 19:30:35 +00:00
select {
2024-04-26 19:30:35 +00:00
case <-timer.C:
2024-05-14 13:07:09 +00:00
for _, err := range lastFinishedTickErrs {
2024-05-14 13:07:09 +00:00
t.Errorf("%v", err)
2024-05-14 13:07:09 +00:00
}
2024-04-26 19:30:35 +00:00
return Fail(t, "Condition never satisfied", msgAndArgs...)
2024-04-26 19:30:35 +00:00
case <-tick:
2024-04-26 19:30:35 +00:00
tick = nil
2024-04-26 19:30:35 +00:00
go func() {
2024-05-14 13:07:09 +00:00
collect := new(CollectT)
2024-05-14 13:07:09 +00:00
defer func() {
2024-05-14 13:07:09 +00:00
ch <- collect.errors
2024-05-14 13:07:09 +00:00
}()
2024-04-26 19:30:35 +00:00
condition(collect)
2024-04-26 19:30:35 +00:00
}()
2024-05-14 13:07:09 +00:00
case errs := <-ch:
2024-05-14 13:07:09 +00:00
if len(errs) == 0 {
2024-04-26 19:30:35 +00:00
return true
2024-04-26 19:30:35 +00:00
}
2024-05-14 13:07:09 +00:00
// Keep the errors from the last ended condition, so that they can be copied to t if timeout is reached.
2024-05-14 13:07:09 +00:00
lastFinishedTickErrs = errs
2024-04-26 19:30:35 +00:00
tick = ticker.C
2024-04-26 19:30:35 +00:00
}
2024-04-26 19:30:35 +00:00
}
2024-04-26 19:30:35 +00:00
}
// Never asserts that the given condition doesn't satisfy in waitFor time,
2024-04-26 19:30:35 +00:00
// periodically checking the target function each tick.
2024-04-26 19:30:35 +00:00
//
2024-04-26 19:30:35 +00:00
// assert.Never(t, func() bool { return false; }, time.Second, 10*time.Millisecond)
2024-04-26 19:30:35 +00:00
func Never(t TestingT, condition func() bool, waitFor time.Duration, tick time.Duration, msgAndArgs ...interface{}) bool {
2024-04-26 19:30:35 +00:00
if h, ok := t.(tHelper); ok {
2024-04-26 19:30:35 +00:00
h.Helper()
2024-04-26 19:30:35 +00:00
}
ch := make(chan bool, 1)
timer := time.NewTimer(waitFor)
2024-04-26 19:30:35 +00:00
defer timer.Stop()
ticker := time.NewTicker(tick)
2024-04-26 19:30:35 +00:00
defer ticker.Stop()
for tick := ticker.C; ; {
2024-04-26 19:30:35 +00:00
select {
2024-04-26 19:30:35 +00:00
case <-timer.C:
2024-04-26 19:30:35 +00:00
return true
2024-04-26 19:30:35 +00:00
case <-tick:
2024-04-26 19:30:35 +00:00
tick = nil
2024-04-26 19:30:35 +00:00
go func() { ch <- condition() }()
2024-04-26 19:30:35 +00:00
case v := <-ch:
2024-04-26 19:30:35 +00:00
if v {
2024-04-26 19:30:35 +00:00
return Fail(t, "Condition satisfied", msgAndArgs...)
2024-04-26 19:30:35 +00:00
}
2024-04-26 19:30:35 +00:00
tick = ticker.C
2024-04-26 19:30:35 +00:00
}
2024-04-26 19:30:35 +00:00
}
2024-04-26 19:30:35 +00:00
}
// ErrorIs asserts that at least one of the errors in err's chain matches target.
2024-04-26 19:30:35 +00:00
// This is a wrapper for errors.Is.
2024-04-26 19:30:35 +00:00
func ErrorIs(t TestingT, err, target error, msgAndArgs ...interface{}) bool {
2024-04-26 19:30:35 +00:00
if h, ok := t.(tHelper); ok {
2024-04-26 19:30:35 +00:00
h.Helper()
2024-04-26 19:30:35 +00:00
}
2024-04-26 19:30:35 +00:00
if errors.Is(err, target) {
2024-04-26 19:30:35 +00:00
return true
2024-04-26 19:30:35 +00:00
}
var expectedText string
2024-04-26 19:30:35 +00:00
if target != nil {
2024-04-26 19:30:35 +00:00
expectedText = target.Error()
2024-04-26 19:30:35 +00:00
}
chain := buildErrorChainString(err)
return Fail(t, fmt.Sprintf("Target error should be in err chain:\n"+
2024-04-26 19:30:35 +00:00
"expected: %q\n"+
2024-04-26 19:30:35 +00:00
"in chain: %s", expectedText, chain,
), msgAndArgs...)
2024-04-26 19:30:35 +00:00
}
// NotErrorIs asserts that at none of the errors in err's chain matches target.
2024-04-26 19:30:35 +00:00
// This is a wrapper for errors.Is.
2024-04-26 19:30:35 +00:00
func NotErrorIs(t TestingT, err, target error, msgAndArgs ...interface{}) bool {
2024-04-26 19:30:35 +00:00
if h, ok := t.(tHelper); ok {
2024-04-26 19:30:35 +00:00
h.Helper()
2024-04-26 19:30:35 +00:00
}
2024-04-26 19:30:35 +00:00
if !errors.Is(err, target) {
2024-04-26 19:30:35 +00:00
return true
2024-04-26 19:30:35 +00:00
}
var expectedText string
2024-04-26 19:30:35 +00:00
if target != nil {
2024-04-26 19:30:35 +00:00
expectedText = target.Error()
2024-04-26 19:30:35 +00:00
}
chain := buildErrorChainString(err)
return Fail(t, fmt.Sprintf("Target error should not be in err chain:\n"+
2024-04-26 19:30:35 +00:00
"found: %q\n"+
2024-04-26 19:30:35 +00:00
"in chain: %s", expectedText, chain,
), msgAndArgs...)
2024-04-26 19:30:35 +00:00
}
// ErrorAs asserts that at least one of the errors in err's chain matches target, and if so, sets target to that error value.
2024-04-26 19:30:35 +00:00
// This is a wrapper for errors.As.
2024-04-26 19:30:35 +00:00
func ErrorAs(t TestingT, err error, target interface{}, msgAndArgs ...interface{}) bool {
2024-04-26 19:30:35 +00:00
if h, ok := t.(tHelper); ok {
2024-04-26 19:30:35 +00:00
h.Helper()
2024-04-26 19:30:35 +00:00
}
2024-04-26 19:30:35 +00:00
if errors.As(err, target) {
2024-04-26 19:30:35 +00:00
return true
2024-04-26 19:30:35 +00:00
}
chain := buildErrorChainString(err)
return Fail(t, fmt.Sprintf("Should be in error chain:\n"+
2024-04-26 19:30:35 +00:00
"expected: %q\n"+
2024-04-26 19:30:35 +00:00
"in chain: %s", target, chain,
), msgAndArgs...)
2024-04-26 19:30:35 +00:00
}
func buildErrorChainString(err error) string {
2024-04-26 19:30:35 +00:00
if err == nil {
2024-04-26 19:30:35 +00:00
return ""
2024-04-26 19:30:35 +00:00
}
e := errors.Unwrap(err)
2024-04-26 19:30:35 +00:00
chain := fmt.Sprintf("%q", err.Error())
2024-04-26 19:30:35 +00:00
for e != nil {
2024-04-26 19:30:35 +00:00
chain += fmt.Sprintf("\n\t%q", e.Error())
2024-04-26 19:30:35 +00:00
e = errors.Unwrap(e)
2024-04-26 19:30:35 +00:00
}
2024-04-26 19:30:35 +00:00
return chain
2024-04-26 19:30:35 +00:00
}