frankban / quicktest

Quick helpers for testing Go applications
MIT License
529 stars 27 forks source link

Add ErrorAs and ErrorIs checkers #110

Closed miquella closed 3 years ago

miquella commented 3 years ago

The ErrorAs and ErrorIs checkers provide convenient ways for working with wrapped errors. They allow test authors to make assertions about errors anywhere in the chain of wrapped errors. Any error that supports the Unwrap() error method is supported, such as those returned by fmt.Errorf() or the github.com/pkg/errors package.

Example ErrorAs usage:

var customError CustomError
if c.Check(err, qt.ErrorAs, &customError) {
    c.Assert(customError.Something, …)
}

Example ErrorIs usage:

c.Assert(err, qt.ErrorIs, os.ErrNotExist)

The initial discussion for this was in #109.

miquella commented 3 years ago

@rogpeppe / @frankban: It wouldn't take too much code to provide a shim for older versions of Go. Happy to add that, if you'd like?

miquella commented 3 years ago

For supporting pre-1.13 versions, I believe we could do something like this (completely untested): https://gist.github.com/miquella/33dbbc1f4ac26c88e2e55663f25ac101

And for post-1.13, we could simply have:

//go:build go1.13
// +build go1.13

package quicktest

import (
    "errors"
)

var errorsAs = errors.As
var errorsIs = errors.Is

But I believe we would need to update the tests to not use fmt.Errorf.

miquella commented 3 years ago

Alternatively, we could simply only expose these two checkers for Go 1.13+. That way support for older versions of Go don't need to be dropped and shims for the standard library don't need to be maintained either.

frankban commented 3 years ago

Alternatively, we could simply only expose these two checkers for Go 1.13+. That way support for older versions of Go don't need to be dropped and shims for the standard library don't need to be maintained either.

Yes we use this approach for other features introduced over time, and I think we probably should stick with this for now. Thanks!

miquella commented 3 years ago

@rogpeppe / @frankban: I've moved the error checkers into separate files with the go1.13 build tag so they're only available for Go 1.13+.

If I were to guess, we probably don't want to do the same with the docs (doc.go), correct? It would effectively exclude the docs for versions of Go prior to 1.13, but scrambles the order of the docs.

miquella commented 3 years ago

@frankban: Thanks for the quick review! (and please don't worry about the last review cycle being longer, I totally understand :slightly_smiling_face:)