220 Commits

Author SHA1 Message Date
ccoVeille
a53be35c3b Improve captureTestingT helper
This helper is used to capture the testing.TB interface, and compare
the log output with the expected output.

This is useful for testing and refactoring purposes.

This commit improves the helper by displaying:
- the captured and expected outputs on a newline.
- the special characters in the captured output, such as newlines and tabs.

Both help with readability.

Here is an example of the output before and after the change:

Before:

    assertions_test.go:3422: Logged Error: Should be in error chain
        expected: *assert.customError
        in chain: "EOF" (*errors.errorString)
    assertions_test.go:3422: Should log Error: Should be in error chain:
        expected: *assert.customError
        in chain: "EOF" (*errors.errorString)

After:
    assertions_test.go:3394: Recorded Error: "Should be in error chain:\nexpected: *assert.customError\nin chain: \"EOF\" (*errors.errorString)\n"
    assertions_test.go:3394: Expected Error: "Should be in error chain\nexpected: *assert.customError\nin chain: \"EOF\" (*errors.errorString)"

The new format helps to identify the differences:
- the missing colon after "Should be in error chain"
- the extra newline in the captured output

Note: I spent 10 minutes on this change, because I lost 10 minutes in
finding the differences between the captured and expected output on a
refactoring I was doing.
2025-07-01 09:45:29 +02:00
Olivier Mengué
44c0281fe0 assert/tests: improve failure reporting in Test{No,}{File,Dir}Exists
Improve error reporting in getTempSymlinkPath by displaying the
file paths.
2025-06-30 18:01:18 +02:00
Olivier Mengué
50277a850b assert/tests: simplify Test{No,}{File,Dir}Exists
In tests of the assert package, move more logic from each test into
the helper getTempSymlinkPath.
2025-06-30 18:01:18 +02:00
Olivier Mengué
d9125497d7 assert/tests: enable parallel testing for Test{,No}{File,Dir}Exists
In package assert, fix TestFileExists, TestNoFileExists, TestDirExists, TestNoDirExists
to be able to run in parallel:
- use t.TempDir() as the storage location for temporary created
  symlinks. This also allows the cleanup of that storage to be
  automatically handled by "go test". testing.T.TempDir is available
  since go1.15.
- enable parallel testing on each test
2025-06-30 18:01:18 +02:00
Olivier Mengué
5488b2163b assert: improve EqualValues test coverage to 100%
Extend TestNotEqualValues to also test EqualValues by leveraging the fact
that they are inverse functions. The same test cases are used to verify
that EqualValues returns the opposite result of NotEqualValues.

This change ensures both success and failure paths are tested for
EqualValues, covering the error formatting and failure reporting code
that was previously untested.

Coverage improvement:
- EqualValues: 57.1% → 100.0%
- Overall package: 68.4% → 68.5%

The test function was renamed to TestEqualValuesAndNotEqualValues to
reflect its dual purpose while maintaining all existing test logic.

Co-Authored-By: sketch <hello@sketch.dev>
Change-ID: s30d4192b08186d88k
2025-06-16 16:16:09 +02:00
Olivier Mengué
0b5b5e64f9 assert: add Benchmark_isEmpty
Add a benchmark that shows that isEmpty does memory allocations.

$ go test -bench Benchmark_isEmpty
goos: darwin
goarch: arm64
pkg: github.com/stretchr/testify/assert
cpu: Apple M2
Benchmark_isEmpty-8   	15074973	       76.73 ns/op	      8 B/op	      1 allocs/op

We can do better!
2025-06-04 12:19:44 +02:00
Olivier Mengué
c519b7942b assert.Empty: comprehensive doc of "Empty"-ness rules
Document the assert.Empty rules more comprehensively. This exposes our
quirks to the user to avoid wrong expectations.

Add many many many more test cases that document edges cases and will allow
to catch breaking changes and avoid regressions.
2025-06-03 00:11:08 +02:00
Olivier Mengué
a5d5c3395e
Merge pull request #1745 from ccoveille-forks/improve-tests-empty-notempty
assert: check test failure message for Empty and NotEmpty
2025-05-31 14:48:10 +02:00
Olivier Mengué
bf47cc8868 assert/tests: add Helper() in all testing.T mocks
Add an Helper() method to all mocks in tests of package 'assert'.
2025-05-25 21:56:50 +02:00
Olivier Mengué
603c2a0348 assert,require: enable parallel testing on (almost) all top tests
Enable parallel testing for almost all tests in packages 'assert' and
'require' by calling t.Parallel() as the first line of the test.

A few tests are incompatible and will be fixed separately. They are
marked with a FIXME.
Incompatible tests: TestFileExists, TestNoFileExists, TestDirExists,
TestNoDirExists.

Before:
  $ go test -count=10 ./assert ./require
  ok  	github.com/stretchr/testify/assert	7.575s
  ok  	github.com/stretchr/testify/require	1.501s

After:
  $ go test -count=10 ./assert ./require
  ok  	github.com/stretchr/testify/assert	1.703s
  ok  	github.com/stretchr/testify/require	1.245s
