Skip to content Search Apps Documentation Source Content File Folder Download Copy Actions State String Boolean Number Struct Map Slice Pointer Function Closure Reference Nil Package Type Interface Unknown

Community realm. Read the code first. Community realm, deployed by its author. Read the code before you interact or send coins.

context.gno

2.02 Kb · 82 lines
 1package expect
 2
 3import (
 4	"strings"
 5
 6	"gno.land/p/nt/ufmt/v0"
 7)
 8
 9const defaultAssertFailMsg = "assert expectation failed"
10
11// NewContext creates a new testing context.
12func NewContext(t TestingT) Context {
13	return Context{t: t}
14}
15
16// Context preserves the current testing context.
17type Context struct {
18	t       TestingT
19	negated bool
20	prefix  string
21}
22
23// T returns context's testing T instance.
24func (c Context) T() TestingT {
25	if c.t == nil {
26		panic("expect: context is not initialized")
27	}
28	return c.t
29}
30
31// Prefix returns context's error prefix.
32func (c Context) Prefix() string {
33	return c.prefix
34}
35
36// IsNegated checks if current context negates current assert expectations.
37func (c Context) IsNegated() bool {
38	return c.negated
39}
40
41// CheckExpectation checks an assert expectation and calls a callback on fail.
42// It returns true when the asserted expectation fails.
43// Callback is called when a negated assertion succeeds or when non negated assertion fails.
44func (c Context) CheckExpectation(success bool, cb func(Context) string) bool {
45	failed := (c.negated && success) || (!c.negated && !success)
46	if failed {
47		msg := cb(c)
48		if strings.TrimSpace(msg) == "" {
49			msg = defaultAssertFailMsg
50		}
51
52		c.Fail(msg)
53	}
54	return failed
55}
56
57// Fail makes the current test fail with a custom message.
58func (c Context) Fail(msg string, args ...any) {
59	if c.prefix != "" {
60		msg = c.prefix + " - " + msg
61	}
62
63	c.t.Fatalf(msg, args...)
64}
65
66// TestingT defines a minimal interface for `testing.T` instances.
67type TestingT interface {
68	Helper()
69	Fatal(args ...any)
70	Fatalf(format string, args ...any)
71}
72
73// MockTestingT creates a new testing mock that writes testing output to a string builder.
74func MockTestingT(output *strings.Builder) TestingT {
75	return &testingT{output}
76}
77
78type testingT struct{ buf *strings.Builder }
79
80func (testingT) Helper()                          {}
81func (t testingT) Fatal(args ...any)              { t.buf.WriteString(ufmt.Sprintln(args...)) }
82func (t testingT) Fatalf(fmt string, args ...any) { t.buf.WriteString(ufmt.Sprintf(fmt+"\n", args...)) }