forked from remogatto/prettytest
/
prettytest.go
350 lines (291 loc) · 8.43 KB
/
prettytest.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
/*
Copyright (c) 2010 Andrea Fazzi
Permission is hereby granted, free of charge, to any person obtaining
a copy of this software and associated documentation files (the
"Software"), to deal in the Software without restriction, including
without limitation the rights to use, copy, modify, merge, publish,
distribute, sublicense, and/or sell copies of the Software, and to
permit persons to whom the Software is furnished to do so, subject to
the following conditions:
The above copyright notice and this permission notice shall be
included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
/*
PrettyTest is a simple testing library for golang. It aims to
simplify/prettify testing in golang.
It features:
* a simple assertion vocabulary for better readability
* customizable formatters through interfaces
* before/after functions
* integrated with the go test command
* pretty and colorful output with reports
This is the skeleton of a typical prettytest test file:
package foo
import (
"testing"
"github.com/remogatto/prettytest"
)
// Start of setup
type testSuite struct {
prettytest.Suite
}
func TestRunner(t *testing.T) {
prettytest.Run(
t,
new(testSuite),
)
}
// End of setup
// Tests start here
func (t *testSuite) TestTrueIsTrue() {
t.True(true)
}
See example/example_test.go and prettytest_test.go for comprehensive
usage examples.
*/
package prettytest
import (
"reflect"
"regexp"
"runtime"
"strings"
)
const (
STATUS_NO_ASSERTIONS = iota
STATUS_PASS
STATUS_FAIL
STATUS_MUST_FAIL
STATUS_PENDING
)
var (
ErrorLog []*Error
)
type Error struct {
Suite *Suite
TestFunc *TestFunc
Assertion *Assertion
}
type callerInfo struct {
name, fn string
line int
}
func newCallerInfo(skip int) *callerInfo {
pc, fn, line, ok := runtime.Caller(skip)
if !ok {
panic("An error occured while retrieving caller info!")
}
splits := strings.Split(runtime.FuncForPC(pc).Name(), ".")
return &callerInfo{splits[len(splits)-1], fn, line}
}
type tCatcher interface {
setT(t T)
suite() *Suite
setPackageName(name string)
setSuiteName(name string)
testFuncs() map[string]*TestFunc
init()
}
func logError(error *Error) {
ErrorLog = append(ErrorLog, error)
}
type TestFunc struct {
Name, CallerName string
Status int
Assertions []*Assertion
suite *Suite
mustFail bool
}
type T interface {
Fail()
}
type Suite struct {
T T
Package, Name string
TestFuncs map[string]*TestFunc
}
func (s *Suite) setT(t T) { s.T = t }
func (s *Suite) init() { s.TestFuncs = make(map[string]*TestFunc) }
func (s *Suite) suite() *Suite { return s }
func (s *Suite) setPackageName(name string) { s.Package = name }
func (s *Suite) setSuiteName(name string) { s.Name = name }
func (s *Suite) testFuncs() map[string]*TestFunc { return s.TestFuncs }
func (s *Suite) appendTestFuncFromMethod(method *callerInfo) *TestFunc {
name := method.name
if _, ok := s.TestFuncs[name]; !ok {
s.TestFuncs[name] = &TestFunc{
Name: name,
Status: STATUS_PASS,
suite: s,
}
}
return s.TestFuncs[name]
}
func (s *Suite) currentTestFunc() *TestFunc {
callerName := newCallerInfo(3).name
if _, ok := s.TestFuncs[callerName]; !ok {
s.TestFuncs[callerName] = &TestFunc{
Name: callerName,
Status: STATUS_NO_ASSERTIONS,
}
}
return s.TestFuncs[callerName]
}
func (testFunc *TestFunc) resetLastError() {
if len(ErrorLog) > 0 {
ErrorLog[len(ErrorLog)-1].Assertion.Passed = true
ErrorLog = append(ErrorLog[:len(ErrorLog)-1])
testFunc.Status = STATUS_PASS
for i := 0; i < len(testFunc.Assertions); i++ {
if !testFunc.Assertions[i].Passed {
testFunc.Status = STATUS_FAIL
}
}
}
}
func (testFunc *TestFunc) logError(message string) {
assertion := &Assertion{ErrorMessage: message}
error := &Error{testFunc.suite, testFunc, assertion}
logError(error)
}
func (testFunc *TestFunc) appendAssertion(assertion *Assertion) *Assertion {
testFunc.Assertions = append(testFunc.Assertions, assertion)
return assertion
}
func (testFunc *TestFunc) status() int {
return testFunc.Status
}
func (s *Suite) setup(errorMessage string, customMessages []string) *Assertion {
var message string
if len(customMessages) > 0 {
message = strings.Join(customMessages, "\t\t\n")
} else {
message = errorMessage
}
// Retrieve the testing method
callerInfo := newCallerInfo(3)
assertionName := newCallerInfo(2).name
testFunc := s.appendTestFuncFromMethod(callerInfo)
assertion := &Assertion{
Line: callerInfo.line,
Filename: callerInfo.fn,
Name: assertionName,
suite: s,
testFunc: testFunc,
ErrorMessage: message,
Passed: true,
}
testFunc.appendAssertion(assertion)
return assertion
}
// Run runs the test suites.
func Run(t T, suites ...tCatcher) {
run(t, new(TDDFormatter), suites...)
}
// Run runs the test suites using the given formatter.
func RunWithFormatter(t T, formatter Formatter, suites ...tCatcher) {
run(t, formatter, suites...)
}
// Run tests. Use default formatter.
func run(t T, formatter Formatter, suites ...tCatcher) {
var (
beforeAllFound, afterAllFound bool
beforeAll, afterAll, before, after reflect.Value
totalPassed, totalFailed, totalPending, totalNoAssertions, totalExpectedFailures int
)
ErrorLog = make([]*Error, 0)
// flag.Parse()
for _, s := range suites {
beforeAll, afterAll, before, after = reflect.Value{}, reflect.Value{}, reflect.Value{}, reflect.Value{}
s.setT(t)
s.init()
iType := reflect.TypeOf(s)
splits := strings.Split(iType.String(), ".")
s.setPackageName(splits[0][1:])
s.setSuiteName(splits[1])
formatter.PrintSuiteInfo(s.suite())
// search for Before and After methods
for i := 0; i < iType.NumMethod(); i++ {
method := iType.Method(i)
if ok, _ := regexp.MatchString("^BeforeAll", method.Name); ok {
if !beforeAllFound {
beforeAll = method.Func
beforeAllFound = true
continue
}
}
if ok, _ := regexp.MatchString("^AfterAll", method.Name); ok {
if !afterAllFound {
afterAll = method.Func
afterAllFound = true
continue
}
}
if ok, _ := regexp.MatchString("^Before", method.Name); ok {
before = method.Func
}
if ok, _ := regexp.MatchString("^After", method.Name); ok {
after = method.Func
}
}
if beforeAll.IsValid() {
beforeAll.Call([]reflect.Value{reflect.ValueOf(s)})
}
for i := 0; i < iType.NumMethod(); i++ {
method := iType.Method(i)
if filterMethod(method.Name) {
if ok, _ := regexp.MatchString(formatter.AllowedMethodsPattern(), method.Name); ok {
if before.IsValid() {
before.Call([]reflect.Value{reflect.ValueOf(s)})
}
method.Func.Call([]reflect.Value{reflect.ValueOf(s)})
if after.IsValid() {
after.Call([]reflect.Value{reflect.ValueOf(s)})
}
testFunc, ok := s.testFuncs()[method.Name]
if !ok {
testFunc = &TestFunc{Name: method.Name, Status: STATUS_NO_ASSERTIONS}
}
if testFunc.mustFail {
if testFunc.Status != STATUS_FAIL {
testFunc.Status = STATUS_FAIL
testFunc.logError("The test was expected to fail")
} else {
testFunc.Status = STATUS_MUST_FAIL
}
}
switch testFunc.Status {
case STATUS_PASS:
totalPassed++
case STATUS_FAIL:
totalFailed++
t.Fail()
case STATUS_MUST_FAIL:
totalExpectedFailures++
case STATUS_PENDING:
totalPending++
case STATUS_NO_ASSERTIONS:
totalNoAssertions++
}
formatter.PrintStatus(testFunc)
}
}
}
if afterAll.IsValid() {
afterAll.Call([]reflect.Value{reflect.ValueOf(s)})
}
formatter.PrintErrorLog(ErrorLog)
formatter.PrintFinalReport(&FinalReport{Passed: totalPassed,
Failed: totalFailed,
Pending: totalPending,
ExpectedFailures: totalExpectedFailures,
NoAssertions: totalNoAssertions,
})
}
}