2025-05-23 16:17:12 +02:00
ccoVeille
559d23ae66
check test failure message for Empty and NotEmpty
Only the tests are updated, code is unchanged.

Previously, the tests were checking only the result of the asserter.
Using captureTestingT helper allows to check the error message
2025-05-22 18:51:32 +02:00
Bart Venter
9fc264e324
assert: add IsNotType (#1730)
Add the `IsNotType` assertion, which is the inverse
of the existing `IsType` assertion. It allows users to assert that an
object is not of a specific type.

Additionally, minor documentation improvements were made.

## Summary
This PR adds a new assertion function, `IsNotType`, to the
`testify/assert` package. It complements the existing `IsType` function
by providing a way to assert that an object is not of a specific type.

## Changes
* Added the `IsNotType` function to the `assert` package.
* Wrote unit tests for `IsNotType` to ensure correctness.
* Updated documentation to include examples and usage for `IsNotType`.

## Motivation
The `testify/assert` package already provides an `IsType` function to
check if an object is of a specific type. However, there was no built-in
way to assert that an object is **not** of a specific type. This PR
addresses that gap by introducing the `IsNotType` function, improving
the library's completeness and usability.

## Example usage
```go
assert.IsNotType(t, &MyStruct{}, actualObject)
```

## Related issues
_N/A_
2025-05-22 11:45:11 +02:00
ccoVeille
9bcca2f950
Format assertions files with gofumpt 2025-05-13 14:17:27 +02:00
ccoVeille
c2116b4194
Improve ErrorAs failure message when error is nil
Before:

    Should be in error chain:
    expected: *assert.customError
    in chain:

After:
    An error is expected but got nil.
    expected: *assert.customError

The message `An error is expected but got nil.` is the one already
reported by `assert.Error`
2025-05-08 20:48:57 +02:00
Bracken
111716d6f9
Merge pull request #1729 from siliconbrain/fix-subset-notsubset-mixed-type
fix Subset/NotSubset when calling with mixed input types
2025-05-08 13:42:27 +01:00
Bracken
d338e951cf
Merge pull request #1681 from tsioftas/tsioftas/erroris-improve
Improve ErrorIs message when error is nil but an error was expected
2025-05-08 11:40:41 +01:00
Bracken
f4244f1680
Merge pull request #1427 from cszczepaniak/cs/quicker_eventually
assert: check early in Eventually, EventuallyWithT, and Never
2025-05-06 14:28:41 +01:00
Dudás Ádám
2a9c44b1d8 fix Subset/NotSubset when calling with mixed input types (array/slice list with map subset) 2025-04-23 14:31:40 +00:00
tsioftas
5ed1b90367
Update assert/assertions_test.go
Co-authored-by: Bracken <abdawson@gmail.com>
2025-04-03 14:17:58 +03:00
Bracken
c3915e850a
Merge branch 'master' into refactor/simplify-with-sprintf-q 2025-03-23 14:22:18 +01:00
Craig Davison
c60c3bd7fb dereference target 2025-01-03 14:34:16 -07:00
Craig Davison
1c717c00c1 Add return 2024-12-31 15:35:31 -07:00
Craig Davison
ca6698b8a1 assert.ErrorAs: log target type 2024-12-31 15:09:40 -07:00
Oleksandr Redko
30f3cef5ad Apply suggestions from code review
Co-authored-by: Olivier Mengué <dolmen@cpan.org>
2024-12-10 14:08:46 +02:00
Oleksandr Redko
d57bac8721 refactor: use %q to simplify fmt.Sprintf 2024-11-24 18:28:03 +02:00
tsioftas
19ddcbb61a go fmt 2024-11-18 12:20:16 +00:00
tsioftas
7434b149f3 Improve ErrorIs message when error is nil but an error was expected 2024-11-18 11:48:33 +00:00
Hisham Akmal
118fb83466
NotSame should fail if args are not pointers #1661 (#1664)
## Summary
Reduces the confusion assosciated with NotSame that previously would
check nothing if any of the values is not a pointer. The changes made
were tested using TestSame, TestNotSame, and Test_samePointers tests,
and the changes did clear the tests.

## Changes
1. Modified samePointers to return another bool value(ok) that would
determine if the 2 values are of pointer type or not, while the returned
"same" bool value would determine if the 2 pointers are same.
2. Modified assert.NotSame to call Fail() if the 2 values are either
i)pointers pointing to the same address or ii)either/both of the values
are not pointers.
3. Modified assert.Same to call Fail() if the 2 values are either
i)pointers not pointing to the same address or ii)either/both of the
values are not pointers.
4. Modified Test_samePointers to handle the new behavior of samePointers
by checking both if the inputs are pointers (ok) and if they point to
the same object (same).

## Motivation
Ensure NotSame accurately verifies pointer sameness by handling
non-pointer inputs explicitly, improving clarity and reducing potential
misuse.

## Related issues
Closes #1661

---------

