Debian Codegraph @

helpers/tdsuite/suite.go

raw
1 // Copyright (c) 2021, Maxime Soulé
2 // All rights reserved.
3 //
4 // This source code is licensed under the BSD-style license found in the
5 // LICENSE file in the root directory of this source tree.
6
7 package tdsuite
8
9 import (
10 "fmt"
11 "reflect"
12 "strings"
13 "testing"
14 "unicode"
15 "unicode/utf8"
16
17 "github.com/maxatome/go-testdeep/internal/types"
18 "github.com/maxatome/go-testdeep/td"
19 )
20
21 var tType = reflect.TypeOf((*td.T)(nil))
22
23 // Setup is an interface a tests suite can implement. When running the
24 // tests suite, Setup method is called once before any test runs. If
25 // Setup returns an error, the tests suite aborts: no tests are run.
26 //
27 // t.Cleanup() can be called in Setup method. It can replace the
28 // definition of a [Destroy] method. It can also be used together, in
29 // this case cleanup registered functions are called after [Destroy].
30 type Setup interface {
31 Setup(t *td.T) error
32 }
33
34 // PreTest is an interface a tests suite can implement. PreTest method
35 // is called before each test is run, in the same subtest as the test
36 // itself. If PreTest returns an error, the subtest aborts: the test
37 // is not run.
38 //
39 // t.Cleanup() can be called in PreTest method. It can replace the
40 // definition of a [PostTest] method. It can also be used together, in
41 // this case cleanup registered functions are called after [PostTest].
42 type PreTest interface {
43 PreTest(t *td.T, testName string) error
44 }
45
46 // PostTest is an interface a tests suite can implement. PostTest
47 // method is called after each test is run, in the same subtest as
48 // the test itself. If [PreTest] interface is implemented and [PreTest]
49 // method returned an error, PostTest is never called.
50 type PostTest interface {
51 PostTest(t *td.T, testName string) error
52 }
53
54 // BetweenTests is an interface a tests suite can
55 // implement. BetweenTests method is called between 2 tests. If it
56 // returns an error, the tests suite aborts: no more tests are run.
57 type BetweenTests interface {
58 BetweenTests(t *td.T, previousTestName, nextTestName string) error
59 }
60
61 // Destroy is an interface a tests suite can implement. When running
62 // the tests suite, Destroy method is called once after all tests
63 // ran. If [Setup] interface is implemented and [Setup] method returned an
64 // error, Destroy is never called.
65 type Destroy interface {
66 Destroy(t *td.T) error
67 }
68
69 func emptyPrePostTest(t *td.T, testName string) error { return nil }
70 func emptyBetweenTests(t *td.T, prev, next string) error { return nil }
71
72 // isTest returns true if "name" is a valid test name.
73 // Derived from go sources in cmd/go/internal/load/test.go.
74 func isTest(name string) bool {
75 if !strings.HasPrefix(name, "Test") {
76 return false
77 }
78 if len(name) == 4 { // "Test" is ok
79 return true
80 }
81 r, _ := utf8.DecodeRuneInString(name[4:])
82 return !unicode.IsLower(r)
83 }
84
85 // shouldContinue returns true if the tests suite should continue
86 // based on ret, the value(s) returned by a test call.
87 func shouldContinue(t *td.T, testName string, ret []reflect.Value) bool {
88 var (
89 err error
90 cont bool
91 )
92
93 switch len(ret) {
94 case 0:
95 return true
96
97 case 1:
98 switch v := ret[0].Interface().(type) {
99 case bool:
100 return v
101 case error: // non-nil error
102 cont, err = false, v
103 default: // nil error
104 return true
105 }
106
107 default:
108 cont = ret[0].Interface().(bool)
109 err, _ = ret[1].Interface().(error) // nil error fails conversion
110 }
111
112 if err != nil {
113 t.Helper()
114 t.Errorf("%s error: %s", testName, err)
115 }
116 return cont
117 }
118
119 // Run runs the tests suite suite using tb as base testing
120 // framework. tb is typically a [*testing.T] as in:
121 //
122 // func TestSuite(t *testing.T) {
123 // tdsuite.Run(t, &Suite{})
124 // }
125 //
126 // but it can also be a [*td.T] of course.
127 //
128 // config can be used to alter the internal [*td.T] instance. See
129 // [td.ContextConfig] for detailed options, as:
130 //
131 // func TestSuite(t *testing.T) {
132 // tdsuite.Run(t, &Suite{}, td.ContextConfig{
133 // UseEqual: true, // use the Equal method to compare if available
134 // BeLax: true, // able to compare different but convertible types
135 // })
136 // }
137 //
138 // Run returns true if all the tests succeeded, false otherwise.
139 //
140 // Note that if suite is not an empty struct, it should be a pointer
141 // if its contents has to be altered by hooks & tests methods.
142 //
143 // If suite is a pointer, it has access to non-pointer & pointer
144 // methods hooks & tests. If suite is not a pointer, it only has
145 // access to non-pointer methods hooks & tests.
146 func Run(tb testing.TB, suite any, config ...td.ContextConfig) bool {
147 t := td.NewT(tb, config...)
148
149 t.Helper()
150 if suite == nil {
151 t.Fatal("Run(): suite parameter cannot be nil")
152 return false // only for tests
153 }
154
155 typ := reflect.TypeOf(suite)
156
157 // The suite is not a pointer and in its pointer version it has
158 // access to more method. Check the user isn't making a mistake by
159 // not passing a pointer
160 if possibleMistakes := diffWithPtrMethods(typ); len(possibleMistakes) > 0 {
161 t.Logf("Run(): several methods are not accessible as suite is not a pointer but %T: %s",
162 suite, strings.Join(possibleMistakes, ", "))
163 }
164
165 var methods []int
166 for i, num := 0, typ.NumMethod(); i < num; i++ {
167 m := typ.Method(i)
168
169 if isTest(m.Name) {
170 mt := m.Type
171
172 if mt.IsVariadic() {
173 t.Logf("Run(): method %T.%s skipped, variadic parameters not supported",
174 suite, m.Name)
175 continue
176 }
177
178 // Check input parameters
179 switch mt.NumIn() {
180 case 2:
181 // TestXxx(*td.T)
182 if mt.In(1) != tType {
183 t.Logf("Run(): method %T.%s skipped, unrecognized parameter type %s. Only *td.T allowed",
184 suite, m.Name, mt.In(1))
185 continue
186 }
187
188 case 3:
189 // TestXxx(*td.T, *td.T)
190 if mt.In(1) != tType || mt.In(2) != tType {
191 var log string
192 if mt.In(1) != tType {
193 if mt.In(2) != tType {
194 log = fmt.Sprintf("parameters types (%s, %s)", mt.In(1), mt.In(2))
195 } else {
196 log = fmt.Sprintf("first parameter type %s", mt.In(1))
197 }
198 } else {
199 log = fmt.Sprintf("second parameter type %s", mt.In(2))
200 }
201 t.Logf("Run(): method %T.%s skipped, unrecognized %s. Only (*td.T, *td.T) allowed",
202 suite, m.Name, log)
203 continue
204 }
205
206 case 1:
207 t.Logf("Run(): method %T.%s skipped, no input parameters",
208 suite, m.Name)
209 continue
210
211 default:
212 t.Logf("Run(): method %T.%s skipped, too many parameters",
213 suite, m.Name)
214 continue
215 }
216
217 // Check output parameters
218 switch mt.NumOut() {
219 case 0:
220 case 1:
221 switch mt.Out(0) {
222 case types.Bool, types.Error:
223 default:
224 t.Fatalf("Run(): method %T.%s returns %s value. Only bool or error are allowed",
225 suite, m.Name, mt.Out(0))
226 return false // only for tests
227 }
228 case 2:
229 if mt.Out(0) != types.Bool || mt.Out(1) != types.Error {
230 t.Fatalf("Run(): method %T.%s returns (%s, %s) values. Only (bool, error) is allowed",
231 suite, m.Name, mt.Out(0), mt.Out(1))
232 return false // only for tests
233 }
234 default:
235 t.Fatalf("Run(): method %T.%s returns %d values. Only 0, 1 (bool or error) or 2 (bool, error) values are allowed",
236 suite, m.Name, mt.NumOut())
237 return false // only for tests
238 }
239
240 methods = append(methods, i)
241 }
242 }
243
244 if len(methods) == 0 {
245 t.Fatalf("Run(): no test methods found for type %T", suite)
246 return false // only for tests
247 }
248
249 run(t, suite, methods)
250
251 return !t.Failed()
252 }
253
254 func run(t *td.T, suite any, methods []int) {
255 t.Helper()
256
257 suiteType := reflect.TypeOf(suite)
258
259 // setup
260 if s, ok := suite.(Setup); ok {
261 if err := s.Setup(t); err != nil {
262 t.Errorf("%T suite setup error: %s", suite, err)
263 return
264 }
265 } else if _, exists := suiteType.MethodByName("Setup"); exists {
266 t.Errorf("%T suite has a Setup method but it does not match Setup(t *td.T) error", suite)
267 }
268
269 // destroy
270 if s, ok := suite.(Destroy); ok {
271 defer func() {
272 if err := s.Destroy(t); err != nil {
273 t.Errorf("%T suite destroy error: %s", suite, err)
274 }
275 }()
276 } else if _, exists := suiteType.MethodByName("Destroy"); exists {
277 t.Errorf("%T suite has a Destroy method but it does not match Destroy(t *td.T) error", suite)
278 }
279
280 preTest := emptyPrePostTest
281 if s, ok := suite.(PreTest); ok {
282 preTest = s.PreTest
283 } else if _, exists := suiteType.MethodByName("PreTest"); exists {
284 t.Errorf("%T suite has a PreTest method but it does not match PreTest(t *td.T, testName string) error", suite)
285 }
286
287 postTest := emptyPrePostTest
288 if s, ok := suite.(PostTest); ok {
289 postTest = s.PostTest
290 } else if _, exists := suiteType.MethodByName("PostTest"); exists {
291 t.Errorf("%T suite has a PostTest method but it does not match PostTest(t *td.T, testName string) error", suite)
292 }
293
294 between := emptyBetweenTests
295 if s, ok := suite.(BetweenTests); ok {
296 between = s.BetweenTests
297 } else if _, exists := suiteType.MethodByName("BetweenTests"); exists {
298 t.Errorf("%T suite has a BetweenTests method but it does not match BetweenTests(t *td.T, previousTestName, nextTestName string) error", suite)
299 }
300
301 vs := reflect.ValueOf(suite)
302 typ := reflect.TypeOf(suite)
303
304 for i, method := range methods {
305 m := typ.Method(method)
306 mt := m.Type
307
308 call := vs.Method(method).Call
309
310 cont := true
311 if mt.NumIn() == 2 {
312 t.Run(m.Name, func(t *td.T) {
313 if err := preTest(t, m.Name); err != nil {
314 t.Errorf("%s pre-test error: %s", m.Name, err)
315 return
316 }
317 defer func() {
318 if err := postTest(t, m.Name); err != nil {
319 t.Errorf("%s post-test error: %s", m.Name, err)
320 }
321 }()
322
323 cont = shouldContinue(t, m.Name, call([]reflect.Value{reflect.ValueOf(t)}))
324 })
325 } else {
326 t.RunAssertRequire(m.Name, func(assert, require *td.T) {
327 if err := preTest(assert, m.Name); err != nil {
328 assert.Errorf("%s pre-test error: %s", m.Name, err)
329 return
330 }
331 defer func() {
332 if err := postTest(assert, m.Name); err != nil {
333 assert.Errorf("%s post-test error: %s", m.Name, err)
334 }
335 }()
336
337 cont = shouldContinue(assert, m.Name, call([]reflect.Value{
338 reflect.ValueOf(assert),
339 reflect.ValueOf(require),
340 }))
341 })
342 }
343
344 if !cont {
345 t.Logf("%s required discontinuing suite tests", m.Name)
346 break
347 }
348
349 if i != len(methods)-1 {
350 next := typ.Method(methods[i+1]).Name
351 if err := between(t, m.Name, next); err != nil {
352 t.Errorf("%s / %s between-tests error: %s", m.Name, next, err)
353 break
354 }
355 }
356 }
357 }
358
359 func diffWithPtrMethods(typ reflect.Type) []string {
360 if typ.Kind() == reflect.Ptr {
361 return nil
362 }
363
364 ptyp := reflect.PtrTo(typ)
365 if typ.NumMethod() == ptyp.NumMethod() {
366 return nil
367 }
368
369 keep := func(m reflect.Method) bool {
370 switch m.Name {
371 case "Setup", "PreTest", "PostTest", "BetweenTests", "Destroy":
372 return true
373 default:
374 return isTest(m.Name)
375 }
376 }
377
378 var nonPtrMethods []string
379 for i, num := 0, typ.NumMethod(); i < num; i++ {
380 if m := typ.Method(i); keep(m) {
381 nonPtrMethods = append(nonPtrMethods, m.Name)
382 }
383 }
384
385 var onlyPtrMethods []string
386 for ni, pi, num := 0, 0, ptyp.NumMethod(); pi < num; pi++ {
387 if m := ptyp.Method(pi); keep(m) {
388 if ni >= len(nonPtrMethods) || nonPtrMethods[ni] != m.Name {
389 onlyPtrMethods = append(onlyPtrMethods, m.Name)
390 } else {
391 ni++
392 }
393 }
394 }
395
396 return onlyPtrMethods
397 }