-
-
Notifications
You must be signed in to change notification settings - Fork 18
/
got.go
111 lines (96 loc) · 2.52 KB
/
got.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
// Package got is an enjoyable golang test framework.
package got
import (
"flag"
"os"
"reflect"
"regexp"
"strings"
"sync"
"github.com/ysmood/gop"
"github.com/ysmood/got/lib/diff"
)
// Testable interface. Usually, you use *testing.T as it.
type Testable interface {
Name() string // same as testing.common.Name
Skipped() bool // same as testing.common.Skipped
Failed() bool // same as testing.common.Failed
Cleanup(func()) // same as testing.common.Cleanup
FailNow() // same as testing.common.FailNow
Fail() // same as testing.common.Fail
Helper() // same as testing.common.Helper
Logf(format string, args ...interface{}) // same as testing.common.Logf
SkipNow() // same as testing.common.Skip
}
// G is the helper context, it provides some handy helpers for testing
type G struct {
Testable
Assertions
Utils
snapshots *sync.Map
}
// Setup returns a helper to init G instance
func Setup(init func(g G)) func(t Testable) G {
return func(t Testable) G {
g := New(t)
if init != nil {
init(g)
}
return g
}
}
// T is the shortcut for New
func T(t Testable) G {
return New(t)
}
// New G instance
func New(t Testable) G {
eh := NewDefaultAssertionError(gop.ThemeDefault, diff.ThemeDefault)
g := G{
t,
Assertions{Testable: t, ErrorHandler: eh},
Utils{t},
&sync.Map{},
}
g.loadSnapshots()
return g
}
// DefaultFlags will set the "go test" flag if not yet presented.
// It must be executed in the init() function.
// Such as the timeout:
//
// DefaultFlags("timeout=10s")
func DefaultFlags(flags ...string) {
// remove default timeout from "go test"
filtered := []string{}
for _, arg := range os.Args {
if arg != "-test.timeout=10m0s" {
filtered = append(filtered, arg)
}
}
os.Args = filtered
list := map[string]struct{}{}
reg := regexp.MustCompile(`^-test\.(\w+)`)
for _, arg := range os.Args {
ms := reg.FindStringSubmatch(arg)
if ms != nil {
list[ms[1]] = struct{}{}
}
}
for _, flag := range flags {
if _, has := list[strings.Split(flag, "=")[0]]; !has {
os.Args = append(os.Args, "-test."+flag)
}
}
}
// Parallel config of "go test -parallel"
func Parallel() (n int) {
flag.Parse()
flag.Visit(func(f *flag.Flag) {
if f.Name == "test.parallel" {
v := reflect.ValueOf(f.Value).Elem().Convert(reflect.TypeOf(n))
n = v.Interface().(int)
}
})
return
}