-
Notifications
You must be signed in to change notification settings - Fork 23
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
fix(deps): update module github.com/stretchr/testify to v1.10.0 #231
base: master
Are you sure you want to change the base?
Conversation
edb037c
to
dc00d40
Compare
dc00d40
to
530ca27
Compare
530ca27
to
e5d5dac
Compare
[puLL-Merge] - stretchr/[email protected] Diffdiff --git .github/workflows/main.yml .github/workflows/main.yml
index 9458c398e..1dd4e650f 100644
--- .github/workflows/main.yml
+++ .github/workflows/main.yml
@@ -29,6 +29,7 @@ jobs:
- "1.19"
- "1.20"
- "1.21"
+ - "1.22"
steps:
- uses: actions/checkout@v4
- name: Setup Go
diff --git .github/workflows/release.yml .github/workflows/release.yml
index 21ffe56a3..08adf73d1 100644
--- .github/workflows/release.yml
+++ .github/workflows/release.yml
@@ -16,6 +16,6 @@ jobs:
uses: actions/checkout@v4
- name: Create GitHub release from tag
- uses: softprops/action-gh-release@v1
+ uses: softprops/action-gh-release@v2
with:
generate_release_notes: true
diff --git .gitignore .gitignore
index 5aacdb7cc..6e1bb22a2 100644
--- .gitignore
+++ .gitignore
@@ -22,3 +22,9 @@ _testmain.go
*.exe
.DS_Store
+
+# Output of "go test -c"
+/assert/assert.test
+/require/require.test
+/suite/suite.test
+/mock/mock.test
diff --git README.md README.md
index edb260abc..b2dbd16ea 100644
--- README.md
+++ README.md
@@ -1,7 +1,9 @@
Testify - Thou Shalt Write Tests
================================
-ℹ️ We are working on testify v2 and would love to hear what you'd like to see in it, have your say here: https://cutt.ly/testify
+> [!NOTE]
+> Testify is being maintained at v1, no breaking changes will be accepted in this repo.
+> [See discussion about v2](https://github.com/stretchr/testify/discussions/1560).
[![Build Status](https://github.com/stretchr/testify/actions/workflows/main.yml/badge.svg?branch=master)](https://github.com/stretchr/testify/actions/workflows/main.yml) [![Go Report Card](https://goreportcard.com/badge/github.com/stretchr/testify)](https://goreportcard.com/report/github.com/stretchr/testify) [![PkgGoDev](https://pkg.go.dev/badge/github.com/stretchr/testify)](https://pkg.go.dev/github.com/stretchr/testify)
@@ -18,10 +20,9 @@ Get started:
* Install testify with [one line of code](#installation), or [update it with another](#staying-up-to-date)
* For an introduction to writing test code in Go, see https://go.dev/doc/code#Testing
* Check out the API Documentation https://pkg.go.dev/github.com/stretchr/testify
+ * Use [testifylint](https://github.com/Antonboom/testifylint) (via [golanci-lint](https://golangci-lint.run/)) to avoid common mistakes
* A little about [Test-Driven Development (TDD)](https://en.wikipedia.org/wiki/Test-driven_development)
-
-
[`assert`](https://pkg.go.dev/github.com/stretchr/testify/assert "API documentation") package
-------------------------------------------------------------------------------------------
@@ -224,6 +225,8 @@ You can use the [mockery tool](https://vektra.github.io/mockery/latest/) to auto
[`suite`](https://pkg.go.dev/github.com/stretchr/testify/suite "API documentation") package
-----------------------------------------------------------------------------------------
+> [!WARNING]
+> The suite package does not support parallel tests. See [#934](https://github.com/stretchr/testify/issues/934).
The `suite` package provides functionality that you might be used to from more common object-oriented languages. With it, you can build a testing suite as a struct, build setup/teardown methods and testing methods on your struct, and run them with 'go test' as per normal.
diff --git _codegen/main.go _codegen/main.go
index 11cdbfbc6..7158afc9f 100644
--- _codegen/main.go
+++ _codegen/main.go
@@ -107,7 +107,9 @@ func parseTemplates() (*template.Template, *template.Template, error) {
}
funcTemplate = string(f)
}
- tmpl, err := template.New("function").Parse(funcTemplate)
+ tmpl, err := template.New("function").Funcs(template.FuncMap{
+ "replace": strings.ReplaceAll,
+ }).Parse(funcTemplate)
if err != nil {
return nil, nil, err
}
diff --git assert/assertion_compare.go assert/assertion_compare.go
index 4d4b4aad6..7e19eba09 100644
--- assert/assertion_compare.go
+++ assert/assertion_compare.go
@@ -7,10 +7,13 @@ import (
"time"
)
-type CompareType int
+// Deprecated: CompareType has only ever been for internal use and has accidentally been published since v1.6.0. Do not use it.
+type CompareType = compareResult
+
+type compareResult int
const (
- compareLess CompareType = iota - 1
+ compareLess compareResult = iota - 1
compareEqual
compareGreater
)
@@ -39,7 +42,7 @@ var (
bytesType = reflect.TypeOf([]byte{})
)
-func compare(obj1, obj2 interface{}, kind reflect.Kind) (CompareType, bool) {
+func compare(obj1, obj2 interface{}, kind reflect.Kind) (compareResult, bool) {
obj1Value := reflect.ValueOf(obj1)
obj2Value := reflect.ValueOf(obj2)
@@ -325,7 +328,13 @@ func compare(obj1, obj2 interface{}, kind reflect.Kind) (CompareType, bool) {
timeObj2 = obj2Value.Convert(timeType).Interface().(time.Time)
}
- return compare(timeObj1.UnixNano(), timeObj2.UnixNano(), reflect.Int64)
+ if timeObj1.Before(timeObj2) {
+ return compareLess, true
+ }
+ if timeObj1.Equal(timeObj2) {
+ return compareEqual, true
+ }
+ return compareGreater, true
}
case reflect.Slice:
{
@@ -345,7 +354,7 @@ func compare(obj1, obj2 interface{}, kind reflect.Kind) (CompareType, bool) {
bytesObj2 = obj2Value.Convert(bytesType).Interface().([]byte)
}
- return CompareType(bytes.Compare(bytesObj1, bytesObj2)), true
+ return compareResult(bytes.Compare(bytesObj1, bytesObj2)), true
}
case reflect.Uintptr:
{
@@ -381,7 +390,7 @@ func Greater(t TestingT, e1 interface{}, e2 interface{}, msgAndArgs ...interface
if h, ok := t.(tHelper); ok {
h.Helper()
}
- return compareTwoValues(t, e1, e2, []CompareType{compareGreater}, "\"%v\" is not greater than \"%v\"", msgAndArgs...)
+ return compareTwoValues(t, e1, e2, []compareResult{compareGreater}, "\"%v\" is not greater than \"%v\"", msgAndArgs...)
}
// GreaterOrEqual asserts that the first element is greater than or equal to the second
@@ -394,7 +403,7 @@ func GreaterOrEqual(t TestingT, e1 interface{}, e2 interface{}, msgAndArgs ...in
if h, ok := t.(tHelper); ok {
h.Helper()
}
- return compareTwoValues(t, e1, e2, []CompareType{compareGreater, compareEqual}, "\"%v\" is not greater than or equal to \"%v\"", msgAndArgs...)
+ return compareTwoValues(t, e1, e2, []compareResult{compareGreater, compareEqual}, "\"%v\" is not greater than or equal to \"%v\"", msgAndArgs...)
}
// Less asserts that the first element is less than the second
@@ -406,7 +415,7 @@ func Less(t TestingT, e1 interface{}, e2 interface{}, msgAndArgs ...interface{})
if h, ok := t.(tHelper); ok {
h.Helper()
}
- return compareTwoValues(t, e1, e2, []CompareType{compareLess}, "\"%v\" is not less than \"%v\"", msgAndArgs...)
+ return compareTwoValues(t, e1, e2, []compareResult{compareLess}, "\"%v\" is not less than \"%v\"", msgAndArgs...)
}
// LessOrEqual asserts that the first element is less than or equal to the second
@@ -419,7 +428,7 @@ func LessOrEqual(t TestingT, e1 interface{}, e2 interface{}, msgAndArgs ...inter
if h, ok := t.(tHelper); ok {
h.Helper()
}
- return compareTwoValues(t, e1, e2, []CompareType{compareLess, compareEqual}, "\"%v\" is not less than or equal to \"%v\"", msgAndArgs...)
+ return compareTwoValues(t, e1, e2, []compareResult{compareLess, compareEqual}, "\"%v\" is not less than or equal to \"%v\"", msgAndArgs...)
}
// Positive asserts that the specified element is positive
@@ -431,7 +440,7 @@ func Positive(t TestingT, e interface{}, msgAndArgs ...interface{}) bool {
h.Helper()
}
zero := reflect.Zero(reflect.TypeOf(e))
- return compareTwoValues(t, e, zero.Interface(), []CompareType{compareGreater}, "\"%v\" is not positive", msgAndArgs...)
+ return compareTwoValues(t, e, zero.Interface(), []compareResult{compareGreater}, "\"%v\" is not positive", msgAndArgs...)
}
// Negative asserts that the specified element is negative
@@ -443,10 +452,10 @@ func Negative(t TestingT, e interface{}, msgAndArgs ...interface{}) bool {
h.Helper()
}
zero := reflect.Zero(reflect.TypeOf(e))
- return compareTwoValues(t, e, zero.Interface(), []CompareType{compareLess}, "\"%v\" is not negative", msgAndArgs...)
+ return compareTwoValues(t, e, zero.Interface(), []compareResult{compareLess}, "\"%v\" is not negative", msgAndArgs...)
}
-func compareTwoValues(t TestingT, e1 interface{}, e2 interface{}, allowedComparesResults []CompareType, failMessage string, msgAndArgs ...interface{}) bool {
+func compareTwoValues(t TestingT, e1 interface{}, e2 interface{}, allowedComparesResults []compareResult, failMessage string, msgAndArgs ...interface{}) bool {
if h, ok := t.(tHelper); ok {
h.Helper()
}
@@ -469,7 +478,7 @@ func compareTwoValues(t TestingT, e1 interface{}, e2 interface{}, allowedCompare
return true
}
-func containsValue(values []CompareType, value CompareType) bool {
+func containsValue(values []compareResult, value compareResult) bool {
for _, v := range values {
if v == value {
return true
diff --git assert/assertion_compare_test.go assert/assertion_compare_test.go
index 95a7a7b1a..bf6b8160b 100644
--- assert/assertion_compare_test.go
+++ assert/assertion_compare_test.go
@@ -59,6 +59,7 @@ func TestCompare(t *testing.T) {
{less: uintptr(1), greater: uintptr(2), cType: "uintptr"},
{less: customUintptr(1), greater: customUintptr(2), cType: "uint64"},
{less: time.Now(), greater: time.Now().Add(time.Hour), cType: "time.Time"},
+ {less: time.Date(2024, 0, 0, 0, 0, 0, 0, time.Local), greater: time.Date(2263, 0, 0, 0, 0, 0, 0, time.Local), cType: "time.Time"},
{less: customTime(time.Now()), greater: customTime(time.Now().Add(time.Hour)), cType: "time.Time"},
{less: []byte{1, 1}, greater: []byte{1, 2}, cType: "[]byte"},
{less: customBytes([]byte{1, 1}), greater: customBytes([]byte{1, 2}), cType: "[]byte"},
@@ -392,8 +393,8 @@ func Test_compareTwoValuesDifferentValuesTypes(t *testing.T) {
{v1: float64(12), v2: "123"},
{v1: "float(12)", v2: float64(1)},
} {
- compareResult := compareTwoValues(mockT, currCase.v1, currCase.v2, []CompareType{compareLess, compareEqual, compareGreater}, "testFailMessage")
- False(t, compareResult)
+ result := compareTwoValues(mockT, currCase.v1, currCase.v2, []compareResult{compareLess, compareEqual, compareGreater}, "testFailMessage")
+ False(t, result)
}
}
@@ -411,8 +412,8 @@ func Test_compareTwoValuesNotComparableValues(t *testing.T) {
{v1: map[string]int{}, v2: map[string]int{}},
{v1: make([]int, 5), v2: make([]int, 5)},
} {
- compareResult := compareTwoValues(mockT, currCase.v1, currCase.v2, []CompareType{compareLess, compareEqual, compareGreater}, "testFailMessage")
- False(t, compareResult)
+ result := compareTwoValues(mockT, currCase.v1, currCase.v2, []compareResult{compareLess, compareEqual, compareGreater}, "testFailMessage")
+ False(t, result)
}
}
@@ -420,35 +421,35 @@ func Test_compareTwoValuesCorrectCompareResult(t *testing.T) {
mockT := new(testing.T)
for _, currCase := range []struct {
- v1 interface{}
- v2 interface{}
- compareTypes []CompareType
+ v1 interface{}
+ v2 interface{}
+ allowedResults []compareResult
}{
- {v1: 1, v2: 2, compareTypes: []CompareType{compareLess}},
- {v1: 1, v2: 2, compareTypes: []CompareType{compareLess, compareEqual}},
- {v1: 2, v2: 2, compareTypes: []CompareType{compareGreater, compareEqual}},
- {v1: 2, v2: 2, compareTypes: []CompareType{compareEqual}},
- {v1: 2, v2: 1, compareTypes: []CompareType{compareEqual, compareGreater}},
- {v1: 2, v2: 1, compareTypes: []CompareType{compareGreater}},
+ {v1: 1, v2: 2, allowedResults: []compareResult{compareLess}},
+ {v1: 1, v2: 2, allowedResults: []compareResult{compareLess, compareEqual}},
+ {v1: 2, v2: 2, allowedResults: []compareResult{compareGreater, compareEqual}},
+ {v1: 2, v2: 2, allowedResults: []compareResult{compareEqual}},
+ {v1: 2, v2: 1, allowedResults: []compareResult{compareEqual, compareGreater}},
+ {v1: 2, v2: 1, allowedResults: []compareResult{compareGreater}},
} {
- compareResult := compareTwoValues(mockT, currCase.v1, currCase.v2, currCase.compareTypes, "testFailMessage")
- True(t, compareResult)
+ result := compareTwoValues(mockT, currCase.v1, currCase.v2, currCase.allowedResults, "testFailMessage")
+ True(t, result)
}
}
func Test_containsValue(t *testing.T) {
for _, currCase := range []struct {
- values []CompareType
- value CompareType
+ values []compareResult
+ value compareResult
result bool
}{
- {values: []CompareType{compareGreater}, value: compareGreater, result: true},
- {values: []CompareType{compareGreater, compareLess}, value: compareGreater, result: true},
- {values: []CompareType{compareGreater, compareLess}, value: compareLess, result: true},
- {values: []CompareType{compareGreater, compareLess}, value: compareEqual, result: false},
+ {values: []compareResult{compareGreater}, value: compareGreater, result: true},
+ {values: []compareResult{compareGreater, compareLess}, value: compareGreater, result: true},
+ {values: []compareResult{compareGreater, compareLess}, value: compareLess, result: true},
+ {values: []compareResult{compareGreater, compareLess}, value: compareEqual, result: false},
} {
- compareResult := containsValue(currCase.values, currCase.value)
- Equal(t, currCase.result, compareResult)
+ result := containsValue(currCase.values, currCase.value)
+ Equal(t, currCase.result, result)
}
}
diff --git assert/assertion_format.go assert/assertion_format.go
index 3ddab109a..190634165 100644
--- assert/assertion_format.go
+++ assert/assertion_format.go
@@ -104,8 +104,8 @@ func EqualExportedValuesf(t TestingT, expected interface{}, actual interface{},
return EqualExportedValues(t, expected, actual, append([]interface{}{msg}, args...)...)
}
-// EqualValuesf asserts that two objects are equal or convertible to the same types
-// and equal.
+// EqualValuesf asserts that two objects are equal or convertible to the larger
+// type and equal.
//
// assert.EqualValuesf(t, uint32(123), int32(123), "error message %s", "formatted")
func EqualValuesf(t TestingT, expected interface{}, actual interface{}, msg string, args ...interface{}) bool {
@@ -186,7 +186,7 @@ func Eventuallyf(t TestingT, condition func() bool, waitFor time.Duration, tick
// assert.EventuallyWithTf(t, func(c *assert.CollectT, "error message %s", "formatted") {
// // add assertions as needed; any assertion failure will fail the current tick
// assert.True(c, externalValue, "expected 'externalValue' to be true")
-// }, 1*time.Second, 10*time.Second, "external state has not changed to 'true'; still false")
+// }, 10*time.Second, 1*time.Second, "external state has not changed to 'true'; still false")
func EventuallyWithTf(t TestingT, condition func(collect *CollectT), waitFor time.Duration, tick time.Duration, msg string, args ...interface{}) bool {
if h, ok := t.(tHelper); ok {
h.Helper()
@@ -568,6 +568,23 @@ func NotContainsf(t TestingT, s interface{}, contains interface{}, msg string, a
return NotContains(t, s, contains, append([]interface{}{msg}, args...)...)
}
+// NotElementsMatchf asserts that the specified listA(array, slice...) is NOT equal to specified
+// listB(array, slice...) ignoring the order of the elements. If there are duplicate elements,
+// the number of appearances of each of them in both lists should not match.
+// This is an inverse of ElementsMatch.
+//
+// assert.NotElementsMatchf(t, [1, 1, 2, 3], [1, 1, 2, 3], "error message %s", "formatted") -> false
+//
+// assert.NotElementsMatchf(t, [1, 1, 2, 3], [1, 2, 3], "error message %s", "formatted") -> true
+//
+// assert.NotElementsMatchf(t, [1, 2, 3], [1, 2, 4], "error message %s", "formatted") -> true
+func NotElementsMatchf(t TestingT, listA interface{}, listB interface{}, msg string, args ...interface{}) bool {
+ if h, ok := t.(tHelper); ok {
+ h.Helper()
+ }
+ return NotElementsMatch(t, listA, listB, append([]interface{}{msg}, args...)...)
+}
+
// NotEmptyf asserts that the specified object is NOT empty. I.e. not nil, "", false, 0 or either
// a slice or a channel with len == 0.
//
@@ -604,7 +621,16 @@ func NotEqualValuesf(t TestingT, expected interface{}, actual interface{}, msg s
return NotEqualValues(t, expected, actual, append([]interface{}{msg}, args...)...)
}
-// NotErrorIsf asserts that at none of the errors in err's chain matches target.
+// NotErrorAsf asserts that none of the errors in err's chain matches target,
+// but if so, sets target to that error value.
+func NotErrorAsf(t TestingT, err error, target interface{}, msg string, args ...interface{}) bool {
+ if h, ok := t.(tHelper); ok {
+ h.Helper()
+ }
+ return NotErrorAs(t, err, target, append([]interface{}{msg}, args...)...)
+}
+
+// NotErrorIsf asserts that none of the errors in err's chain matches target.
// This is a wrapper for errors.Is.
func NotErrorIsf(t TestingT, err error, target error, msg string, args ...interface{}) bool {
if h, ok := t.(tHelper); ok {
diff --git assert/assertion_forward.go assert/assertion_forward.go
index a84e09bd4..21629087b 100644
--- assert/assertion_forward.go
+++ assert/assertion_forward.go
@@ -186,8 +186,8 @@ func (a *Assertions) EqualExportedValuesf(expected interface{}, actual interface
return EqualExportedValuesf(a.t, expected, actual, msg, args...)
}
-// EqualValues asserts that two objects are equal or convertible to the same types
-// and equal.
+// EqualValues asserts that two objects are equal or convertible to the larger
+// type and equal.
//
// a.EqualValues(uint32(123), int32(123))
func (a *Assertions) EqualValues(expected interface{}, actual interface{}, msgAndArgs ...interface{}) bool {
@@ -197,8 +197,8 @@ func (a *Assertions) EqualValues(expected interface{}, actual interface{}, msgAn
return EqualValues(a.t, expected, actual, msgAndArgs...)
}
-// EqualValuesf asserts that two objects are equal or convertible to the same types
-// and equal.
+// EqualValuesf asserts that two objects are equal or convertible to the larger
+// type and equal.
//
// a.EqualValuesf(uint32(123), int32(123), "error message %s", "formatted")
func (a *Assertions) EqualValuesf(expected interface{}, actual interface{}, msg string, args ...interface{}) bool {
@@ -336,7 +336,7 @@ func (a *Assertions) Eventually(condition func() bool, waitFor time.Duration, ti
// a.EventuallyWithT(func(c *assert.CollectT) {
// // add assertions as needed; any assertion failure will fail the current tick
// assert.True(c, externalValue, "expected 'externalValue' to be true")
-// }, 1*time.Second, 10*time.Second, "external state has not changed to 'true'; still false")
+// }, 10*time.Second, 1*time.Second, "external state has not changed to 'true'; still false")
func (a *Assertions) EventuallyWithT(condition func(collect *CollectT), waitFor time.Duration, tick time.Duration, msgAndArgs ...interface{}) bool {
if h, ok := a.t.(tHelper); ok {
h.Helper()
@@ -361,7 +361,7 @@ func (a *Assertions) EventuallyWithT(condition func(collect *CollectT), waitFor
// a.EventuallyWithTf(func(c *assert.CollectT, "error message %s", "formatted") {
// // add assertions as needed; any assertion failure will fail the current tick
// assert.True(c, externalValue, "expected 'externalValue' to be true")
-// }, 1*time.Second, 10*time.Second, "external state has not changed to 'true'; still false")
+// }, 10*time.Second, 1*time.Second, "external state has not changed to 'true'; still false")
func (a *Assertions) EventuallyWithTf(condition func(collect *CollectT), waitFor time.Duration, tick time.Duration, msg string, args ...interface{}) bool {
if h, ok := a.t.(tHelper); ok {
h.Helper()
@@ -1128,6 +1128,40 @@ func (a *Assertions) NotContainsf(s interface{}, contains interface{}, msg strin
return NotContainsf(a.t, s, contains, msg, args...)
}
+// NotElementsMatch asserts that the specified listA(array, slice...) is NOT equal to specified
+// listB(array, slice...) ignoring the order of the elements. If there are duplicate elements,
+// the number of appearances of each of them in both lists should not match.
+// This is an inverse of ElementsMatch.
+//
+// a.NotElementsMatch([1, 1, 2, 3], [1, 1, 2, 3]) -> false
+//
+// a.NotElementsMatch([1, 1, 2, 3], [1, 2, 3]) -> true
+//
+// a.NotElementsMatch([1, 2, 3], [1, 2, 4]) -> true
+func (a *Assertions) NotElementsMatch(listA interface{}, listB interface{}, msgAndArgs ...interface{}) bool {
+ if h, ok := a.t.(tHelper); ok {
+ h.Helper()
+ }
+ return NotElementsMatch(a.t, listA, listB, msgAndArgs...)
+}
+
+// NotElementsMatchf asserts that the specified listA(array, slice...) is NOT equal to specified
+// listB(array, slice...) ignoring the order of the elements. If there are duplicate elements,
+// the number of appearances of each of them in both lists should not match.
+// This is an inverse of ElementsMatch.
+//
+// a.NotElementsMatchf([1, 1, 2, 3], [1, 1, 2, 3], "error message %s", "formatted") -> false
+//
+// a.NotElementsMatchf([1, 1, 2, 3], [1, 2, 3], "error message %s", "formatted") -> true
+//
+// a.NotElementsMatchf([1, 2, 3], [1, 2, 4], "error message %s", "formatted") -> true
+func (a *Assertions) NotElementsMatchf(listA interface{}, listB interface{}, msg string, args ...interface{}) bool {
+ if h, ok := a.t.(tHelper); ok {
+ h.Helper()
+ }
+ return NotElementsMatchf(a.t, listA, listB, msg, args...)
+}
+
// NotEmpty asserts that the specified object is NOT empty. I.e. not nil, "", false, 0 or either
// a slice or a channel with len == 0.
//
@@ -1200,7 +1234,25 @@ func (a *Assertions) NotEqualf(expected interface{}, actual interface{}, msg str
return NotEqualf(a.t, expected, actual, msg, args...)
}
-// NotErrorIs asserts that at none of the errors in err's chain matches target.
+// NotErrorAs asserts that none of the errors in err's chain matches target,
+// but if so, sets target to that error value.
+func (a *Assertions) NotErrorAs(err error, target interface{}, msgAndArgs ...interface{}) bool {
+ if h, ok := a.t.(tHelper); ok {
+ h.Helper()
+ }
+ return NotErrorAs(a.t, err, target, msgAndArgs...)
+}
+
+// NotErrorAsf asserts that none of the errors in err's chain matches target,
+// but if so, sets target to that error value.
+func (a *Assertions) NotErrorAsf(err error, target interface{}, msg string, args ...interface{}) bool {
+ if h, ok := a.t.(tHelper); ok {
+ h.Helper()
+ }
+ return NotErrorAsf(a.t, err, target, msg, args...)
+}
+
+// NotErrorIs asserts that none of the errors in err's chain matches target.
// This is a wrapper for errors.Is.
func (a *Assertions) NotErrorIs(err error, target error, msgAndArgs ...interface{}) bool {
if h, ok := a.t.(tHelper); ok {
@@ -1209,7 +1261,7 @@ func (a *Assertions) NotErrorIs(err error, target error, msgAndArgs ...interface
return NotErrorIs(a.t, err, target, msgAndArgs...)
}
-// NotErrorIsf asserts that at none of the errors in err's chain matches target.
+// NotErrorIsf asserts that none of the errors in err's chain matches target.
// This is a wrapper for errors.Is.
func (a *Assertions) NotErrorIsf(err error, target error, msg string, args ...interface{}) bool {
if h, ok := a.t.(tHelper); ok {
diff --git assert/assertion_order.go assert/assertion_order.go
index 00df62a05..1d2f71824 100644
--- assert/assertion_order.go
+++ assert/assertion_order.go
@@ -6,7 +6,7 @@ import (
)
// isOrdered checks that collection contains orderable elements.
-func isOrdered(t TestingT, object interface{}, allowedComparesResults []CompareType, failMessage string, msgAndArgs ...interface{}) bool {
+func isOrdered(t TestingT, object interface{}, allowedComparesResults []compareResult, failMessage string, msgAndArgs ...interface{}) bool {
objKind := reflect.TypeOf(object).Kind()
if objKind != reflect.Slice && objKind != reflect.Array {
return false
@@ -50,7 +50,7 @@ func isOrdered(t TestingT, object interface{}, allowedComparesResults []CompareT
// assert.IsIncreasing(t, []float{1, 2})
// assert.IsIncreasing(t, []string{"a", "b"})
func IsIncreasing(t TestingT, object interface{}, msgAndArgs ...interface{}) bool {
- return isOrdered(t, object, []CompareType{compareLess}, "\"%v\" is not less than \"%v\"", msgAndArgs...)
+ return isOrdered(t, object, []compareResult{compareLess}, "\"%v\" is not less than \"%v\"", msgAndArgs...)
}
// IsNonIncreasing asserts that the collection is not increasing
@@ -59,7 +59,7 @@ func IsIncreasing(t TestingT, object interface{}, msgAndArgs ...interface{}) boo
// assert.IsNonIncreasing(t, []float{2, 1})
// assert.IsNonIncreasing(t, []string{"b", "a"})
func IsNonIncreasing(t TestingT, object interface{}, msgAndArgs ...interface{}) bool {
- return isOrdered(t, object, []CompareType{compareEqual, compareGreater}, "\"%v\" is not greater than or equal to \"%v\"", msgAndArgs...)
+ return isOrdered(t, object, []compareResult{compareEqual, compareGreater}, "\"%v\" is not greater than or equal to \"%v\"", msgAndArgs...)
}
// IsDecreasing asserts that the collection is decreasing
@@ -68,7 +68,7 @@ func IsNonIncreasing(t TestingT, object interface{}, msgAndArgs ...interface{})
// assert.IsDecreasing(t, []float{2, 1})
// assert.IsDecreasing(t, []string{"b", "a"})
func IsDecreasing(t TestingT, object interface{}, msgAndArgs ...interface{}) bool {
- return isOrdered(t, object, []CompareType{compareGreater}, "\"%v\" is not greater than \"%v\"", msgAndArgs...)
+ return isOrdered(t, object, []compareResult{compareGreater}, "\"%v\" is not greater than \"%v\"", msgAndArgs...)
}
// IsNonDecreasing asserts that the collection is not decreasing
@@ -77,5 +77,5 @@ func IsDecreasing(t TestingT, object interface{}, msgAndArgs ...interface{}) boo
// assert.IsNonDecreasing(t, []float{1, 2})
// assert.IsNonDecreasing(t, []string{"a", "b"})
func IsNonDecreasing(t TestingT, object interface{}, msgAndArgs ...interface{}) bool {
- return isOrdered(t, object, []CompareType{compareLess, compareEqual}, "\"%v\" is not less than or equal to \"%v\"", msgAndArgs...)
+ return isOrdered(t, object, []compareResult{compareLess, compareEqual}, "\"%v\" is not less than or equal to \"%v\"", msgAndArgs...)
}
diff --git assert/assertions.go assert/assertions.go
index 0b7570f21..4e91332bb 100644
--- assert/assertions.go
+++ assert/assertions.go
@@ -19,7 +19,9 @@ import (
"github.com/davecgh/go-spew/spew"
"github.com/pmezard/go-difflib/difflib"
- "gopkg.in/yaml.v3"
+
+ // Wrapper around gopkg.in/yaml.v3
+ "github.com/stretchr/testify/assert/yaml"
)
//go:generate sh -c "cd ../_codegen && go build && cd - && ../_codegen/_codegen -output-package=assert -template=assertion_format.go.tmpl"
@@ -45,6 +47,10 @@ type BoolAssertionFunc func(TestingT, bool, ...interface{}) bool
// for table driven tests.
type ErrorAssertionFunc func(TestingT, error, ...interface{}) bool
+// PanicAssertionFunc is a common function prototype when validating a panic value. Can be useful
+// for table driven tests.
+type PanicAssertionFunc = func(t TestingT, f PanicTestFunc, msgAndArgs ...interface{}) bool
+
// Comparison is a custom function that returns true on success and false on failure
type Comparison func() (success bool)
@@ -496,7 +502,13 @@ func Same(t TestingT, expected, actual interface{}, msgAndArgs ...interface{}) b
h.Helper()
}
- if !samePointers(expected, actual) {
+ same, ok := samePointers(expected, actual)
+ if !ok {
+ return Fail(t, "Both arguments must be pointers", msgAndArgs...)
+ }
+
+ if !same {
+ // both are pointers but not the same type & pointing to the same address
return Fail(t, fmt.Sprintf("Not same: \n"+
"expected: %p %#v\n"+
"actual : %p %#v", expected, expected, actual, actual), msgAndArgs...)
@@ -516,7 +528,13 @@ func NotSame(t TestingT, expected, actual interface{}, msgAndArgs ...interface{}
h.Helper()
}
- if samePointers(expected, actual) {
+ same, ok := samePointers(expected, actual)
+ if !ok {
+ //fails when the arguments are not pointers
+ return !(Fail(t, "Both arguments must be pointers", msgAndArgs...))
+ }
+
+ if same {
return Fail(t, fmt.Sprintf(
"Expected and actual point to the same object: %p %#v",
expected, expected), msgAndArgs...)
@@ -524,21 +542,23 @@ func NotSame(t TestingT, expected, actual interface{}, msgAndArgs ...interface{}
return true
}
-// samePointers compares two generic interface objects and returns whether
-// they point to the same object
-func samePointers(first, second interface{}) bool {
+// samePointers checks if two generic interface objects are pointers of the same
+// type pointing to the same object. It returns two values: same indicating if
+// they are the same type and point to the same object, and ok indicating that
+// both inputs are pointers.
+func samePointers(first, second interface{}) (same bool, ok bool) {
firstPtr, secondPtr := reflect.ValueOf(first), reflect.ValueOf(second)
if firstPtr.Kind() != reflect.Ptr || secondPtr.Kind() != reflect.Ptr {
- return false
+ return false, false //not both are pointers
}
firstType, secondType := reflect.TypeOf(first), reflect.TypeOf(second)
if firstType != secondType {
- return false
+ return false, true // both are pointers, but of different types
}
// compare pointer addresses
- return first == second
+ return first == second, true
}
// formatUnequalValues takes two values of arbitrary types and returns string
@@ -572,8 +592,8 @@ func truncatingFormat(data interface{}) string {
return value
}
-// EqualValues asserts that two objects are equal or convertible to the same types
-// and equal.
+// EqualValues asserts that two objects are equal or convertible to the larger
+// type and equal.
//
// assert.EqualValues(t, uint32(123), int32(123))
func EqualValues(t TestingT, expected, actual interface{}, msgAndArgs ...interface{}) bool {
@@ -615,21 +635,6 @@ func EqualExportedValues(t TestingT, expected, actual interface{}, msgAndArgs ..
return Fail(t, fmt.Sprintf("Types expected to match exactly\n\t%v != %v", aType, bType), msgAndArgs...)
}
- if aType.Kind() == reflect.Ptr {
- aType = aType.Elem()
- }
- if bType.Kind() == reflect.Ptr {
- bType = bType.Elem()
- }
-
- if aType.Kind() != reflect.Struct {
- return Fail(t, fmt.Sprintf("Types expected to both be struct or pointer to struct \n\t%v != %v", aType.Kind(), reflect.Struct), msgAndArgs...)
- }
-
- if bType.Kind() != reflect.Struct {
- return Fail(t, fmt.Sprintf("Types expected to both be struct or pointer to struct \n\t%v != %v", bType.Kind(), reflect.Struct), msgAndArgs...)
- }
-
expected = copyExportedFields(expected)
actual = copyExportedFields(actual)
@@ -1170,6 +1175,39 @@ func formatListDiff(listA, listB interface{}, extraA, extraB []interface{}) stri
return msg.String()
}
+// NotElementsMatch asserts that the specified listA(array, slice...) is NOT equal to specified
+// listB(array, slice...) ignoring the order of the elements. If there are duplicate elements,
+// the number of appearances of each of them in both lists should not match.
+// This is an inverse of ElementsMatch.
+//
+// assert.NotElementsMatch(t, [1, 1, 2, 3], [1, 1, 2, 3]) -> false
+//
+// assert.NotElementsMatch(t, [1, 1, 2, 3], [1, 2, 3]) -> true
+//
+// assert.NotElementsMatch(t, [1, 2, 3], [1, 2, 4]) -> true
+func NotElementsMatch(t TestingT, listA, listB interface{}, msgAndArgs ...interface{}) (ok bool) {
+ if h, ok := t.(tHelper); ok {
+ h.Helper()
+ }
+ if isEmpty(listA) && isEmpty(listB) {
+ return Fail(t, "listA and listB contain the same elements", msgAndArgs)
+ }
+
+ if !isList(t, listA, msgAndArgs...) {
+ return Fail(t, "listA is not a list type", msgAndArgs...)
+ }
+ if !isList(t, listB, msgAndArgs...) {
+ return Fail(t, "listB is not a list type", msgAndArgs...)
+ }
+
+ extraA, extraB := diffLists(listA, listB)
+ if len(extraA) == 0 && len(extraB) == 0 {
+ return Fail(t, "listA and listB contain the same elements", msgAndArgs)
+ }
+
+ return true
+}
+
// Condition uses a Comparison to assert a complex condition.
func Condition(t TestingT, comp Comparison, msgAndArgs ...interface{}) bool {
if h, ok := t.(tHelper); ok {
@@ -1488,6 +1526,9 @@ func InEpsilon(t TestingT, expected, actual interface{}, epsilon float64, msgAnd
if err != nil {
return Fail(t, err.Error(), msgAndArgs...)
}
+ if math.IsNaN(actualEpsilon) {
+ return Fail(t, "relative error is NaN", msgAndArgs...)
+ }
if actualEpsilon > epsilon {
return Fail(t, fmt.Sprintf("Relative error is too high: %#v (expected)\n"+
" < %#v (actual)", epsilon, actualEpsilon), msgAndArgs...)
@@ -1611,7 +1652,6 @@ func ErrorContains(t TestingT, theError error, contains string, msgAndArgs ...in
// matchRegexp return true if a specified regexp matches a string.
func matchRegexp(rx interface{}, str interface{}) bool {
-
var r *regexp.Regexp
if rr, ok := rx.(*regexp.Regexp); ok {
r = rr
@@ -1619,7 +1659,14 @@ func matchRegexp(rx interface{}, str interface{}) bool {
r = regexp.MustCompile(fmt.Sprint(rx))
}
- return (r.FindStringIndex(fmt.Sprint(str)) != nil)
+ switch v := str.(type) {
+ case []byte:
+ return r.Match(v)
+ case string:
+ return r.MatchString(v)
+ default:
+ return r.MatchString(fmt.Sprint(v))
+ }
}
@@ -1872,7 +1919,7 @@ var spewConfigStringerEnabled = spew.ConfigState{
MaxDepth: 10,
}
-type tHelper interface {
+type tHelper = interface {
Helper()
}
@@ -1911,6 +1958,9 @@ func Eventually(t TestingT, condition func() bool, waitFor time.Duration, tick t
// CollectT implements the TestingT interface and collects all errors.
type CollectT struct {
+ // A slice of errors. Non-nil slice denotes a failure.
+ // If it's non-nil but len(c.errors) == 0, this is also a failure
+ // obtained by direct c.FailNow() call.
errors []error
}
@@ -1919,9 +1969,10 @@ func (c *CollectT) Errorf(format string, args ...interface{}) {
c.errors = append(c.errors, fmt.Errorf(format, args...))
}
-// FailNow panics.
-func (*CollectT) FailNow() {
- panic("Assertion failed")
+// FailNow stops execution by calling runtime.Goexit.
+func (c *CollectT) FailNow() {
+ c.fail()
+ runtime.Goexit()
}
// Deprecated: That was a method for internal usage that should not have been published. Now just panics.
@@ -1934,6 +1985,16 @@ func (*CollectT) Copy(TestingT) {
panic("Copy() is deprecated")
}
+func (c *CollectT) fail() {
+ if !c.failed() {
+ c.errors = []error{} // Make it non-nil to mark a failure.
+ }
+}
+
+func (c *CollectT) failed() bool {
+ return c.errors != nil
+}
+
// EventuallyWithT asserts that given condition will be met in waitFor time,
// periodically checking target function each tick. In contrast to Eventually,
// it supplies a CollectT to the condition function, so that the condition
@@ -1951,14 +2012,14 @@ func (*CollectT) Copy(TestingT) {
// assert.EventuallyWithT(t, func(c *assert.CollectT) {
// // add assertions as needed; any assertion failure will fail the current tick
// assert.True(c, externalValue, "expected 'externalValue' to be true")
-// }, 1*time.Second, 10*time.Second, "external state has not changed to 'true'; still false")
+// }, 10*time.Second, 1*time.Second, "external state has not changed to 'true'; still false")
func EventuallyWithT(t TestingT, condition func(collect *CollectT), waitFor time.Duration, tick time.Duration, msgAndArgs ...interface{}) bool {
if h, ok := t.(tHelper); ok {
h.Helper()
}
var lastFinishedTickErrs []error
- ch := make(chan []error, 1)
+ ch := make(chan *CollectT, 1)
timer := time.NewTimer(waitFor)
defer timer.Stop()
@@ -1978,16 +2039,16 @@ func EventuallyWithT(t TestingT, condition func(collect *CollectT), waitFor time
go func() {
collect := new(CollectT)
defer func() {
- ch <- collect.errors
+ ch <- collect
}()
condition(collect)
}()
- case errs := <-ch:
- if len(errs) == 0 {
+ case collect := <-ch:
+ if !collect.failed() {
return true
}
// Keep the errors from the last ended condition, so that they can be copied to t if timeout is reached.
- lastFinishedTickErrs = errs
+ lastFinishedTickErrs = collect.errors
tick = ticker.C
}
}
@@ -2049,7 +2110,7 @@ func ErrorIs(t TestingT, err, target error, msgAndArgs ...interface{}) bool {
), msgAndArgs...)
}
-// NotErrorIs asserts that at none of the errors in err's chain matches target.
+// NotErrorIs asserts that none of the errors in err's chain matches target.
// This is a wrapper for errors.Is.
func NotErrorIs(t TestingT, err, target error, msgAndArgs ...interface{}) bool {
if h, ok := t.(tHelper); ok {
@@ -2090,6 +2151,24 @@ func ErrorAs(t TestingT, err error, target interface{}, msgAndArgs ...interface{
), msgAndArgs...)
}
+// NotErrorAs asserts that none of the errors in err's chain matches target,
+// but if so, sets target to that error value.
+func NotErrorAs(t TestingT, err error, target interface{}, msgAndArgs ...interface{}) bool {
+ if h, ok := t.(tHelper); ok {
+ h.Helper()
+ }
+ if !errors.As(err, target) {
+ return true
+ }
+
+ chain := buildErrorChainString(err)
+
+ return Fail(t, fmt.Sprintf("Target error should not be in err chain:\n"+
+ "found: %q\n"+
+ "in chain: %s", target, chain,
+ ), msgAndArgs...)
+}
+
func buildErrorChainString(err error) string {
if err == nil {
return ""
diff --git assert/assertions_test.go assert/assertions_test.go
index 2a6e47234..9f859fa8d 100644
--- assert/assertions_test.go
+++ assert/assertions_test.go
@@ -449,6 +449,56 @@ func TestEqualExportedValues(t *testing.T) {
+ Exported: (int) 1,
notExported: (interface {}) <nil>`,
},
+ {
+ value1: []int{1, 2},
+ value2: []int{1, 2},
+ expectedEqual: true,
+ },
+ {
+ value1: []int{1, 2},
+ value2: []int{1, 3},
+ expectedEqual: false,
+ expectedFail: `
+ Diff:
+ --- Expected
+ +++ Actual
+ @@ -2,3 +2,3 @@
+ (int) 1,
+ - (int) 2
+ + (int) 3
+ }`,
+ },
+ {
+ value1: []*Nested{
+ {1, 2},
+ {3, 4},
+ },
+ value2: []*Nested{
+ {1, "a"},
+ {3, "b"},
+ },
+ expectedEqual: true,
+ },
+ {
+ value1: []*Nested{
+ {1, 2},
+ {3, 4},
+ },
+ value2: []*Nested{
+ {1, "a"},
+ {2, "b"},
+ },
+ expectedEqual: false,
+ expectedFail: `
+ Diff:
+ --- Expected
+ +++ Actual
+ @@ -6,3 +6,3 @@
+ (*assert.Nested)({
+ - Exported: (int) 3,
+ + Exported: (int) 2,
+ notExported: (interface {}) <nil>`,
+ },
}
for _, c := range cases {
@@ -605,39 +655,59 @@ func Test_samePointers(t *testing.T) {
second interface{}
}
tests := []struct {
- name string
- args args
- assertion BoolAssertionFunc
+ name string
+ args args
+ same BoolAssertionFunc
+ ok BoolAssertionFunc
}{
{
- name: "1 != 2",
- args: args{first: 1, second: 2},
- assertion: False,
+ name: "1 != 2",
+ args: args{first: 1, second: 2},
+ same: False,
+ ok: False,
},
{
- name: "1 != 1 (not same ptr)",
- args: args{first: 1, second: 1},
- assertion: False,
+ name: "1 != 1 (not same ptr)",
+ args: args{first: 1, second: 1},
+ same: False,
+ ok: False,
},
{
- name: "ptr(1) == ptr(1)",
- args: args{first: p, second: p},
- assertion: True,
+ name: "ptr(1) == ptr(1)",
+ args: args{first: p, second: p},
+ same: True,
+ ok: True,
},
{
- name: "int(1) != float32(1)",
- args: args{first: int(1), second: float32(1)},
- assertion: False,
+ name: "int(1) != float32(1)",
+ args: args{first: int(1), second: float32(1)},
+ same: False,
+ ok: False,
},
{
- name: "array != slice",
- args: args{first: [2]int{1, 2}, second: []int{1, 2}},
- assertion: False,
+ name: "array != slice",
+ args: args{first: [2]int{1, 2}, second: []int{1, 2}},
+ same: False,
+ ok: False,
+ },
+ {
+ name: "non-pointer vs pointer (1 != ptr(2))",
+ args: args{first: 1, second: p},
+ same: False,
+ ok: False,
+ },
+ {
+ name: "pointer vs non-pointer (ptr(2) != 1)",
+ args: args{first: p, second: 1},
+ same: False,
+ ok: False,
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
- tt.assertion(t, samePointers(tt.args.first, tt.args.second))
+ same, ok := samePointers(tt.args.first, tt.args.second)
+ tt.same(t, same)
+ tt.ok(t, ok)
})
}
}
@@ -1319,6 +1389,52 @@ func TestDiffLists(t *testing.T) {
}
}
+func TestNotElementsMatch(t *testing.T) {
+ mockT := new(testing.T)
+
+ cases := []struct {
+ expected interface{}
+ actual interface{}
+ result bool
+ }{
+ // not matching
+ {[]int{1}, []int{}, true},
+ {[]int{}, []int{2}, true},
+ {[]int{1}, []int{2}, true},
+ {[]int{1}, []int{1, 1}, true},
+ {[]int{1, 2}, []int{3, 4}, true},
+ {[]int{3, 4}, []int{1, 2}, true},
+ {[]int{1, 1, 2, 3}, []int{1, 2, 3}, true},
+ {[]string{"hello"}, []string{"world"}, true},
+ {[]string{"hello", "hello"}, []string{"world", "world"}, true},
+ {[3]string{"hello", "hello", "hello"}, [3]string{"world", "world", "world"}, true},
+
+ // matching
+ {nil, nil, false},
+ {[]int{}, nil, false},
+ {[]int{}, []int{}, false},
+ {[]int{1}, []int{1}, false},
+ {[]int{1, 1}, []int{1, 1}, false},
+ {[]int{1, 2}, []int{2, 1}, false},
+ {[2]int{1, 2}, [2]int{2, 1}, false},
+ {[]int{1, 1, 2}, []int{1, 2, 1}, false},
+ {[]string{"hello", "world"}, []string{"world", "hello"}, false},
+ {[]string{"hello", "hello"}, []string{"hello", "hello"}, false},
+ {[]string{"hello", "hello", "world"}, []string{"hello", "world", "hello"}, false},
+ {[3]string{"hello", "hello", "world"}, [3]string{"hello", "world", "hello"}, false},
+ }
+
+ for _, c := range cases {
+ t.Run(fmt.Sprintf("NotElementsMatch(%#v, %#v)", c.expected, c.actual), func(t *testing.T) {
+ res := NotElementsMatch(mockT, c.actual, c.expected)
+
+ if res != c.result {
+ t.Errorf("NotElementsMatch(%#v, %#v) should return %v", c.actual, c.expected, c.result)
+ }
+ })
+ }
+}
+
func TestCondition(t *testing.T) {
mockT := new(testing.T)
@@ -1940,6 +2056,14 @@ func TestInEpsilon(t *testing.T) {
{math.NaN(), 0, 1},
{0, math.NaN(), 1},
{0, 0, math.NaN()},
+ {math.Inf(1), 1, 1},
+ {math.Inf(-1), 1, 1},
+ {1, math.Inf(1), 1},
+ {1, math.Inf(-1), 1},
+ {math.Inf(1), math.Inf(1), 1},
+ {math.Inf(1), math.Inf(-1), 1},
+ {math.Inf(-1), math.Inf(1), 1},
+ {math.Inf(-1), math.Inf(-1), 1},
}
for _, tc := range cases {
@@ -1972,13 +2096,16 @@ func TestRegexp(t *testing.T) {
}{
{"^start", "start of the line"},
{"end$", "in the end"},
+ {"end$", "in the end"},
{"[0-9]{3}[.-]?[0-9]{2}[.-]?[0-9]{2}", "My phone number is 650.12.34"},
}
for _, tc := range cases {
True(t, Regexp(mockT, tc.rx, tc.str))
True(t, Regexp(mockT, regexp.MustCompile(tc.rx), tc.str))
+ True(t, Regexp(mockT, regexp.MustCompile(tc.rx), []byte(tc.str)))
False(t, NotRegexp(mockT, tc.rx, tc.str))
+ False(t, NotRegexp(mockT, tc.rx, []byte(tc.str)))
False(t, NotRegexp(mockT, regexp.MustCompile(tc.rx), tc.str))
}
@@ -1993,7 +2120,9 @@ func TestRegexp(t *testing.T) {
for _, tc := range cases {
False(t, Regexp(mockT, tc.rx, tc.str), "Expected \"%s\" to not match \"%s\"", tc.rx, tc.str)
False(t, Regexp(mockT, regexp.MustCompile(tc.rx), tc.str))
+ False(t, Regexp(mockT, regexp.MustCompile(tc.rx), []byte(tc.str)))
True(t, NotRegexp(mockT, tc.rx, tc.str))
+ True(t, NotRegexp(mockT, tc.rx, []byte(tc.str)))
True(t, NotRegexp(mockT, regexp.MustCompile(tc.rx), tc.str))
}
}
@@ -2789,6 +2918,42 @@ func TestErrorAssertionFunc(t *testing.T) {
}
}
+func ExamplePanicAssertionFunc() {
+ t := &testing.T{} // provided by test
+
+ tests := []struct {
+ name string
+ panicFn PanicTestFunc
+ assertion PanicAssertionFunc
+ }{
+ {"with panic", func() { panic(nil) }, Panics},
+ {"without panic", func() {}, NotPanics},
+ }
+
+ for _, tt := range tests {
+ t.Run(tt.name, func(t *testing.T) {
+ tt.assertion(t, tt.panicFn)
+ })
+ }
+}
+
+func TestPanicAssertionFunc(t *testing.T) {
+ tests := []struct {
+ name string
+ panicFn PanicTestFunc
+ assertion PanicAssertionFunc
+ }{
+ {"not panic", func() {}, NotPanics},
+ {"panic", func() { panic(nil) }, Panics},
+ }
+
+ for _, tt := range tests {
+ t.Run(tt.name, func(t *testing.T) {
+ tt.assertion(t, tt.panicFn)
+ })
+ }
+}
+
func TestEventuallyFalse(t *testing.T) {
mockT := new(testing.T)
@@ -2836,16 +3001,15 @@ func TestEventuallyWithTFalse(t *testing.T) {
func TestEventuallyWithTTrue(t *testing.T) {
mockT := new(errorsCapturingT)
- state := 0
+ counter := 0
condition := func(collect *CollectT) {
- defer func() {
- state += 1
- }()
- True(collect, state == 2)
+ counter += 1
+ True(collect, counter == 2)
}
True(t, EventuallyWithT(mockT, condition, 100*time.Millisecond, 20*time.Millisecond))
Len(t, mockT.errors, 0)
+ Equal(t, 2, counter, "Condition is expected to be called 2 times")
}
func TestEventuallyWithT_ConcurrencySafe(t *testing.T) {
@@ -2883,6 +3047,17 @@ func TestEventuallyWithT_ReturnsTheLatestFinishedConditionErrors(t *testing.T) {
Len(t, mockT.errors, 2)
}
+func TestEventuallyWithTFailNow(t *testing.T) {
+ mockT := new(CollectT)
+
+ condition := func(collect *CollectT) {
+ collect.FailNow()
+ }
+
+ False(t, EventuallyWithT(mockT, condition, 100*time.Millisecond, 20*time.Millisecond))
+ Len(t, mockT.errors, 1)
+}
+
func TestNeverFalse(t *testing.T) {
condition := func() bool {
return false
@@ -3172,7 +3347,6 @@ func TestNotErrorIs(t *testing.T) {
}
func TestErrorAs(t *testing.T) {
- mockT := new(testing.T)
tests := []struct {
err error
result bool
@@ -3185,9 +3359,38 @@ func TestErrorAs(t *testing.T) {
tt := tt
var target *customError
t.Run(fmt.Sprintf("ErrorAs(%#v,%#v)", tt.err, target), func(t *testing.T) {
+ mockT := new(testing.T)
res := ErrorAs(mockT, tt.err, &target)
if res != tt.result {
- t.Errorf("ErrorAs(%#v,%#v) should return %t)", tt.err, target, tt.result)
+ t.Errorf("ErrorAs(%#v,%#v) should return %t", tt.err, target, tt.result)
+ }
+ if res == mockT.Failed() {
+ t.Errorf("The test result (%t) should be reflected in the testing.T type (%t)", res, !mockT.Failed())
+ }
+ })
+ }
+}
+
+func TestNotErrorAs(t *testing.T) {
+ tests := []struct {
+ err error
+ result bool
+ }{
+ {fmt.Errorf("wrap: %w", &customError{}), false},
+ {io.EOF, true},
+ {nil, true},
+ }
+ for _, tt := range tests {
+ tt := tt
+ var target *customError
+ t.Run(fmt.Sprintf("NotErrorAs(%#v,%#v)", tt.err, target), func(t *testing.T) {
+ mockT := new(testing.T)
+ res := NotErrorAs(mockT, tt.err, &target)
+ if res != tt.result {
+ t.Errorf("NotErrorAs(%#v,%#v) should not return %t", tt.err, target, tt.result)
+ }
+ if res == mockT.Failed() {
+ t.Errorf("The test result (%t) should be reflected in the testing.T type (%t)", res, !mockT.Failed())
}
})
}
diff --git a/assert/yaml/yaml_custom.go b/assert/yaml/yaml_custom.go
new file mode 100644
index 000000000..baa0cc7d7
--- /dev/null
+++ assert/yaml/yaml_custom.go
@@ -0,0 +1,25 @@
+//go:build testify_yaml_custom && !testify_yaml_fail && !testify_yaml_default
+// +build testify_yaml_custom,!testify_yaml_fail,!testify_yaml_default
+
+// Package yaml is an implementation of YAML functions that calls a pluggable implementation.
+//
+// This implementation is selected with the testify_yaml_custom build tag.
+//
+// go test -tags testify_yaml_custom
+//
+// This implementation can be used at build time to replace the default implementation
+// to avoid linking with [gopkg.in/yaml.v3].
+//
+// In your test package:
+//
+// import assertYaml "github.com/stretchr/testify/assert/yaml"
+//
+// func init() {
+// assertYaml.Unmarshal = func (in []byte, out interface{}) error {
+// // ...
+// return nil
+// }
+// }
+package yaml
+
+var Unmarshal func(in []byte, out interface{}) error
diff --git a/assert/yaml/yaml_default.go b/assert/yaml/yaml_default.go
new file mode 100644
index 000000000..b83c6cf64
--- /dev/null
+++ assert/yaml/yaml_default.go
@@ -0,0 +1,37 @@
+//go:build !testify_yaml_fail && !testify_yaml_custom
+// +build !testify_yaml_fail,!testify_yaml_custom
+
+// Package yaml is just an indirection to handle YAML deserialization.
+//
+// This package is just an indirection that allows the builder to override the
+// indirection with an alternative implementation of this package that uses
+// another implementation of YAML deserialization. This allows to not either not
+// use YAML deserialization at all, or to use another implementation than
+// [gopkg.in/yaml.v3] (for example for license compatibility reasons, see [PR #1120]).
+//
+// Alternative implementations are selected using build tags:
+//
+// - testify_yaml_fail: [Unmarshal] always fails with an error
+// - testify_yaml_custom: [Unmarshal] is a variable. Caller must initialize it
+// before calling any of [github.com/stretchr/testify/assert.YAMLEq] or
+// [github.com/stretchr/testify/assert.YAMLEqf].
+//
+// Usage:
+//
+// go test -tags testify_yaml_fail
+//
+// You can check with "go list" which implementation is linked:
+//
+// go list -f '{{.Imports}}' github.com/stretchr/testify/assert/yaml
+// go list -tags testify_yaml_fail -f '{{.Imports}}' github.com/stretchr/testify/assert/yaml
+// go list -tags testify_yaml_custom -f '{{.Imports}}' github.com/stretchr/testify/assert/yaml
+//
+// [PR #1120]: https://github.com/stretchr/testify/pull/1120
+package yaml
+
+import goyaml "gopkg.in/yaml.v3"
+
+// Unmarshal is just a wrapper of [gopkg.in/yaml.v3.Unmarshal].
+func Unmarshal(in []byte, out interface{}) error {
+ return goyaml.Unmarshal(in, out)
+}
diff --git a/assert/yaml/yaml_fail.go b/assert/yaml/yaml_fail.go
new file mode 100644
index 000000000..e78f7dfe6
--- /dev/null
+++ assert/yaml/yaml_fail.go
@@ -0,0 +1,18 @@
+//go:build testify_yaml_fail && !testify_yaml_custom && !testify_yaml_default
+// +build testify_yaml_fail,!testify_yaml_custom,!testify_yaml_default
+
+// Package yaml is an implementation of YAML functions that always fail.
+//
+// This implementation can be used at build time to replace the default implementation
+// to avoid linking with [gopkg.in/yaml.v3]:
+//
+// go test -tags testify_yaml_fail
+package yaml
+
+import "errors"
+
+var errNotImplemented = errors.New("YAML functions are not available (see https://pkg.go.dev/github.com/stretchr/testify/assert/yaml)")
+
+func Unmarshal([]byte, interface{}) error {
+ return errNotImplemented
+}
diff --git doc.go doc.go
index aac5ef34b..babc122f2 100644
--- doc.go
+++ doc.go
@@ -1,4 +1,3 @@
-// ** We are working on testify v2 and would love to hear what you'd like to see in it, have your say here: https://cutt.ly/testify **
// Package testify is a set of packages that provide many tools for testifying that your code will behave as you intend.
//
// testify contains the following packages:
@@ -8,4 +7,9 @@
// The mock package provides a system by which it is possible to mock your objects and verify calls are happening as expected.
//
// The suite package provides a basic structure for using structs as testing suites, and methods on those structs as tests. It includes setup/teardown functionality in the way of interfaces.
+//
+// A [golangci-lint] compatible linter for testify is available called [testifylint].
+//
+// [golangci-lint]: https://golangci-lint.run/
+// [testifylint]: https://github.com/Antonboom/testifylint
package testify
diff --git mock/mock.go mock/mock.go
index 213bde2ea..eb5682df9 100644
--- mock/mock.go
+++ mock/mock.go
@@ -80,12 +80,12 @@ type Call struct {
requires []*Call
}
-func newCall(parent *Mock, methodName string, callerInfo []string, methodArguments ...interface{}) *Call {
+func newCall(parent *Mock, methodName string, callerInfo []string, methodArguments Arguments, returnArguments Arguments) *Call {
return &Call{
Parent: parent,
Method: methodName,
Arguments: methodArguments,
- ReturnArguments: make([]interface{}, 0),
+ ReturnArguments: returnArguments,
callerInfo: callerInfo,
Repeatability: 0,
WaitFor: nil,
@@ -256,7 +256,7 @@ func (c *Call) Unset() *Call {
// calls have been called as expected. The referenced calls may be from the
// same mock instance and/or other mock instances.
//
-// Mock.On("Do").Return(nil).Notbefore(
+// Mock.On("Do").Return(nil).NotBefore(
// Mock.On("Init").Return(nil)
// )
func (c *Call) NotBefore(calls ...*Call) *Call {
@@ -273,6 +273,20 @@ func (c *Call) NotBefore(calls ...*Call) *Call {
return c
}
+// InOrder defines the order in which the calls should be made
+//
+// For example:
+//
+// InOrder(
+// Mock.On("init").Return(nil),
+// Mock.On("Do").Return(nil),
+// )
+func InOrder(calls ...*Call) {
+ for i := 1; i < len(calls); i++ {
+ calls[i].NotBefore(calls[i-1])
+ }
+}
+
// Mock is the workhorse used to track activity on another object.
// For an example of its usage, refer to the "Example Usage" section at the top
// of this document.
@@ -351,7 +365,8 @@ func (m *Mock) On(methodName string, arguments ...interface{}) *Call {
m.mutex.Lock()
defer m.mutex.Unlock()
- c := newCall(m, methodName, assert.CallerInfo(), arguments...)
+
+ c := newCall(m, methodName, assert.CallerInfo(), arguments, make([]interface{}, 0))
m.ExpectedCalls = append(m.ExpectedCalls, c)
return c
}
@@ -491,11 +506,12 @@ func (m *Mock) MethodCalled(methodName string, arguments ...interface{}) Argumen
m.mutex.Unlock()
if closestCall != nil {
- m.fail("\n\nmock: Unexpected Method Call\n-----------------------------\n\n%s\n\nThe closest call I have is: \n\n%s\n\n%s\nDiff: %s",
+ m.fail("\n\nmock: Unexpected Method Call\n-----------------------------\n\n%s\n\nThe closest call I have is: \n\n%s\n\n%s\nDiff: %s\nat: %s\n",
callString(methodName, arguments, true),
callString(methodName, closestCall.Arguments, true),
diffArguments(closestCall.Arguments, arguments),
strings.TrimSpace(mismatch),
+ assert.CallerInfo(),
)
} else {
m.fail("\nassert: mock: I don't know what to return because the method call was unexpected.\n\tEither do Mock.On(\"%s\").Return(...) first, or remove the %s() call.\n\tThis method was unexpected:\n\t\t%s\n\tat: %s", methodName, methodName, callString(methodName, arguments, true), assert.CallerInfo())
@@ -529,7 +545,7 @@ func (m *Mock) MethodCalled(methodName string, arguments ...interface{}) Argumen
call.totalCalls++
// add the call
- m.Calls = append(m.Calls, *newCall(m, methodName, assert.CallerInfo(), arguments...))
+ m.Calls = append(m.Calls, *newCall(m, methodName, assert.CallerInfo(), arguments, call.ReturnArguments))
m.mutex.Unlock()
// block if specified
@@ -764,9 +780,17 @@ const (
)
// AnythingOfTypeArgument contains the type of an argument
-// for use when type checking. Used in Diff and Assert.
+// for use when type checking. Used in [Arguments.Diff] and [Arguments.Assert].
//
-// Deprecated: this is an implementation detail that must not be used. Use [AnythingOfType] instead.
+// Deprecated: this is an implementation detail that must not be used. Use the [AnythingOfType] constructor instead, example:
+//
+// m.On("Do", mock.AnythingOfType("string"))
+//
+// All explicit type declarations can be replaced with interface{} as is expected by [Mock.On], example:
+//
+// func anyString interface{} {
+// return mock.AnythingOfType("string")
+// }
type AnythingOfTypeArgument = anythingOfTypeArgument
// anythingOfTypeArgument is a string that contains the type of an argument
@@ -780,53 +804,54 @@ type anythingOfTypeArgument string
//
// For example:
//
-// Assert(t, AnythingOfType("string"), AnythingOfType("int"))
+// args.Assert(t, AnythingOfType("string"), AnythingOfType("int"))
func AnythingOfType(t string) AnythingOfTypeArgument {
return anythingOfTypeArgument(t)
}
// IsTypeArgument is a struct that contains the type of an argument
-// for use when type checking. This is an alternative to AnythingOfType.
-// Used in Diff and Assert.
+// for use when type checking. This is an alternative to [AnythingOfType].
+// Used in [Arguments.Diff] and [Arguments.Assert].
type IsTypeArgument struct {
t reflect.Type
}
// IsType returns an IsTypeArgument object containing the type to check for.
// You can provide a zero-value of the type to check. This is an
-// alternative to AnythingOfType. Used in Diff and Assert.
+// alternative to [AnythingOfType]. Used in [Arguments.Diff] and [Arguments.Assert].
//
// For example:
-// Assert(t, IsType(""), IsType(0))
+//
+// args.Assert(t, IsType(""), IsType(0))
func IsType(t interface{}) *IsTypeArgument {
return &IsTypeArgument{t: reflect.TypeOf(t)}
}
-// FunctionalOptionsArgument is a struct that contains the type and value of an functional option argument
-// for use when type checking.
+// FunctionalOptionsArgument contains a list of functional options arguments
+// expected for use when matching a list of arguments.
type FunctionalOptionsArgument struct {
- value interface{}
+ values []interface{}
}
// String returns the string representation of FunctionalOptionsArgument
func (f *FunctionalOptionsArgument) String() string {
var name string
- tValue := reflect.ValueOf(f.value)
- if tValue.Len() > 0 {
- name = "[]" + reflect.TypeOf(tValue.Index(0).Interface()).String()
+ if len(f.values) > 0 {
+ name = "[]" + reflect.TypeOf(f.values[0]).String()
}
- return strings.Replace(fmt.Sprintf("%#v", f.value), "[]interface {}", name, 1)
+ return strings.Replace(fmt.Sprintf("%#v", f.values), "[]interface {}", name, 1)
}
-// FunctionalOptions returns an FunctionalOptionsArgument object containing the functional option type
-// and the values to check of
+// FunctionalOptions returns an [FunctionalOptionsArgument] object containing
+// the expected functional-options to check for.
//
// For example:
-// Assert(t, FunctionalOptions("[]foo.FunctionalOption", foo.Opt1(), foo.Opt2()))
-func FunctionalOptions(value ...interface{}) *FunctionalOptionsArgument {
+//
+// args.Assert(t, FunctionalOptions(foo.Opt1("strValue"), foo.Opt2(613)))
+func FunctionalOptions(values ...interface{}) *FunctionalOptionsArgument {
return &FunctionalOptionsArgument{
- value: value,
+ values: values,
}
}
@@ -873,10 +898,11 @@ func (f argumentMatcher) String() string {
// and false otherwise.
//
// Example:
-// m.On("Do", MatchedBy(func(req *http.Request) bool { return req.Host == "example.com" }))
//
-// |fn|, must be a function accepting a single argument (of the expected type)
-// which returns a bool. If |fn| doesn't match the required signature,
+// m.On("Do", MatchedBy(func(req *http.Request) bool { return req.Host == "example.com" }))
+//
+// fn must be a function accepting a single argument (of the expected type)
+// which returns a bool. If fn doesn't match the required signature,
// MatchedBy() panics.
func MatchedBy(fn interface{}) argumentMatcher {
fnType := reflect.TypeOf(fn)
@@ -979,20 +1005,17 @@ func (args Arguments) Diff(objects []interface{}) (string, int) {
output = fmt.Sprintf("%s\t%d: FAIL: type %s != type %s - %s\n", output, i, expected.t.Name(), actualT.Name(), actualFmt)
}
case *FunctionalOptionsArgument:
- t := expected.value
-
var name string
- tValue := reflect.ValueOf(t)
- if tValue.Len() > 0 {
- name = "[]" + reflect.TypeOf(tValue.Index(0).Interface()).String()
+ if len(expected.values) > 0 {
+ name = "[]" + reflect.TypeOf(expected.values[0]).String()
}
- tName := reflect.TypeOf(t).Name()
- if name != reflect.TypeOf(actual).String() && tValue.Len() != 0 {
+ const tName = "[]interface{}"
+ if name != reflect.TypeOf(actual).String() && len(expected.values) != 0 {
differences++
output = fmt.Sprintf("%s\t%d: FAIL: type %s != type %s - %s\n", output, i, tName, reflect.TypeOf(actual).Name(), actualFmt)
} else {
- if ef, af := assertOpts(t, actual); ef == "" && af == "" {
+ if ef, af := assertOpts(expected.values, actual); ef == "" && af == "" {
// match
output = fmt.Sprintf("%s\t%d: PASS: %s == %s\n", output, i, tName, tName)
} else {
@@ -1092,7 +1115,7 @@ func (args Arguments) Error(index int) error {
return nil
}
if s, ok = obj.(error); !ok {
- panic(fmt.Sprintf("assert: arguments: Error(%d) failed because object wasn't correct type: %v", index, args.Get(index)))
+ panic(fmt.Sprintf("assert: arguments: Error(%d) failed because object wasn't correct type: %v", index, obj))
}
return s
}
@@ -1181,32 +1204,38 @@ type tHelper interface {
func assertOpts(expected, actual interface{}) (expectedFmt, actualFmt string) {
expectedOpts := reflect.ValueOf(expected)
actualOpts := reflect.ValueOf(actual)
+
+ var expectedFuncs []*runtime.Func
var expectedNames []string
for i := 0; i < expectedOpts.Len(); i++ {
- expectedNames = append(expectedNames, funcName(expectedOpts.Index(i).Interface()))
+ f := runtimeFunc(expectedOpts.Index(i).Interface())
+ expectedFuncs = append(expectedFuncs, f)
+ expectedNames = append(expectedNames, funcName(f))
}
+ var actualFuncs []*runtime.Func
var actualNames []string
for i := 0; i < actualOpts.Len(); i++ {
- actualNames = append(actualNames, funcName(actualOpts.Index(i).Interface()))
+ f := runtimeFunc(actualOpts.Index(i).Interface())
+ actualFuncs = append(actualFuncs, f)
+ actualNames = append(actualNames, funcName(f))
}
- if !assert.ObjectsAreEqual(expectedNames, actualNames) {
+
+ if expectedOpts.Len() != actualOpts.Len() {
expectedFmt = fmt.Sprintf("%v", expectedNames)
actualFmt = fmt.Sprintf("%v", actualNames)
return
}
for i := 0; i < expectedOpts.Len(); i++ {
- expectedOpt := expectedOpts.Index(i).Interface()
- actualOpt := actualOpts.Index(i).Interface()
-
- expectedFunc := expectedNames[i]
- actualFunc := actualNames[i]
- if expectedFunc != actualFunc {
- expectedFmt = expectedFunc
- actualFmt = actualFunc
+ if !isFuncSame(expectedFuncs[i], actualFuncs[i]) {
+ expectedFmt = expectedNames[i]
+ actualFmt = actualNames[i]
return
}
+ expectedOpt := expectedOpts.Index(i).Interface()
+ actualOpt := actualOpts.Index(i).Interface()
+
ot := reflect.TypeOf(expectedOpt)
var expectedValues []reflect.Value
var actualValues []reflect.Value
@@ -1224,9 +1253,9 @@ func assertOpts(expected, actual interface{}) (expectedFmt, actualFmt string) {
reflect.ValueOf(actualOpt).Call(actualValues)
for i := 0; i < ot.NumIn(); i++ {
- if !assert.ObjectsAreEqual(expectedValues[i].Interface(), actualValues[i].Interface()) {
- expectedFmt = fmt.Sprintf("%s %+v", expectedNames[i], expectedValues[i].Interface())
- actualFmt = fmt.Sprintf("%s %+v", expectedNames[i], actualValues[i].Interface())
+ if expectedArg, actualArg := expectedValues[i].Interface(), actualValues[i].Interface(); !assert.ObjectsAreEqual(expectedArg, actualArg) {
+ expectedFmt = fmt.Sprintf("%s(%T) -> %#v", expectedNames[i], expectedArg, expectedArg)
+ actualFmt = fmt.Sprintf("%s(%T) -> %#v", expectedNames[i], actualArg, actualArg)
return
}
}
@@ -1235,7 +1264,25 @@ func assertOpts(expected, actual interface{}) (expectedFmt, actualFmt string) {
return "", ""
}
-func funcName(opt interface{}) string {
- n := runtime.FuncForPC(reflect.ValueOf(opt).Pointer()).Name()
- return strings.TrimSuffix(path.Base(n), path.Ext(n))
+func runtimeFunc(opt interface{}) *runtime.Func {
+ return runtime.FuncForPC(reflect.ValueOf(opt).Pointer())
+}
+
+func funcName(f *runtime.Func) string {
+ name := f.Name()
+ trimmed := strings.TrimSuffix(path.Base(name), path.Ext(name))
+ splitted := strings.Split(trimmed, ".")
+
+ if len(splitted) == 0 {
+ return trimmed
+ }
+
+ return splitted[len(splitted)-1]
+}
+
+func isFuncSame(f1, f2 *runtime.Func) bool {
+ f1File, f1Loc := f1.FileLine(f1.Entry())
+ f2File, f2Loc := f2.FileLine(f2.Entry())
+
+ return f1File == f2File && f1Loc == f2Loc
}
diff --git mock/mock_test.go mock/mock_test.go
index b80a8a75b..04664d44b 100644
--- mock/mock_test.go
+++ mock/mock_test.go
@@ -50,11 +50,22 @@ func OpStr(s string) OptionFn {
o.str = s
}
}
+
+func OpBytes(b []byte) OptionFn {
+ return func(m *options) {
+ m.str = string(b)
+ }
+}
+
func (i *TestExampleImplementation) TheExampleMethodFunctionalOptions(x string, opts ...OptionFn) error {
args := i.Called(x, opts)
return args.Error(0)
}
+func TheExampleMethodFunctionalOptionsIndirect(i *TestExampleImplementation) {
+ i.TheExampleMethodFunctionalOptions("test", OpNum(1), OpStr("foo"))
+}
+
//go:noinline
func (i *TestExampleImplementation) TheExampleMethod2(yesorno bool) {
i.Called(yesorno)
@@ -937,6 +948,26 @@ func Test_Mock_Return_NotBefore_In_Order(t *testing.T) {
})
}
+func Test_Mock_Return_InOrder_Uses_NotBefore(t *testing.T) {
+ var mockedService = new(TestExampleImplementation)
+
+ InOrder(
+ mockedService.
+ On("TheExampleMethod", 1, 2, 3).
+ Return(4, nil),
+ mockedService.
+ On("TheExampleMethod2", true).
+ Return(),
+ )
+
+ require.NotPa,nics(t, func() {
+ mockedService.TheExampleMethod(1, 2, 3)
+ })
+ require.NotPanics(t, func() {
+ mockedService.TheExampleMethod2(true)
+ })
+}
+
func Test_Mock_Return_NotBefore_Out_Of_Order(t *testing.T) {
var mockedService = new(TestExampleImplementation)
@@ -967,6 +998,35 @@ TheExampleMethod(int,int,int)
})
}
+func Test_Mock_Return_InOrder_Uses_NotBefore_Out_Of_Order(t *testing.T) {
+ var mockedService = new(TestExampleImplementation)
+
+ InOrder(
+ mockedService.
+ On("TheExampleMethod", 1, 2, 3).
+ Return(4, nil).Twice(),
+ mockedService.
+ On("TheExampleMethod2", true).
+ Return(),
+ )
+
+ expectedPanicString := `mock: Unexpected Method Call
+-----------------------------
+
+TheExampleMethod2(bool)
+ 0: true
+
+Must not be called before:
+
+TheExampleMethod(int,int,int)
+ 0: 1
+ 1: 2
+ 2: 3`
+ require.PanicsWithValue(t, expectedPanicString, func() {
+ mockedService.TheExampleMethod2(true)
+ })
+}
+
func Test_Mock_Return_NotBefore_Not_Enough_Times(t *testing.T) {
var mockedService = new(TestExampleImplementation)
@@ -1022,6 +1082,7 @@ func Test_Mock_Return_NotBefore_Different_Mock_In_Order(t *testing.T) {
mockedService2.TheExampleMethod2(true)
})
}
+
func Test_Mock_Return_NotBefore_Different_Mock_Out_Of_Order(t *testing.T) {
var (
mockedService1 = new(TestExampleImplementation)
@@ -1206,7 +1267,7 @@ func Test_Mock_Called_blocks(t *testing.T) {
var mockedService = new(TestExampleImplementation)
- mockedService.Mock.On("asyncCall", 1, 2, 3).Return(5, "6", true).After(2 * time.Millisecond)
+ mockedService.Mock.On("asyncCall", 1, 2, 3).Return(5, "6", true).After(20 * time.Millisecond)
ch := make(chan Arguments)
@@ -1215,7 +1276,7 @@ func Test_Mock_Called_blocks(t *testing.T) {
select {
case <-ch:
t.Fatal("should have waited")
- case <-time.After(1 * time.Millisecond):
+ case <-time.After(10 * time.Millisecond):
}
returnArguments := <-ch
@@ -1472,6 +1533,51 @@ func Test_Mock_AssertExpectationsFunctionalOptionsType_Empty(t *testing.T) {
}
+func Test_Mock_AssertExpectationsFunctionalOptionsType_Indirectly(t *testing.T) {
+
+ var mockedService = new(TestExampleImplementation)
+
+ mockedService.On("TheExampleMethodFunctionalOptions", "test", FunctionalOptions(OpNum(1), OpStr("foo"))).Return(nil).Once()
+
+ tt := new(testing.T)
+ assert.False(t, mockedService.AssertExpectations(tt))
+
+ // make the call now
+ TheExampleMethodFunctionalOptionsIndirect(mockedService)
+
+ // now assert expectations
+ assert.True(t, mockedService.AssertExpectations(tt))
+
+}
+
+func Test_Mock_AssertExpectationsFunctionalOptionsType_Diff_Func(t *testing.T) {
+
+ var mockedService = new(TestExampleImplementation)
+
+ mockedService.On("TheExampleMethodFunctionalOptions", "test", FunctionalOptions(OpStr("this"))).Return(nil).Once()
+
+ tt := new(testing.T)
+ assert.False(t, mockedService.AssertExpectations(tt))
+
+ assert.Panics(t, func() {
+ mockedService.TheExampleMethodFunctionalOptions("test", OpBytes([]byte("this")))
+ })
+}
+
+func Test_Mock_AssertExpectationsFunctionalOptionsType_Diff_Arg(t *testing.T) {
+
+ var mockedService = new(TestExampleImplementation)
+
+ mockedService.On("TheExampleMethodFunctionalOptions", "test", FunctionalOptions(OpStr("this"))).Return(nil).Once()
+
+ tt := new(testing.T)
+ assert.False(t, mockedService.AssertExpectations(tt))
+
+ assert.Panics(t, func() {
+ mockedService.TheExampleMethodFunctionalOptions("test", OpStr("that"))
+ })
+}
+
func Test_Mock_AssertExpectations_With_Repeatability(t *testing.T) {
var mockedService = new(TestExampleImplementation)
@@ -1980,7 +2086,7 @@ func TestArgumentMatcherToPrintMismatch(t *testing.T) {
defer func() {
if r := recover(); r != nil {
matchingExp := regexp.MustCompile(
- `\s+mock: Unexpected Method Call\s+-*\s+GetTime\(int\)\s+0: 1\s+The closest call I have is:\s+GetTime\(mock.argumentMatcher\)\s+0: mock.argumentMatcher\{.*?\}\s+Diff:.*\(int=1\) not matched by func\(int\) bool`)
+ `\s+mock: Unexpected Method Call\s+-*\s+GetTime\(int\)\s+0: 1\s+The closest call I have is:\s+GetTime\(mock.argumentMatcher\)\s+0: mock.argumentMatcher\{.*?\}\s+Diff:.*\(int=1\) not matched by func\(int\) bool\nat: \[[^\]]+mock\/mock_test.go`)
assert.Regexp(t, matchingExp, r)
}
}()
@@ -1997,7 +2103,7 @@ func TestArgumentMatcherToPrintMismatchWithReferenceType(t *testing.T) {
defer func() {
if r := recover(); r != nil {
matchingExp := regexp.MustCompile(
- `\s+mock: Unexpected Method Call\s+-*\s+GetTimes\(\[\]int\)\s+0: \[\]int\{1\}\s+The closest call I have is:\s+GetTimes\(mock.argumentMatcher\)\s+0: mock.argumentMatcher\{.*?\}\s+Diff:.*\(\[\]int=\[1\]\) not matched by func\(\[\]int\) bool`)
+ `\s+mock: Unexpected Method Call\s+-*\s+GetTimes\(\[\]int\)\s+0: \[\]int\{1\}\s+The closest call I have is:\s+GetTimes\(mock.argumentMatcher\)\s+0: mock.argumentMatcher\{.*?\}\s+Diff:.*\(\[\]int=\[1\]\) not matched by func\(\[\]int\) bool\nat: \[[^\]]+mock\/mock_test.go`)
assert.Regexp(t, matchingExp, r)
}
}()
@@ -2028,7 +2134,7 @@ func TestClosestCallMismatchedArgumentInformationShowsTheClosest(t *testing.T) {
func TestClosestCallFavorsFirstMock(t *testing.T) {
defer func() {
if r := recover(); r != nil {
- diffRegExp := `Difference found in argument 0:\s+--- Expected\s+\+\+\+ Actual\s+@@ -2,4 \+2,4 @@\s+\(bool\) true,\s+- \(bool\) true,\s+- \(bool\) true\s+\+ \(bool\) false,\s+\+ \(bool\) false\s+}\s+`
+ diffRegExp := `Difference found in argument 0:\s+--- Expected\s+\+\+\+ Actual\s+@@ -2,4 \+2,4 @@\s+\(bool\) true,\s+- \(bool\) true,\s+- \(bool\) true\s+\+ \(bool\) false,\s+\+ \(bool\) false\s+}\s+Diff: 0: FAIL: \(\[\]bool=\[(true\s?|false\s?){3}]\) != \(\[\]bool=\[(true\s?|false\s?){3}\]\)`
matchingExp := regexp.MustCompile(unexpectedCallRegex(`TheExampleMethod7([]bool)`, `0: \[\]bool{true, false, false}`, `0: \[\]bool{true, true, true}`, diffRegExp))
assert.Regexp(t, matchingExp, r)
}
@@ -2044,7 +2150,7 @@ func TestClosestCallFavorsFirstMock(t *testing.T) {
func TestClosestCallUsesRepeatabilityToFindClosest(t *testing.T) {
defer func() {
if r := recover(); r != nil {
- diffRegExp := `Difference found in argument 0:\s+--- Expected\s+\+\+\+ Actual\s+@@ -1,4 \+1,4 @@\s+\(\[\]bool\) \(len=3\) {\s+- \(bool\) false,\s+- \(bool\) false,\s+\+ \(bool\) true,\s+\+ \(bool\) true,\s+\(bool\) false\s+`
+ diffRegExp := `Difference found in argument 0:\s+--- Expected\s+\+\+\+ Actual\s+@@ -1,4 \+1,4 @@\s+\(\[\]bool\) \(len=3\) {\s+- \(bool\) false,\s+- \(bool\) false,\s+\+ \(bool\) true,\s+\+ \(bool\) true,\s+\(bool\) false\s+Diff: 0: FAIL: \(\[\]bool=\[(true\s?|false\s?){3}]\) != \(\[\]bool=\[(true\s?|false\s?){3}\]\)`
matchingExp := regexp.MustCompile(unexpectedCallRegex(`TheExampleMethod7([]bool)`, `0: \[\]bool{true, true, false}`, `0: \[\]bool{false, false, false}`, diffRegExp))
assert.Regexp(t, matchingExp, r)
}
@@ -2101,7 +2207,7 @@ func Test_isBetterMatchThanReturnsFalseIfRepeatabilityIsLessThanOrEqualToOther(t
func unexpectedCallRegex(method, calledArg, expectedArg, diff string) string {
rMethod := regexp.QuoteMeta(method)
- return fmt.Sprintf(`\s+mock: Unexpected Method Call\s+-*\s+%s\s+%s\s+The closest call I have is:\s+%s\s+%s\s+%s`,
+ return fmt.Sprintf(`\s+mock: Unexpected Method Call\s+-*\s+%s\s+%s\s+The closest call I have is:\s+%s\s+%s\s+%s\nat: \[[^\]]+mock\/mock_test.go`,
rMethod, calledArg, rMethod, expectedArg, diff)
}
diff --git require/require.go require/require.go
index 506a82f80..d8921950d 100644
--- require/require.go
+++ require/require.go
@@ -34,9 +34,9 @@ func Conditionf(t TestingT, comp assert.Comparison, msg string, args ...interfac
// Contains asserts that the specified string, list(array, slice...) or map contains the
// specified substring or element.
//
-// assert.Contains(t, "Hello World", "World")
-// assert.Contains(t, ["Hello", "World"], "World")
-// assert.Contains(t, {"Hello": "World"}, "Hello")
+// require.Contains(t, "Hello World", "World")
+// require.Contains(t, ["Hello", "World"], "World")
+// require.Contains(t, {"Hello": "World"}, "Hello")
func Contains(t TestingT, s interface{}, contains interface{}, msgAndArgs ...interface{}) {
if h, ok := t.(tHelper); ok {
h.Helper()
@@ -50,9 +50,9 @@ func Contains(t TestingT, s interface{}, contains interface{}, msgAndArgs ...int
// Containsf asserts that the specified string, list(array, slice...) or map contains the
// specified substring or element.
//
-// assert.Containsf(t, "Hello World", "World", "error message %s", "formatted")
-// assert.Containsf(t, ["Hello", "World"], "World", "error message %s", "formatted")
-// assert.Containsf(t, {"Hello": "World"}, "Hello", "error message %s", "formatted")
+// require.Containsf(t, "Hello World", "World", "error message %s", "formatted")
+// require.Containsf(t, ["Hello", "World"], "World", "error message %s", "formatted")
+// require.Containsf(t, {"Hello": "World"}, "Hello", "error message %s", "formatted")
func Containsf(t TestingT, s interface{}, contains interface{}, msg string, args ...interface{}) {
if h, ok := t.(tHelper); ok {
h.Helper()
@@ -91,7 +91,7 @@ func DirExistsf(t TestingT, path string, msg string, args ...interface{}) {
// listB(array, slice...) ignoring the order of the elements. If there are duplicate elements,
// the number of appearances of each of them in both lists should match.
//
-// assert.ElementsMatch(t, [1, 3, 2, 3], [1, 3, 3, 2])
+// require.ElementsMatch(t, [1, 3, 2, 3], [1, 3, 3, 2])
func ElementsMatch(t TestingT, listA interface{}, listB interface{}, msgAndArgs ...interface{}) {
if h, ok := t.(tHelper); ok {
h.Helper()
@@ -106,7 +106,7 @@ func ElementsMatch(t TestingT, listA interface{}, listB interface{}, msgAndArgs
// listB(array, slice...) ignoring the order of the elements. If there are duplicate elements,
// the number of appearances of each of them in both lists should match.
//
-// assert.ElementsMatchf(t, [1, 3, 2, 3], [1, 3, 3, 2], "error message %s", "formatted")
+// require.ElementsMatchf(t, [1, 3, 2, 3], [1, 3, 3, 2], "error message %s", "formatted")
func ElementsMatchf(t TestingT, listA interface{}, listB interface{}, msg string, args ...interface{}) {
if h, ok := t.(tHelper); ok {
h.Helper()
@@ -120,7 +120,7 @@ func ElementsMatchf(t TestingT, listA interface{}, listB interface{}, msg string
// Empty asserts that the specified object is empty. I.e. nil, "", false, 0 or either
// a slice or a channel with len == 0.
//
-// assert.Empty(t, obj)
+// require.Empty(t, obj)
func Empty(t TestingT, object interface{}, msgAndArgs ...interface{}) {
if h, ok := t.(tHelper); ok {
h.Helper()
@@ -134,7 +134,7 @@ func Empty(t TestingT, object interface{}, msgAndArgs ...interface{}) {
// Emptyf asserts that the specified object is empty. I.e. nil, "", false, 0 or either
// a slice or a channel with len == 0.
//
-// assert.Emptyf(t, obj, "error message %s", "formatted")
+// require.Emptyf(t, obj, "error message %s", "formatted")
func Emptyf(t TestingT, object interface{}, msg string, args ...interface{}) {
if h, ok := t.(tHelper); ok {
h.Helper()
@@ -147,7 +147,7 @@ func Emptyf(t TestingT, object interface{}, msg string, args ...interface{}) {
// Equal asserts that two objects are equal.
//
-// assert.Equal(t, 123, 123)
+// require.Equal(t, 123, 123)
//
// Pointer variable equality is determined based on the equality of the
// referenced values (as opposed to the memory addresses). Function equality
@@ -166,7 +166,7 @@ func Equal(t TestingT, expected interface{}, actual interface{}, msgAndArgs ...i
// and that it is equal to the provided error.
//
// actualObj, err := SomeFunction()
-// assert.EqualError(t, err, expectedErrorString)
+// require.EqualError(t, err, expectedErrorString)
func EqualError(t TestingT, theError error, errString string, msgAndArgs ...interface{}) {
if h, ok := t.(tHelper); ok {
h.Helper()
@@ -181,7 +181,7 @@ func EqualError(t TestingT, theError error, errString string, msgAndArgs ...inte
// and that it is equal to the provided error.
//
// actualObj, err := SomeFunction()
-// assert.EqualErrorf(t, err, expectedErrorString, "error message %s", "formatted")
+// require.EqualErrorf(t, err, expectedErrorString, "error message %s", "formatted")
func EqualErrorf(t TestingT, theError error, errString string, msg string, args ...interface{}) {
if h, ok := t.(tHelper); ok {
h.Helper()
@@ -200,8 +200,8 @@ func EqualErrorf(t TestingT, theError error, errString string, msg string, args
// Exported int
// notExported int
// }
-// assert.EqualExportedValues(t, S{1, 2}, S{1, 3}) => true
-// assert.EqualExportedValues(t, S{1, 2}, S{2, 3}) => false
+// require.EqualExportedValues(t, S{1, 2}, S{1, 3}) => true
+// require.EqualExportedValues(t, S{1, 2}, S{2, 3}) => false
func EqualExportedValues(t TestingT, expected interface{}, actual interface{}, msgAndArgs ...interface{}) {
if h, ok := t.(tHelper); ok {
h.Helper()
@@ -220,8 +220,8 @@ func EqualExportedValues(t TestingT, expected interface{}, actual interface{}, m
// Exported int
// notExported int
// }
-// assert.EqualExportedValuesf(t, S{1, 2}, S{1, 3}, "error message %s", "formatted") => true
-// assert.EqualExportedValuesf(t, S{1, 2}, S{2, 3}, "error message %s", "formatted") => false
+// require.EqualExportedValuesf(t, S{1, 2}, S{1, 3}, "error message %s", "formatted") => true
+// require.EqualExportedValuesf(t, S{1, 2}, S{2, 3}, "error message %s", "formatted") => false
func EqualExportedValuesf(t TestingT, expected interface{}, actual interface{}, msg string, args ...interface{}) {
if h, ok := t.(tHelper); ok {
h.Helper()
@@ -232,10 +232,10 @@ func EqualExportedValuesf(t TestingT, expected interface{}, actual interface{},
t.FailNow()
}
-// EqualValues asserts that two objects are equal or convertible to the same types
-// and equal.
+// EqualValues asserts that two objects are equal or convertible to the larger
+// type and equal.
//
-// assert.EqualValues(t, uint32(123), int32(123))
+// require.EqualValues(t, uint32(123), int32(123))
func EqualValues(t TestingT, expected interface{}, actual interface{}, msgAndArgs ...interface{}) {
if h, ok := t.(tHelper); ok {
h.Helper()
@@ -246,10 +246,10 @@ func EqualValues(t TestingT, expected interface{}, actual interface{}, msgAndArg
t.FailNow()
}
-// EqualValuesf asserts that two objects are equal or convertible to the same types
-// and equal.
+// EqualValuesf asserts that two objects are equal or convertible to the larger
+// type and equal.
//
-// assert.EqualValuesf(t, uint32(123), int32(123), "error message %s", "formatted")
+// require.EqualValuesf(t, uint32(123), int32(123), "error message %s", "formatted")
func EqualValuesf(t TestingT, expected interface{}, actual interface{}, msg string, args ...interface{}) {
if h, ok := t.(tHelper); ok {
h.Helper()
@@ -262,7 +262,7 @@ func EqualValuesf(t TestingT, expected interface{}, actual interface{}, msg stri
// Equalf asserts that two objects are equal.
//
-// assert.Equalf(t, 123, 123, "error message %s", "formatted")
+// require.Equalf(t, 123, 123, "error message %s", "formatted")
//
// Pointer variable equality is determined based on the equality of the
// referenced values (as opposed to the memory addresses). Function equality
@@ -280,8 +280,8 @@ func Equalf(t TestingT, expected interface{}, actual interface{}, msg string, ar
// Error asserts that a function returned an error (i.e. not `nil`).
//
// actualObj, err := SomeFunction()
-// if assert.Error(t, err) {
-// assert.Equal(t, expectedError, err)
+// if require.Error(t, err) {
+// require.Equal(t, expectedError, err)
// }
func Error(t TestingT, err error, msgAndArgs ...interface{}) {
if h, ok := t.(tHelper); ok {
@@ -321,7 +321,7 @@ func ErrorAsf(t TestingT, err error, target interface{}, msg string, args ...int
// and that the error contains the specified substring.
//
// actualObj, err := SomeFunction()
-// assert.ErrorContains(t, err, expectedErrorSubString)
+// require.ErrorContains(t, err, expectedErrorSubString)
func ErrorContains(t TestingT, theError error, contains string, msgAndArgs ...interface{}) {
if h, ok := t.(tHelper); ok {
h.Helper()
@@ -336,7 +336,7 @@ func ErrorContains(t TestingT, theError error, contains string, msgAndArgs ...in
// and that the error contains the specified substring.
//
// actualObj, err := SomeFunction()
-// assert.ErrorContainsf(t, err, expectedErrorSubString, "error message %s", "formatted")
+// require.ErrorContainsf(t, err, expectedErrorSubString, "error message %s", "formatted")
func ErrorContainsf(t TestingT, theError error, contains string, msg string, args ...interface{}) {
if h, ok := t.(tHelper); ok {
h.Helper()
@@ -374,8 +374,8 @@ func ErrorIsf(t TestingT, err error, target error, msg string, args ...interface
// Errorf asserts that a function returned an error (i.e. not `nil`).
//
// actualObj, err := SomeFunction()
-// if assert.Errorf(t, err, "error message %s", "formatted") {
-// assert.Equal(t, expectedErrorf, err)
+// if require.Errorf(t, err, "error message %s", "formatted") {
+// require.Equal(t, expectedErrorf, err)
// }
func Errorf(t TestingT, err error, msg string, args ...interface{}) {
if h, ok := t.(tHelper); ok {
@@ -390,7 +390,7 @@ func Errorf(t TestingT, err error, msg string, args ...interface{}) {
// Eventually asserts that given condition will be met in waitFor time,
// periodically checking target function each tick.
//
-// assert.Eventually(t, func() bool { return true; }, time.Second, 10*time.Millisecond)
+// require.Eventually(t, func() bool { return true; }, time.Second, 10*time.Millisecond)
func Eventually(t TestingT, condition func() bool, waitFor time.Duration, tick time.Duration, msgAndArgs ...interface{}) {
if h, ok := t.(tHelper); ok {
h.Helper()
@@ -415,10 +415,10 @@ func Eventually(t TestingT, condition func() bool, waitFor time.Duration, tick t
// time.Sleep(8*time.Second)
// externalValue = true
// }()
-// assert.EventuallyWithT(t, func(c *assert.CollectT) {
+// require.EventuallyWithT(t, func(c *require.CollectT) {
// // add assertions as needed; any assertion failure will fail the current tick
-// assert.True(c, externalValue, "expected 'externalValue' to be true")
-// }, 1*time.Second, 10*time.Second, "external state has not changed to 'true'; still false")
+// require.True(c, externalValue, "expected 'externalValue' to be true")
+// }, 10*time.Second, 1*time.Second, "external state has not changed to 'true'; still false")
func EventuallyWithT(t TestingT, condition func(collect *assert.CollectT), waitFor time.Duration, tick time.Duration, msgAndArgs ...interface{}) {
if h, ok := t.(tHelper); ok {
h.Helper()
@@ -443,10 +443,10 @@ func EventuallyWithT(t TestingT, condition func(collect *assert.CollectT), waitF
// time.Sleep(8*time.Second)
// externalValue = true
// }()
-// assert.EventuallyWithTf(t, func(c *assert.CollectT, "error message %s", "formatted") {
+// require.EventuallyWithTf(t, func(c *require.CollectT, "error message %s", "formatted") {
// // add assertions as needed; any assertion failure will fail the current tick
-// assert.True(c, externalValue, "expected 'externalValue' to be true")
-// }, 1*time.Second, 10*time.Second, "external state has not changed to 'true'; still false")
+// require.True(c, externalValue, "expected 'externalValue' to be true")
+// }, 10*time.Second, 1*time.Second, "external state has not changed to 'true'; still false")
func EventuallyWithTf(t TestingT, condition func(collect *assert.CollectT), waitFor time.Duration, tick time.Duration, msg string, args ...interface{}) {
if h, ok := t.(tHelper); ok {
h.Helper()
@@ -460,7 +460,7 @@ func EventuallyWithTf(t TestingT, condition func(collect *assert.CollectT), wait
// Eventuallyf asserts that given condition will be met in waitFor time,
// periodically checking target function each tick.
//
-// assert.Eventuallyf(t, func() bool { return true; }, time.Second, 10*time.Millisecond, "error message %s", "formatted")
+// require.Eventuallyf(t, func() bool { return true; }, time.Second, 10*time.Millisecond, "error message %s", "formatted")
func Eventuallyf(t TestingT, condition func() bool, waitFor time.Duration, tick time.Duration, msg string, args ...interface{}) {
if h, ok := t.(tHelper); ok {
h.Helper()
@@ -473,7 +473,7 @@ func Eventuallyf(t TestingT, condition func() bool, waitFor time.Duration, tick
// Exactly asserts that two objects are equal in value and type.
//
-// assert.Exactly(t, int32(123), int64(123))
+// require.Exactly(t, int32(123), int64(123))
func Exactly(t TestingT, expected interface{}, actual interface{}, msgAndArgs ...interface{}) {
if h, ok := t.(tHelper); ok {
h.Helper()
@@ -486,7 +486,7 @@ func Exactly(t TestingT, expected interface{}, actual interface{}, msgAndArgs ..
// Exactlyf asserts that two objects are equal in value and type.
//
-// assert.Exactlyf(t, int32(123), int64(123), "error message %s", "formatted")
+// require.Exactlyf(t, int32(123), int64(123), "error message %s", "formatted")
func Exactlyf(t TestingT, expected interface{}, actual interface{}, msg string, args ...interface{}) {
if h, ok := t.(tHelper); ok {
h.Helper()
@@ -543,7 +543,7 @@ func Failf(t TestingT, failureMessage string, msg string, args ...interface{}) {
// False asserts that the specified value is false.
//
-// assert.False(t, myBool)
+// require.False(t, myBool)
func False(t TestingT, value bool, msgAndArgs ...interface{}) {
if h, ok := t.(tHelper); ok {
h.Helper()
@@ -556,7 +556,7 @@ func False(t TestingT, value bool, msgAndArgs ...interface{}) {
// Falsef asserts that the specified value is false.
//
-// assert.Falsef(t, myBool, "error message %s", "formatted")
+// require.Falsef(t, myBool, "error message %s", "formatted")
func Falsef(t TestingT, value bool, msg string, args ...interface{}) {
if h, ok := t.(tHelper); ok {
h.Helper()
@@ -593,9 +593,9 @@ func FileExistsf(t TestingT, path string, msg string, args ...interface{}) {
// Greater asserts that the first element is greater than the second
//
-// assert.Greater(t, 2, 1)
-// assert.Greater(t, float64(2), float64(1))
-// assert.Greater(t, "b", "a")
+// require.Greater(t, 2, 1)
+// require.Greater(t, float64(2), float64(1))
+// require.Greater(t, "b", "a")
func Greater(t TestingT, e1 interface{}, e2 interface{}, msgAndArgs ...interface{}) {
if h, ok := t.(tHelper); ok {
h.Helper()
@@ -608,10 +608,10 @@ func Greater(t TestingT, e1 interface{}, e2 interface{}, msgAndArgs ...interface
// GreaterOrEqual asserts that the first element is greater than or equal to the second
//
-// assert.GreaterOrEqual(t, 2, 1)
-// assert.GreaterOrEqual(t, 2, 2)
-// assert.GreaterOrEqual(t, "b", "a")
-// assert.GreaterOrEqual(t, "b", "b")
+// require.GreaterOrEqual(t, 2, 1)
+// require.GreaterOrEqual(t, 2, 2)
+// require.GreaterOrEqual(t, "b", "a")
+// require.GreaterOrEqual(t, "b", "b")
func GreaterOrEqual(t TestingT, e1 interface{}, e2 interface{}, msgAndArgs ...interface{}) {
if h, ok := t.(tHelper); ok {
h.Helper()
@@ -624,10 +624,10 @@ func GreaterOrEqual(t TestingT, e1 interface{}, e2 interface{}, msgAndArgs ...in
// GreaterOrEqualf asserts that the first element is greater than or equal to the second
//
-// assert.GreaterOrEqualf(t, 2, 1, "error message %s", "formatted")
-// assert.GreaterOrEqualf(t, 2, 2, "error message %s", "formatted")
-// assert.GreaterOrEqualf(t, "b", "a", "error message %s", "formatted")
-// assert.GreaterOrEqualf(t, "b", "b", "error message %s", "formatted")
+// require.GreaterOrEqualf(t, 2, 1, "error message %s", "formatted")
+// require.GreaterOrEqualf(t, 2, 2, "error message %s", "formatted")
+// require.GreaterOrEqualf(t, "b", "a", "error message %s", "formatted")
+// require.GreaterOrEqualf(t, "b", "b", "error message %s", "formatted")
func GreaterOrEqualf(t TestingT, e1 interface{}, e2 interface{}, msg string, args ...interface{}) {
if h, ok := t.(tHelper); ok {
h.Helper()
@@ -640,9 +640,9 @@ func GreaterOrEqualf(t TestingT, e1 interface{}, e2 interface{}, msg string, arg
// Greaterf asserts that the first element is greater than the second
//
-// assert.Greaterf(t, 2, 1, "error message %s", "formatted")
-// assert.Greaterf(t, float64(2), float64(1), "error message %s", "formatted")
-// assert.Greaterf(t, "b", "a", "error message %s", "formatted")
+// require.Greaterf(t, 2, 1, "error message %s", "formatted")
+// require.Greaterf(t, float64(2), float64(1), "error message %s", "formatted")
+// require.Greaterf(t, "b", "a", "error message %s", "formatted")
func Greaterf(t TestingT, e1 interface{}, e2 interface{}, msg string, args ...interface{}) {
if h, ok := t.(tHelper); ok {
h.Helper()
@@ -656,7 +656,7 @@ func Greaterf(t TestingT, e1 interface{}, e2 interface{}, msg string, args ...in
// HTTPBodyContains asserts that a specified handler returns a
// body that contains a string.
//
-// assert.HTTPBodyContains(t, myHandler, "GET", "www.google.com", nil, "I'm Feeling Lucky")
+// require.HTTPBodyContains(t, myHandler, "GET", "www.google.com", nil, "I'm Feeling Lucky")
//
// Returns whether the assertion was successful (true) or not (false).
func HTTPBodyContains(t TestingT, handler http.HandlerFunc, method string, url string, values url.Values, str interface{}, msgAndArgs ...interface{}) {
@@ -672,7 +672,7 @@ func HTTPBodyContains(t TestingT, handler http.HandlerFunc, method string, url s
// HTTPBodyContainsf asserts that a specified handler returns a
// body that contains a string.
//
-// assert.HTTPBodyContainsf(t, myHandler, "GET", "www.google.com", nil, "I'm Feeling Lucky", "error message %s", "formatted")
+// require.HTTPBodyContainsf(t, myHandler, "GET", "www.google.com", nil, "I'm Feeling Lucky", "error message %s", "formatted")
//
// Returns whether the assertion was successful (true) or not (false).
func HTTPBodyContainsf(t TestingT, handler http.HandlerFunc, method string, url string, values url.Values, str interface{}, msg string, args ...interface{}) {
@@ -688,7 +688,7 @@ func HTTPBodyContainsf(t TestingT, handler http.HandlerFunc, method string, url
// HTTPBodyNotContains asserts that a specified handler returns a
// body that does not contain a string.
//
-// assert.HTTPBodyNotContains(t, myHandler, "GET", "www.google.com", nil, "I'm Feeling Lucky")
+// require.HTTPBodyNotContains(t, myHandler, "GET", "www.google.com", nil, "I'm Feeling Lucky")
//
// Returns whether the assertion was successful (true) or not (false).
func HTTPBodyNotContains(t TestingT, handler http.HandlerFunc, method string, url string, values url.Values, str interface{}, msgAndArgs ...interface{}) {
@@ -704,7 +704,7 @@ func HTTPBodyNotContains(t TestingT, handler http.HandlerFunc, method string, ur
// HTTPBodyNotContainsf asserts that a specified handler returns a
// body that does not contain a string.
//
-// assert.HTTPBodyNotContainsf(t, myHandler, "GET", "www.google.com", nil, "I'm Feeling Lucky", "error message %s", "formatted")
+// require.HTTPBodyNotContainsf(t, myHandler, "GET", "www.google.com", nil, "I'm Feeling Lucky", "error message %s", "formatted")
//
// Returns whether the assertion was successful (true) or not (false).
func HTTPBodyNotContainsf(t TestingT, handler http.HandlerFunc, method string, url string, values url.Values, str interface{}, msg string, args ...interface{}) {
@@ -719,7 +719,7 @@ func HTTPBodyNotContainsf(t TestingT, handler http.HandlerFunc, method string, u
// HTTPError asserts that a specified handler returns an error status code.
//
-// assert.HTTPError(t, myHandler, "POST", "/a/b/c", url.Values{"a": []string{"b", "c"}}
+// require.HTTPError(t, myHandler, "POST", "/a/b/c", url.Values{"a": []string{"b", "c"}}
//
// Returns whether the assertion was successful (true) or not (false).
func HTTPError(t TestingT, handler http.HandlerFunc, method string, url string, values url.Values, msgAndArgs ...interface{}) {
@@ -734,7 +734,7 @@ func HTTPError(t TestingT, handler http.HandlerFunc, method string, url string,
// HTTPErrorf asserts that a specified handler returns an error status code.
//
-// assert.HTTPErrorf(t, myHandler, "POST", "/a/b/c", url.Values{"a": []string{"b", "c"}}
+// require.HTTPErrorf(t, myHandler, "POST", "/a/b/c", url.Values{"a": []string{"b", "c"}}
//
// Returns whether the assertion was successful (true) or not (false).
func HTTPErrorf(t TestingT, handler http.HandlerFunc, method string, url string, values url.Values, msg string, args ...interface{}) {
@@ -749,7 +749,7 @@ func HTTPErrorf(t TestingT, handler http.HandlerFunc, method string, url string,
// HTTPRedirect asserts that a specified handler returns a redirect status code.
//
-// assert.HTTPRedirect(t, myHandler, "GET", "/a/b/c", url.Values{"a": []string{"b", "c"}}
+// require.HTTPRedirect(t, myHandler, "GET", "/a/b/c", url.Values{"a": []string{"b", "c"}}
//
// Returns whether the assertion was successful (true) or not (false).
func HTTPRedirect(t TestingT, handler http.HandlerFunc, method string, url string, values url.Values, msgAndArgs ...interface{}) {
@@ -764,7 +764,7 @@ func HTTPRedirect(t TestingT, handler http.HandlerFunc, method string, url strin
// HTTPRedirectf asserts that a specified handler returns a redirect status code.
//
-// assert.HTTPRedirectf(t, myHandler, "GET", "/a/b/c", url.Values{"a": []string{"b", "c"}}
+// require.HTTPRedirectf(t, myHandler, "GET", "/a/b/c", url.Values{"a": []string{"b", "c"}}
//
// Returns whether the assertion was successful (true) or not (false).
func HTTPRedirectf(t TestingT, handler http.HandlerFunc, method string, url string, values url.Values, msg string, args ...interface{}) {
@@ -779,7 +779,7 @@ func HTTPRedirectf(t TestingT, handler http.HandlerFunc, method string, url stri
// HTTPStatusCode asserts that a specified handler returns a specified status code.
//
-// assert.HTTPStatusCode(t, myHandler, "GET", "/notImplemented", nil, 501)
+// require.HTTPStatusCode(t, myHandler, "GET", "/notImplemented", nil, 501)
//
// Returns whether the assertion was successful (true) or not (false).
func HTTPStatusCode(t TestingT, handler http.HandlerFunc, method string, url string, values url.Values, statuscode int, msgAndArgs ...interface{}) {
@@ -794,7 +794,7 @@ func HTTPStatusCode(t TestingT, handler http.HandlerFunc, method string, url str
// HTTPStatusCodef asserts that a specified handler returns a specified status code.
//
-// assert.HTTPStatusCodef(t, myHandler, "GET", "/notImplemented", nil, 501, "error message %s", "formatted")
+// require.HTTPStatusCodef(t, myHandler, "GET", "/notImplemented", nil, 501, "error message %s", "formatted")
//
// Returns whether the assertion was successful (true) or not (false).
func HTTPStatusCodef(t TestingT, handler http.HandlerFunc, method string, url string, values url.Values, statuscode int, msg string, args ...interface{}) {
@@ -809,7 +809,7 @@ func HTTPStatusCodef(t TestingT, handler http.HandlerFunc, method string, url st
// HTTPSuccess asserts that a specified handler returns a success status code.
//
-// assert.HTTPSuccess(t, myHandler, "POST", "http://www.google.com", nil)
+// require.HTTPSuccess(t, myHandler, "POST", "http://www.google.com", nil)
//
// Returns whether the assertion was successful (true) or not (false).
func HTTPSuccess(t TestingT, handler http.HandlerFunc, method string, url string, values url.Values, msgAndArgs ...interface{}) {
@@ -824,7 +824,7 @@ func HTTPSuccess(t TestingT, handler http.HandlerFunc, method string, url string
// HTTPSuccessf asserts that a specified handler returns a success status code.
//
-// assert.HTTPSuccessf(t, myHandler, "POST", "http://www.google.com", nil, "error message %s", "formatted")
+// require.HTTPSuccessf(t, myHandler, "POST", "http://www.google.com", nil, "error message %s", "formatted")
//
// Returns whether the assertion was successful (true) or not (false).
func HTTPSuccessf(t TestingT, handler http.HandlerFunc, method string, url string, values url.Values, msg string, args ...interface{}) {
@@ -839,7 +839,7 @@ func HTTPSuccessf(t TestingT, handler http.HandlerFunc, method string, url strin
// Implements asserts that an object is implemented by the specified interface.
//
-// assert.Implements(t, (*MyInterface)(nil), new(MyObject))
+// require.Implements(t, (*MyInterface)(nil), new(MyObject))
func Implements(t TestingT, interfaceObject interface{}, object interface{}, msgAndArgs ...interface{}) {
if h, ok := t.(tHelper); ok {
h.Helper()
@@ -852,7 +852,7 @@ func Implements(t TestingT, interfaceObject interface{}, object interface{}, msg
// Implementsf asserts that an object is implemented by the specified interface.
//
-// assert.Implementsf(t, (*MyInterface)(nil), new(MyObject), "error message %s", "formatted")
+// require.Implementsf(t, (*MyInterface)(nil), new(MyObject), "error message %s", "formatted")
func Implementsf(t TestingT, interfaceObject interface{}, object interface{}, msg string, args ...interface{}) {
if h, ok := t.(tHelper); ok {
h.Helper()
@@ -865,7 +865,7 @@ func Implementsf(t TestingT, interfaceObject interface{}, object interface{}, ms
// InDelta asserts that the two numerals are within delta of each other.
//
-// assert.InDelta(t, math.Pi, 22/7.0, 0.01)
+// require.InDelta(t, math.Pi, 22/7.0, 0.01)
func InDelta(t TestingT, expected interface{}, actual interface{}, delta float64, msgAndArgs ...interface{}) {
if h, ok := t.(tHelper); ok {
h.Helper()
@@ -922,7 +922,7 @@ func InDeltaSlicef(t TestingT, expected interface{}, actual interface{}, delta f
// InDeltaf asserts that the two numerals are within delta of each other.
//
-// assert.InDeltaf(t, math.Pi, 22/7.0, 0.01, "error message %s", "formatted")
+// require.InDeltaf(t, math.Pi, 22/7.0, 0.01, "error message %s", "formatted")
func InDeltaf(t TestingT, expected interface{}, actual interface{}, delta float64, msg string, args ...interface{}) {
if h, ok := t.(tHelper); ok {
h.Helper()
@@ -979,9 +979,9 @@ func InEpsilonf(t TestingT, expected interface{}, actual interface{}, epsilon fl
// IsDecreasing asserts that the collection is decreasing
//
-// assert.IsDecreasing(t, []int{2, 1, 0})
-// assert.IsDecreasing(t, []float{2, 1})
-// assert.IsDecreasing(t, []string{"b", "a"})
+// require.IsDecreasing(t, []int{2, 1, 0})
+// require.IsDecreasing(t, []float{2, 1})
+// require.IsDecreasing(t, []string{"b", "a"})
func IsDecreasing(t TestingT, object interface{}, msgAndArgs ...interface{}) {
if h, ok := t.(tHelper); ok {
h.Helper()
@@ -994,9 +994,9 @@ func IsDecreasing(t TestingT, object interface{}, msgAndArgs ...interface{}) {
// IsDecreasingf asserts that the collection is decreasing
//
-// assert.IsDecreasingf(t, []int{2, 1, 0}, "error message %s", "formatted")
-// assert.IsDecreasingf(t, []float{2, 1}, "error message %s", "formatted")
-// assert.IsDecreasingf(t, []string{"b", "a"}, "error message %s", "formatted")
+// require.IsDecreasingf(t, []int{2, 1, 0}, "error message %s", "formatted")
+// require.IsDecreasingf(t, []float{2, 1}, "error message %s", "formatted")
+// require.IsDecreasingf(t, []string{"b", "a"}, "error message %s", "formatted")
func IsDecreasingf(t TestingT, object interface{}, msg string, args ...interface{}) {
if h, ok := t.(tHelper); ok {
h.Helper()
@@ -1009,9 +1009,9 @@ func IsDecreasingf(t TestingT, object interface{}, msg string, args ...interface
// IsIncreasing asserts that the collection is increasing
//
-// assert.IsIncreasing(t, []int{1, 2, 3})
-// assert.IsIncreasing(t, []float{1, 2})
-// assert.IsIncreasing(t, []string{"a", "b"})
+// require.IsIncreasing(t, []int{1, 2, 3})
+// require.IsIncreasing(t, []float{1, 2})
+// require.IsIncreasing(t, []string{"a", "b"})
func IsIncreasing(t TestingT, object interface{}, msgAndArgs ...interface{}) {
if h, ok := t.(tHelper); ok {
h.Helper()
@@ -1024,9 +1024,9 @@ func IsIncreasing(t TestingT, object interface{}, msgAndArgs ...interface{}) {
// IsIncreasingf asserts that the collection is increasing
//
-// assert.IsIncreasingf(t, []int{1, 2, 3}, "error message %s", "formatted")
-// assert.IsIncreasingf(t, []float{1, 2}, "error message %s", "formatted")
-// assert.IsIncreasingf(t, []string{"a", "b"}, "error message %s", "formatted")
+// require.IsIncreasingf(t, []int{1, 2, 3}, "error message %s", "formatted")
+// require.IsIncreasingf(t, []float{1, 2}, "error message %s", "formatted")
+// require.IsIncreasingf(t, []string{"a", "b"}, "error message %s", "formatted")
func IsIncreasingf(t TestingT, object interface{}, msg string, args ...interface{}) {
if h, ok := t.(tHelper); ok {
h.Helper()
@@ -1039,9 +1039,9 @@ func IsIncreasingf(t TestingT, object interface{}, msg string, args ...interface
// IsNonDecreasing asserts that the collection is not decreasing
//
-// assert.IsNonDecreasing(t, []int{1, 1, 2})
-// assert.IsNonDecreasing(t, []float{1, 2})
-// assert.IsNonDecreasing(t, []string{"a", "b"})
+// require.IsNonDecreasing(t, []int{1, 1, 2})
+// require.IsNonDecreasing(t, []float{1, 2})
+// require.IsNonDecreasing(t, []string{"a", "b"})
func IsNonDecreasing(t TestingT, object interface{}, msgAndArgs ...interface{}) {
if h, ok := t.(tHelper); ok {
h.Helper()
@@ -1054,9 +1054,9 @@ func IsNonDecreasing(t TestingT, object interface{}, msgAndArgs ...interface{})
// IsNonDecreasingf asserts that the collection is not decreasing
//
-// assert.IsNonDecreasingf(t, []int{1, 1, 2}, "error message %s", "formatted")
-// assert.IsNonDecreasingf(t, []float{1, 2}, "error message %s", "formatted")
-// assert.IsNonDecreasingf(t, []string{"a", "b"}, "error message %s", "formatted")
+// require.IsNonDecreasingf(t, []int{1, 1, 2}, "error message %s", "formatted")
+// require.IsNonDecreasingf(t, []float{1, 2}, "error message %s", "formatted")
+// require.IsNonDecreasingf(t, []string{"a", "b"}, "error message %s", "formatted")
func IsNonDecreasingf(t TestingT, object interface{}, msg string, args ...interface{}) {
if h, ok := t.(tHelper); ok {
h.Helper()
@@ -1069,9 +1069,9 @@ func IsNonDecreasingf(t TestingT, object interface{}, msg string, args ...interf
// IsNonIncreasing asserts that the collection is not increasing
//
-// assert.IsNonIncreasing(t, []int{2, 1, 1})
-// assert.IsNonIncreasing(t, []float{2, 1})
-// assert.IsNonIncreasing(t, []string{"b", "a"})
+// require.IsNonIncreasing(t, []int{2, 1, 1})
+// require.IsNonIncreasing(t, []float{2, 1})
+// require.IsNonIncreasing(t, []string{"b", "a"})
func IsNonIncreasing(t TestingT, object interface{}, msgAndArgs ...interface{}) {
if h, ok := t.(tHelper); ok {
h.Helper()
@@ -1084,9 +1084,9 @@ func IsNonIncreasing(t TestingT, object interface{}, msgAndArgs ...interface{})
// IsNonIncreasingf asserts that the collection is not increasing
//
-// assert.IsNonIncreasingf(t, []int{2, 1, 1}, "error message %s", "formatted")
-// assert.IsNonIncreasingf(t, []float{2, 1}, "error message %s", "formatted")
-// assert.IsNonIncreasingf(t, []string{"b", "a"}, "error message %s", "formatted")
+// require.IsNonIncreasingf(t, []int{2, 1, 1}, "error message %s", "formatted")
+// require.IsNonIncreasingf(t, []float{2, 1}, "error message %s", "formatted")
+// require.IsNonIncreasingf(t, []string{"b", "a"}, "error message %s", "formatted")
func IsNonIncreasingf(t TestingT, object interface{}, msg string, args ...interface{}) {
if h, ok := t.(tHelper); ok {
h.Helper()
@@ -1121,7 +1121,7 @@ func IsTypef(t TestingT, expectedType interface{}, object interface{}, msg strin
// JSONEq asserts that two JSON strings are equivalent.
//
-// assert.JSONEq(t, `{"hello": "world", "foo": "bar"}`, `{"foo": "bar", "hello": "world"}`)
+// require.JSONEq(t, `{"hello": "world", "foo": "bar"}`, `{"foo": "bar", "hello": "world"}`)
func JSONEq(t TestingT, expected string, actual string, msgAndArgs ...interface{}) {
if h, ok := t.(tHelper); ok {
h.Helper()
@@ -1134,7 +1134,7 @@ func JSONEq(t TestingT, expected string, actual string, msgAndArgs ...interface{
// JSONEqf asserts that two JSON strings are equivalent.
//
-// assert.JSONEqf(t, `{"hello": "world", "foo": "bar"}`, `{"foo": "bar", "hello": "world"}`, "error message %s", "formatted")
+// require.JSONEqf(t, `{"hello": "world", "foo": "bar"}`, `{"foo": "bar", "hello": "world"}`, "error message %s", "formatted")
func JSONEqf(t TestingT, expected string, actual string, msg string, args ...interface{}) {
if h, ok := t.(tHelper); ok {
h.Helper()
@@ -1148,7 +1148,7 @@ func JSONEqf(t TestingT, expected string, actual string, msg string, args ...int
// Len asserts that the specified object has specific length.
// Len also fails if the object has a type that len() not accept.
//
-// assert.Len(t, mySlice, 3)
+// require.Len(t, mySlice, 3)
func Len(t TestingT, object interface{}, length int, msgAndArgs ...interface{}) {
if h, ok := t.(tHelper); ok {
h.Helper()
@@ -1162,7 +1162,7 @@ func Len(t TestingT, object interface{}, length int, msgAndArgs ...interface{})
// Lenf asserts that the specified object has specific length.
// Lenf also fails if the object has a type that len() not accept.
//
-// assert.Lenf(t, mySlice, 3, "error message %s", "formatted")
+// require.Lenf(t, mySlice, 3, "error message %s", "formatted")
func Lenf(t TestingT, object interface{}, length int, msg string, args ...interface{}) {
if h, ok := t.(tHelper); ok {
h.Helper()
@@ -1175,9 +1175,9 @@ func Lenf(t TestingT, object interface{}, length int, msg string, args ...interf
// Less asserts that the first element is less than the second
//
-// assert.Less(t, 1, 2)
-// assert.Less(t, float64(1), float64(2))
-// assert.Less(t, "a", "b")
+// require.Less(t, 1, 2)
+// require.Less(t, float64(1), float64(2))
+// require.Less(t, "a", "b")
func Less(t TestingT, e1 interface{}, e2 interface{}, msgAndArgs ...interface{}) {
if h, ok := t.(tHelper); ok {
h.Helper()
@@ -1190,10 +1190,10 @@ func Less(t TestingT, e1 interface{}, e2 interface{}, msgAndArgs ...interface{})
// LessOrEqual asserts that the first element is less than or equal to the second
//
-// assert.LessOrEqual(t, 1, 2)
-// assert.LessOrEqual(t, 2, 2)
-// assert.LessOrEqual(t, "a", "b")
-// assert.LessOrEqual(t, "b", "b")
+// require.LessOrEqual(t, 1, 2)
+// require.LessOrEqual(t, 2, 2)
+// require.LessOrEqual(t, "a", "b")
+// require.LessOrEqual(t, "b", "b")
func LessOrEqual(t TestingT, e1 interface{}, e2 interface{}, msgAndArgs ...interface{}) {
if h, ok := t.(tHelper); ok {
h.Helper()
@@ -1206,10 +1206,10 @@ func LessOrEqual(t TestingT, e1 interface{}, e2 interface{}, msgAndArgs ...inter
// LessOrEqualf asserts that the first element is less than or equal to the second
//
-// assert.LessOrEqualf(t, 1, 2, "error message %s", "formatted")
-// assert.LessOrEqualf(t, 2, 2, "error message %s", "formatted")
-// assert.LessOrEqualf(t, "a", "b", "error message %s", "formatted")
-// assert.LessOrEqualf(t, "b", "b", "error message %s", "formatted")
+// require.LessOrEqualf(t, 1, 2, "error message %s", "formatted")
+// require.LessOrEqualf(t, 2, 2, "error message %s", "formatted")
+// require.LessOrEqualf(t, "a", "b", "error message %s", "formatted")
+// require.LessOrEqualf(t, "b", "b", "error message %s", "formatted")
func LessOrEqualf(t TestingT, e1 interface{}, e2 interface{}, msg string, args ...interface{}) {
if h, ok := t.(tHelper); ok {
h.Helper()
@@ -1222,9 +1222,9 @@ func LessOrEqualf(t TestingT, e1 interface{}, e2 interface{}, msg string, args .
// Lessf asserts that the first element is less than the second
//
-// assert.Lessf(t, 1, 2, "error message %s", "formatted")
-// assert.Lessf(t, float64(1), float64(2), "error message %s", "formatted")
-// assert.Lessf(t, "a", "b", "error message %s", "formatted")
+// require.Lessf(t, 1, 2, "error message %s", "formatted")
+// require.Lessf(t, float64(1), float64(2), "error message %s", "formatted")
+// require.Lessf(t, "a", "b", "error message %s", "formatted")
func Lessf(t TestingT, e1 interface{}, e2 interface{}, msg string, args ...interface{}) {
if h, ok := t.(tHelper); ok {
h.Helper()
@@ -1237,8 +1237,8 @@ func Lessf(t TestingT, e1 interface{}, e2 interface{}, msg string, args ...inter
// Negative asserts that the specified element is negative
//
-// assert.Negative(t, -1)
-// assert.Negative(t, -1.23)
+// require.Negative(t, -1)
+// require.Negative(t, -1.23)
func Negative(t TestingT, e interface{}, msgAndArgs ...interface{}) {
if h, ok := t.(tHelper); ok {
h.Helper()
@@ -1251,8 +1251,8 @@ func Negative(t TestingT, e interface{}, msgAndArgs ...interface{}) {
// Negativef asserts that the specified element is negative
//
-// assert.Negativef(t, -1, "error message %s", "formatted")
-// assert.Negativef(t, -1.23, "error message %s", "formatted")
+// require.Negativef(t, -1, "error message %s", "formatted")
+// require.Negativef(t, -1.23, "error message %s", "formatted")
func Negativef(t TestingT, e interface{}, msg string, args ...interface{}) {
if h, ok := t.(tHelper); ok {
h.Helper()
@@ -1266,7 +1266,7 @@ func Negativef(t TestingT, e interface{}, msg string, args ...interface{}) {
// Never asserts that the given condition doesn't satisfy in waitFor time,
// periodically checking the target function each tick.
//
-// assert.Never(t, func() bool { return false; }, time.Second, 10*time.Millisecond)
+// require.Never(t, func() bool { return false; }, time.Second, 10*time.Millisecond)
func Never(t TestingT, condition func() bool, waitFor time.Duration, tick time.Duration, msgAndArgs ...interface{}) {
if h, ok := t.(tHelper); ok {
h.Helper()
@@ -1280,7 +1280,7 @@ func Never(t TestingT, condition func() bool, waitFor time.Duration, tick time.D
// Neverf asserts that the given condition doesn't satisfy in waitFor time,
// periodically checking the target function each tick.
//
-// assert.Neverf(t, func() bool { return false; }, time.Second, 10*time.Millisecond, "error message %s", "formatted")
+// require.Neverf(t, func() bool { return false; }, time.Second, 10*time.Millisecond, "error message %s", "formatted")
func Neverf(t TestingT, condition func() bool, waitFor time.Duration, tick time.Duration, msg string, args ...interface{}) {
if h, ok := t.(tHelper); ok {
h.Helper()
@@ -1293,7 +1293,7 @@ func Neverf(t TestingT, condition func() bool, waitFor time.Duration, tick time.
// Nil asserts that the specified object is nil.
//
-// assert.Nil(t, err)
+// require.Nil(t, err)
func Nil(t TestingT, object interface{}, msgAndArgs ...interface{}) {
if h, ok := t.(tHelper); ok {
h.Helper()
@@ -1306,7 +1306,7 @@ func Nil(t TestingT, object interface{}, msgAndArgs ...interface{}) {
// Nilf asserts that the specified object is nil.
//
-// assert.Nilf(t, err, "error message %s", "formatted")
+// require.Nilf(t, err, "error message %s", "formatted")
func Nilf(t TestingT, object interface{}, msg string, args ...interface{}) {
if h, ok := t.(tHelper); ok {
h.Helper()
@@ -1344,8 +1344,8 @@ func NoDirExistsf(t TestingT, path string, msg string, args ...interface{}) {
// NoError asserts that a function returned no error (i.e. `nil`).
//
// actualObj, err := SomeFunction()
-// if assert.NoError(t, err) {
-// assert.Equal(t, expectedObj, actualObj)
+// if require.NoError(t, err) {
+// require.Equal(t, expectedObj, actualObj)
// }
func NoError(t TestingT, err error, msgAndArgs ...interface{}) {
if h, ok := t.(tHelper); ok {
@@ -1360,8 +1360,8 @@ func NoError(t TestingT, err error, msgAndArgs ...interface{}) {
// NoErrorf asserts that a function returned no error (i.e. `nil`).
//
// actualObj, err := SomeFunction()
-// if assert.NoErrorf(t, err, "error message %s", "formatted") {
-// assert.Equal(t, expectedObj, actualObj)
+// if require.NoErrorf(t, err, "error message %s", "formatted") {
+// require.Equal(t, expectedObj, actualObj)
// }
func NoErrorf(t TestingT, err error, msg string, args ...interface{}) {
if h, ok := t.(tHelper); ok {
@@ -1400,9 +1400,9 @@ func NoFileExistsf(t TestingT, path string, msg string, args ...interface{}) {
// NotContains asserts that the specified string, list(array, slice...) or map does NOT contain the
// specified substring or element.
//
-// assert.NotContains(t, "Hello World", "Earth")
-// assert.NotContains(t, ["Hello", "World"], "Earth")
-// assert.NotContains(t, {"Hello": "World"}, "Earth")
+// require.NotContains(t, "Hello World", "Earth")
+// require.NotContains(t, ["Hello", "World"], "Earth")
+// require.NotContains(t, {"Hello": "World"}, "Earth")
func NotContains(t TestingT, s interface{}, contains interface{}, msgAndArgs ...interface{}) {
if h, ok := t.(tHelper); ok {
h.Helper()
@@ -1416,9 +1416,9 @@ func NotContains(t TestingT, s interface{}, contains interface{}, msgAndArgs ...
// NotContainsf asserts that the specified string, list(array, slice...) or map does NOT contain the
// specified substring or element.
//
-// assert.NotContainsf(t, "Hello World", "Earth", "error message %s", "formatted")
-// assert.NotContainsf(t, ["Hello", "World"], "Earth", "error message %s", "formatted")
-// assert.NotContainsf(t, {"Hello": "World"}, "Earth", "error message %s", "formatted")
+// require.NotContainsf(t, "Hello World", "Earth", "error message %s", "formatted")
+// require.NotContainsf(t, ["Hello", "World"], "Earth", "error message %s", "formatted")
+// require.NotContainsf(t, {"Hello": "World"}, "Earth", "error message %s", "formatted")
func NotContainsf(t TestingT, s interface{}, contains interface{}, msg string, args ...interface{}) {
if h, ok := t.(tHelper); ok {
h.Helper()
@@ -1429,11 +1429,51 @@ func NotContainsf(t TestingT, s interface{}, contains interface{}, msg string, a
t.FailNow()
}
+// NotElementsMatch asserts that the specified listA(array, slice...) is NOT equal to specified
+// listB(array, slice...) ignoring the order of the elements. If there are duplicate elements,
+// the number of appearances of each of them in both lists should not match.
+// This is an inverse of ElementsMatch.
+//
+// require.NotElementsMatch(t, [1, 1, 2, 3], [1, 1, 2, 3]) -> false
+//
+// require.NotElementsMatch(t, [1, 1, 2, 3], [1, 2, 3]) -> true
+//
+// require.NotElementsMatch(t, [1, 2, 3], [1, 2, 4]) -> true
+func NotElementsMatch(t TestingT, listA interface{}, listB interface{}, msgAndArgs ...interface{}) {
+ if h, ok := t.(tHelper); ok {
+ h.Helper()
+ }
+ if assert.NotElementsMatch(t, listA, listB, msgAndArgs...) {
+ return
+ }
+ t.FailNow()
+}
+
+// NotElementsMatchf asserts that the specified listA(array, slice...) is NOT equal to specified
+// listB(array, slice...) ignoring the order of the elements. If there are duplicate elements,
+// the number of appearances of each of them in both lists should not match.
+// This is an inverse of ElementsMatch.
+//
+// require.NotElementsMatchf(t, [1, 1, 2, 3], [1, 1, 2, 3], "error message %s", "formatted") -> false
+//
+// require.NotElementsMatchf(t, [1, 1, 2, 3], [1, 2, 3], "error message %s", "formatted") -> true
+//
+// require.NotElementsMatchf(t, [1, 2, 3], [1, 2, 4], "error message %s", "formatted") -> true
+func NotElementsMatchf(t TestingT, listA interface{}, listB interface{}, msg string, args ...interface{}) {
+ if h, ok := t.(tHelper); ok {
+ h.Helper()
+ }
+ if assert.NotElementsMatchf(t, listA, listB, msg, args...) {
+ return
+ }
+ t.FailNow()
+}
+
// NotEmpty asserts that the specified object is NOT empty. I.e. not nil, "", false, 0 or either
// a slice or a channel with len == 0.
//
-// if assert.NotEmpty(t, obj) {
-// assert.Equal(t, "two", obj[1])
+// if require.NotEmpty(t, obj) {
+// require.Equal(t, "two", obj[1])
// }
func NotEmpty(t TestingT, object interface{}, msgAndArgs ...interface{}) {
if h, ok := t.(tHelper); ok {
@@ -1448,8 +1488,8 @@ func NotEmpty(t TestingT, object interface{}, msgAndArgs ...interface{}) {
// NotEmptyf asserts that the specified object is NOT empty. I.e. not nil, "", false, 0 or either
// a slice or a channel with len == 0.
//
-// if assert.NotEmptyf(t, obj, "error message %s", "formatted") {
-// assert.Equal(t, "two", obj[1])
+// if require.NotEmptyf(t, obj, "error message %s", "formatted") {
+// require.Equal(t, "two", obj[1])
// }
func NotEmptyf(t TestingT, object interface{}, msg string, args ...interface{}) {
if h, ok := t.(tHelper); ok {
@@ -1463,7 +1503,7 @@ func NotEmptyf(t TestingT, object interface{}, msg string, args ...interface{})
// NotEqual asserts that the specified values are NOT equal.
//
-// assert.NotEqual(t, obj1, obj2)
+// require.NotEqual(t, obj1, obj2)
//
// Pointer variable equality is determined based on the equality of the
// referenced values (as opposed to the memory addresses).
@@ -1479,7 +1519,7 @@ func NotEqual(t TestingT, expected interface{}, actual interface{}, msgAndArgs .
// NotEqualValues asserts that two objects are not equal even when converted to the same type
//
-// assert.NotEqualValues(t, obj1, obj2)
+// require.NotEqualValues(t, obj1, obj2)
func NotEqualValues(t TestingT, expected interface{}, actual interface{}, msgAndArgs ...interface{}) {
if h, ok := t.(tHelper); ok {
h.Helper()
@@ -1492,7 +1532,7 @@ func NotEqualValues(t TestingT, expected interface{}, actual interface{}, msgAnd
// NotEqualValuesf asserts that two objects are not equal even when converted to the same type
//
-// assert.NotEqualValuesf(t, obj1, obj2, "error message %s", "formatted")
+// require.NotEqualValuesf(t, obj1, obj2, "error message %s", "formatted")
func NotEqualValuesf(t TestingT, expected interface{}, actual interface{}, msg string, args ...interface{}) {
if h, ok := t.(tHelper); ok {
h.Helper()
@@ -1505,7 +1545,7 @@ func NotEqualValuesf(t TestingT, expected interface{}, actual interface{}, msg s
// NotEqualf asserts that the specified values are NOT equal.
//
-// assert.NotEqualf(t, obj1, obj2, "error message %s", "formatted")
+// require.NotEqualf(t, obj1, obj2, "error message %s", "formatted")
//
// Pointer variable equality is determined based on the equality of the
// referenced values (as opposed to the memory addresses).
@@ -1519,7 +1559,31 @@ func NotEqualf(t TestingT, expected interface{}, actual interface{}, msg string,
t.FailNow()
}
-// NotErrorIs asserts that at none of the errors in err's chain matches target.
+// NotErrorAs asserts that none of the errors in err's chain matches target,
+// but if so, sets target to that error value.
+func NotErrorAs(t TestingT, err error, target interface{}, msgAndArgs ...interface{}) {
+ if h, ok := t.(tHelper); ok {
+ h.Helper()
+ }
+ if assert.NotErrorAs(t, err, target, msgAndArgs...) {
+ return
+ }
+ t.FailNow()
+}
+
+// NotErrorAsf asserts that none of the errors in err's chain matches target,
+// but if so, sets target to that error value.
+func NotErrorAsf(t TestingT, err error, target interface{}, msg string, args ...interface{}) {
+ if h, ok := t.(tHelper); ok {
+ h.Helper()
+ }
+ if assert.NotErrorAsf(t, err, target, msg, args...) {
+ return
+ }
+ t.FailNow()
+}
+
+// NotErrorIs asserts that none of the errors in err's chain matches target.
// This is a wrapper for errors.Is.
func NotErrorIs(t TestingT, err error, target error, msgAndArgs ...interface{}) {
if h, ok := t.(tHelper); ok {
@@ -1531,7 +1595,7 @@ func NotErrorIs(t TestingT, err error, target error, msgAndArgs ...interface{})
t.FailNow()
}
-// NotErrorIsf asserts that at none of the errors in err's chain matches target.
+// NotErrorIsf asserts that none of the errors in err's chain matches target.
// This is a wrapper for errors.Is.
func NotErrorIsf(t TestingT, err error, target error, msg string, args ...interface{}) {
if h, ok := t.(tHelper); ok {
@@ -1545,7 +1609,7 @@ func NotErrorIsf(t TestingT, err error, target error, msg string, args ...interf
// NotImplements asserts that an object does not implement the specified interface.
//
-// assert.NotImplements(t, (*MyInterface)(nil), new(MyObject))
+// require.NotImplements(t, (*MyInterface)(nil), new(MyObject))
func NotImplements(t TestingT, interfaceObject interface{}, object interface{}, msgAndArgs ...interface{}) {
if h, ok := t.(tHelper); ok {
h.Helper()
@@ -1558,7 +1622,7 @@ func NotImplements(t TestingT, interfaceObject interface{}, object interface{},
// NotImplementsf asserts that an object does not implement the specified interface.
//
-// assert.NotImplementsf(t, (*MyInterface)(nil), new(MyObject), "error message %s", "formatted")
+// require.NotImplementsf(t, (*MyInterface)(nil), new(MyObject), "error message %s", "formatted")
func NotImplementsf(t TestingT, interfaceObject interface{}, object interface{}, msg string, args ...interface{}) {
if h, ok := t.(tHelper); ok {
h.Helper()
@@ -1571,7 +1635,7 @@ func NotImplementsf(t TestingT, interfaceObject interface{}, object interface{},
// NotNil asserts that the specified object is not nil.
//
-// assert.NotNil(t, err)
+// require.NotNil(t, err)
func NotNil(t TestingT, object interface{}, msgAndArgs ...interface{}) {
if h, ok := t.(tHelper); ok {
h.Helper()
@@ -1584,7 +1648,7 @@ func NotNil(t TestingT, object interface{}, msgAndArgs ...interface{}) {
// NotNilf asserts that the specified object is not nil.
//
-// assert.NotNilf(t, err, "error message %s", "formatted")
+// require.NotNilf(t, err, "error message %s", "formatted")
func NotNilf(t TestingT, object interface{}, msg string, args ...interface{}) {
if h, ok := t.(tHelper); ok {
h.Helper()
@@ -1597,7 +1661,7 @@ func NotNilf(t TestingT, object interface{}, msg string, args ...interface{}) {
// NotPanics asserts that the code inside the specified PanicTestFunc does NOT panic.
//
-// assert.NotPanics(t, func(){ RemainCalm() })
+// require.NotPanics(t, func(){ RemainCalm() })
func NotPanics(t TestingT, f assert.PanicTestFunc, msgAndArgs ...interface{}) {
if h, ok := t.(tHelper); ok {
h.Helper()
@@ -1610,7 +1674,7 @@ func NotPanics(t TestingT, f assert.PanicTestFunc, msgAndArgs ...interface{}) {
// NotPanicsf asserts that the code inside the specified PanicTestFunc does NOT panic.
//
-// assert.NotPanicsf(t, func(){ RemainCalm() }, "error message %s", "formatted")
+// require.NotPanicsf(t, func(){ RemainCalm() }, "error message %s", "formatted")
func NotPanicsf(t TestingT, f assert.PanicTestFunc, msg string, args ...interface{}) {
if h, ok := t.(tHelper); ok {
h.Helper()
@@ -1623,8 +1687,8 @@ func NotPanicsf(t TestingT, f assert.PanicTestFunc, msg string, args ...interfac
// NotRegexp asserts that a specified regexp does not match a string.
//
-// assert.NotRegexp(t, regexp.MustCompile("starts"), "it's starting")
-// assert.NotRegexp(t, "^start", "it's not starting")
+// require.NotRegexp(t, regexp.MustCompile("starts"), "it's starting")
+// require.NotRegexp(t, "^start", "it's not starting")
func NotRegexp(t TestingT, rx interface{}, str interface{}, msgAndArgs ...interface{}) {
if h, ok := t.(tHelper); ok {
h.Helper()
@@ -1637,8 +1701,8 @@ func NotRegexp(t TestingT, rx interface{}, str interface{}, msgAndArgs ...interf
// NotRegexpf asserts that a specified regexp does not match a string.
//
-// assert.NotRegexpf(t, regexp.MustCompile("starts"), "it's starting", "error message %s", "formatted")
-// assert.NotRegexpf(t, "^start", "it's not starting", "error message %s", "formatted")
+// require.NotRegexpf(t, regexp.MustCompile("starts"), "it's starting", "error message %s", "formatted")
+// require.NotRegexpf(t, "^start", "it's not starting", "error message %s", "formatted")
func NotRegexpf(t TestingT, rx interface{}, str interface{}, msg string, args ...interface{}) {
if h, ok := t.(tHelper); ok {
h.Helper()
@@ -1651,7 +1715,7 @@ func NotRegexpf(t TestingT, rx interface{}, str interface{}, msg string, args ..
// NotSame asserts that two pointers do not reference the same object.
//
-// assert.NotSame(t, ptr1, ptr2)
+// require.NotSame(t, ptr1, ptr2)
//
// Both arguments must be pointer variables. Pointer variable sameness is
// determined based on the equality of both type and value.
@@ -1667,7 +1731,7 @@ func NotSame(t TestingT, expected interface{}, actual interface{}, msgAndArgs ..
// NotSamef asserts that two pointers do not reference the same object.
//
-// assert.NotSamef(t, ptr1, ptr2, "error message %s", "formatted")
+// require.NotSamef(t, ptr1, ptr2, "error message %s", "formatted")
//
// Both arguments must be pointer variables. Pointer variable sameness is
// determined based on the equality of both type and value.
@@ -1685,8 +1749,8 @@ func NotSamef(t TestingT, expected interface{}, actual interface{}, msg string,
// contain all elements given in the specified subset list(array, slice...) or
// map.
//
-// assert.NotSubset(t, [1, 3, 4], [1, 2])
-// assert.NotSubset(t, {"x": 1, "y": 2}, {"z": 3})
+// require.NotSubset(t, [1, 3, 4], [1, 2])
+// require.NotSubset(t, {"x": 1, "y": 2}, {"z": 3})
func NotSubset(t TestingT, list interface{}, subset interface{}, msgAndArgs ...interface{}) {
if h, ok := t.(tHelper); ok {
h.Helper()
@@ -1701,8 +1765,8 @@ func NotSubset(t TestingT, list interface{}, subset interface{}, msgAndArgs ...i
// contain all elements given in the specified subset list(array, slice...) or
// map.
//
-// assert.NotSubsetf(t, [1, 3, 4], [1, 2], "error message %s", "formatted")
-// assert.NotSubsetf(t, {"x": 1, "y": 2}, {"z": 3}, "error message %s", "formatted")
+// require.NotSubsetf(t, [1, 3, 4], [1, 2], "error message %s", "formatted")
+// require.NotSubsetf(t, {"x": 1, "y": 2}, {"z": 3}, "error message %s", "formatted")
func NotSubsetf(t TestingT, list interface{}, subset interface{}, msg string, args ...interface{}) {
if h, ok := t.(tHelper); ok {
h.Helper()
@@ -1737,7 +1801,7 @@ func NotZerof(t TestingT, i interface{}, msg string, args ...interface{}) {
// Panics asserts that the code inside the specified PanicTestFunc panics.
//
-// assert.Panics(t, func(){ GoCrazy() })
+// require.Panics(t, func(){ GoCrazy() })
func Panics(t TestingT, f assert.PanicTestFunc, msgAndArgs ...interface{}) {
if h, ok := t.(tHelper); ok {
h.Helper()
@@ -1752,7 +1816,7 @@ func Panics(t TestingT, f assert.PanicTestFunc, msgAndArgs ...interface{}) {
// panics, and that the recovered panic value is an error that satisfies the
// EqualError comparison.
//
-// assert.PanicsWithError(t, "crazy error", func(){ GoCrazy() })
+// require.PanicsWithError(t, "crazy error", func(){ GoCrazy() })
func PanicsWithError(t TestingT, errString string, f assert.PanicTestFunc, msgAndArgs ...interface{}) {
if h, ok := t.(tHelper); ok {
h.Helper()
@@ -1767,7 +1831,7 @@ func PanicsWithError(t TestingT, errString string, f assert.PanicTestFunc, msgAn
// panics, and that the recovered panic value is an error that satisfies the
// EqualError comparison.
//
-// assert.PanicsWithErrorf(t, "crazy error", func(){ GoCrazy() }, "error message %s", "formatted")
+// require.PanicsWithErrorf(t, "crazy error", func(){ GoCrazy() }, "error message %s", "formatted")
func PanicsWithErrorf(t TestingT, errString string, f assert.PanicTestFunc, msg string, args ...interface{}) {
if h, ok := t.(tHelper); ok {
h.Helper()
@@ -1781,7 +1845,7 @@ func PanicsWithErrorf(t TestingT, errString string, f assert.PanicTestFunc, msg
// PanicsWithValue asserts that the code inside the specified PanicTestFunc panics, and that
// the recovered panic value equals the expected panic value.
//
-// assert.PanicsWithValue(t, "crazy error", func(){ GoCrazy() })
+// require.PanicsWithValue(t, "crazy error", func(){ GoCrazy() })
func PanicsWithValue(t TestingT, expected interface{}, f assert.PanicTestFunc, msgAndArgs ...interface{}) {
if h, ok := t.(tHelper); ok {
h.Helper()
@@ -1795,7 +1859,7 @@ func PanicsWithValue(t TestingT, expected interface{}, f assert.PanicTestFunc, m
// PanicsWithValuef asserts that the code inside the specified PanicTestFunc panics, and that
// the recovered panic value equals the expected panic value.
//
-// assert.PanicsWithValuef(t, "crazy error", func(){ GoCrazy() }, "error message %s", "formatted")
+// require.PanicsWithValuef(t, "crazy error", func(){ GoCrazy() }, "error message %s", "formatted")
func PanicsWithValuef(t TestingT, expected interface{}, f assert.PanicTestFunc, msg string, args ...interface{}) {
if h, ok := t.(tHelper); ok {
h.Helper()
@@ -1808,7 +1872,7 @@ func PanicsWithValuef(t TestingT, expected interface{}, f assert.PanicTestFunc,
// Panicsf asserts that the code inside the specified PanicTestFunc panics.
//
-// assert.Panicsf(t, func(){ GoCrazy() }, "error message %s", "formatted")
+// require.Panicsf(t, func(){ GoCrazy() }, "error message %s", "formatted")
func Panicsf(t TestingT, f assert.PanicTestFunc, msg string, args ...interface{}) {
if h, ok := t.(tHelper); ok {
h.Helper()
@@ -1821,8 +1885,8 @@ func Panicsf(t TestingT, f assert.PanicTestFunc, msg string, args ...interface{}
// Positive asserts that the specified element is positive
//
-// assert.Positive(t, 1)
-// assert.Positive(t, 1.23)
+// require.Positive(t, 1)
+// require.Positive(t, 1.23)
func Positive(t TestingT, e interface{}, msgAndArgs ...interface{}) {
if h, ok := t.(tHelper); ok {
h.Helper()
@@ -1835,8 +1899,8 @@ func Positive(t, TestingT, e interface{}, msgAndArgs ...interface{}) {
// Positivef asserts that the specified element is positive
//
-// assert.Positivef(t, 1, "error message %s", "formatted")
-// assert.Positivef(t, 1.23, "error message %s", "formatted")
+// require.Positivef(t, 1, "error message %s", "formatted")
+// require.Positivef(t, 1.23, "error message %s", "formatted")
func Positivef(t TestingT, e interface{}, msg string, args ...interface{}) {
if h, ok := t.(tHelper); ok {
h.Helper()
@@ -1849,8 +1913,8 @@ func Positivef(t TestingT, e interface{}, msg string, args ...interface{}) {
// Regexp asserts that a specified regexp matches a string.
//
-// assert.Regexp(t, regexp.MustCompile("start"), "it's starting")
-// assert.Regexp(t, "start...$", "it's not starting")
+// require.Regexp(t, regexp.MustCompile("start"), "it's starting")
+// require.Regexp(t, "start...$", "it's not starting")
func Regexp(t TestingT, rx interface{}, str interface{}, msgAndArgs ...interface{}) {
if h, ok := t.(tHelper); ok {
h.Helper()
@@ -1863,8 +1927,8 @@ func Regexp(t TestingT, rx interface{}, str interface{}, msgAndArgs ...interface
// Regexpf asserts that a specified regexp matches a string.
//
-// assert.Regexpf(t, regexp.MustCompile("start"), "it's starting", "error message %s", "formatted")
-// assert.Regexpf(t, "start...$", "it's not starting", "error message %s", "formatted")
+// require.Regexpf(t, regexp.MustCompile("start"), "it's starting", "error message %s", "formatted")
+// require.Regexpf(t, "start...$", "it's not starting", "error message %s", "formatted")
func Regexpf(t TestingT, rx interface{}, str interface{}, msg string, args ...interface{}) {
if h, ok := t.(tHelper); ok {
h.Helper()
@@ -1877,7 +1941,7 @@ func Regexpf(t TestingT, rx interface{}, str interface{}, msg string, args ...in
// Same asserts that two pointers reference the same object.
//
-// assert.Same(t, ptr1, ptr2)
+// require.Same(t, ptr1, ptr2)
//
// Both arguments must be pointer variables. Pointer variable sameness is
// determined based on the equality of both type and value.
@@ -1893,7 +1957,7 @@ func Same(t TestingT, expected interface{}, actual interface{}, msgAndArgs ...in
// Samef asserts that two pointers reference the same object.
//
-// assert.Samef(t, ptr1, ptr2, "error message %s", "formatted")
+// require.Samef(t, ptr1, ptr2, "error message %s", "formatted")
//
// Both arguments must be pointer variables. Pointer variable sameness is
// determined based on the equality of both type and value.
@@ -1910,8 +1974,8 @@ func Samef(t TestingT, expected interface{}, actual interface{}, msg string, arg
// Subset asserts that the specified list(array, slice...) or map contains all
// elements given in the specified subset list(array, slice...) or map.
//
-// assert.Subset(t, [1, 2, 3], [1, 2])
-// assert.Subset(t, {"x": 1, "y": 2}, {"x": 1})
+// require.Subset(t, [1, 2, 3], [1, 2])
+// require.Subset(t, {"x": 1, "y": 2}, {"x": 1})
func Subset(t TestingT, list interface{}, subset interface{}, msgAndArgs ...interface{}) {
if h, ok := t.(tHelper); ok {
h.Helper()
@@ -1925,8 +1989,8 @@ func Subset(t TestingT, list interface{}, subset interface{}, msgAndArgs ...inte
// Subsetf asserts that the specified list(array, slice...) or map contains all
// elements given in the specified subset list(array, slice...) or map.
//
-// assert.Subsetf(t, [1, 2, 3], [1, 2], "error message %s", "formatted")
-// assert.Subsetf(t, {"x": 1, "y": 2}, {"x": 1}, "error message %s", "formatted")
+// require.Subsetf(t, [1, 2, 3], [1, 2], "error message %s", "formatted")
+// require.Subsetf(t, {"x": 1, "y": 2}, {"x": 1}, "error message %s", "formatted")
func Subsetf(t TestingT, list interface{}, subset interface{}, msg string, args ...interface{}) {
if h, ok := t.(tHelper); ok {
h.Helper()
@@ -1939,7 +2003,7 @@ func Subsetf(t TestingT, list interface{}, subset interface{}, msg string, args
// True asserts that the specified value is true.
//
-// assert.True(t, myBool)
+// require.True(t, myBool)
func True(t TestingT, value bool, msgAndArgs ...interface{}) {
if h, ok := t.(tHelper); ok {
h.Helper()
@@ -1952,7 +2016,7 @@ func True(t TestingT, value bool, msgAndArgs ...interface{}) {
// Truef asserts that the specified value is true.
//
-// assert.Truef(t, myBool, "error message %s", "formatted")
+// require.Truef(t, myBool, "error message %s", "formatted")
func Truef(t TestingT, value bool, msg string, args ...interface{}) {
if h, ok := t.(tHelper); ok {
h.Helper()
@@ -1965,7 +2029,7 @@ func Truef(t TestingT, value bool, msg string, args ...interface{}) {
// WithinDuration asserts that the two times are within duration delta of each other.
//
-// assert.WithinDuration(t, time.Now(), time.Now(), 10*time.Second)
+// require.WithinDuration(t, time.Now(), time.Now(), 10*time.Second)
func WithinDuration(t TestingT, expected time.Time, actual time.Time, delta time.Duration, msgAndArgs ...interface{}) {
if h, ok := t.(tHelper); ok {
h.Helper()
@@ -1978,7 +2042,7 @@ func WithinDuration(t TestingT, expected time.Time, actual time.Time, delta time
// WithinDurationf asserts that the two times are within duration delta of each other.
//
-// assert.WithinDurationf(t, time.Now(), time.Now(), 10*time.Second, "error message %s", "formatted")
+// require.WithinDurationf(t, time.Now(), time.Now(), 10*time.Second, "error message %s", "formatted")
func WithinDurationf(t TestingT, expected time.Time, actual time.Time, delta time.Duration, msg string, args ...interface{}) {
if h, ok := t.(tHelper); ok {
h.Helper()
@@ -1991,7 +2055,7 @@ func WithinDurationf(t TestingT, expected time.Time, actual time.Time, delta tim
// WithinRange asserts that a time is within a time range (inclusive).
//
-// assert.WithinRange(t, time.Now(), time.Now().Add(-time.Second), time.Now().Add(time.Second))
+// require.WithinRange(t, time.Now(), time.Now().Add(-time.Second), time.Now().Add(time.Second))
func WithinRange(t TestingT, actual time.Time, start time.Time, end time.Time, msgAndArgs ...interface{}) {
if h, ok := t.(tHelper); ok {
h.Helper()
@@ -2004,7 +2068,7 @@ func WithinRange(t TestingT, actual time.Time, start time.Time, end time.Time, m
// WithinRangef asserts that a time is within a time range (inclusive).
//
-// assert.WithinRangef(t, time.Now(), time.Now().Add(-time.Second), time.Now().Add(time.Second), "error message %s", "formatted")
+// require.WithinRangef(t, time.Now(), time.Now().Add(-time.Second), time.Now().Add(time.Second), "error message %s", "formatted")
func WithinRangef(t TestingT, actual time.Time, start time.Time, end time.Time, msg string, args ...interface{}) {
if h, ok := t.(tHelper); ok {
h.Helper()
diff --git require/require.go.tmpl require/require.go.tmpl
index 55e42ddeb..8b3283685 100644
--- require/require.go.tmpl
+++ require/require.go.tmpl
@@ -1,4 +1,4 @@
-{{.Comment}}
+{{ replace .Comment "assert." "require."}}
func {{.DocInfo.Name}}(t TestingT, {{.Params}}) {
if h, ok := t.(tHelper); ok { h.Helper() }
if assert.{{.DocInfo.Name}}(t, {{.ForwardedParams}}) { return }
diff --git require/require_forward.go require/require_forward.go
index eee8310a5..1bd87304f 100644
--- require/require_forward.go
+++ require/require_forward.go
@@ -187,8 +187,8 @@ func (a *Assertions) EqualExportedValuesf(expected interface{}, actual interface
EqualExportedValuesf(a.t, expected, actual, msg, args...)
}
-// EqualValues asserts that two objects are equal or convertible to the same types
-// and equal.
+// EqualValues asserts that two objects are equal or convertible to the larger
+// type and equal.
//
// a.EqualValues(uint32(123), int32(123))
func (a *Assertions) EqualValues(expected interface{}, actual interface{}, msgAndArgs ...interface{}) {
@@ -198,8 +198,8 @@ func (a *Assertions) EqualValues(expected interface{}, actual interface{}, msgAn
EqualValues(a.t, expected, actual, msgAndArgs...)
}
-// EqualValuesf asserts that two objects are equal or convertible to the same types
-// and equal.
+// EqualValuesf asserts that two objects are equal or convertible to the larger
+// type and equal.
//
// a.EqualValuesf(uint32(123), int32(123), "error message %s", "formatted")
func (a *Assertions) EqualValuesf(expected interface{}, actual interface{}, msg string, args ...interface{}) {
@@ -337,7 +337,7 @@ func (a *Assertions) Eventually(condition func() bool, waitFor time.Duration, ti
// a.EventuallyWithT(func(c *assert.CollectT) {
// // add assertions as needed; any assertion failure will fail the current tick
// assert.True(c, externalValue, "expected 'externalValue' to be true")
-// }, 1*time.Second, 10*time.Second, "external state has not changed to 'true'; still false")
+// }, 10*time.Second, 1*time.Second, "external state has not changed to 'true'; still false")
func (a *Assertions) EventuallyWithT(condition func(collect *assert.CollectT), waitFor time.Duration, tick time.Duration, msgAndArgs ...interface{}) {
if h, ok := a.t.(tHelper); ok {
h.Helper()
@@ -362,7 +362,7 @@ func (a *Assertions) EventuallyWithT(condition func(collect *assert.CollectT), w
// a.EventuallyWithTf(func(c *assert.CollectT, "error message %s", "formatted") {
// // add assertions as needed; any assertion failure will fail the current tick
// assert.True(c, externalValue, "expected 'externalValue' to be true")
-// }, 1*time.Second, 10*time.Second, "external state has not changed to 'true'; still false")
+// }, 10*time.Second, 1*time.Second, "external state has not changed to 'true'; still false")
func (a *Assertions) EventuallyWithTf(condition func(collect *assert.CollectT), waitFor time.Duration, tick time.Duration, msg string, args ...interface{}) {
if h, ok := a.t.(tHelper); ok {
h.Helper()
@@ -1129,6 +1129,40 @@ func (a *Assertions) NotContainsf(s interface{}, contains interface{}, msg strin
NotContainsf(a.t, s, contains, msg, args...)
}
+// NotElementsMatch asserts that the specified listA(array, slice...) is NOT equal to specified
+// listB(array, slice...) ignoring the order of the elements. If there are duplicate elements,
+// the number of appearances of each of them in both lists should not match.
+// This is an inverse of ElementsMatch.
+//
+// a.NotElementsMatch([1, 1, 2, 3], [1, 1, 2, 3]) -> false
+//
+// a.NotElementsMatch([1, 1, 2, 3], [1, 2, 3]) -> true
+//
+// a.NotElementsMatch([1, 2, 3], [1, 2, 4]) -> true
+func (a *Assertions) NotElementsMatch(listA interface{}, listB interface{}, msgAndArgs ...interface{}) {
+ if h, ok := a.t.(tHelper); ok {
+ h.Helper()
+ }
+ NotElementsMatch(a.t, listA, listB, msgAndArgs...)
+}
+
+// NotElementsMatchf asserts that the specified listA(array, slice...) is NOT equal to specified
+// listB(array, slice...) ignoring the order of the elements. If there are duplicate elements,
+// the number of appearances of each of them in both lists should not match.
+// This is an inverse of ElementsMatch.
+//
+// a.NotElementsMatchf([1, 1, 2, 3], [1, 1, 2, 3], "error message %s", "formatted") -> false
+//
+// a.NotElementsMatchf([1, 1, 2, 3], [1, 2, 3], "error message %s", "formatted") -> true
+//
+// a.NotElementsMatchf([1, 2, 3], [1, 2, 4], "error message %s", "formatted") -> true
+func (a *Assertions) NotElementsMatchf(listA interface{}, listB interface{}, msg string, args ...interface{}) {
+ if h, ok := a.t.(tHelper); ok {
+ h.Helper()
+ }
+ NotElementsMatchf(a.t, listA, listB, msg, args...)
+}
+
// NotEmpty asserts that the specified object is NOT empty. I.e. not nil, "", false, 0 or either
// a slice or a channel with len == 0.
//
@@ -1201,7 +1235,25 @@ func (a *Assertions) NotEqualf(expected interface{}, actual interface{}, msg str
NotEqualf(a.t, expected, actual, msg, args...)
}
-// NotErrorIs asserts that at none of the errors in err's chain matches target.
+// NotErrorAs asserts that none of the errors in err's chain matches target,
+// but if so, sets target to that error value.
+func (a *Assertions) NotErrorAs(err error, target interface{}, msgAndArgs ...interface{}) {
+ if h, ok := a.t.(tHelper); ok {
+ h.Helper()
+ }
+ NotErrorAs(a.t, err, target, msgAndArgs...)
+}
+
+// NotErrorAsf asserts that none of the errors in err's chain matches target,
+// but if so, sets target to that error value.
+func (a *Assertions) NotErrorAsf(err error, target interface{}, msg string, args ...interface{}) {
+ if h, ok := a.t.(tHelper); ok {
+ h.Helper()
+ }
+ NotErrorAsf(a.t, err, target, msg, args...)
+}
+
+// NotErrorIs asserts that none of the errors in err's chain matches target.
// This is a wrapper for errors.Is.
func (a *Assertions) NotErrorIs(err error, target error, msgAndArgs ...interface{}) {
if h, ok := a.t.(tHelper); ok {
@@ -1210,7 +1262,7 @@ func (a *Assertions) NotErrorIs(err error, target error, msgAndArgs ...interface
NotErrorIs(a.t, err, target, msgAndArgs...)
}
-// NotErrorIsf asserts that at none of the errors in err's chain matches target.
+// NotErrorIsf asserts that none of the errors in err's chain matches target.
// This is a wrapper for errors.Is.
func (a *Assertions) NotErrorIsf(err error, target error, msg string, args ...interface{}) {
if h, ok := a.t.(tHelper); ok {
diff --git require/requirements.go require/requirements.go
index 91772dfeb..6b7ce929e 100644
--- require/requirements.go
+++ require/requirements.go
@@ -6,7 +6,7 @@ type TestingT interface {
FailNow()
}
-type tHelper interface {
+type tHelper = interface {
Helper()
}
diff --git require/requirements_test.go require/requirements_test.go
index febf0c187..824b159fa 100644
--- require/requirements_test.go
+++ require/requirements_test.go
@@ -5,6 +5,8 @@ import (
"errors"
"testing"
"time"
+
+ "github.com/stretchr/testify/assert"
)
// AssertionTesterInterface defines an interface to be used for testing assertion methods
@@ -681,3 +683,30 @@ func TestErrorAssertionFunc(t *testing.T) {
})
}
}
+
+func TestEventuallyWithTFalse(t *testing.T) {
+ mockT := new(MockT)
+
+ condition := func(collect *assert.CollectT) {
+ True(collect, false)
+ }
+
+ EventuallyWithT(mockT, condition, 100*time.Millisecond, 20*time.Millisecond)
+ True(t, mockT.Failed, "Check should fail")
+}
+
+func TestEventuallyWithTTrue(t *testing.T) {
+ mockT := new(MockT)
+
+ counter := 0
+ condition := func(collect *assert.CollectT) {
+ defer func() {
+ counter += 1
+ }()
+ True(collect, counter == 1)
+ }
+
+ EventuallyWithT(mockT, condition, 100*time.Millisecond, 20*time.Millisecond)
+ False(t, mockT.Failed, "Check should pass")
+ Equal(t, 2, counter, "Condition is expected to be called 2 times")
+}
diff --git suite/doc.go suite/doc.go
index 8d55a3aa8..05a562f72 100644
--- suite/doc.go
+++ suite/doc.go
@@ -5,6 +5,8 @@
// or individual tests (depending on which interface(s) you
// implement).
//
+// The suite package does not support parallel tests. See [issue 934].
+//
// A testing suite is usually built by first extending the built-in
// suite functionality from suite.Suite in testify. Alternatively,
// you could reproduce that logic on your own if you wanted (you
@@ -63,4 +65,6 @@
// func TestExampleTestSuite(t *testing.T) {
// suite.Run(t, new(ExampleTestSuite))
// }
+//
+// [issue 934]: https://github.com/stretchr/testify/issues/934
package suite
diff --git suite/suite_test.go suite/suite_test.go
index db57a5fd2..b97eb4311 100644
--- suite/suite_test.go
+++ suite/suite_test.go
@@ -604,14 +604,44 @@ func TestFailfastSuite(t *testing.T) {
}},
)
assert.False(t, ok)
+ var expect []string
if failFast {
// Test A Fails and because we are running with failfast Test B never runs and we proceed straight to TearDownSuite
- assert.Equal(t, "SetupSuite;SetupTest;Test A Fails;TearDownTest;TearDownSuite", strings.Join(s.callOrder, ";"))
+ expect = []string{"SetupSuite", "SetupTest", "Test A Fails", "TearDownTest", "TearDownSuite"}
} else {
// Test A Fails and because we are running without failfast we continue and run Test B and then proceed to TearDownSuite
- assert.Equal(t, "SetupSuite;SetupTest;Test A Fails;TearDownTest;SetupTest;Test B Passes;TearDownTest;TearDownSuite", strings.Join(s.callOrder, ";"))
+ expect = []string{"SetupSuite", "SetupTest", "Test A Fails", "TearDownTest", "SetupTest", "Test B Passes", "TearDownTest", "TearDownSuite"}
}
+ callOrderAssert(t, expect, s.callOrder)
}
+
+type tHelper interface {
+ Helper()
+}
+
+// callOrderAssert is a help with confirms that asserts that expect
+// matches one or more times in callOrder. This makes it compatible
+// with go test flag -count=X where X > 1.
+func callOrderAssert(t *testing.T, expect, callOrder []string) {
+ var ti interface{} = t
+ if h, ok := ti.(tHelper); ok {
+ h.Helper()
+ }
+
+ callCount := len(callOrder)
+ expectCount := len(expect)
+ if callCount > expectCount && callCount%expectCount == 0 {
+ // Command line flag -count=X where X > 1.
+ for len(callOrder) >= expectCount {
+ assert.Equal(t, expect, callOrder[:expectCount])
+ callOrder = callOrder[expectCount:]
+ }
+ return
+ }
+
+ assert.Equal(t, expect, callOrder)
+}
+
func TestFailfastSuiteFailFastOn(t *testing.T) {
// To test this with failfast on (and isolated from other intended test failures in our test suite) we launch it in its own process
cmd := exec.Command("go", "test", "-v", "-race", "-run", "TestFailfastSuite", "-failfast")
Here's my review of the pull request: DescriptionThis PR makes several updates and improvements across the testify library, including adding support for Go 1.22, updating GitHub Actions, enhancing documentation, fixing bugs, and improving test coverage. ChangesChanges
sequenceDiagram
participant User
participant Testify
participant Go
User->>Testify: Write tests using testify
Testify->>Go: Run tests
Go->>Testify: Return test results
Testify->>User: Report test results
Note over User,Testify: New features:
Note over User,Testify: Go 1.22 support
Note over User,Testify: Improved error messages
Note over User,Testify: Enhanced mock ordering
Note over User,Testify: Better time comparisons
Possible Issues
Security HotspotsNone identified. This PR appears to be a comprehensive update to the testify library, improving its functionality, compatibility, and user experience. The changes seem well-considered and should benefit users of the library. |
This PR contains the following updates:
v1.9.0
->v1.10.0
Release Notes
stretchr/testify (github.com/stretchr/testify)
v1.10.0
Compare Source
What's Changed
Functional Changes
Fixes
Documantation, Build & CI
New Contributors
Full Changelog: stretchr/testify@v1.9.0...v1.10.0
Configuration
📅 Schedule: Branch creation - "* 0-4 * * 3" (UTC), Automerge - At any time (no schedule defined).
🚦 Automerge: Disabled by config. Please merge this manually once you are satisfied.
♻ Rebasing: Whenever PR is behind base branch, or you tick the rebase/retry checkbox.
🔕 Ignore: Close this PR and you won't be reminded about this update again.
This PR was generated by Mend Renovate. View the repository job log.