From 4cb531e2e45e911b6ea77f3616b8c0e41dda42dd Mon Sep 17 00:00:00 2001 From: Matthieu MOREL Date: Sun, 30 Jun 2024 16:43:36 +0200 Subject: [PATCH] doc: update error-compare and define unwrapped-error Co-authored-by: ccoVeille <3875889+ccoVeille@users.noreply.github.com> --- CONTRIBUTING.md | 25 ++++++++++++++++++++++--- 1 file changed, 22 insertions(+), 3 deletions(-) diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index 2914942..22d836f 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -143,7 +143,7 @@ Describe a new checker in [checkers section](./README.md#checkers). - [require-len](#require-len) - [suite-test-name](#suite-test-name) - [useless-assert](#useless-assert) - +- [unwrapped-error](#unwrapped-error) --- ### elements-match @@ -169,22 +169,41 @@ Describe a new checker in [checkers section](./README.md#checkers). --- +### unwrapped-error + +```go +❌ assert.Contains(t, err.Error(), "not found") + assert.Equal(t, err.Error(), "user not found") + +✅ assert.ErrorContains(t, err, "not found") + assert.EqualError(t, err, "user not found") + assert.ErrorIs(t, err, ErrUserNotFound) + assert.NotErrorIs(t, err, errSentinel) +``` + +**Autofix**: true.
+**Enabled by default**: true.
+**Reason**: Using testify methods will avoid the risk of nil pointer exception that might happen with the use of the `Error()` method on the `error` interface.
+**Related issues**: [#47](https://github.com/Antonboom/testifylint/issues/47) + +--- + ### error-compare ```go ❌ assert.ErrorContains(t, err, "not found") assert.EqualError(t, err, "user not found") - assert.Equal(t, err.Error(), "user not found") assert.Equal(t, err, errSentinel) // Through `reflect.DeepEqual` causes error strings to be compared. assert.NotEqual(t, err, errSentinel) // etc. ✅ assert.ErrorIs(t, err, ErrUserNotFound) + assert.ErrorAs(t, err, &target) ``` **Autofix**: false.
**Enabled by default**: true.
-**Reason**: The `Error()` method on the `error` interface exists for humans, not code.
+**Reason**: The `assert.ErrorContains()` is commonly used as an anti-pattern. The code and tests often needs to be adapted to be able to use `assert.ErrorIs()` or `assert.ErrorAs()` methods.
**Related issues**: [#47](https://github.com/Antonboom/testifylint/issues/47) ---