forked from tankyouoss/godog
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathrun.go
293 lines (241 loc) · 6.5 KB
/
run.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
package godog
import (
"fmt"
"go/build"
"io"
"math/rand"
"os"
"path/filepath"
"runtime"
"strconv"
"strings"
"sync"
"github.com/cucumber/messages-go/v10"
"github.com/elmagician/godog/colors"
"github.com/elmagician/godog/formatters"
"github.com/elmagician/godog/internal/models"
"github.com/elmagician/godog/internal/parser"
"github.com/elmagician/godog/internal/storage"
"github.com/elmagician/godog/internal/utils"
)
const (
exitSuccess int = iota
exitFailure
exitOptionError
)
type testSuiteInitializer func(*TestSuiteContext)
type scenarioInitializer func(*ScenarioContext)
type runner struct {
randomSeed int64
stopOnFailure, strict bool
features []*models.Feature
testSuiteInitializer testSuiteInitializer
scenarioInitializer scenarioInitializer
storage *storage.Storage
fmt Formatter
}
func (r *runner) concurrent(rate int) (failed bool) {
var copyLock sync.Mutex
if fmt, ok := r.fmt.(storageFormatter); ok {
fmt.SetStorage(r.storage)
}
testSuiteContext := TestSuiteContext{}
if r.testSuiteInitializer != nil {
r.testSuiteInitializer(&testSuiteContext)
}
testRunStarted := models.TestRunStarted{StartedAt: utils.TimeNowFunc()}
r.storage.MustInsertTestRunStarted(testRunStarted)
r.fmt.TestRunStarted()
// run before suite handlers
for _, f := range testSuiteContext.beforeSuiteHandlers {
f()
}
queue := make(chan int, rate)
for _, ft := range r.features {
pickles := make([]*messages.Pickle, len(ft.Pickles))
if r.randomSeed != 0 {
r := rand.New(rand.NewSource(r.randomSeed))
perm := r.Perm(len(ft.Pickles))
for i, v := range perm {
pickles[v] = ft.Pickles[i]
}
} else {
copy(pickles, ft.Pickles)
}
for i, p := range pickles {
pickle := *p
queue <- i // reserve space in queue
if i == 0 {
r.fmt.Feature(ft.GherkinDocument, ft.Uri, ft.Content)
}
go func(fail *bool, pickle *messages.Pickle) {
defer func() {
<-queue // free a space in queue
}()
if r.stopOnFailure && *fail {
return
}
suite := &suite{
fmt: r.fmt,
randomSeed: r.randomSeed,
strict: r.strict,
storage: r.storage,
}
if r.scenarioInitializer != nil {
sc := ScenarioContext{suite: suite}
r.scenarioInitializer(&sc)
}
err := suite.runPickle(pickle)
if suite.shouldFail(err) {
copyLock.Lock()
*fail = true
copyLock.Unlock()
}
}(&failed, &pickle)
}
}
// wait until last are processed
for i := 0; i < rate; i++ {
queue <- i
}
close(queue)
// run after suite handlers
for _, f := range testSuiteContext.afterSuiteHandlers {
f()
}
// print summary
r.fmt.Summary()
return
}
func runWithOptions(suiteName string, runner runner, opt Options) int {
var output io.Writer = os.Stdout
if nil != opt.Output {
output = opt.Output
}
if formatterParts := strings.SplitN(opt.Format, ":", 2); len(formatterParts) > 1 {
f, err := os.Create(formatterParts[1])
if err != nil {
err = fmt.Errorf(
`couldn't create file with name: "%s", error: %s`,
formatterParts[1], err.Error(),
)
fmt.Fprintln(os.Stderr, err)
return exitOptionError
}
defer f.Close()
output = f
opt.Format = formatterParts[0]
}
if opt.NoColors {
output = colors.Uncolored(output)
} else {
output = colors.Colored(output)
}
if opt.ShowStepDefinitions {
s := suite{}
sc := ScenarioContext{suite: &s}
runner.scenarioInitializer(&sc)
printStepDefinitions(s.steps, output)
return exitOptionError
}
if len(opt.Paths) == 0 {
inf, err := os.Stat("features")
if err == nil && inf.IsDir() {
opt.Paths = []string{"features"}
}
}
if opt.Concurrency < 1 {
opt.Concurrency = 1
}
formatter := formatters.FindFmt(opt.Format)
if nil == formatter {
var names []string
for name := range formatters.AvailableFormatters() {
names = append(names, name)
}
fmt.Fprintln(os.Stderr, fmt.Errorf(
`unregistered formatter name: "%s", use one of: %s`,
opt.Format,
strings.Join(names, ", "),
))
return exitOptionError
}
runner.fmt = formatter(suiteName, output)
var err error
if runner.features, err = parser.ParseFeatures(opt.Tags, opt.Paths); err != nil {
fmt.Fprintln(os.Stderr, err)
return exitOptionError
}
runner.storage = storage.NewStorage()
for _, feat := range runner.features {
runner.storage.MustInsertFeature(feat)
for _, pickle := range feat.Pickles {
runner.storage.MustInsertPickle(pickle)
}
}
// user may have specified -1 option to create random seed
runner.randomSeed = opt.Randomize
if runner.randomSeed == -1 {
runner.randomSeed = makeRandomSeed()
}
runner.stopOnFailure = opt.StopOnFailure
runner.strict = opt.Strict
// store chosen seed in environment, so it could be seen in formatter summary report
os.Setenv("GODOG_SEED", strconv.FormatInt(runner.randomSeed, 10))
// determine tested package
_, filename, _, _ := runtime.Caller(1)
os.Setenv("GODOG_TESTED_PACKAGE", runsFromPackage(filename))
failed := runner.concurrent(opt.Concurrency)
// @TODO: should prevent from having these
os.Setenv("GODOG_SEED", "")
os.Setenv("GODOG_TESTED_PACKAGE", "")
if failed && opt.Format != "events" {
return exitFailure
}
return exitSuccess
}
func runsFromPackage(fp string) string {
dir := filepath.Dir(fp)
gopaths := filepath.SplitList(build.Default.GOPATH)
for _, gp := range gopaths {
gp = filepath.Join(gp, "src")
if strings.Index(dir, gp) == 0 {
return strings.TrimLeft(strings.Replace(dir, gp, "", 1), string(filepath.Separator))
}
}
return dir
}
// TestSuite allows for configuration
// of the Test Suite Execution
type TestSuite struct {
Name string
TestSuiteInitializer func(*TestSuiteContext)
ScenarioInitializer func(*ScenarioContext)
Options *Options
}
// Run will execute the test suite.
//
// If options are not set, it will reads
// all configuration options from flags.
//
// The exit codes may vary from:
// 0 - success
// 1 - failed
// 2 - command line usage error
// 128 - or higher, os signal related error exit codes
//
// If there are flag related errors they will be directed to os.Stderr
func (ts TestSuite) Run() int {
if ts.Options == nil {
ts.Options = &Options{}
ts.Options.Output = colors.Colored(os.Stdout)
flagSet := flagSet(ts.Options)
if err := flagSet.Parse(os.Args[1:]); err != nil {
fmt.Fprintln(os.Stderr, err)
return exitOptionError
}
ts.Options.Paths = flagSet.Args()
}
r := runner{testSuiteInitializer: ts.TestSuiteInitializer, scenarioInitializer: ts.ScenarioInitializer}
return runWithOptions(ts.Name, r, *ts.Options)
}