Co-authored-by: Bracken <abdawson@gmail.com>
2024-10-28 11:08:04 +00:00
Bracken
8302de98b1
Merge branch 'master' into master 2024-10-26 19:41:18 +01:00
Bracken
dce9e58ee3
Merge branch 'master' into fix/equal-exported-values-accepts-everything 2024-10-23 23:37:57 +01:00
Yaroslav Brustinov
6555fd4da6 Fix issue #1662 (comparing infs should fail) 2024-10-16 17:25:23 +03:00
Oleksandr Redko
2063e81696 assert: fix typos in comments 2024-10-04 18:02:45 +03:00
Pal Sivertsen
aade8450b3 Improve tests for ErrorIs/ErrorAs
Checks that the assertion result matches what's set in `testing.T`.
2024-10-04 12:43:45 +02:00
Pal Sivertsen
3380867632 Add NotErrorAs assertion
The library already had assertions for `ErrorIs`, `NotErrorIs` and
`ErrorAs`. This commit adds the `NotErrorAs` assertion which is the
inverse of `ErrorAs`.
2024-10-04 12:43:45 +02:00
Connor Szczepaniak
bae586f140
colocate never/eventually tests 2024-07-09 08:44:49 -05:00
Connor Szczepaniak
bf2c747cca
simplify tests 2024-07-09 08:44:03 -05:00
Connor Szczepaniak
ab114f88b1
test never when it fails quickly 2024-07-09 08:44:03 -05:00
cszczepaniak
f96316432b
test that we succeed quickly 2024-07-09 08:31:19 -05:00
Vladimir Kochnev
b074924938
assert: collect.FailNow() should not panic (#1481)
## Summary
`collect.FailNow()` should exit goroutine without a panic to be usable
with `require` package.

## Changes
`collect.FailNow()` just does `runtime.Goexit()` instead of `panic()`.
For example `FailNow()` from `testing` package [behaves
similarly](https://cs.opensource.google/go/go/+/refs/tags/go1.21.2:src/testing/testing.go;l=973).

## Motivation

I just want `require` package to be usable with `EventuallyWithT` e.g. I
want this example to pass but it panics:

```go
package main

import (
	"testing"
	"time"

	"github.com/stretchr/testify/assert"
	"github.com/stretchr/testify/require"
)

func TestRequireEventuallyWithT(t *testing.T) {
	state := 0
	require.EventuallyWithT(t, func(c *assert.CollectT) {
		defer func() { state += 1 }()
		require.True(c, state == 2)
	}, 100*time.Millisecond, 10*time.Millisecond)
}
```

See https://go.dev/play/p/Oqd95IT7qxQ

## Related issues
Fixes https://github.com/stretchr/testify/issues/1396
Fixes https://github.com/stretchr/testify/issues/1457
2024-06-13 22:09:51 +02:00
hendry.wiranto
7af3ed34c2 feat: new assertion NotElementsMatch 2024-05-28 21:36:34 +07:00
Reda Chlieh
df81388b27
Merge branch 'master' into fix/equal-exported-values-accepts-everything 2024-05-23 10:26:47 +02:00
Kevin Burke
a9e6121b1c
assert: handle []byte array properly
The regexp package works more efficiently on bytes; if you have bytes,
it is easier to pass these directly to assert.Regexp than to convert
them to a string first.

In addition, FindIndex/FindStringIndex are unnecessary here because we
immediately throw away the result - let's just call Match() instead.
2024-04-17 12:18:13 -07:00
Reda Chlieh
42d887f28b
Remove type validation in EqualExportedValues 2024-04-11 22:54:14 +02:00
Fahim Bagar
8585d8de96
Add PanicAssertionFunc (#1337, #730)
Add a `PanicAssertionFunc` to ease writing table-driven tests for panic
assertion.

Closes #730
2024-03-05 10:13:30 +01:00
Bracken
5b6926d686
Merge pull request #1385 from hslatman/not-implements
Add `NotImplements` and variants
2024-02-28 16:02:08 +00:00
ccoVeille
85d8bb6eea
fix typos in comments, tests and github templates 2024-02-24 23:48:24 +01:00
Arjun Mahishi
6e59f20c0d http_assertions: assert that the msgAndArgs actually works in tests
This commit also adds the method `Failed() bool` to the mockTestingT
struct. This is usefull for asserting failure in tests
2024-02-23 22:41:24 +05:30
Bracken
9f0ad86b78
Merge pull request #1517 from Lucaber/equalExportedValues-ptr
Support Pointer to Struct in EqualExportedValues
2024-02-22 17:16:44 +00:00
Bracken Dawson
7b3de08425
Revert "assert: ObjectsAreEqual: use time.Equal for time.Time type"
This reverts commit 34763e0df3d560ca247996a0e9291fa919a3abc6.

time.Time.Equal only tests that the two instances refer to the same instant, but time.Time also carries zone information, so this caused two non-equal instances to be considered equal.
2024-02-18 20:43:45 +00:00
Kevin Burke
89c0872acd
try to do the whole format string 2024-02-15 11:35:07 -07:00