Debian Codegraph @

terst/terst.go

raw symbols SCIP
1 // This file was AUTOMATICALLY GENERATED by terst-import (smuggol) from github.com/robertkrimen/terst
2
3 /*
4 Package terst is a terse (terst = test + terse), easy-to-use testing library for Go.
5
6 terst is compatible with (and works via) the standard testing package: http://golang.org/pkg/testing
7
8 var is = terst.Is
9
10 func Test(t *testing.T) {
11 terst.Terst(t, func() {
12 is("abc", "abc")
13
14 is(1, ">", 0)
15
16 var abc []int
17 is(abc, nil)
18 }
19 }
20
21 Do not import terst directly, instead use `terst-import` to copy it into your testing environment:
22
23 https://github.com/robertkrimen/terst/tree/master/terst-import
24
25 $ go get github.com/robertkrimen/terst/terst-import
26
27 $ terst-import
28 */
29 package terst
30
31 import (
32 "bytes"
33 "errors"
34 "fmt"
35 "math/big"
36 "reflect"
37 "regexp"
38 goruntime "runtime"
39 "strings"
40 "sync"
41 "testing"
42 "time"
43 )
44
45 // Is compares two values (got & expect) and returns true if the comparison is true,
46 // false otherwise. In addition, if the comparison is false, Is will report the error
47 // in a manner similar to testing.T.Error(...). Is also takes an optional argument,
48 // a comparator, that changes how the comparison is made. The following
49 // comparators are available:
50 //
51 // == # got == expect (default)
52 // != # got != expect
53 //
54 // > # got > expect (float32, uint, uint16, int, int64, ...)
55 // >= # got >= expect
56 // < # got < expect
57 // <= # got <= expect
58 //
59 // =~ # regexp.MustCompile(expect).Match{String}(got)
60 // !~ # !regexp.MustCompile(expect).Match{String}(got)
61 //
62 // Basic usage with the default comparator (==):
63 //
64 // Is(<got>, <expect>)
65 //
66 // Specifying a different comparator:
67 //
68 // Is(<got>, <comparator>, <expect>)
69 //
70 // A simple comparison:
71 //
72 // Is(2 + 2, 4)
73 //
74 // A bit trickier:
75 //
76 // Is(1, ">", 0)
77 // Is(2 + 2, "!=", 5)
78 // Is("Nothing happens.", "=~", `ing(\s+)happens\.$`)
79 //
80 // Is should only be called under a Terst(t, ...) call. For a standalone version,
81 // use IsErr. If no scope is found and the comparison is false, then Is will panic the error.
82 func Is(arguments ...interface{}) bool {
83 err := IsErr(arguments...)
84 if err != nil {
85 call := Caller()
86 if call == nil {
87 panic(err)
88 }
89 call.Error(err)
90 return false
91 }
92 return true
93 }
94
95 type (
96 // ErrFail indicates a comparison failure (e.g. 0 > 1).
97 ErrFail error
98
99 // ErrInvalid indicates an invalid comparison (e.g. bool == string).
100 ErrInvalid error
101 )
102
103 var errInvalid = errors.New("invalid")
104
105 var registry = struct {
106 table map[uintptr]*_scope
107 lock sync.RWMutex
108 }{
109 table: map[uintptr]*_scope{},
110 }
111
112 func registerScope(pc uintptr, scope *_scope) {
113 registry.lock.Lock()
114 defer registry.lock.Unlock()
115 registry.table[pc] = scope
116 }
117
118 func getScope() *_scope {
119 s, _ := findScope()
120 return s
121 }
122
123 func floatCompare(a float64, b float64) int {
124 if a > b {
125 return 1
126 } else if a < b {
127 return -1
128 }
129 // NaN == NaN
130 return 0
131 }
132
133 func bigIntCompare(a *big.Int, b *big.Int) int {
134 return a.Cmp(b)
135 }
136
137 func bigInt(value int64) *big.Int {
138 return big.NewInt(value)
139 }
140
141 func bigUint(value uint64) *big.Int {
142 return big.NewInt(0).SetUint64(value)
143 }
144
145 func toString(value interface{}) (string, error) {
146 switch value := value.(type) {
147 case string:
148 return value, nil
149 case fmt.Stringer:
150 return value.String(), nil
151 case error:
152 return value.Error(), nil
153 }
154 return "", errInvalid
155 }
156
157 func matchString(got string, expect *regexp.Regexp) (int, error) {
158 if expect.MatchString(got) {
159 return 0, nil
160 }
161 return -1, nil
162 }
163
164 func match(got []byte, expect *regexp.Regexp) (int, error) {
165 if expect.Match(got) {
166 return 0, nil
167 }
168 return -1, nil
169 }
170
171 func compareMatch(got, expect interface{}) (int, error) {
172 switch got := got.(type) {
173 case []byte:
174 switch expect := expect.(type) {
175 case string:
176 matcher, err := regexp.Compile(expect)
177 if err != nil {
178 return 0, err
179 }
180 return match(got, matcher)
181 case *regexp.Regexp:
182 return match(got, expect)
183 }
184 default:
185 if got, err := toString(got); err == nil {
186 switch expect := expect.(type) {
187 case string:
188 matcher, err := regexp.Compile(expect)
189 if err != nil {
190 return 0, err
191 }
192 return matchString(got, matcher)
193 case *regexp.Regexp:
194 return matchString(got, expect)
195 }
196 } else {
197 return 0, err
198 }
199 }
200 return 0, errInvalid
201 }
202
203 func floatPromote(value reflect.Value) (float64, error) {
204 kind := value.Kind()
205 if reflect.Int <= kind && kind <= reflect.Int64 {
206 return float64(value.Int()), nil
207 }
208 if reflect.Uint <= kind && kind <= reflect.Uint64 {
209 return float64(value.Uint()), nil
210 }
211 if reflect.Float32 <= kind && kind <= reflect.Float64 {
212 return value.Float(), nil
213 }
214 return 0, errInvalid
215 }
216
217 func bigIntPromote(value reflect.Value) (*big.Int, error) {
218 kind := value.Kind()
219 if reflect.Int <= kind && kind <= reflect.Int64 {
220 return bigInt(value.Int()), nil
221 }
222 if reflect.Uint <= kind && kind <= reflect.Uint64 {
223 return bigUint(value.Uint()), nil
224 }
225 return nil, errInvalid
226 }
227
228 func compareOther(got, expect interface{}) (int, error) {
229 switch expect.(type) {
230 case float32, float64:
231 return compareNumber(got, expect)
232 case uint, uint8, uint16, uint32, uint64:
233 return compareNumber(got, expect)
234 case int, int8, int16, int32, int64:
235 return compareNumber(got, expect)
236 case string:
237 var err error
238 got, err = toString(got)
239 if err != nil {
240 return 0, err
241 }
242 case nil:
243 got := reflect.ValueOf(got)
244 switch got.Kind() {
245 case reflect.Chan, reflect.Func, reflect.Map, reflect.Ptr, reflect.Slice, reflect.Interface:
246 if got.IsNil() {
247 return 0, nil
248 }
249 return -1, nil
250 case reflect.Invalid: // reflect.Invalid: var abc interface{} = nil
251 return 0, nil
252 }
253 return 0, errInvalid
254 }
255
256 if reflect.ValueOf(got).Type() != reflect.ValueOf(expect).Type() {
257 return 0, errInvalid
258 }
259
260 if reflect.DeepEqual(got, expect) {
261 return 0, nil
262 }
263 return -1, nil
264 }
265
266 func compareNumber(got, expect interface{}) (int, error) {
267 gotRv := reflect.ValueOf(got)
268 gotKind := gotRv.Kind()
269 expectRv := reflect.ValueOf(expect)
270 expectKind := expectRv.Kind()
271 if reflect.Float32 <= gotKind && gotKind <= reflect.Float64 ||
272 reflect.Float32 <= expectKind && expectKind <= reflect.Float64 {
273 got, err := floatPromote(gotRv)
274 if err != nil {
275 return 0, err
276 }
277 expect, err := floatPromote(expectRv)
278 if err != nil {
279 return 0, err
280 }
281 return floatCompare(got, expect), nil
282 }
283
284 goBigInt, err := bigIntPromote(gotRv)
285 if err != nil {
286 return 0, err
287 }
288 expectBigInt, err := bigIntPromote(expectRv)
289 if err != nil {
290 return 0, err
291 }
292 return goBigInt.Cmp(expectBigInt), nil
293 }
294
295 // IsErr compares two values (got & expect) and returns nil if the comparison is true, an ErrFail if
296 // the comparison is false, or an ErrInvalid if the comparison is invalid. IsErr also
297 // takes an optional argument, a comparator, that changes how the comparison is made.
298 //
299 // Is & IsErr are similar but different:
300 //
301 // Is(...) // Should only be called within a Terst(...) call
302 // IsErr(...) // A standalone comparator, the same as Is, just without the automatic reporting
303 func IsErr(arguments ...interface{}) error {
304 var got, expect interface{}
305 comparator := "=="
306 switch len(arguments) {
307 case 0, 1:
308 return fmt.Errorf("invalid number of arguments to IsErr: %d", len(arguments))
309 case 2:
310 got, expect = arguments[0], arguments[1]
311 default:
312 if value, ok := arguments[1].(string); ok {
313 comparator = value
314 } else {
315 return fmt.Errorf("invalid comparator: %v", arguments[1])
316 }
317 got, expect = arguments[0], arguments[2]
318 }
319
320 var result int
321 var err error
322
323 switch comparator {
324 case "<", "<=", ">", ">=":
325 result, err = compareNumber(got, expect)
326 case "=~", "!~":
327 result, err = compareMatch(got, expect)
328 case "==", "!=":
329 result, err = compareOther(got, expect)
330 default:
331 return fmt.Errorf("invalid comparator: %s", comparator)
332 }
333
334 if err == errInvalid {
335 return ErrInvalid(fmt.Errorf(
336 "\nINVALID (%s):\n got: %v (%T)\n expected: %v (%T)",
337 comparator,
338 got, got,
339 expect, expect,
340 ))
341 } else if err != nil {
342 return err
343 }
344
345 equality, pass := false, false
346
347 switch comparator {
348 case "==", "=~":
349 equality = true
350 pass = result == 0
351 case "!=", "!~":
352 equality = true
353 pass = result != 0
354 case "<":
355 pass = result < 0
356 case "<=":
357 pass = result <= 0
358 case ">":
359 pass = result > 0
360 case ">=":
361 pass = result >= 0
362 }
363
364 if !pass {
365 if equality {
366 if comparator[1] == '~' {
367 if value, ok := got.([]byte); ok {
368 return ErrFail(fmt.Errorf(
369 "\nFAIL (%s)\n got: %s %v%s\nexpected: %v%s",
370 comparator,
371 value, got, typeKindString(got),
372 expect, typeKindString(expect),
373 ))
374 }
375 }
376 return ErrFail(fmt.Errorf(
377 "\nFAIL (%s)\n got: %v%s\nexpected: %v%s",
378 comparator,
379 got, typeKindString(got),
380 expect, typeKindString(expect),
381 ))
382 }
383 return ErrFail(fmt.Errorf(
384 "\nFAIL (%s)\n got: %v%s\nexpected: %s %v%s",
385 comparator,
386 got, typeKindString(got),
387 comparator, expect, typeKindString(expect),
388 ))
389 }
390
391 return nil
392 }
393
394 func typeKindString(value interface{}) string {
395 reflectValue := reflect.ValueOf(value)
396 kind := reflectValue.Kind().String()
397 result := fmt.Sprintf("%T", value)
398 if kind == result {
399 if kind == "string" {
400 return ""
401 }
402 return fmt.Sprintf(" (%T)", value)
403 }
404 return fmt.Sprintf(" (%T=%s)", value, kind)
405 }
406
407 func (s *_scope) reset() {
408 s.name = ""
409 s.output = s.output[:0]
410 s.start = time.Time{}
411 s.duration = 0
412 }
413
414 // Terst creates a testing scope, where Is can be called and errors will be reported
415 // according to the top-level location of the comparison, and not where the Is call
416 // actually takes place. For example:
417 //
418 // func test(value int) {
419 // Is(value, 5) // <--- This failure is reported below.
420 // }
421 //
422 // Terst(t, func(){
423 //
424 // Is(2, ">", 3) // <--- An error is reported here.
425 //
426 // test(5) // <--- An error is reported here.
427 //
428 // })
429 func Terst(t *testing.T, arguments ...func()) {
430 curScope := &_scope{
431 t: t,
432 }
433
434 pc, _, _, ok := goruntime.Caller(1) // TODO Associate with the Test... func
435 if !ok {
436 panic("Here be dragons.")
437 }
438
439 _, curScope.testFunc = findTestFunc()
440
441 registerScope(pc, curScope)
442
443 for _, fn := range arguments {
444 func() {
445 curScope.reset()
446 name := curScope.testFunc.Name()
447 index := strings.LastIndex(curScope.testFunc.Name(), ".")
448 if index >= 0 {
449 name = name[index+1:] + "(Terst)"
450 } else {
451 name = "(Terst)"
452 }
453 name = "(Terst)"
454 curScope.name = name
455 curScope.start = time.Now()
456 defer func() {
457 curScope.duration = time.Now().Sub(curScope.start)
458 if err := recover(); err != nil {
459 curScope.t.Fail()
460 curScope.report()
461 panic(err)
462 }
463 curScope.report()
464 }()
465 fn()
466 }()
467 }
468 }
469
470 // From "testing"
471 func (s *_scope) report() {
472 format := "~~~ %s: (Terst)\n%s"
473 if s.t.Failed() {
474 fmt.Printf(format, "FAIL", s.output)
475 } else if testing.Verbose() && len(s.output) > 0 {
476 fmt.Printf(format, "PASS", s.output)
477 }
478 }
479
480 func (s *_scope) log(call entry, str string) {
481 s.mu.Lock()
482 defer s.mu.Unlock()
483 s.output = append(s.output, decorate(call, str)...)
484 }
485
486 // decorate prefixes the string with the file and line of the call site
487 // and inserts the final newline if needed and indentation tabs for formascing.
488 func decorate(call entry, s string) string {
489
490 file, line := call.File, call.Line
491 if call.PC > 0 {
492 // Truncate file name at last file name separator.
493 if index := strings.LastIndex(file, "/"); index >= 0 {
494 file = file[index+1:]
495 } else if index = strings.LastIndex(file, "\\"); index >= 0 {
496 file = file[index+1:]
497 }
498 } else {
499 file = "???"
500 line = 1
501 }
502 buf := new(bytes.Buffer)
503 // Every line is indented at least one tab.
504 buf.WriteByte('\t')
505 fmt.Fprintf(buf, "%s:%d: ", file, line)
506 lines := strings.Split(s, "\n")
507 if l := len(lines); l > 1 && lines[l-1] == "" {
508 lines = lines[:l-1]
509 }
510 for i, line := range lines {
511 if i > 0 {
512 // Second and subsequent lines are indented an extra tab.
513 buf.WriteString("\n\t\t")
514 }
515 buf.WriteString(line)
516 }
517 buf.WriteByte('\n')
518 return buf.String()
519 }
520
521 func findScope() (*_scope, entry) {
522 registry.lock.RLock()
523 defer registry.lock.RUnlock()
524 table := registry.table
525 depth := 2 // Starting depth
526 call := entry{}
527 for {
528 pc, _, _, ok := goruntime.Caller(depth)
529 if !ok {
530 break
531 }
532 if s, exists := table[pc]; exists {
533 pc, file, line, _ := goruntime.Caller(depth - 3) // Terst(...) + func(){}() + fn() => ???()
534 call.PC = pc
535 call.File = file
536 call.Line = line
537 return s, call
538 }
539 depth++
540 }
541 return nil, entry{}
542 }
543
544 // Call is a reference to a line immediately under a Terst testing scope.
545 type Call struct {
546 scope *_scope
547 entry entry
548 }
549
550 // Caller will search the stack, looking for a Terst testing scope. If a scope
551 // is found, then Caller returns a Call for logging errors, accessing testing.T, etc.
552 // If no scope is found, Caller returns nil.
553 func Caller() *Call {
554 curScope, entry := findScope()
555 if curScope == nil {
556 return nil
557 }
558 return &Call{
559 scope: curScope,
560 entry: entry,
561 }
562 }
563
564 // TestFunc returns the *runtime.Func entry for the top-level Test...(t testing.T)
565 // function.
566 func (cl *Call) TestFunc() *goruntime.Func {
567 return cl.scope.testFunc
568 }
569
570 // T returns the original testing.T passed to Terst(...)
571 func (cl *Call) T() *testing.T {
572 return cl.scope.t
573 }
574
575 // Log is the terst version of `testing.T.Log`
576 func (cl *Call) Log(arguments ...interface{}) {
577 cl.scope.log(cl.entry, fmt.Sprintln(arguments...))
578 }
579
580 // Logf is the terst version of `testing.T.Logf`
581 func (cl *Call) Logf(format string, arguments ...interface{}) {
582 cl.scope.log(cl.entry, fmt.Sprintf(format, arguments...))
583 }
584
585 // Error is the terst version of `testing.T.Error`
586 func (cl *Call) Error(arguments ...interface{}) {
587 cl.scope.log(cl.entry, fmt.Sprintln(arguments...))
588 cl.scope.t.Fail()
589 }
590
591 // Errorf is the terst version of `testing.T.Errorf`
592 func (cl *Call) Errorf(format string, arguments ...interface{}) {
593 cl.scope.log(cl.entry, fmt.Sprintf(format, arguments...))
594 cl.scope.t.Fail()
595 }
596
597 // Skip is the terst version of `testing.T.Skip`
598 func (cl *Call) Skip(arguments ...interface{}) {
599 cl.scope.log(cl.entry, fmt.Sprintln(arguments...))
600 cl.scope.t.SkipNow()
601 }
602
603 // Skipf is the terst version of `testing.T.Skipf`
604 func (cl *Call) Skipf(format string, arguments ...interface{}) {
605 cl.scope.log(cl.entry, fmt.Sprintf(format, arguments...))
606 cl.scope.t.SkipNow()
607 }
608
609 type _scope struct {
610 t *testing.T
611 testFunc *goruntime.Func
612 name string
613 mu sync.RWMutex
614 output []byte
615 start time.Time
616 duration time.Duration
617 }
618
619 type entry struct {
620 PC uintptr
621 File string
622 Line int
623 Func *goruntime.Func
624 }
625
626 func findFunc(match string) (entry, *goruntime.Func) {
627 depth := 2 // Starting depth
628 for {
629 pc, file, line, ok := goruntime.Caller(depth)
630 if !ok {
631 break
632 }
633 fn := goruntime.FuncForPC(pc)
634 name := fn.Name()
635 if index := strings.LastIndex(name, match); index >= 0 {
636 // Assume we have an instance of TestXyzzy in a _test file
637 return entry{
638 PC: pc,
639 File: file,
640 Line: line,
641 Func: fn,
642 }, fn
643 }
644 depth++
645 }
646 return entry{}, nil
647 }
648
649 func findTestFunc() (entry, *goruntime.Func) {
650 return findFunc(".Test")
651 }
652
653 func findTerstFunc() (entry, *goruntime.Func) {
654 return findFunc(".Terst")
655 }