error.gno

1.27 Kb ยท 52 lines
 1package expect
 2
 3import "gno.land/p/demo/ufmt"
 4
 5// NewErrorChecker creates a new checker of errors.
 6func NewErrorChecker(ctx Context, err error) ErrorChecker {
 7	return ErrorChecker{ctx, err}
 8}
 9
10// ErrorChecker asserts error values.
11type ErrorChecker struct {
12	ctx Context
13	err error
14}
15
16// Not negates the next called expectation.
17func (c ErrorChecker) Not() ErrorChecker {
18	c.ctx.negated = !c.ctx.negated
19	return c
20}
21
22// WithMessage asserts that current error contains an expected message.
23func (c ErrorChecker) WithMessage(msg string) {
24	c.ctx.T().Helper()
25
26	if c.err == nil {
27		c.ctx.Fail("Expected an error with message\nGot: nil\nWant: %s", msg)
28		return
29	}
30
31	NewMessageChecker(c.ctx, c.err.Error(), MessageTypeError).WithMessage(msg)
32}
33
34// WithError asserts that current error message is the same as an expected error.
35func (c ErrorChecker) WithError(err error) {
36	c.ctx.T().Helper()
37
38	if c.err == nil {
39		if err != nil {
40			c.ctx.Fail("Expected an error\nGot: nil\nWant: %s", err.Error())
41		}
42		return
43	}
44
45	got := c.err.Error()
46	c.ctx.CheckExpectation(got == err.Error(), func(ctx Context) string {
47		if !ctx.IsNegated() {
48			return ufmt.Sprintf("Expected errors to match\nGot: %s\nWant: %s", got, err.Error())
49		}
50		return ufmt.Sprintf("Expected errors to be different\nGot: %s", got)
51	})
52}