/p/g17khqpukees4237dtn3astzapmp462vjhsz6st4/expect
Directory · 13 Files
Expect Package
Package for testing Gno packages and realms using function chaining and expressive semantics.
Asserting Values
Use Value() to check that a value meets expectations. Chain Not() to negate an assertion,
and use AsInt(), AsString(), AsBoolean() (and similar) to narrow to type-specific assertions.
1package expect_test
2
3import (
4 "errors"
5 "testing"
6
7 "gno.land/p/g17khqpukees4237dtn3astzapmp462vjhsz6st4/expect"
8)
9
10func TestReadmeValue(t *testing.T) {
11 // Assert integer value
12 score := 42
13 expect.Value(t, score).ToEqual(42)
14 expect.Value(t, score).Not().ToEqual(0)
15 expect.Value(t, score).AsInt().ToBeLowerThan(100)
16
17 // Assert string value
18 name := "Alice"
19 expect.Value(t, name).AsString().ToEqual("Alice")
20 expect.Value(t, name).AsString().ToHaveLength(5)
21
22 // Assert boolean value
23 expect.Value(t, true).AsBoolean().ToBeTruthy()
24
25 // Assert pointer value
26 var v any
27 expect.Value(t, v).ToBeNil()
28
29 // Assert error value
30 err := errors.New("foo bar")
31 expect.Value(t, err).ToEqual(err)
32 expect.Value(t, err).ToContainErrorString("foo")
33}
Asserting Functions
Use Func() to check that a function returns an error, panics, or returns an expected value.
Chain .ToFail(), .ToPanic(), or .ToReturn() and then assert the message or value.
Package supports four type of functions:
- func()
- func() any
- func() error
- func() (any, error)
1package expect_test
2
3import (
4 "errors"
5 "testing"
6
7 "gno.land/p/g17khqpukees4237dtn3astzapmp462vjhsz6st4/expect"
8)
9
10func TestReadmeFunc(t *testing.T) {
11 foo := func() int {
12 return 42
13 }
14
15 fooPanic := func() {
16 panic("boom!")
17 }
18
19 err := errors.New("boom!")
20 fooError := func(err error) error {
21 return err
22 }
23
24 // Assert that "fooError" function returns an error
25 expect.Func(t, func() error {
26 return fooError(err)
27 }).ToFail().WithError(err)
28
29 // Assert that "fooPanic" function panics with a message
30 expect.Func(t, func() {
31 fooPanic()
32 }).ToPanic().WithMessage("boom!")
33
34 // Assert that "foo" function returns 42
35 expect.Func(t, func() any {
36 return foo()
37 }).ToReturn(42)
38}