aboutsummaryrefslogtreecommitdiffstats
path: root/vendor/github.com/frankban/quicktest/checker_err.go
blob: f56ec217abaf6f4e745a69e3e01e5e5bd467449e (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
// Licensed under the MIT license, see LICENSE file for details.

package quicktest

import (
	"errors"
	"fmt"
)

// ErrorAs checks that the error is or wraps a specific error type. If so, it
// assigns it to the provided pointer. This is analogous to calling errors.As.
//
// For instance:
//
//     // Checking for a specific error type
//     c.Assert(err, qt.ErrorAs, new(*os.PathError))
//
//     // Checking fields on a specific error type
//     var pathError *os.PathError
//     if c.Check(err, qt.ErrorAs, &pathError) {
//         c.Assert(pathError.Path, qt.Equals, "some_path")
//     }
//
var ErrorAs Checker = &errorAsChecker{
	argNames: []string{"got", "as"},
}

type errorAsChecker struct {
	argNames
}

// Check implements Checker.Check by checking that got is an error whose error
// chain matches args[0] and assigning it to args[0].
func (c *errorAsChecker) Check(got interface{}, args []interface{}, note func(key string, value interface{})) (err error) {
	if err := checkFirstArgIsError(got, note); err != nil {
		return err
	}

	gotErr := got.(error)
	defer func() {
		// A panic is raised when the target is not a pointer to an interface
		// or error.
		if r := recover(); r != nil {
			err = BadCheckf("%s", r)
		}
	}()
	as := args[0]
	if errors.As(gotErr, as) {
		return nil
	}

	note("error", Unquoted("wanted type is not found in error chain"))
	note("got", gotErr)
	note("as", Unquoted(fmt.Sprintf("%T", as)))
	return ErrSilent
}

// ErrorIs checks that the error is or wraps a specific error value. This is
// analogous to calling errors.Is.
//
// For instance:
//
//     c.Assert(err, qt.ErrorIs, os.ErrNotExist)
//
var ErrorIs Checker = &errorIsChecker{
	argNames: []string{"got", "want"},
}

type errorIsChecker struct {
	argNames
}

// Check implements Checker.Check by checking that got is an error whose error
// chain matches args[0].
func (c *errorIsChecker) Check(got interface{}, args []interface{}, note func(key string, value interface{})) error {
	if got == nil && args[0] == nil {
		return nil
	}
	if err := checkFirstArgIsError(got, note); err != nil {
		return err
	}

	gotErr := got.(error)
	wantErr, ok := args[0].(error)
	if !ok && args[0] != nil {
		note("want", args[0])
		return BadCheckf("second argument is not an error")
	}

	if !errors.Is(gotErr, wantErr) {
		return errors.New("wanted error is not found in error chain")
	}
	return nil
}