Debian Codegraph @

quicktest.go

raw
1 // Licensed under the MIT license, see LICENSE file for details.
2
3 package quicktest
4
5 import (
6 "fmt"
7 "reflect"
8 "strings"
9 "sync"
10 "testing"
11 )
12
13 // Check runs the given check using the provided t and continues execution in
14 // case of failure. For instance:
15 //
16 // qt.Check(t, answer, qt.Equals, 42)
17 // qt.Check(t, got, qt.IsNil, qt.Commentf("iteration %d", i))
18 //
19 // Additional args (not consumed by the checker), when provided, are included as
20 // comments in the failure output when the check fails.
21 func Check(t testing.TB, got interface{}, checker Checker, args ...interface{}) bool {
22 t.Helper()
23 return New(t).Check(got, checker, args...)
24 }
25
26 // Assert runs the given check using the provided t and stops execution in case
27 // of failure. For instance:
28 //
29 // qt.Assert(t, got, qt.DeepEquals, []int{42, 47})
30 // qt.Assert(t, got, qt.ErrorMatches, "bad wolf .*", qt.Commentf("a comment"))
31 //
32 // Additional args (not consumed by the checker), when provided, are included as
33 // comments in the failure output when the check fails.
34 func Assert(t testing.TB, got interface{}, checker Checker, args ...interface{}) bool {
35 t.Helper()
36 return New(t).Assert(got, checker, args...)
37 }
38
39 // New returns a new checker instance that uses t to fail the test when checks
40 // fail. It only ever calls the Fatal, Error and (when available) Run methods
41 // of t. For instance.
42 //
43 // func TestFoo(t *testing.T) {
44 // t.Run("A=42", func(t *testing.T) {
45 // c := qt.New(t)
46 // c.Assert(a, qt.Equals, 42)
47 // })
48 // }
49 //
50 // The library already provides some base checkers, and more can be added by
51 // implementing the Checker interface.
52 //
53 // If there is a likelihood that Defer will be called, then
54 // a call to Done should be deferred after calling New.
55 // For example:
56 //
57 // func TestFoo(t *testing.T) {
58 // c := qt.New(t)
59 // defer c.Done()
60 // c.Setenv("HOME", "/non-existent")
61 // c.Assert(os.Getenv("HOME"), qt.Equals, "/non-existent")
62 // })
63 //
64 // A value of C that's has a non-nil TB field but is otherwise zero is valid.
65 // So:
66 //
67 // c := &qt.C{TB: t}
68 //
69 // is valid a way to create a C value; it's exactly the same as:
70 //
71 // c := qt.New(t)
72 //
73 // Methods on C may be called concurrently, assuming the underlying
74 // `testing.TB` implementation also allows that.
75 func New(t testing.TB) *C {
76 return &C{
77 TB: t,
78 }
79 }
80
81 // C is a quicktest checker. It embeds a testing.TB value and provides
82 // additional checking functionality. If an Assert or Check operation fails, it
83 // uses the wrapped TB value to fail the test appropriately.
84 type C struct {
85 testing.TB
86
87 mu sync.Mutex
88 doneNeeded bool
89 deferred func()
90 format formatFunc
91 }
92
93 // cleaner is implemented by testing.TB on Go 1.14 and later.
94 type cleaner interface {
95 Cleanup(func())
96 }
97
98 // Defer registers a function to be called when c.Done is
99 // called. Deferred functions will be called in last added, first called
100 // order. If c.Done is not called by the end of the test, the test
101 // may panic. Note that if Cleanup is called, there is no
102 // need to call Done.
103 //
104 // Deprecated: in Go >= 1.14 use testing.TB.Cleanup instead.
105 func (c *C) Defer(f func()) {
106 c.mu.Lock()
107 defer c.mu.Unlock()
108 if cleaner, ok := c.TB.(cleaner); ok {
109 // Use TB.Cleanup when available, but add a check
110 // that Done has been called so that we don't run
111 // into unexpected Go version incompatibilities.
112 if !c.doneNeeded {
113 c.doneNeeded = true
114 cleaner.Cleanup(func() {
115 c.mu.Lock()
116 defer c.mu.Unlock()
117 if c.doneNeeded {
118 panic("Done not called after Defer")
119 }
120 })
121 }
122
123 cleaner.Cleanup(f)
124
125 return
126 }
127
128 oldDeferred := c.deferred
129 if oldDeferred != nil {
130 c.deferred = func() {
131 defer oldDeferred()
132 f()
133 }
134 } else {
135 c.deferred = f
136 }
137 }
138
139 // Done calls all the functions registered by Defer in reverse
140 // registration order. After it's called, the functions are
141 // unregistered, so calling Done twice will only call them once.
142 //
143 // When a test function is called by Run, Done will be called
144 // automatically on the C value passed into it.
145 //
146 // Deprecated: in Go >= 1.14 this is no longer needed if using
147 // testing.TB.Cleanup.
148 func (c *C) Done() {
149 c.mu.Lock()
150 deferred := c.deferred
151 c.deferred = nil
152 c.doneNeeded = false
153 c.mu.Unlock()
154
155 if deferred != nil {
156 deferred()
157 }
158 }
159
160 // SetFormat sets the function used to print values in test failures.
161 // By default Format is used.
162 // Any subsequent subtests invoked with c.Run will also use this function by
163 // default.
164 func (c *C) SetFormat(format func(interface{}) string) {
165 c.mu.Lock()
166 c.format = format
167 c.mu.Unlock()
168 }
169
170 // getFormat returns the format function
171 // safely acquired under lock.
172 func (c *C) getFormat() func(interface{}) string {
173 c.mu.Lock()
174 defer c.mu.Unlock()
175 return c.format
176 }
177
178 // Check runs the given check and continues execution in case of failure.
179 // For instance:
180 //
181 // c.Check(answer, qt.Equals, 42)
182 // c.Check(got, qt.IsNil, qt.Commentf("iteration %d", i))
183 //
184 // Additional args (not consumed by the checker), when provided, are included
185 // as comments in the failure output when the check fails.
186 func (c *C) Check(got interface{}, checker Checker, args ...interface{}) bool {
187 c.TB.Helper()
188 return check(c, checkParams{
189 fail: c.TB.Error,
190 checker: checker,
191 got: got,
192 args: args,
193 })
194 }
195
196 // Assert runs the given check and stops execution in case of failure.
197 // For instance:
198 //
199 // c.Assert(got, qt.DeepEquals, []int{42, 47})
200 // c.Assert(got, qt.ErrorMatches, "bad wolf .*", qt.Commentf("a comment"))
201 //
202 // Additional args (not consumed by the checker), when provided, are included
203 // as comments in the failure output when the check fails.
204 func (c *C) Assert(got interface{}, checker Checker, args ...interface{}) bool {
205 c.TB.Helper()
206 return check(c, checkParams{
207 fail: c.TB.Fatal,
208 checker: checker,
209 got: got,
210 args: args,
211 })
212 }
213
214 var (
215 stringType = reflect.TypeOf("")
216 boolType = reflect.TypeOf(true)
217 tbType = reflect.TypeOf(new(testing.TB)).Elem()
218 )
219
220 // Run runs f as a subtest of t called name. It's a wrapper around
221 // the Run method of c.TB that provides the quicktest checker to f. When
222 // the function completes, c.Done will be called to run any
223 // functions registered with c.Defer.
224 //
225 // c.TB must implement a Run method of the following form:
226 //
227 // Run(string, func(T)) bool
228 //
229 // where T is any type that is assignable to testing.TB.
230 // Implementations include *testing.T, *testing.B and *C itself.
231 //
232 // The TB field in the subtest will hold the value passed
233 // by Run to its argument function.
234 //
235 // func TestFoo(t *testing.T) {
236 // c := qt.New(t)
237 // c.Run("A=42", func(c *qt.C) {
238 // // This assertion only stops the current subtest.
239 // c.Assert(a, qt.Equals, 42)
240 // })
241 // }
242 //
243 // A panic is raised when Run is called and the embedded concrete type does not
244 // implement a Run method with a correct signature.
245 func (c *C) Run(name string, f func(c *C)) bool {
246 badType := func(m string) {
247 panic(fmt.Sprintf("cannot execute Run with underlying concrete type %T (%s)", c.TB, m))
248 }
249 m := reflect.ValueOf(c.TB).MethodByName("Run")
250 if !m.IsValid() {
251 // c.TB doesn't implement a Run method.
252 badType("no Run method")
253 }
254 mt := m.Type()
255 if mt.NumIn() != 2 ||
256 mt.In(0) != stringType ||
257 mt.NumOut() != 1 ||
258 mt.Out(0) != boolType {
259 // The Run method doesn't have the right argument counts and types.
260 badType("wrong argument count for Run method")
261 }
262 farg := mt.In(1)
263 if farg.Kind() != reflect.Func ||
264 farg.NumIn() != 1 ||
265 farg.NumOut() != 0 ||
266 !farg.In(0).AssignableTo(tbType) {
267 // The first argument to the Run function arg isn't right.
268 badType("bad first argument type for Run method")
269 }
270 cFormat := c.getFormat()
271 fv := reflect.MakeFunc(farg, func(args []reflect.Value) []reflect.Value {
272 c2 := New(args[0].Interface().(testing.TB))
273 defer c2.Done()
274 c2.SetFormat(cFormat)
275 f(c2)
276 return nil
277 })
278 return m.Call([]reflect.Value{reflect.ValueOf(name), fv})[0].Interface().(bool)
279 }
280
281 // Parallel signals that this test is to be run in parallel with (and only with) other parallel tests.
282 // It's a wrapper around *testing.T.Parallel.
283 //
284 // A panic is raised when Parallel is called and the embedded concrete type does not
285 // implement Parallel, for instance if TB's concrete type is a benchmark.
286 func (c *C) Parallel() {
287 p, ok := c.TB.(interface {
288 Parallel()
289 })
290 if !ok {
291 panic(fmt.Sprintf("cannot execute Parallel with underlying concrete type %T", c.TB))
292 }
293 p.Parallel()
294 }
295
296 // check performs the actual check with the provided params.
297 // In case of failure p.fail is called. In the fail report values are formatted
298 // using p.format.
299 func check(c *C, p checkParams) bool {
300 c.TB.Helper()
301 rp := reportParams{
302 got: p.got,
303 args: p.args,
304 format: c.getFormat(),
305 }
306 if rp.format == nil {
307 // No format set; use the default: Format.
308 rp.format = Format
309 }
310
311 // Allow checkers to annotate messages.
312 note := func(key string, value interface{}) {
313 rp.notes = append(rp.notes, note{
314 key: key,
315 value: value,
316 })
317 }
318
319 // Ensure that we have a checker.
320 if p.checker == nil {
321 p.fail(report(BadCheckf("nil checker provided"), rp))
322 return false
323 }
324
325 // Extract comments if provided.
326 for len(p.args) > 0 {
327 comment, ok := p.args[len(p.args)-1].(Comment)
328 if !ok {
329 break
330 }
331 rp.comments = append([]Comment{comment}, rp.comments...)
332 p.args = p.args[:len(p.args)-1]
333 }
334 rp.args = p.args
335
336 // Validate that we have the correct number of arguments.
337 rp.argNames = p.checker.ArgNames()
338 wantNumArgs := len(rp.argNames) - 1
339 if gotNumArgs := len(rp.args); gotNumArgs != wantNumArgs {
340 if gotNumArgs > 0 {
341 note("got args", rp.args)
342 }
343 if wantNumArgs > 0 {
344 note("want args", Unquoted(strings.Join(rp.argNames[1:], ", ")))
345 }
346 var prefix string
347 if gotNumArgs > wantNumArgs {
348 prefix = "too many arguments provided to checker"
349 } else {
350 prefix = "not enough arguments provided to checker"
351 }
352 p.fail(report(BadCheckf("%s: got %d, want %d", prefix, gotNumArgs, wantNumArgs), rp))
353 return false
354 }
355
356 // Execute the check and report the failure if necessary.
357 if err := p.checker.Check(p.got, p.args, note); err != nil {
358 p.fail(report(err, rp))
359 return false
360 }
361 return true
362 }
363
364 // checkParams holds parameters for executing a check.
365 type checkParams struct {
366 fail func(...interface{})
367 checker Checker
368 got interface{}
369 args []interface{}
370 }