fix some faulty defers in tests

Calling "defer assert.NilError(t, someCommand())" executes "someCommand()"
immediately, but doesn't assert the error until the defer.
https://go.dev/play/p/EO--y7OYerg

    package main

    import (
        "errors"
        "testing"

        "gotest.tools/v3/assert"
    )

    func TestDefer(t *testing.T) {
        doSomething := func() error {
            t.Log("doSomething failed with an error!")
            return errors.New("foo error")
        }

        defer assert.NilError(t, doSomething())

        t.Log("running test")
        t.Log("running test")
        t.Log("running test")
    }

Produces:

    === RUN   TestDefer
        prog_test.go:12: doSomething failed with an error!
        prog_test.go:18: running test
        prog_test.go:19: running test
        prog_test.go:20: running test
        prog_test.go:21: assertion failed: error is not nil: foo error
    --- FAIL: TestDefer (0.00s)
    FAIL

Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
This commit is contained in:
Sebastiaan van Stijn
2025-10-27 12:33:11 +01:00
parent 370ca31ecf
commit 6040a2f686
5 changed files with 19 additions and 7 deletions

View File

@@ -235,13 +235,15 @@ func TestVolCreateValidation(t *testing.T) {
}
v, err := r.Create(tc.name, tc.opts)
if v != nil {
defer assert.Check(t, r.Remove(v))
defer func() {
assert.Check(t, r.Remove(v))
}()
}
if tc.expectedErr == "" {
assert.NilError(t, err)
} else {
assert.Check(t, cerrdefs.IsInvalidArgument(err), "got: %T", err)
assert.ErrorContains(t, err, tc.expectedErr)
assert.Check(t, is.ErrorContains(err, tc.expectedErr))
}
})
}