assertions.go

   1package assert
   2
   3import (
   4	"bufio"
   5	"bytes"
   6	"encoding/json"
   7	"errors"
   8	"fmt"
   9	"math"
  10	"os"
  11	"reflect"
  12	"regexp"
  13	"runtime"
  14	"runtime/debug"
  15	"strings"
  16	"time"
  17	"unicode"
  18	"unicode/utf8"
  19
  20	"github.com/davecgh/go-spew/spew"
  21	"github.com/pmezard/go-difflib/difflib"
  22
  23	// Wrapper around gopkg.in/yaml.v3
  24	"github.com/stretchr/testify/assert/yaml"
  25)
  26
  27//go:generate sh -c "cd ../_codegen && go build && cd - && ../_codegen/_codegen -output-package=assert -template=assertion_format.go.tmpl"
  28
  29// TestingT is an interface wrapper around *testing.T
  30type TestingT interface {
  31	Errorf(format string, args ...interface{})
  32}
  33
  34// ComparisonAssertionFunc is a common function prototype when comparing two values.  Can be useful
  35// for table driven tests.
  36type ComparisonAssertionFunc func(TestingT, interface{}, interface{}, ...interface{}) bool
  37
  38// ValueAssertionFunc is a common function prototype when validating a single value.  Can be useful
  39// for table driven tests.
  40type ValueAssertionFunc func(TestingT, interface{}, ...interface{}) bool
  41
  42// BoolAssertionFunc is a common function prototype when validating a bool value.  Can be useful
  43// for table driven tests.
  44type BoolAssertionFunc func(TestingT, bool, ...interface{}) bool
  45
  46// ErrorAssertionFunc is a common function prototype when validating an error value.  Can be useful
  47// for table driven tests.
  48type ErrorAssertionFunc func(TestingT, error, ...interface{}) bool
  49
  50// PanicAssertionFunc is a common function prototype when validating a panic value.  Can be useful
  51// for table driven tests.
  52type PanicAssertionFunc = func(t TestingT, f PanicTestFunc, msgAndArgs ...interface{}) bool
  53
  54// Comparison is a custom function that returns true on success and false on failure
  55type Comparison func() (success bool)
  56
  57/*
  58	Helper functions
  59*/
  60
  61// ObjectsAreEqual determines if two objects are considered equal.
  62//
  63// This function does no assertion of any kind.
  64func ObjectsAreEqual(expected, actual interface{}) bool {
  65	if expected == nil || actual == nil {
  66		return expected == actual
  67	}
  68
  69	exp, ok := expected.([]byte)
  70	if !ok {
  71		return reflect.DeepEqual(expected, actual)
  72	}
  73
  74	act, ok := actual.([]byte)
  75	if !ok {
  76		return false
  77	}
  78	if exp == nil || act == nil {
  79		return exp == nil && act == nil
  80	}
  81	return bytes.Equal(exp, act)
  82}
  83
  84// copyExportedFields iterates downward through nested data structures and creates a copy
  85// that only contains the exported struct fields.
  86func copyExportedFields(expected interface{}) interface{} {
  87	if isNil(expected) {
  88		return expected
  89	}
  90
  91	expectedType := reflect.TypeOf(expected)
  92	expectedKind := expectedType.Kind()
  93	expectedValue := reflect.ValueOf(expected)
  94
  95	switch expectedKind {
  96	case reflect.Struct:
  97		result := reflect.New(expectedType).Elem()
  98		for i := 0; i < expectedType.NumField(); i++ {
  99			field := expectedType.Field(i)
 100			isExported := field.IsExported()
 101			if isExported {
 102				fieldValue := expectedValue.Field(i)
 103				if isNil(fieldValue) || isNil(fieldValue.Interface()) {
 104					continue
 105				}
 106				newValue := copyExportedFields(fieldValue.Interface())
 107				result.Field(i).Set(reflect.ValueOf(newValue))
 108			}
 109		}
 110		return result.Interface()
 111
 112	case reflect.Ptr:
 113		result := reflect.New(expectedType.Elem())
 114		unexportedRemoved := copyExportedFields(expectedValue.Elem().Interface())
 115		result.Elem().Set(reflect.ValueOf(unexportedRemoved))
 116		return result.Interface()
 117
 118	case reflect.Array, reflect.Slice:
 119		var result reflect.Value
 120		if expectedKind == reflect.Array {
 121			result = reflect.New(reflect.ArrayOf(expectedValue.Len(), expectedType.Elem())).Elem()
 122		} else {
 123			result = reflect.MakeSlice(expectedType, expectedValue.Len(), expectedValue.Len())
 124		}
 125		for i := 0; i < expectedValue.Len(); i++ {
 126			index := expectedValue.Index(i)
 127			if isNil(index) {
 128				continue
 129			}
 130			unexportedRemoved := copyExportedFields(index.Interface())
 131			result.Index(i).Set(reflect.ValueOf(unexportedRemoved))
 132		}
 133		return result.Interface()
 134
 135	case reflect.Map:
 136		result := reflect.MakeMap(expectedType)
 137		for _, k := range expectedValue.MapKeys() {
 138			index := expectedValue.MapIndex(k)
 139			unexportedRemoved := copyExportedFields(index.Interface())
 140			result.SetMapIndex(k, reflect.ValueOf(unexportedRemoved))
 141		}
 142		return result.Interface()
 143
 144	default:
 145		return expected
 146	}
 147}
 148
 149// ObjectsExportedFieldsAreEqual determines if the exported (public) fields of two objects are
 150// considered equal. This comparison of only exported fields is applied recursively to nested data
 151// structures.
 152//
 153// This function does no assertion of any kind.
 154//
 155// Deprecated: Use [EqualExportedValues] instead.
 156func ObjectsExportedFieldsAreEqual(expected, actual interface{}) bool {
 157	expectedCleaned := copyExportedFields(expected)
 158	actualCleaned := copyExportedFields(actual)
 159	return ObjectsAreEqualValues(expectedCleaned, actualCleaned)
 160}
 161
 162// ObjectsAreEqualValues gets whether two objects are equal, or if their
 163// values are equal.
 164func ObjectsAreEqualValues(expected, actual interface{}) bool {
 165	if ObjectsAreEqual(expected, actual) {
 166		return true
 167	}
 168
 169	expectedValue := reflect.ValueOf(expected)
 170	actualValue := reflect.ValueOf(actual)
 171	if !expectedValue.IsValid() || !actualValue.IsValid() {
 172		return false
 173	}
 174
 175	expectedType := expectedValue.Type()
 176	actualType := actualValue.Type()
 177	if !expectedType.ConvertibleTo(actualType) {
 178		return false
 179	}
 180
 181	if !isNumericType(expectedType) || !isNumericType(actualType) {
 182		// Attempt comparison after type conversion
 183		return reflect.DeepEqual(
 184			expectedValue.Convert(actualType).Interface(), actual,
 185		)
 186	}
 187
 188	// If BOTH values are numeric, there are chances of false positives due
 189	// to overflow or underflow. So, we need to make sure to always convert
 190	// the smaller type to a larger type before comparing.
 191	if expectedType.Size() >= actualType.Size() {
 192		return actualValue.Convert(expectedType).Interface() == expected
 193	}
 194
 195	return expectedValue.Convert(actualType).Interface() == actual
 196}
 197
 198// isNumericType returns true if the type is one of:
 199// int, int8, int16, int32, int64, uint, uint8, uint16, uint32, uint64,
 200// float32, float64, complex64, complex128
 201func isNumericType(t reflect.Type) bool {
 202	return t.Kind() >= reflect.Int && t.Kind() <= reflect.Complex128
 203}
 204
 205/* CallerInfo is necessary because the assert functions use the testing object
 206internally, causing it to print the file:line of the assert method, rather than where
 207the problem actually occurred in calling code.*/
 208
 209// CallerInfo returns an array of strings containing the file and line number
 210// of each stack frame leading from the current test to the assert call that
 211// failed.
 212func CallerInfo() []string {
 213
 214	var pc uintptr
 215	var ok bool
 216	var file string
 217	var line int
 218	var name string
 219
 220	callers := []string{}
 221	for i := 0; ; i++ {
 222		pc, file, line, ok = runtime.Caller(i)
 223		if !ok {
 224			// The breaks below failed to terminate the loop, and we ran off the
 225			// end of the call stack.
 226			break
 227		}
 228
 229		// This is a huge edge case, but it will panic if this is the case, see #180
 230		if file == "<autogenerated>" {
 231			break
 232		}
 233
 234		f := runtime.FuncForPC(pc)
 235		if f == nil {
 236			break
 237		}
 238		name = f.Name()
 239
 240		// testing.tRunner is the standard library function that calls
 241		// tests. Subtests are called directly by tRunner, without going through
 242		// the Test/Benchmark/Example function that contains the t.Run calls, so
 243		// with subtests we should break when we hit tRunner, without adding it
 244		// to the list of callers.
 245		if name == "testing.tRunner" {
 246			break
 247		}
 248
 249		parts := strings.Split(file, "/")
 250		if len(parts) > 1 {
 251			filename := parts[len(parts)-1]
 252			dir := parts[len(parts)-2]
 253			if (dir != "assert" && dir != "mock" && dir != "require") || filename == "mock_test.go" {
 254				callers = append(callers, fmt.Sprintf("%s:%d", file, line))
 255			}
 256		}
 257
 258		// Drop the package
 259		segments := strings.Split(name, ".")
 260		name = segments[len(segments)-1]
 261		if isTest(name, "Test") ||
 262			isTest(name, "Benchmark") ||
 263			isTest(name, "Example") {
 264			break
 265		}
 266	}
 267
 268	return callers
 269}
 270
 271// Stolen from the `go test` tool.
 272// isTest tells whether name looks like a test (or benchmark, according to prefix).
 273// It is a Test (say) if there is a character after Test that is not a lower-case letter.
 274// We don't want TesticularCancer.
 275func isTest(name, prefix string) bool {
 276	if !strings.HasPrefix(name, prefix) {
 277		return false
 278	}
 279	if len(name) == len(prefix) { // "Test" is ok
 280		return true
 281	}
 282	r, _ := utf8.DecodeRuneInString(name[len(prefix):])
 283	return !unicode.IsLower(r)
 284}
 285
 286func messageFromMsgAndArgs(msgAndArgs ...interface{}) string {
 287	if len(msgAndArgs) == 0 || msgAndArgs == nil {
 288		return ""
 289	}
 290	if len(msgAndArgs) == 1 {
 291		msg := msgAndArgs[0]
 292		if msgAsStr, ok := msg.(string); ok {
 293			return msgAsStr
 294		}
 295		return fmt.Sprintf("%+v", msg)
 296	}
 297	if len(msgAndArgs) > 1 {
 298		return fmt.Sprintf(msgAndArgs[0].(string), msgAndArgs[1:]...)
 299	}
 300	return ""
 301}
 302
 303// Aligns the provided message so that all lines after the first line start at the same location as the first line.
 304// Assumes that the first line starts at the correct location (after carriage return, tab, label, spacer and tab).
 305// The longestLabelLen parameter specifies the length of the longest label in the output (required because this is the
 306// basis on which the alignment occurs).
 307func indentMessageLines(message string, longestLabelLen int) string {
 308	outBuf := new(bytes.Buffer)
 309
 310	for i, scanner := 0, bufio.NewScanner(strings.NewReader(message)); scanner.Scan(); i++ {
 311		// no need to align first line because it starts at the correct location (after the label)
 312		if i != 0 {
 313			// append alignLen+1 spaces to align with "{{longestLabel}}:" before adding tab
 314			outBuf.WriteString("\n\t" + strings.Repeat(" ", longestLabelLen+1) + "\t")
 315		}
 316		outBuf.WriteString(scanner.Text())
 317	}
 318
 319	return outBuf.String()
 320}
 321
 322type failNower interface {
 323	FailNow()
 324}
 325
 326// FailNow fails test
 327func FailNow(t TestingT, failureMessage string, msgAndArgs ...interface{}) bool {
 328	if h, ok := t.(tHelper); ok {
 329		h.Helper()
 330	}
 331	Fail(t, failureMessage, msgAndArgs...)
 332
 333	// We cannot extend TestingT with FailNow() and
 334	// maintain backwards compatibility, so we fallback
 335	// to panicking when FailNow is not available in
 336	// TestingT.
 337	// See issue #263
 338
 339	if t, ok := t.(failNower); ok {
 340		t.FailNow()
 341	} else {
 342		panic("test failed and t is missing `FailNow()`")
 343	}
 344	return false
 345}
 346
 347// Fail reports a failure through
 348func Fail(t TestingT, failureMessage string, msgAndArgs ...interface{}) bool {
 349	if h, ok := t.(tHelper); ok {
 350		h.Helper()
 351	}
 352	content := []labeledContent{
 353		{"Error Trace", strings.Join(CallerInfo(), "\n\t\t\t")},
 354		{"Error", failureMessage},
 355	}
 356
 357	// Add test name if the Go version supports it
 358	if n, ok := t.(interface {
 359		Name() string
 360	}); ok {
 361		content = append(content, labeledContent{"Test", n.Name()})
 362	}
 363
 364	message := messageFromMsgAndArgs(msgAndArgs...)
 365	if len(message) > 0 {
 366		content = append(content, labeledContent{"Messages", message})
 367	}
 368
 369	t.Errorf("\n%s", ""+labeledOutput(content...))
 370
 371	return false
 372}
 373
 374type labeledContent struct {
 375	label   string
 376	content string
 377}
 378
 379// labeledOutput returns a string consisting of the provided labeledContent. Each labeled output is appended in the following manner:
 380//
 381//	\t{{label}}:{{align_spaces}}\t{{content}}\n
 382//
 383// The initial carriage return is required to undo/erase any padding added by testing.T.Errorf. The "\t{{label}}:" is for the label.
 384// If a label is shorter than the longest label provided, padding spaces are added to make all the labels match in length. Once this
 385// alignment is achieved, "\t{{content}}\n" is added for the output.
 386//
 387// 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.
 388func labeledOutput(content ...labeledContent) string {
 389	longestLabel := 0
 390	for _, v := range content {
 391		if len(v.label) > longestLabel {
 392			longestLabel = len(v.label)
 393		}
 394	}
 395	var output string
 396	for _, v := range content {
 397		output += "\t" + v.label + ":" + strings.Repeat(" ", longestLabel-len(v.label)) + "\t" + indentMessageLines(v.content, longestLabel) + "\n"
 398	}
 399	return output
 400}
 401
 402// Implements asserts that an object is implemented by the specified interface.
 403//
 404//	assert.Implements(t, (*MyInterface)(nil), new(MyObject))
 405func Implements(t TestingT, interfaceObject interface{}, object interface{}, msgAndArgs ...interface{}) bool {
 406	if h, ok := t.(tHelper); ok {
 407		h.Helper()
 408	}
 409	interfaceType := reflect.TypeOf(interfaceObject).Elem()
 410
 411	if object == nil {
 412		return Fail(t, fmt.Sprintf("Cannot check if nil implements %v", interfaceType), msgAndArgs...)
 413	}
 414	if !reflect.TypeOf(object).Implements(interfaceType) {
 415		return Fail(t, fmt.Sprintf("%T must implement %v", object, interfaceType), msgAndArgs...)
 416	}
 417
 418	return true
 419}
 420
 421// NotImplements asserts that an object does not implement the specified interface.
 422//
 423//	assert.NotImplements(t, (*MyInterface)(nil), new(MyObject))
 424func NotImplements(t TestingT, interfaceObject interface{}, object interface{}, msgAndArgs ...interface{}) bool {
 425	if h, ok := t.(tHelper); ok {
 426		h.Helper()
 427	}
 428	interfaceType := reflect.TypeOf(interfaceObject).Elem()
 429
 430	if object == nil {
 431		return Fail(t, fmt.Sprintf("Cannot check if nil does not implement %v", interfaceType), msgAndArgs...)
 432	}
 433	if reflect.TypeOf(object).Implements(interfaceType) {
 434		return Fail(t, fmt.Sprintf("%T implements %v", object, interfaceType), msgAndArgs...)
 435	}
 436
 437	return true
 438}
 439
 440// IsType asserts that the specified objects are of the same type.
 441func IsType(t TestingT, expectedType interface{}, object interface{}, msgAndArgs ...interface{}) bool {
 442	if h, ok := t.(tHelper); ok {
 443		h.Helper()
 444	}
 445
 446	if !ObjectsAreEqual(reflect.TypeOf(object), reflect.TypeOf(expectedType)) {
 447		return Fail(t, fmt.Sprintf("Object expected to be of type %v, but was %v", reflect.TypeOf(expectedType), reflect.TypeOf(object)), msgAndArgs...)
 448	}
 449
 450	return true
 451}
 452
 453// Equal asserts that two objects are equal.
 454//
 455//	assert.Equal(t, 123, 123)
 456//
 457// Pointer variable equality is determined based on the equality of the
 458// referenced values (as opposed to the memory addresses). Function equality
 459// cannot be determined and will always fail.
 460func Equal(t TestingT, expected, actual interface{}, msgAndArgs ...interface{}) bool {
 461	if h, ok := t.(tHelper); ok {
 462		h.Helper()
 463	}
 464	if err := validateEqualArgs(expected, actual); err != nil {
 465		return Fail(t, fmt.Sprintf("Invalid operation: %#v == %#v (%s)",
 466			expected, actual, err), msgAndArgs...)
 467	}
 468
 469	if !ObjectsAreEqual(expected, actual) {
 470		diff := diff(expected, actual)
 471		expected, actual = formatUnequalValues(expected, actual)
 472		return Fail(t, fmt.Sprintf("Not equal: \n"+
 473			"expected: %s\n"+
 474			"actual  : %s%s", expected, actual, diff), msgAndArgs...)
 475	}
 476
 477	return true
 478
 479}
 480
 481// validateEqualArgs checks whether provided arguments can be safely used in the
 482// Equal/NotEqual functions.
 483func validateEqualArgs(expected, actual interface{}) error {
 484	if expected == nil && actual == nil {
 485		return nil
 486	}
 487
 488	if isFunction(expected) || isFunction(actual) {
 489		return errors.New("cannot take func type as argument")
 490	}
 491	return nil
 492}
 493
 494// Same asserts that two pointers reference the same object.
 495//
 496//	assert.Same(t, ptr1, ptr2)
 497//
 498// Both arguments must be pointer variables. Pointer variable sameness is
 499// determined based on the equality of both type and value.
 500func Same(t TestingT, expected, actual interface{}, msgAndArgs ...interface{}) bool {
 501	if h, ok := t.(tHelper); ok {
 502		h.Helper()
 503	}
 504
 505	same, ok := samePointers(expected, actual)
 506	if !ok {
 507		return Fail(t, "Both arguments must be pointers", msgAndArgs...)
 508	}
 509
 510	if !same {
 511		// both are pointers but not the same type & pointing to the same address
 512		return Fail(t, fmt.Sprintf("Not same: \n"+
 513			"expected: %p %#v\n"+
 514			"actual  : %p %#v", expected, expected, actual, actual), msgAndArgs...)
 515	}
 516
 517	return true
 518}
 519
 520// NotSame asserts that two pointers do not reference the same object.
 521//
 522//	assert.NotSame(t, ptr1, ptr2)
 523//
 524// Both arguments must be pointer variables. Pointer variable sameness is
 525// determined based on the equality of both type and value.
 526func NotSame(t TestingT, expected, actual interface{}, msgAndArgs ...interface{}) bool {
 527	if h, ok := t.(tHelper); ok {
 528		h.Helper()
 529	}
 530
 531	same, ok := samePointers(expected, actual)
 532	if !ok {
 533		//fails when the arguments are not pointers
 534		return !(Fail(t, "Both arguments must be pointers", msgAndArgs...))
 535	}
 536
 537	if same {
 538		return Fail(t, fmt.Sprintf(
 539			"Expected and actual point to the same object: %p %#v",
 540			expected, expected), msgAndArgs...)
 541	}
 542	return true
 543}
 544
 545// samePointers checks if two generic interface objects are pointers of the same
 546// type pointing to the same object. It returns two values: same indicating if
 547// they are the same type and point to the same object, and ok indicating that
 548// both inputs are pointers.
 549func samePointers(first, second interface{}) (same bool, ok bool) {
 550	firstPtr, secondPtr := reflect.ValueOf(first), reflect.ValueOf(second)
 551	if firstPtr.Kind() != reflect.Ptr || secondPtr.Kind() != reflect.Ptr {
 552		return false, false //not both are pointers
 553	}
 554
 555	firstType, secondType := reflect.TypeOf(first), reflect.TypeOf(second)
 556	if firstType != secondType {
 557		return false, true // both are pointers, but of different types
 558	}
 559
 560	// compare pointer addresses
 561	return first == second, true
 562}
 563
 564// formatUnequalValues takes two values of arbitrary types and returns string
 565// representations appropriate to be presented to the user.
 566//
 567// If the values are not of like type, the returned strings will be prefixed
 568// with the type name, and the value will be enclosed in parentheses similar
 569// to a type conversion in the Go grammar.
 570func formatUnequalValues(expected, actual interface{}) (e string, a string) {
 571	if reflect.TypeOf(expected) != reflect.TypeOf(actual) {
 572		return fmt.Sprintf("%T(%s)", expected, truncatingFormat(expected)),
 573			fmt.Sprintf("%T(%s)", actual, truncatingFormat(actual))
 574	}
 575	switch expected.(type) {
 576	case time.Duration:
 577		return fmt.Sprintf("%v", expected), fmt.Sprintf("%v", actual)
 578	}
 579	return truncatingFormat(expected), truncatingFormat(actual)
 580}
 581
 582// truncatingFormat formats the data and truncates it if it's too long.
 583//
 584// This helps keep formatted error messages lines from exceeding the
 585// bufio.MaxScanTokenSize max line length that the go testing framework imposes.
 586func truncatingFormat(data interface{}) string {
 587	value := fmt.Sprintf("%#v", data)
 588	max := bufio.MaxScanTokenSize - 100 // Give us some space the type info too if needed.
 589	if len(value) > max {
 590		value = value[0:max] + "<... truncated>"
 591	}
 592	return value
 593}
 594
 595// EqualValues asserts that two objects are equal or convertible to the larger
 596// type and equal.
 597//
 598//	assert.EqualValues(t, uint32(123), int32(123))
 599func EqualValues(t TestingT, expected, actual interface{}, msgAndArgs ...interface{}) bool {
 600	if h, ok := t.(tHelper); ok {
 601		h.Helper()
 602	}
 603
 604	if !ObjectsAreEqualValues(expected, actual) {
 605		diff := diff(expected, actual)
 606		expected, actual = formatUnequalValues(expected, actual)
 607		return Fail(t, fmt.Sprintf("Not equal: \n"+
 608			"expected: %s\n"+
 609			"actual  : %s%s", expected, actual, diff), msgAndArgs...)
 610	}
 611
 612	return true
 613
 614}
 615
 616// EqualExportedValues asserts that the types of two objects are equal and their public
 617// fields are also equal. This is useful for comparing structs that have private fields
 618// that could potentially differ.
 619//
 620//	 type S struct {
 621//		Exported     	int
 622//		notExported   	int
 623//	 }
 624//	 assert.EqualExportedValues(t, S{1, 2}, S{1, 3}) => true
 625//	 assert.EqualExportedValues(t, S{1, 2}, S{2, 3}) => false
 626func EqualExportedValues(t TestingT, expected, actual interface{}, msgAndArgs ...interface{}) bool {
 627	if h, ok := t.(tHelper); ok {
 628		h.Helper()
 629	}
 630
 631	aType := reflect.TypeOf(expected)
 632	bType := reflect.TypeOf(actual)
 633
 634	if aType != bType {
 635		return Fail(t, fmt.Sprintf("Types expected to match exactly\n\t%v != %v", aType, bType), msgAndArgs...)
 636	}
 637
 638	expected = copyExportedFields(expected)
 639	actual = copyExportedFields(actual)
 640
 641	if !ObjectsAreEqualValues(expected, actual) {
 642		diff := diff(expected, actual)
 643		expected, actual = formatUnequalValues(expected, actual)
 644		return Fail(t, fmt.Sprintf("Not equal (comparing only exported fields): \n"+
 645			"expected: %s\n"+
 646			"actual  : %s%s", expected, actual, diff), msgAndArgs...)
 647	}
 648
 649	return true
 650}
 651
 652// Exactly asserts that two objects are equal in value and type.
 653//
 654//	assert.Exactly(t, int32(123), int64(123))
 655func Exactly(t TestingT, expected, actual interface{}, msgAndArgs ...interface{}) bool {
 656	if h, ok := t.(tHelper); ok {
 657		h.Helper()
 658	}
 659
 660	aType := reflect.TypeOf(expected)
 661	bType := reflect.TypeOf(actual)
 662
 663	if aType != bType {
 664		return Fail(t, fmt.Sprintf("Types expected to match exactly\n\t%v != %v", aType, bType), msgAndArgs...)
 665	}
 666
 667	return Equal(t, expected, actual, msgAndArgs...)
 668
 669}
 670
 671// NotNil asserts that the specified object is not nil.
 672//
 673//	assert.NotNil(t, err)
 674func NotNil(t TestingT, object interface{}, msgAndArgs ...interface{}) bool {
 675	if !isNil(object) {
 676		return true
 677	}
 678	if h, ok := t.(tHelper); ok {
 679		h.Helper()
 680	}
 681	return Fail(t, "Expected value not to be nil.", msgAndArgs...)
 682}
 683
 684// isNil checks if a specified object is nil or not, without Failing.
 685func isNil(object interface{}) bool {
 686	if object == nil {
 687		return true
 688	}
 689
 690	value := reflect.ValueOf(object)
 691	switch value.Kind() {
 692	case
 693		reflect.Chan, reflect.Func,
 694		reflect.Interface, reflect.Map,
 695		reflect.Ptr, reflect.Slice, reflect.UnsafePointer:
 696
 697		return value.IsNil()
 698	}
 699
 700	return false
 701}
 702
 703// Nil asserts that the specified object is nil.
 704//
 705//	assert.Nil(t, err)
 706func Nil(t TestingT, object interface{}, msgAndArgs ...interface{}) bool {
 707	if isNil(object) {
 708		return true
 709	}
 710	if h, ok := t.(tHelper); ok {
 711		h.Helper()
 712	}
 713	return Fail(t, fmt.Sprintf("Expected nil, but got: %#v", object), msgAndArgs...)
 714}
 715
 716// isEmpty gets whether the specified object is considered empty or not.
 717func isEmpty(object interface{}) bool {
 718
 719	// get nil case out of the way
 720	if object == nil {
 721		return true
 722	}
 723
 724	objValue := reflect.ValueOf(object)
 725
 726	switch objValue.Kind() {
 727	// collection types are empty when they have no element
 728	case reflect.Chan, reflect.Map, reflect.Slice:
 729		return objValue.Len() == 0
 730	// pointers are empty if nil or if the value they point to is empty
 731	case reflect.Ptr:
 732		if objValue.IsNil() {
 733			return true
 734		}
 735		deref := objValue.Elem().Interface()
 736		return isEmpty(deref)
 737	// for all other types, compare against the zero value
 738	// array types are empty when they match their zero-initialized state
 739	default:
 740		zero := reflect.Zero(objValue.Type())
 741		return reflect.DeepEqual(object, zero.Interface())
 742	}
 743}
 744
 745// Empty asserts that the specified object is empty.  I.e. nil, "", false, 0 or either
 746// a slice or a channel with len == 0.
 747//
 748//	assert.Empty(t, obj)
 749func Empty(t TestingT, object interface{}, msgAndArgs ...interface{}) bool {
 750	pass := isEmpty(object)
 751	if !pass {
 752		if h, ok := t.(tHelper); ok {
 753			h.Helper()
 754		}
 755		Fail(t, fmt.Sprintf("Should be empty, but was %v", object), msgAndArgs...)
 756	}
 757
 758	return pass
 759
 760}
 761
 762// NotEmpty asserts that the specified object is NOT empty.  I.e. not nil, "", false, 0 or either
 763// a slice or a channel with len == 0.
 764//
 765//	if assert.NotEmpty(t, obj) {
 766//	  assert.Equal(t, "two", obj[1])
 767//	}
 768func NotEmpty(t TestingT, object interface{}, msgAndArgs ...interface{}) bool {
 769	pass := !isEmpty(object)
 770	if !pass {
 771		if h, ok := t.(tHelper); ok {
 772			h.Helper()
 773		}
 774		Fail(t, fmt.Sprintf("Should NOT be empty, but was %v", object), msgAndArgs...)
 775	}
 776
 777	return pass
 778
 779}
 780
 781// getLen tries to get the length of an object.
 782// It returns (0, false) if impossible.
 783func getLen(x interface{}) (length int, ok bool) {
 784	v := reflect.ValueOf(x)
 785	defer func() {
 786		ok = recover() == nil
 787	}()
 788	return v.Len(), true
 789}
 790
 791// Len asserts that the specified object has specific length.
 792// Len also fails if the object has a type that len() not accept.
 793//
 794//	assert.Len(t, mySlice, 3)
 795func Len(t TestingT, object interface{}, length int, msgAndArgs ...interface{}) bool {
 796	if h, ok := t.(tHelper); ok {
 797		h.Helper()
 798	}
 799	l, ok := getLen(object)
 800	if !ok {
 801		return Fail(t, fmt.Sprintf("\"%v\" could not be applied builtin len()", object), msgAndArgs...)
 802	}
 803
 804	if l != length {
 805		return Fail(t, fmt.Sprintf("\"%v\" should have %d item(s), but has %d", object, length, l), msgAndArgs...)
 806	}
 807	return true
 808}
 809
 810// True asserts that the specified value is true.
 811//
 812//	assert.True(t, myBool)
 813func True(t TestingT, value bool, msgAndArgs ...interface{}) bool {
 814	if !value {
 815		if h, ok := t.(tHelper); ok {
 816			h.Helper()
 817		}
 818		return Fail(t, "Should be true", msgAndArgs...)
 819	}
 820
 821	return true
 822
 823}
 824
 825// False asserts that the specified value is false.
 826//
 827//	assert.False(t, myBool)
 828func False(t TestingT, value bool, msgAndArgs ...interface{}) bool {
 829	if value {
 830		if h, ok := t.(tHelper); ok {
 831			h.Helper()
 832		}
 833		return Fail(t, "Should be false", msgAndArgs...)
 834	}
 835
 836	return true
 837
 838}
 839
 840// NotEqual asserts that the specified values are NOT equal.
 841//
 842//	assert.NotEqual(t, obj1, obj2)
 843//
 844// Pointer variable equality is determined based on the equality of the
 845// referenced values (as opposed to the memory addresses).
 846func NotEqual(t TestingT, expected, actual interface{}, msgAndArgs ...interface{}) bool {
 847	if h, ok := t.(tHelper); ok {
 848		h.Helper()
 849	}
 850	if err := validateEqualArgs(expected, actual); err != nil {
 851		return Fail(t, fmt.Sprintf("Invalid operation: %#v != %#v (%s)",
 852			expected, actual, err), msgAndArgs...)
 853	}
 854
 855	if ObjectsAreEqual(expected, actual) {
 856		return Fail(t, fmt.Sprintf("Should not be: %#v\n", actual), msgAndArgs...)
 857	}
 858
 859	return true
 860
 861}
 862
 863// NotEqualValues asserts that two objects are not equal even when converted to the same type
 864//
 865//	assert.NotEqualValues(t, obj1, obj2)
 866func NotEqualValues(t TestingT, expected, actual interface{}, msgAndArgs ...interface{}) bool {
 867	if h, ok := t.(tHelper); ok {
 868		h.Helper()
 869	}
 870
 871	if ObjectsAreEqualValues(expected, actual) {
 872		return Fail(t, fmt.Sprintf("Should not be: %#v\n", actual), msgAndArgs...)
 873	}
 874
 875	return true
 876}
 877
 878// containsElement try loop over the list check if the list includes the element.
 879// return (false, false) if impossible.
 880// return (true, false) if element was not found.
 881// return (true, true) if element was found.
 882func containsElement(list interface{}, element interface{}) (ok, found bool) {
 883
 884	listValue := reflect.ValueOf(list)
 885	listType := reflect.TypeOf(list)
 886	if listType == nil {
 887		return false, false
 888	}
 889	listKind := listType.Kind()
 890	defer func() {
 891		if e := recover(); e != nil {
 892			ok = false
 893			found = false
 894		}
 895	}()
 896
 897	if listKind == reflect.String {
 898		elementValue := reflect.ValueOf(element)
 899		return true, strings.Contains(listValue.String(), elementValue.String())
 900	}
 901
 902	if listKind == reflect.Map {
 903		mapKeys := listValue.MapKeys()
 904		for i := 0; i < len(mapKeys); i++ {
 905			if ObjectsAreEqual(mapKeys[i].Interface(), element) {
 906				return true, true
 907			}
 908		}
 909		return true, false
 910	}
 911
 912	for i := 0; i < listValue.Len(); i++ {
 913		if ObjectsAreEqual(listValue.Index(i).Interface(), element) {
 914			return true, true
 915		}
 916	}
 917	return true, false
 918
 919}
 920
 921// Contains asserts that the specified string, list(array, slice...) or map contains the
 922// specified substring or element.
 923//
 924//	assert.Contains(t, "Hello World", "World")
 925//	assert.Contains(t, ["Hello", "World"], "World")
 926//	assert.Contains(t, {"Hello": "World"}, "Hello")
 927func Contains(t TestingT, s, contains interface{}, msgAndArgs ...interface{}) bool {
 928	if h, ok := t.(tHelper); ok {
 929		h.Helper()
 930	}
 931
 932	ok, found := containsElement(s, contains)
 933	if !ok {
 934		return Fail(t, fmt.Sprintf("%#v could not be applied builtin len()", s), msgAndArgs...)
 935	}
 936	if !found {
 937		return Fail(t, fmt.Sprintf("%#v does not contain %#v", s, contains), msgAndArgs...)
 938	}
 939
 940	return true
 941
 942}
 943
 944// NotContains asserts that the specified string, list(array, slice...) or map does NOT contain the
 945// specified substring or element.
 946//
 947//	assert.NotContains(t, "Hello World", "Earth")
 948//	assert.NotContains(t, ["Hello", "World"], "Earth")
 949//	assert.NotContains(t, {"Hello": "World"}, "Earth")
 950func NotContains(t TestingT, s, contains interface{}, msgAndArgs ...interface{}) bool {
 951	if h, ok := t.(tHelper); ok {
 952		h.Helper()
 953	}
 954
 955	ok, found := containsElement(s, contains)
 956	if !ok {
 957		return Fail(t, fmt.Sprintf("%#v could not be applied builtin len()", s), msgAndArgs...)
 958	}
 959	if found {
 960		return Fail(t, fmt.Sprintf("%#v should not contain %#v", s, contains), msgAndArgs...)
 961	}
 962
 963	return true
 964
 965}
 966
 967// Subset asserts that the specified list(array, slice...) or map contains all
 968// elements given in the specified subset list(array, slice...) or map.
 969//
 970//	assert.Subset(t, [1, 2, 3], [1, 2])
 971//	assert.Subset(t, {"x": 1, "y": 2}, {"x": 1})
 972func Subset(t TestingT, list, subset interface{}, msgAndArgs ...interface{}) (ok bool) {
 973	if h, ok := t.(tHelper); ok {
 974		h.Helper()
 975	}
 976	if subset == nil {
 977		return true // we consider nil to be equal to the nil set
 978	}
 979
 980	listKind := reflect.TypeOf(list).Kind()
 981	if listKind != reflect.Array && listKind != reflect.Slice && listKind != reflect.Map {
 982		return Fail(t, fmt.Sprintf("%q has an unsupported type %s", list, listKind), msgAndArgs...)
 983	}
 984
 985	subsetKind := reflect.TypeOf(subset).Kind()
 986	if subsetKind != reflect.Array && subsetKind != reflect.Slice && listKind != reflect.Map {
 987		return Fail(t, fmt.Sprintf("%q has an unsupported type %s", subset, subsetKind), msgAndArgs...)
 988	}
 989
 990	if subsetKind == reflect.Map && listKind == reflect.Map {
 991		subsetMap := reflect.ValueOf(subset)
 992		actualMap := reflect.ValueOf(list)
 993
 994		for _, k := range subsetMap.MapKeys() {
 995			ev := subsetMap.MapIndex(k)
 996			av := actualMap.MapIndex(k)
 997
 998			if !av.IsValid() {
 999				return Fail(t, fmt.Sprintf("%#v does not contain %#v", list, subset), msgAndArgs...)
1000			}
1001			if !ObjectsAreEqual(ev.Interface(), av.Interface()) {
1002				return Fail(t, fmt.Sprintf("%#v does not contain %#v", list, subset), msgAndArgs...)
1003			}
1004		}
1005
1006		return true
1007	}
1008
1009	subsetList := reflect.ValueOf(subset)
1010	for i := 0; i < subsetList.Len(); i++ {
1011		element := subsetList.Index(i).Interface()
1012		ok, found := containsElement(list, element)
1013		if !ok {
1014			return Fail(t, fmt.Sprintf("%#v could not be applied builtin len()", list), msgAndArgs...)
1015		}
1016		if !found {
1017			return Fail(t, fmt.Sprintf("%#v does not contain %#v", list, element), msgAndArgs...)
1018		}
1019	}
1020
1021	return true
1022}
1023
1024// NotSubset asserts that the specified list(array, slice...) or map does NOT
1025// contain all elements given in the specified subset list(array, slice...) or
1026// map.
1027//
1028//	assert.NotSubset(t, [1, 3, 4], [1, 2])
1029//	assert.NotSubset(t, {"x": 1, "y": 2}, {"z": 3})
1030func NotSubset(t TestingT, list, subset interface{}, msgAndArgs ...interface{}) (ok bool) {
1031	if h, ok := t.(tHelper); ok {
1032		h.Helper()
1033	}
1034	if subset == nil {
1035		return Fail(t, "nil is the empty set which is a subset of every set", msgAndArgs...)
1036	}
1037
1038	listKind := reflect.TypeOf(list).Kind()
1039	if listKind != reflect.Array && listKind != reflect.Slice && listKind != reflect.Map {
1040		return Fail(t, fmt.Sprintf("%q has an unsupported type %s", list, listKind), msgAndArgs...)
1041	}
1042
1043	subsetKind := reflect.TypeOf(subset).Kind()
1044	if subsetKind != reflect.Array && subsetKind != reflect.Slice && listKind != reflect.Map {
1045		return Fail(t, fmt.Sprintf("%q has an unsupported type %s", subset, subsetKind), msgAndArgs...)
1046	}
1047
1048	if subsetKind == reflect.Map && listKind == reflect.Map {
1049		subsetMap := reflect.ValueOf(subset)
1050		actualMap := reflect.ValueOf(list)
1051
1052		for _, k := range subsetMap.MapKeys() {
1053			ev := subsetMap.MapIndex(k)
1054			av := actualMap.MapIndex(k)
1055
1056			if !av.IsValid() {
1057				return true
1058			}
1059			if !ObjectsAreEqual(ev.Interface(), av.Interface()) {
1060				return true
1061			}
1062		}
1063
1064		return Fail(t, fmt.Sprintf("%q is a subset of %q", subset, list), msgAndArgs...)
1065	}
1066
1067	subsetList := reflect.ValueOf(subset)
1068	for i := 0; i < subsetList.Len(); i++ {
1069		element := subsetList.Index(i).Interface()
1070		ok, found := containsElement(list, element)
1071		if !ok {
1072			return Fail(t, fmt.Sprintf("\"%s\" could not be applied builtin len()", list), msgAndArgs...)
1073		}
1074		if !found {
1075			return true
1076		}
1077	}
1078
1079	return Fail(t, fmt.Sprintf("%q is a subset of %q", subset, list), msgAndArgs...)
1080}
1081
1082// ElementsMatch asserts that the specified listA(array, slice...) is equal to specified
1083// listB(array, slice...) ignoring the order of the elements. If there are duplicate elements,
1084// the number of appearances of each of them in both lists should match.
1085//
1086// assert.ElementsMatch(t, [1, 3, 2, 3], [1, 3, 3, 2])
1087func ElementsMatch(t TestingT, listA, listB interface{}, msgAndArgs ...interface{}) (ok bool) {
1088	if h, ok := t.(tHelper); ok {
1089		h.Helper()
1090	}
1091	if isEmpty(listA) && isEmpty(listB) {
1092		return true
1093	}
1094
1095	if !isList(t, listA, msgAndArgs...) || !isList(t, listB, msgAndArgs...) {
1096		return false
1097	}
1098
1099	extraA, extraB := diffLists(listA, listB)
1100
1101	if len(extraA) == 0 && len(extraB) == 0 {
1102		return true
1103	}
1104
1105	return Fail(t, formatListDiff(listA, listB, extraA, extraB), msgAndArgs...)
1106}
1107
1108// isList checks that the provided value is array or slice.
1109func isList(t TestingT, list interface{}, msgAndArgs ...interface{}) (ok bool) {
1110	kind := reflect.TypeOf(list).Kind()
1111	if kind != reflect.Array && kind != reflect.Slice {
1112		return Fail(t, fmt.Sprintf("%q has an unsupported type %s, expecting array or slice", list, kind),
1113			msgAndArgs...)
1114	}
1115	return true
1116}
1117
1118// diffLists diffs two arrays/slices and returns slices of elements that are only in A and only in B.
1119// If some element is present multiple times, each instance is counted separately (e.g. if something is 2x in A and
1120// 5x in B, it will be 0x in extraA and 3x in extraB). The order of items in both lists is ignored.
1121func diffLists(listA, listB interface{}) (extraA, extraB []interface{}) {
1122	aValue := reflect.ValueOf(listA)
1123	bValue := reflect.ValueOf(listB)
1124
1125	aLen := aValue.Len()
1126	bLen := bValue.Len()
1127
1128	// Mark indexes in bValue that we already used
1129	visited := make([]bool, bLen)
1130	for i := 0; i < aLen; i++ {
1131		element := aValue.Index(i).Interface()
1132		found := false
1133		for j := 0; j < bLen; j++ {
1134			if visited[j] {
1135				continue
1136			}
1137			if ObjectsAreEqual(bValue.Index(j).Interface(), element) {
1138				visited[j] = true
1139				found = true
1140				break
1141			}
1142		}
1143		if !found {
1144			extraA = append(extraA, element)
1145		}
1146	}
1147
1148	for j := 0; j < bLen; j++ {
1149		if visited[j] {
1150			continue
1151		}
1152		extraB = append(extraB, bValue.Index(j).Interface())
1153	}
1154
1155	return
1156}
1157
1158func formatListDiff(listA, listB interface{}, extraA, extraB []interface{}) string {
1159	var msg bytes.Buffer
1160
1161	msg.WriteString("elements differ")
1162	if len(extraA) > 0 {
1163		msg.WriteString("\n\nextra elements in list A:\n")
1164		msg.WriteString(spewConfig.Sdump(extraA))
1165	}
1166	if len(extraB) > 0 {
1167		msg.WriteString("\n\nextra elements in list B:\n")
1168		msg.WriteString(spewConfig.Sdump(extraB))
1169	}
1170	msg.WriteString("\n\nlistA:\n")
1171	msg.WriteString(spewConfig.Sdump(listA))
1172	msg.WriteString("\n\nlistB:\n")
1173	msg.WriteString(spewConfig.Sdump(listB))
1174
1175	return msg.String()
1176}
1177
1178// NotElementsMatch asserts that the specified listA(array, slice...) is NOT equal to specified
1179// listB(array, slice...) ignoring the order of the elements. If there are duplicate elements,
1180// the number of appearances of each of them in both lists should not match.
1181// This is an inverse of ElementsMatch.
1182//
1183// assert.NotElementsMatch(t, [1, 1, 2, 3], [1, 1, 2, 3]) -> false
1184//
1185// assert.NotElementsMatch(t, [1, 1, 2, 3], [1, 2, 3]) -> true
1186//
1187// assert.NotElementsMatch(t, [1, 2, 3], [1, 2, 4]) -> true
1188func NotElementsMatch(t TestingT, listA, listB interface{}, msgAndArgs ...interface{}) (ok bool) {
1189	if h, ok := t.(tHelper); ok {
1190		h.Helper()
1191	}
1192	if isEmpty(listA) && isEmpty(listB) {
1193		return Fail(t, "listA and listB contain the same elements", msgAndArgs)
1194	}
1195
1196	if !isList(t, listA, msgAndArgs...) {
1197		return Fail(t, "listA is not a list type", msgAndArgs...)
1198	}
1199	if !isList(t, listB, msgAndArgs...) {
1200		return Fail(t, "listB is not a list type", msgAndArgs...)
1201	}
1202
1203	extraA, extraB := diffLists(listA, listB)
1204	if len(extraA) == 0 && len(extraB) == 0 {
1205		return Fail(t, "listA and listB contain the same elements", msgAndArgs)
1206	}
1207
1208	return true
1209}
1210
1211// Condition uses a Comparison to assert a complex condition.
1212func Condition(t TestingT, comp Comparison, msgAndArgs ...interface{}) bool {
1213	if h, ok := t.(tHelper); ok {
1214		h.Helper()
1215	}
1216	result := comp()
1217	if !result {
1218		Fail(t, "Condition failed!", msgAndArgs...)
1219	}
1220	return result
1221}
1222
1223// PanicTestFunc defines a func that should be passed to the assert.Panics and assert.NotPanics
1224// methods, and represents a simple func that takes no arguments, and returns nothing.
1225type PanicTestFunc func()
1226
1227// didPanic returns true if the function passed to it panics. Otherwise, it returns false.
1228func didPanic(f PanicTestFunc) (didPanic bool, message interface{}, stack string) {
1229	didPanic = true
1230
1231	defer func() {
1232		message = recover()
1233		if didPanic {
1234			stack = string(debug.Stack())
1235		}
1236	}()
1237
1238	// call the target function
1239	f()
1240	didPanic = false
1241
1242	return
1243}
1244
1245// Panics asserts that the code inside the specified PanicTestFunc panics.
1246//
1247//	assert.Panics(t, func(){ GoCrazy() })
1248func Panics(t TestingT, f PanicTestFunc, msgAndArgs ...interface{}) bool {
1249	if h, ok := t.(tHelper); ok {
1250		h.Helper()
1251	}
1252
1253	if funcDidPanic, panicValue, _ := didPanic(f); !funcDidPanic {
1254		return Fail(t, fmt.Sprintf("func %#v should panic\n\tPanic value:\t%#v", f, panicValue), msgAndArgs...)
1255	}
1256
1257	return true
1258}
1259
1260// PanicsWithValue asserts that the code inside the specified PanicTestFunc panics, and that
1261// the recovered panic value equals the expected panic value.
1262//
1263//	assert.PanicsWithValue(t, "crazy error", func(){ GoCrazy() })
1264func PanicsWithValue(t TestingT, expected interface{}, f PanicTestFunc, msgAndArgs ...interface{}) bool {
1265	if h, ok := t.(tHelper); ok {
1266		h.Helper()
1267	}
1268
1269	funcDidPanic, panicValue, panickedStack := didPanic(f)
1270	if !funcDidPanic {
1271		return Fail(t, fmt.Sprintf("func %#v should panic\n\tPanic value:\t%#v", f, panicValue), msgAndArgs...)
1272	}
1273	if panicValue != expected {
1274		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...)
1275	}
1276
1277	return true
1278}
1279
1280// PanicsWithError asserts that the code inside the specified PanicTestFunc
1281// panics, and that the recovered panic value is an error that satisfies the
1282// EqualError comparison.
1283//
1284//	assert.PanicsWithError(t, "crazy error", func(){ GoCrazy() })
1285func PanicsWithError(t TestingT, errString string, f PanicTestFunc, msgAndArgs ...interface{}) bool {
1286	if h, ok := t.(tHelper); ok {
1287		h.Helper()
1288	}
1289
1290	funcDidPanic, panicValue, panickedStack := didPanic(f)
1291	if !funcDidPanic {
1292		return Fail(t, fmt.Sprintf("func %#v should panic\n\tPanic value:\t%#v", f, panicValue), msgAndArgs...)
1293	}
1294	panicErr, ok := panicValue.(error)
1295	if !ok || panicErr.Error() != errString {
1296		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...)
1297	}
1298
1299	return true
1300}
1301
1302// NotPanics asserts that the code inside the specified PanicTestFunc does NOT panic.
1303//
1304//	assert.NotPanics(t, func(){ RemainCalm() })
1305func NotPanics(t TestingT, f PanicTestFunc, msgAndArgs ...interface{}) bool {
1306	if h, ok := t.(tHelper); ok {
1307		h.Helper()
1308	}
1309
1310	if funcDidPanic, panicValue, panickedStack := didPanic(f); funcDidPanic {
1311		return Fail(t, fmt.Sprintf("func %#v should not panic\n\tPanic value:\t%v\n\tPanic stack:\t%s", f, panicValue, panickedStack), msgAndArgs...)
1312	}
1313
1314	return true
1315}
1316
1317// WithinDuration asserts that the two times are within duration delta of each other.
1318//
1319//	assert.WithinDuration(t, time.Now(), time.Now(), 10*time.Second)
1320func WithinDuration(t TestingT, expected, actual time.Time, delta time.Duration, msgAndArgs ...interface{}) bool {
1321	if h, ok := t.(tHelper); ok {
1322		h.Helper()
1323	}
1324
1325	dt := expected.Sub(actual)
1326	if dt < -delta || dt > delta {
1327		return Fail(t, fmt.Sprintf("Max difference between %v and %v allowed is %v, but difference was %v", expected, actual, delta, dt), msgAndArgs...)
1328	}
1329
1330	return true
1331}
1332
1333// WithinRange asserts that a time is within a time range (inclusive).
1334//
1335//	assert.WithinRange(t, time.Now(), time.Now().Add(-time.Second), time.Now().Add(time.Second))
1336func WithinRange(t TestingT, actual, start, end time.Time, msgAndArgs ...interface{}) bool {
1337	if h, ok := t.(tHelper); ok {
1338		h.Helper()
1339	}
1340
1341	if end.Before(start) {
1342		return Fail(t, "Start should be before end", msgAndArgs...)
1343	}
1344
1345	if actual.Before(start) {
1346		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...)
1347	} else if actual.After(end) {
1348		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...)
1349	}
1350
1351	return true
1352}
1353
1354func toFloat(x interface{}) (float64, bool) {
1355	var xf float64
1356	xok := true
1357
1358	switch xn := x.(type) {
1359	case uint:
1360		xf = float64(xn)
1361	case uint8:
1362		xf = float64(xn)
1363	case uint16:
1364		xf = float64(xn)
1365	case uint32:
1366		xf = float64(xn)
1367	case uint64:
1368		xf = float64(xn)
1369	case int:
1370		xf = float64(xn)
1371	case int8:
1372		xf = float64(xn)
1373	case int16:
1374		xf = float64(xn)
1375	case int32:
1376		xf = float64(xn)
1377	case int64:
1378		xf = float64(xn)
1379	case float32:
1380		xf = float64(xn)
1381	case float64:
1382		xf = xn
1383	case time.Duration:
1384		xf = float64(xn)
1385	default:
1386		xok = false
1387	}
1388
1389	return xf, xok
1390}
1391
1392// InDelta asserts that the two numerals are within delta of each other.
1393//
1394//	assert.InDelta(t, math.Pi, 22/7.0, 0.01)
1395func InDelta(t TestingT, expected, actual interface{}, delta float64, msgAndArgs ...interface{}) bool {
1396	if h, ok := t.(tHelper); ok {
1397		h.Helper()
1398	}
1399
1400	af, aok := toFloat(expected)
1401	bf, bok := toFloat(actual)
1402
1403	if !aok || !bok {
1404		return Fail(t, "Parameters must be numerical", msgAndArgs...)
1405	}
1406
1407	if math.IsNaN(af) && math.IsNaN(bf) {
1408		return true
1409	}
1410
1411	if math.IsNaN(af) {
1412		return Fail(t, "Expected must not be NaN", msgAndArgs...)
1413	}
1414
1415	if math.IsNaN(bf) {
1416		return Fail(t, fmt.Sprintf("Expected %v with delta %v, but was NaN", expected, delta), msgAndArgs...)
1417	}
1418
1419	dt := af - bf
1420	if dt < -delta || dt > delta {
1421		return Fail(t, fmt.Sprintf("Max difference between %v and %v allowed is %v, but difference was %v", expected, actual, delta, dt), msgAndArgs...)
1422	}
1423
1424	return true
1425}
1426
1427// InDeltaSlice is the same as InDelta, except it compares two slices.
1428func InDeltaSlice(t TestingT, expected, actual interface{}, delta float64, msgAndArgs ...interface{}) bool {
1429	if h, ok := t.(tHelper); ok {
1430		h.Helper()
1431	}
1432	if expected == nil || actual == nil ||
1433		reflect.TypeOf(actual).Kind() != reflect.Slice ||
1434		reflect.TypeOf(expected).Kind() != reflect.Slice {
1435		return Fail(t, "Parameters must be slice", msgAndArgs...)
1436	}
1437
1438	actualSlice := reflect.ValueOf(actual)
1439	expectedSlice := reflect.ValueOf(expected)
1440
1441	for i := 0; i < actualSlice.Len(); i++ {
1442		result := InDelta(t, actualSlice.Index(i).Interface(), expectedSlice.Index(i).Interface(), delta, msgAndArgs...)
1443		if !result {
1444			return result
1445		}
1446	}
1447
1448	return true
1449}
1450
1451// InDeltaMapValues is the same as InDelta, but it compares all values between two maps. Both maps must have exactly the same keys.
1452func InDeltaMapValues(t TestingT, expected, actual interface{}, delta float64, msgAndArgs ...interface{}) bool {
1453	if h, ok := t.(tHelper); ok {
1454		h.Helper()
1455	}
1456	if expected == nil || actual == nil ||
1457		reflect.TypeOf(actual).Kind() != reflect.Map ||
1458		reflect.TypeOf(expected).Kind() != reflect.Map {
1459		return Fail(t, "Arguments must be maps", msgAndArgs...)
1460	}
1461
1462	expectedMap := reflect.ValueOf(expected)
1463	actualMap := reflect.ValueOf(actual)
1464
1465	if expectedMap.Len() != actualMap.Len() {
1466		return Fail(t, "Arguments must have the same number of keys", msgAndArgs...)
1467	}
1468
1469	for _, k := range expectedMap.MapKeys() {
1470		ev := expectedMap.MapIndex(k)
1471		av := actualMap.MapIndex(k)
1472
1473		if !ev.IsValid() {
1474			return Fail(t, fmt.Sprintf("missing key %q in expected map", k), msgAndArgs...)
1475		}
1476
1477		if !av.IsValid() {
1478			return Fail(t, fmt.Sprintf("missing key %q in actual map", k), msgAndArgs...)
1479		}
1480
1481		if !InDelta(
1482			t,
1483			ev.Interface(),
1484			av.Interface(),
1485			delta,
1486			msgAndArgs...,
1487		) {
1488			return false
1489		}
1490	}
1491
1492	return true
1493}
1494
1495func calcRelativeError(expected, actual interface{}) (float64, error) {
1496	af, aok := toFloat(expected)
1497	bf, bok := toFloat(actual)
1498	if !aok || !bok {
1499		return 0, fmt.Errorf("Parameters must be numerical")
1500	}
1501	if math.IsNaN(af) && math.IsNaN(bf) {
1502		return 0, nil
1503	}
1504	if math.IsNaN(af) {
1505		return 0, errors.New("expected value must not be NaN")
1506	}
1507	if af == 0 {
1508		return 0, fmt.Errorf("expected value must have a value other than zero to calculate the relative error")
1509	}
1510	if math.IsNaN(bf) {
1511		return 0, errors.New("actual value must not be NaN")
1512	}
1513
1514	return math.Abs(af-bf) / math.Abs(af), nil
1515}
1516
1517// InEpsilon asserts that expected and actual have a relative error less than epsilon
1518func InEpsilon(t TestingT, expected, actual interface{}, epsilon float64, msgAndArgs ...interface{}) bool {
1519	if h, ok := t.(tHelper); ok {
1520		h.Helper()
1521	}
1522	if math.IsNaN(epsilon) {
1523		return Fail(t, "epsilon must not be NaN", msgAndArgs...)
1524	}
1525	actualEpsilon, err := calcRelativeError(expected, actual)
1526	if err != nil {
1527		return Fail(t, err.Error(), msgAndArgs...)
1528	}
1529	if math.IsNaN(actualEpsilon) {
1530		return Fail(t, "relative error is NaN", msgAndArgs...)
1531	}
1532	if actualEpsilon > epsilon {
1533		return Fail(t, fmt.Sprintf("Relative error is too high: %#v (expected)\n"+
1534			"        < %#v (actual)", epsilon, actualEpsilon), msgAndArgs...)
1535	}
1536
1537	return true
1538}
1539
1540// InEpsilonSlice is the same as InEpsilon, except it compares each value from two slices.
1541func InEpsilonSlice(t TestingT, expected, actual interface{}, epsilon float64, msgAndArgs ...interface{}) bool {
1542	if h, ok := t.(tHelper); ok {
1543		h.Helper()
1544	}
1545
1546	if expected == nil || actual == nil {
1547		return Fail(t, "Parameters must be slice", msgAndArgs...)
1548	}
1549
1550	expectedSlice := reflect.ValueOf(expected)
1551	actualSlice := reflect.ValueOf(actual)
1552
1553	if expectedSlice.Type().Kind() != reflect.Slice {
1554		return Fail(t, "Expected value must be slice", msgAndArgs...)
1555	}
1556
1557	expectedLen := expectedSlice.Len()
1558	if !IsType(t, expected, actual) || !Len(t, actual, expectedLen) {
1559		return false
1560	}
1561
1562	for i := 0; i < expectedLen; i++ {
1563		if !InEpsilon(t, expectedSlice.Index(i).Interface(), actualSlice.Index(i).Interface(), epsilon, "at index %d", i) {
1564			return false
1565		}
1566	}
1567
1568	return true
1569}
1570
1571/*
1572	Errors
1573*/
1574
1575// NoError asserts that a function returned no error (i.e. `nil`).
1576//
1577//	  actualObj, err := SomeFunction()
1578//	  if assert.NoError(t, err) {
1579//		   assert.Equal(t, expectedObj, actualObj)
1580//	  }
1581func NoError(t TestingT, err error, msgAndArgs ...interface{}) bool {
1582	if err != nil {
1583		if h, ok := t.(tHelper); ok {
1584			h.Helper()
1585		}
1586		return Fail(t, fmt.Sprintf("Received unexpected error:\n%+v", err), msgAndArgs...)
1587	}
1588
1589	return true
1590}
1591
1592// Error asserts that a function returned an error (i.e. not `nil`).
1593//
1594//	  actualObj, err := SomeFunction()
1595//	  if assert.Error(t, err) {
1596//		   assert.Equal(t, expectedError, err)
1597//	  }
1598func Error(t TestingT, err error, msgAndArgs ...interface{}) bool {
1599	if err == nil {
1600		if h, ok := t.(tHelper); ok {
1601			h.Helper()
1602		}
1603		return Fail(t, "An error is expected but got nil.", msgAndArgs...)
1604	}
1605
1606	return true
1607}
1608
1609// EqualError asserts that a function returned an error (i.e. not `nil`)
1610// and that it is equal to the provided error.
1611//
1612//	actualObj, err := SomeFunction()
1613//	assert.EqualError(t, err,  expectedErrorString)
1614func EqualError(t TestingT, theError error, errString string, msgAndArgs ...interface{}) bool {
1615	if h, ok := t.(tHelper); ok {
1616		h.Helper()
1617	}
1618	if !Error(t, theError, msgAndArgs...) {
1619		return false
1620	}
1621	expected := errString
1622	actual := theError.Error()
1623	// don't need to use deep equals here, we know they are both strings
1624	if expected != actual {
1625		return Fail(t, fmt.Sprintf("Error message not equal:\n"+
1626			"expected: %q\n"+
1627			"actual  : %q", expected, actual), msgAndArgs...)
1628	}
1629	return true
1630}
1631
1632// ErrorContains asserts that a function returned an error (i.e. not `nil`)
1633// and that the error contains the specified substring.
1634//
1635//	actualObj, err := SomeFunction()
1636//	assert.ErrorContains(t, err,  expectedErrorSubString)
1637func ErrorContains(t TestingT, theError error, contains string, msgAndArgs ...interface{}) bool {
1638	if h, ok := t.(tHelper); ok {
1639		h.Helper()
1640	}
1641	if !Error(t, theError, msgAndArgs...) {
1642		return false
1643	}
1644
1645	actual := theError.Error()
1646	if !strings.Contains(actual, contains) {
1647		return Fail(t, fmt.Sprintf("Error %#v does not contain %#v", actual, contains), msgAndArgs...)
1648	}
1649
1650	return true
1651}
1652
1653// matchRegexp return true if a specified regexp matches a string.
1654func matchRegexp(rx interface{}, str interface{}) bool {
1655	var r *regexp.Regexp
1656	if rr, ok := rx.(*regexp.Regexp); ok {
1657		r = rr
1658	} else {
1659		r = regexp.MustCompile(fmt.Sprint(rx))
1660	}
1661
1662	switch v := str.(type) {
1663	case []byte:
1664		return r.Match(v)
1665	case string:
1666		return r.MatchString(v)
1667	default:
1668		return r.MatchString(fmt.Sprint(v))
1669	}
1670
1671}
1672
1673// Regexp asserts that a specified regexp matches a string.
1674//
1675//	assert.Regexp(t, regexp.MustCompile("start"), "it's starting")
1676//	assert.Regexp(t, "start...$", "it's not starting")
1677func Regexp(t TestingT, rx interface{}, str interface{}, msgAndArgs ...interface{}) bool {
1678	if h, ok := t.(tHelper); ok {
1679		h.Helper()
1680	}
1681
1682	match := matchRegexp(rx, str)
1683
1684	if !match {
1685		Fail(t, fmt.Sprintf("Expect \"%v\" to match \"%v\"", str, rx), msgAndArgs...)
1686	}
1687
1688	return match
1689}
1690
1691// NotRegexp asserts that a specified regexp does not match a string.
1692//
1693//	assert.NotRegexp(t, regexp.MustCompile("starts"), "it's starting")
1694//	assert.NotRegexp(t, "^start", "it's not starting")
1695func NotRegexp(t TestingT, rx interface{}, str interface{}, msgAndArgs ...interface{}) bool {
1696	if h, ok := t.(tHelper); ok {
1697		h.Helper()
1698	}
1699	match := matchRegexp(rx, str)
1700
1701	if match {
1702		Fail(t, fmt.Sprintf("Expect \"%v\" to NOT match \"%v\"", str, rx), msgAndArgs...)
1703	}
1704
1705	return !match
1706
1707}
1708
1709// Zero asserts that i is the zero value for its type.
1710func Zero(t TestingT, i interface{}, msgAndArgs ...interface{}) bool {
1711	if h, ok := t.(tHelper); ok {
1712		h.Helper()
1713	}
1714	if i != nil && !reflect.DeepEqual(i, reflect.Zero(reflect.TypeOf(i)).Interface()) {
1715		return Fail(t, fmt.Sprintf("Should be zero, but was %v", i), msgAndArgs...)
1716	}
1717	return true
1718}
1719
1720// NotZero asserts that i is not the zero value for its type.
1721func NotZero(t TestingT, i interface{}, msgAndArgs ...interface{}) bool {
1722	if h, ok := t.(tHelper); ok {
1723		h.Helper()
1724	}
1725	if i == nil || reflect.DeepEqual(i, reflect.Zero(reflect.TypeOf(i)).Interface()) {
1726		return Fail(t, fmt.Sprintf("Should not be zero, but was %v", i), msgAndArgs...)
1727	}
1728	return true
1729}
1730
1731// FileExists checks whether a file exists in the given path. It also fails if
1732// the path points to a directory or there is an error when trying to check the file.
1733func FileExists(t TestingT, path string, msgAndArgs ...interface{}) bool {
1734	if h, ok := t.(tHelper); ok {
1735		h.Helper()
1736	}
1737	info, err := os.Lstat(path)
1738	if err != nil {
1739		if os.IsNotExist(err) {
1740			return Fail(t, fmt.Sprintf("unable to find file %q", path), msgAndArgs...)
1741		}
1742		return Fail(t, fmt.Sprintf("error when running os.Lstat(%q): %s", path, err), msgAndArgs...)
1743	}
1744	if info.IsDir() {
1745		return Fail(t, fmt.Sprintf("%q is a directory", path), msgAndArgs...)
1746	}
1747	return true
1748}
1749
1750// NoFileExists checks whether a file does not exist in a given path. It fails
1751// if the path points to an existing _file_ only.
1752func NoFileExists(t TestingT, path string, msgAndArgs ...interface{}) bool {
1753	if h, ok := t.(tHelper); ok {
1754		h.Helper()
1755	}
1756	info, err := os.Lstat(path)
1757	if err != nil {
1758		return true
1759	}
1760	if info.IsDir() {
1761		return true
1762	}
1763	return Fail(t, fmt.Sprintf("file %q exists", path), msgAndArgs...)
1764}
1765
1766// DirExists checks whether a directory exists in the given path. It also fails
1767// if the path is a file rather a directory or there is an error checking whether it exists.
1768func DirExists(t TestingT, path string, msgAndArgs ...interface{}) bool {
1769	if h, ok := t.(tHelper); ok {
1770		h.Helper()
1771	}
1772	info, err := os.Lstat(path)
1773	if err != nil {
1774		if os.IsNotExist(err) {
1775			return Fail(t, fmt.Sprintf("unable to find file %q", path), msgAndArgs...)
1776		}
1777		return Fail(t, fmt.Sprintf("error when running os.Lstat(%q): %s", path, err), msgAndArgs...)
1778	}
1779	if !info.IsDir() {
1780		return Fail(t, fmt.Sprintf("%q is a file", path), msgAndArgs...)
1781	}
1782	return true
1783}
1784
1785// NoDirExists checks whether a directory does not exist in the given path.
1786// It fails if the path points to an existing _directory_ only.
1787func NoDirExists(t TestingT, path string, msgAndArgs ...interface{}) bool {
1788	if h, ok := t.(tHelper); ok {
1789		h.Helper()
1790	}
1791	info, err := os.Lstat(path)
1792	if err != nil {
1793		if os.IsNotExist(err) {
1794			return true
1795		}
1796		return true
1797	}
1798	if !info.IsDir() {
1799		return true
1800	}
1801	return Fail(t, fmt.Sprintf("directory %q exists", path), msgAndArgs...)
1802}
1803
1804// JSONEq asserts that two JSON strings are equivalent.
1805//
1806//	assert.JSONEq(t, `{"hello": "world", "foo": "bar"}`, `{"foo": "bar", "hello": "world"}`)
1807func JSONEq(t TestingT, expected string, actual string, msgAndArgs ...interface{}) bool {
1808	if h, ok := t.(tHelper); ok {
1809		h.Helper()
1810	}
1811	var expectedJSONAsInterface, actualJSONAsInterface interface{}
1812
1813	if err := json.Unmarshal([]byte(expected), &expectedJSONAsInterface); err != nil {
1814		return Fail(t, fmt.Sprintf("Expected value ('%s') is not valid json.\nJSON parsing error: '%s'", expected, err.Error()), msgAndArgs...)
1815	}
1816
1817	if err := json.Unmarshal([]byte(actual), &actualJSONAsInterface); err != nil {
1818		return Fail(t, fmt.Sprintf("Input ('%s') needs to be valid json.\nJSON parsing error: '%s'", actual, err.Error()), msgAndArgs...)
1819	}
1820
1821	return Equal(t, expectedJSONAsInterface, actualJSONAsInterface, msgAndArgs...)
1822}
1823
1824// YAMLEq asserts that two YAML strings are equivalent.
1825func YAMLEq(t TestingT, expected string, actual string, msgAndArgs ...interface{}) bool {
1826	if h, ok := t.(tHelper); ok {
1827		h.Helper()
1828	}
1829	var expectedYAMLAsInterface, actualYAMLAsInterface interface{}
1830
1831	if err := yaml.Unmarshal([]byte(expected), &expectedYAMLAsInterface); err != nil {
1832		return Fail(t, fmt.Sprintf("Expected value ('%s') is not valid yaml.\nYAML parsing error: '%s'", expected, err.Error()), msgAndArgs...)
1833	}
1834
1835	if err := yaml.Unmarshal([]byte(actual), &actualYAMLAsInterface); err != nil {
1836		return Fail(t, fmt.Sprintf("Input ('%s') needs to be valid yaml.\nYAML error: '%s'", actual, err.Error()), msgAndArgs...)
1837	}
1838
1839	return Equal(t, expectedYAMLAsInterface, actualYAMLAsInterface, msgAndArgs...)
1840}
1841
1842func typeAndKind(v interface{}) (reflect.Type, reflect.Kind) {
1843	t := reflect.TypeOf(v)
1844	k := t.Kind()
1845
1846	if k == reflect.Ptr {
1847		t = t.Elem()
1848		k = t.Kind()
1849	}
1850	return t, k
1851}
1852
1853// diff returns a diff of both values as long as both are of the same type and
1854// are a struct, map, slice, array or string. Otherwise it returns an empty string.
1855func diff(expected interface{}, actual interface{}) string {
1856	if expected == nil || actual == nil {
1857		return ""
1858	}
1859
1860	et, ek := typeAndKind(expected)
1861	at, _ := typeAndKind(actual)
1862
1863	if et != at {
1864		return ""
1865	}
1866
1867	if ek != reflect.Struct && ek != reflect.Map && ek != reflect.Slice && ek != reflect.Array && ek != reflect.String {
1868		return ""
1869	}
1870
1871	var e, a string
1872
1873	switch et {
1874	case reflect.TypeOf(""):
1875		e = reflect.ValueOf(expected).String()
1876		a = reflect.ValueOf(actual).String()
1877	case reflect.TypeOf(time.Time{}):
1878		e = spewConfigStringerEnabled.Sdump(expected)
1879		a = spewConfigStringerEnabled.Sdump(actual)
1880	default:
1881		e = spewConfig.Sdump(expected)
1882		a = spewConfig.Sdump(actual)
1883	}
1884
1885	diff, _ := difflib.GetUnifiedDiffString(difflib.UnifiedDiff{
1886		A:        difflib.SplitLines(e),
1887		B:        difflib.SplitLines(a),
1888		FromFile: "Expected",
1889		FromDate: "",
1890		ToFile:   "Actual",
1891		ToDate:   "",
1892		Context:  1,
1893	})
1894
1895	return "\n\nDiff:\n" + diff
1896}
1897
1898func isFunction(arg interface{}) bool {
1899	if arg == nil {
1900		return false
1901	}
1902	return reflect.TypeOf(arg).Kind() == reflect.Func
1903}
1904
1905var spewConfig = spew.ConfigState{
1906	Indent:                  " ",
1907	DisablePointerAddresses: true,
1908	DisableCapacities:       true,
1909	SortKeys:                true,
1910	DisableMethods:          true,
1911	MaxDepth:                10,
1912}
1913
1914var spewConfigStringerEnabled = spew.ConfigState{
1915	Indent:                  " ",
1916	DisablePointerAddresses: true,
1917	DisableCapacities:       true,
1918	SortKeys:                true,
1919	MaxDepth:                10,
1920}
1921
1922type tHelper = interface {
1923	Helper()
1924}
1925
1926// Eventually asserts that given condition will be met in waitFor time,
1927// periodically checking target function each tick.
1928//
1929//	assert.Eventually(t, func() bool { return true; }, time.Second, 10*time.Millisecond)
1930func Eventually(t TestingT, condition func() bool, waitFor time.Duration, tick time.Duration, msgAndArgs ...interface{}) bool {
1931	if h, ok := t.(tHelper); ok {
1932		h.Helper()
1933	}
1934
1935	ch := make(chan bool, 1)
1936
1937	timer := time.NewTimer(waitFor)
1938	defer timer.Stop()
1939
1940	ticker := time.NewTicker(tick)
1941	defer ticker.Stop()
1942
1943	for tick := ticker.C; ; {
1944		select {
1945		case <-timer.C:
1946			return Fail(t, "Condition never satisfied", msgAndArgs...)
1947		case <-tick:
1948			tick = nil
1949			go func() { ch <- condition() }()
1950		case v := <-ch:
1951			if v {
1952				return true
1953			}
1954			tick = ticker.C
1955		}
1956	}
1957}
1958
1959// CollectT implements the TestingT interface and collects all errors.
1960type CollectT struct {
1961	// A slice of errors. Non-nil slice denotes a failure.
1962	// If it's non-nil but len(c.errors) == 0, this is also a failure
1963	// obtained by direct c.FailNow() call.
1964	errors []error
1965}
1966
1967// Errorf collects the error.
1968func (c *CollectT) Errorf(format string, args ...interface{}) {
1969	c.errors = append(c.errors, fmt.Errorf(format, args...))
1970}
1971
1972// FailNow stops execution by calling runtime.Goexit.
1973func (c *CollectT) FailNow() {
1974	c.fail()
1975	runtime.Goexit()
1976}
1977
1978// Deprecated: That was a method for internal usage that should not have been published. Now just panics.
1979func (*CollectT) Reset() {
1980	panic("Reset() is deprecated")
1981}
1982
1983// Deprecated: That was a method for internal usage that should not have been published. Now just panics.
1984func (*CollectT) Copy(TestingT) {
1985	panic("Copy() is deprecated")
1986}
1987
1988func (c *CollectT) fail() {
1989	if !c.failed() {
1990		c.errors = []error{} // Make it non-nil to mark a failure.
1991	}
1992}
1993
1994func (c *CollectT) failed() bool {
1995	return c.errors != nil
1996}
1997
1998// EventuallyWithT asserts that given condition will be met in waitFor time,
1999// periodically checking target function each tick. In contrast to Eventually,
2000// it supplies a CollectT to the condition function, so that the condition
2001// function can use the CollectT to call other assertions.
2002// The condition is considered "met" if no errors are raised in a tick.
2003// The supplied CollectT collects all errors from one tick (if there are any).
2004// If the condition is not met before waitFor, the collected errors of
2005// the last tick are copied to t.
2006//
2007//	externalValue := false
2008//	go func() {
2009//		time.Sleep(8*time.Second)
2010//		externalValue = true
2011//	}()
2012//	assert.EventuallyWithT(t, func(c *assert.CollectT) {
2013//		// add assertions as needed; any assertion failure will fail the current tick
2014//		assert.True(c, externalValue, "expected 'externalValue' to be true")
2015//	}, 10*time.Second, 1*time.Second, "external state has not changed to 'true'; still false")
2016func EventuallyWithT(t TestingT, condition func(collect *CollectT), waitFor time.Duration, tick time.Duration, msgAndArgs ...interface{}) bool {
2017	if h, ok := t.(tHelper); ok {
2018		h.Helper()
2019	}
2020
2021	var lastFinishedTickErrs []error
2022	ch := make(chan *CollectT, 1)
2023
2024	timer := time.NewTimer(waitFor)
2025	defer timer.Stop()
2026
2027	ticker := time.NewTicker(tick)
2028	defer ticker.Stop()
2029
2030	for tick := ticker.C; ; {
2031		select {
2032		case <-timer.C:
2033			for _, err := range lastFinishedTickErrs {
2034				t.Errorf("%v", err)
2035			}
2036			return Fail(t, "Condition never satisfied", msgAndArgs...)
2037		case <-tick:
2038			tick = nil
2039			go func() {
2040				collect := new(CollectT)
2041				defer func() {
2042					ch <- collect
2043				}()
2044				condition(collect)
2045			}()
2046		case collect := <-ch:
2047			if !collect.failed() {
2048				return true
2049			}
2050			// Keep the errors from the last ended condition, so that they can be copied to t if timeout is reached.
2051			lastFinishedTickErrs = collect.errors
2052			tick = ticker.C
2053		}
2054	}
2055}
2056
2057// Never asserts that the given condition doesn't satisfy in waitFor time,
2058// periodically checking the target function each tick.
2059//
2060//	assert.Never(t, func() bool { return false; }, time.Second, 10*time.Millisecond)
2061func Never(t TestingT, condition func() bool, waitFor time.Duration, tick time.Duration, msgAndArgs ...interface{}) bool {
2062	if h, ok := t.(tHelper); ok {
2063		h.Helper()
2064	}
2065
2066	ch := make(chan bool, 1)
2067
2068	timer := time.NewTimer(waitFor)
2069	defer timer.Stop()
2070
2071	ticker := time.NewTicker(tick)
2072	defer ticker.Stop()
2073
2074	for tick := ticker.C; ; {
2075		select {
2076		case <-timer.C:
2077			return true
2078		case <-tick:
2079			tick = nil
2080			go func() { ch <- condition() }()
2081		case v := <-ch:
2082			if v {
2083				return Fail(t, "Condition satisfied", msgAndArgs...)
2084			}
2085			tick = ticker.C
2086		}
2087	}
2088}
2089
2090// ErrorIs asserts that at least one of the errors in err's chain matches target.
2091// This is a wrapper for errors.Is.
2092func ErrorIs(t TestingT, err, target error, msgAndArgs ...interface{}) bool {
2093	if h, ok := t.(tHelper); ok {
2094		h.Helper()
2095	}
2096	if errors.Is(err, target) {
2097		return true
2098	}
2099
2100	var expectedText string
2101	if target != nil {
2102		expectedText = target.Error()
2103	}
2104
2105	chain := buildErrorChainString(err)
2106
2107	return Fail(t, fmt.Sprintf("Target error should be in err chain:\n"+
2108		"expected: %q\n"+
2109		"in chain: %s", expectedText, chain,
2110	), msgAndArgs...)
2111}
2112
2113// NotErrorIs asserts that none of the errors in err's chain matches target.
2114// This is a wrapper for errors.Is.
2115func NotErrorIs(t TestingT, err, target error, msgAndArgs ...interface{}) bool {
2116	if h, ok := t.(tHelper); ok {
2117		h.Helper()
2118	}
2119	if !errors.Is(err, target) {
2120		return true
2121	}
2122
2123	var expectedText string
2124	if target != nil {
2125		expectedText = target.Error()
2126	}
2127
2128	chain := buildErrorChainString(err)
2129
2130	return Fail(t, fmt.Sprintf("Target error should not be in err chain:\n"+
2131		"found: %q\n"+
2132		"in chain: %s", expectedText, chain,
2133	), msgAndArgs...)
2134}
2135
2136// ErrorAs asserts that at least one of the errors in err's chain matches target, and if so, sets target to that error value.
2137// This is a wrapper for errors.As.
2138func ErrorAs(t TestingT, err error, target interface{}, msgAndArgs ...interface{}) bool {
2139	if h, ok := t.(tHelper); ok {
2140		h.Helper()
2141	}
2142	if errors.As(err, target) {
2143		return true
2144	}
2145
2146	chain := buildErrorChainString(err)
2147
2148	return Fail(t, fmt.Sprintf("Should be in error chain:\n"+
2149		"expected: %q\n"+
2150		"in chain: %s", target, chain,
2151	), msgAndArgs...)
2152}
2153
2154// NotErrorAs asserts that none of the errors in err's chain matches target,
2155// but if so, sets target to that error value.
2156func NotErrorAs(t TestingT, err error, target interface{}, msgAndArgs ...interface{}) bool {
2157	if h, ok := t.(tHelper); ok {
2158		h.Helper()
2159	}
2160	if !errors.As(err, target) {
2161		return true
2162	}
2163
2164	chain := buildErrorChainString(err)
2165
2166	return Fail(t, fmt.Sprintf("Target error should not be in err chain:\n"+
2167		"found: %q\n"+
2168		"in chain: %s", target, chain,
2169	), msgAndArgs...)
2170}
2171
2172func buildErrorChainString(err error) string {
2173	if err == nil {
2174		return ""
2175	}
2176
2177	e := errors.Unwrap(err)
2178	chain := fmt.Sprintf("%q", err.Error())
2179	for e != nil {
2180		chain += fmt.Sprintf("\n\t%q", e.Error())
2181		e = errors.Unwrap(e)
2182	}
2183	return chain
2184}