forked from cucumber/godog
-
Notifications
You must be signed in to change notification settings - Fork 0
/
run_test.go
665 lines (537 loc) · 17.3 KB
/
run_test.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
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
package godog
import (
"bytes"
"context"
"fmt"
"io"
"io/ioutil"
"os"
"path/filepath"
"regexp"
"strconv"
"strings"
"testing"
"github.com/cucumber/gherkin-go/v19"
"github.com/cucumber/messages-go/v16"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
"github.com/cucumber/godog/colors"
"github.com/cucumber/godog/internal/formatters"
"github.com/cucumber/godog/internal/models"
"github.com/cucumber/godog/internal/storage"
)
func okStep() error {
return nil
}
func TestPrintsStepDefinitions(t *testing.T) {
var buf bytes.Buffer
w := colors.Uncolored(&buf)
s := suite{}
ctx := ScenarioContext{suite: &s}
steps := []string{
"^passing step$",
`^with name "([^"])"`,
}
for _, step := range steps {
ctx.Step(step, okStep)
}
printStepDefinitions(s.steps, w)
out := buf.String()
ref := `okStep`
for i, def := range strings.Split(strings.TrimSpace(out), "\n") {
if idx := strings.Index(def, steps[i]); idx == -1 {
t.Fatalf(`step "%s" was not found in output`, steps[i])
}
if idx := strings.Index(def, ref); idx == -1 {
t.Fatalf(`step definition reference "%s" was not found in output: "%s"`, ref, def)
}
}
}
func TestPrintsNoStepDefinitionsIfNoneFound(t *testing.T) {
var buf bytes.Buffer
w := colors.Uncolored(&buf)
s := &suite{}
printStepDefinitions(s.steps, w)
out := strings.TrimSpace(buf.String())
assert.Equal(t, "there were no contexts registered, could not find any step definition..", out)
}
func Test_FailsOrPassesBasedOnStrictModeWhenHasPendingSteps(t *testing.T) {
const path = "any.feature"
gd, err := gherkin.ParseGherkinDocument(strings.NewReader(basicGherkinFeature), (&messages.Incrementing{}).NewId)
require.NoError(t, err)
gd.Uri = path
ft := models.Feature{GherkinDocument: gd}
ft.Pickles = gherkin.Pickles(*gd, path, (&messages.Incrementing{}).NewId)
var beforeScenarioFired, afterScenarioFired int
r := runner{
fmt: formatters.ProgressFormatterFunc("progress", ioutil.Discard),
features: []*models.Feature{&ft},
testSuiteInitializer: func(ctx *TestSuiteContext) {
ctx.ScenarioContext().Before(func(ctx context.Context, sc *Scenario) (context.Context, error) {
beforeScenarioFired++
return ctx, nil
})
ctx.ScenarioContext().After(func(ctx context.Context, sc *Scenario, err error) (context.Context, error) {
afterScenarioFired++
return ctx, nil
})
},
scenarioInitializer: func(ctx *ScenarioContext) {
ctx.Step(`^one$`, func() error { return nil })
ctx.Step(`^two$`, func() error { return ErrPending })
},
}
r.storage = storage.NewStorage()
r.storage.MustInsertFeature(&ft)
for _, pickle := range ft.Pickles {
r.storage.MustInsertPickle(pickle)
}
failed := r.concurrent(1)
require.False(t, failed)
assert.Equal(t, 1, beforeScenarioFired)
assert.Equal(t, 1, afterScenarioFired)
r.strict = true
failed = r.concurrent(1)
require.True(t, failed)
assert.Equal(t, 2, beforeScenarioFired)
assert.Equal(t, 2, afterScenarioFired)
}
func Test_FailsOrPassesBasedOnStrictModeWhenHasUndefinedSteps(t *testing.T) {
const path = "any.feature"
gd, err := gherkin.ParseGherkinDocument(strings.NewReader(basicGherkinFeature), (&messages.Incrementing{}).NewId)
require.NoError(t, err)
gd.Uri = path
ft := models.Feature{GherkinDocument: gd}
ft.Pickles = gherkin.Pickles(*gd, path, (&messages.Incrementing{}).NewId)
r := runner{
fmt: formatters.ProgressFormatterFunc("progress", ioutil.Discard),
features: []*models.Feature{&ft},
scenarioInitializer: func(ctx *ScenarioContext) {
ctx.Step(`^one$`, func() error { return nil })
// two - is undefined
},
}
r.storage = storage.NewStorage()
r.storage.MustInsertFeature(&ft)
for _, pickle := range ft.Pickles {
r.storage.MustInsertPickle(pickle)
}
failed := r.concurrent(1)
require.False(t, failed)
r.strict = true
failed = r.concurrent(1)
require.True(t, failed)
}
func Test_ShouldFailOnError(t *testing.T) {
const path = "any.feature"
gd, err := gherkin.ParseGherkinDocument(strings.NewReader(basicGherkinFeature), (&messages.Incrementing{}).NewId)
require.NoError(t, err)
gd.Uri = path
ft := models.Feature{GherkinDocument: gd}
ft.Pickles = gherkin.Pickles(*gd, path, (&messages.Incrementing{}).NewId)
r := runner{
fmt: formatters.ProgressFormatterFunc("progress", ioutil.Discard),
features: []*models.Feature{&ft},
scenarioInitializer: func(ctx *ScenarioContext) {
ctx.Step(`^two$`, func() error { return fmt.Errorf("error") })
ctx.Step(`^one$`, func() error { return nil })
},
}
r.storage = storage.NewStorage()
r.storage.MustInsertFeature(&ft)
for _, pickle := range ft.Pickles {
r.storage.MustInsertPickle(pickle)
}
failed := r.concurrent(1)
require.True(t, failed)
}
func Test_FailsWithUnknownFormatterOptionError(t *testing.T) {
stderr, closer := bufErrorPipe(t)
defer closer()
defer stderr.Close()
opts := Options{
Format: "unknown",
Paths: []string{"features/load:6"},
Output: ioutil.Discard,
}
status := TestSuite{
Name: "fails",
ScenarioInitializer: func(_ *ScenarioContext) {},
Options: &opts,
}.Run()
require.Equal(t, exitOptionError, status)
closer()
b, err := ioutil.ReadAll(stderr)
require.NoError(t, err)
out := strings.TrimSpace(string(b))
assert.Contains(t, out, `unregistered formatter name: "unknown", use one of`)
}
func Test_FailsWithOptionErrorWhenLookingForFeaturesInUnavailablePath(t *testing.T) {
stderr, closer := bufErrorPipe(t)
defer closer()
defer stderr.Close()
opts := Options{
Format: "progress",
Paths: []string{"unavailable"},
Output: ioutil.Discard,
}
status := TestSuite{
Name: "fails",
ScenarioInitializer: func(_ *ScenarioContext) {},
Options: &opts,
}.Run()
require.Equal(t, exitOptionError, status)
closer()
b, err := ioutil.ReadAll(stderr)
require.NoError(t, err)
out := strings.TrimSpace(string(b))
assert.Equal(t, `feature path "unavailable" is not available`, out)
}
func Test_ByDefaultRunsFeaturesPath(t *testing.T) {
opts := Options{
Format: "progress",
Output: ioutil.Discard,
Strict: true,
}
status := TestSuite{
Name: "fails",
ScenarioInitializer: func(_ *ScenarioContext) {},
Options: &opts,
}.Run()
// should fail in strict mode due to undefined steps
assert.Equal(t, exitFailure, status)
opts.Strict = false
status = TestSuite{
Name: "succeeds",
ScenarioInitializer: func(_ *ScenarioContext) {},
Options: &opts,
}.Run()
// should succeed in non strict mode due to undefined steps
assert.Equal(t, exitSuccess, status)
}
func bufErrorPipe(t *testing.T) (io.ReadCloser, func()) {
stderr := os.Stderr
r, w, err := os.Pipe()
require.NoError(t, err)
os.Stderr = w
return r, func() {
w.Close()
os.Stderr = stderr
}
}
func Test_RandomizeRun_WithStaticSeed(t *testing.T) {
const noRandomFlag = 0
const noConcurrencyFlag = 1
const formatter = "pretty"
const featurePath = "internal/formatters/formatter-tests/features/with_few_empty_scenarios.feature"
fmtOutputScenarioInitializer := func(ctx *ScenarioContext) {
ctx.Step(`^(?:a )?failing step`, failingStepDef)
ctx.Step(`^(?:a )?pending step$`, pendingStepDef)
ctx.Step(`^(?:a )?passing step$`, passingStepDef)
ctx.Step(`^odd (\d+) and even (\d+) number$`, oddEvenStepDef)
}
expectedStatus, expectedOutput := testRun(t,
fmtOutputScenarioInitializer,
formatter, noConcurrencyFlag,
noRandomFlag, []string{featurePath},
)
const staticSeed int64 = 1
actualStatus, actualOutput := testRun(t,
fmtOutputScenarioInitializer,
formatter, noConcurrencyFlag,
staticSeed, []string{featurePath},
)
actualSeed := parseSeed(actualOutput)
assert.Equal(t, staticSeed, actualSeed)
// Removes "Randomized with seed: <seed>" part of the output
actualOutputSplit := strings.Split(actualOutput, "\n")
actualOutputSplit = actualOutputSplit[:len(actualOutputSplit)-2]
actualOutputReduced := strings.Join(actualOutputSplit, "\n")
assert.Equal(t, expectedStatus, actualStatus)
assert.NotEqual(t, expectedOutput, actualOutputReduced)
assertOutput(t, formatter, expectedOutput, actualOutputReduced)
}
func Test_RandomizeRun_RerunWithSeed(t *testing.T) {
const createRandomSeedFlag = -1
const noConcurrencyFlag = 1
const formatter = "pretty"
const featurePath = "internal/formatters/formatter-tests/features/with_few_empty_scenarios.feature"
fmtOutputScenarioInitializer := func(ctx *ScenarioContext) {
ctx.Step(`^(?:a )?failing step`, failingStepDef)
ctx.Step(`^(?:a )?pending step$`, pendingStepDef)
ctx.Step(`^(?:a )?passing step$`, passingStepDef)
ctx.Step(`^odd (\d+) and even (\d+) number$`, oddEvenStepDef)
}
expectedStatus, expectedOutput := testRun(t,
fmtOutputScenarioInitializer,
formatter, noConcurrencyFlag,
createRandomSeedFlag, []string{featurePath},
)
expectedSeed := parseSeed(expectedOutput)
assert.NotZero(t, expectedSeed)
actualStatus, actualOutput := testRun(t,
fmtOutputScenarioInitializer,
formatter, noConcurrencyFlag,
expectedSeed, []string{featurePath},
)
actualSeed := parseSeed(actualOutput)
assert.Equal(t, expectedSeed, actualSeed)
assert.Equal(t, expectedStatus, actualStatus)
assert.Equal(t, expectedOutput, actualOutput)
}
func Test_FormatOutputRun(t *testing.T) {
const noRandomFlag = 0
const noConcurrencyFlag = 1
const formatter = "junit"
const featurePath = "internal/formatters/formatter-tests/features/with_few_empty_scenarios.feature"
fmtOutputScenarioInitializer := func(ctx *ScenarioContext) {
ctx.Step(`^(?:a )?failing step`, failingStepDef)
ctx.Step(`^(?:a )?pending step$`, pendingStepDef)
ctx.Step(`^(?:a )?passing step$`, passingStepDef)
ctx.Step(`^odd (\d+) and even (\d+) number$`, oddEvenStepDef)
}
expectedStatus, expectedOutput := testRun(t,
fmtOutputScenarioInitializer,
formatter, noConcurrencyFlag,
noRandomFlag, []string{featurePath},
)
dir := filepath.Join(os.TempDir(), t.Name())
err := os.MkdirAll(dir, 0755)
require.NoError(t, err)
defer os.RemoveAll(dir)
file := filepath.Join(dir, "result.xml")
actualStatus, actualOutput := testRun(t,
fmtOutputScenarioInitializer,
formatter+":"+file, noConcurrencyFlag,
noRandomFlag, []string{featurePath},
)
result, err := ioutil.ReadFile(file)
require.NoError(t, err)
actualOutputFromFile := string(result)
assert.Equal(t, expectedStatus, actualStatus)
assert.Empty(t, actualOutput)
assert.Equal(t, expectedOutput, actualOutputFromFile)
}
func Test_FormatOutputRun_Error(t *testing.T) {
const noRandomFlag = 0
const noConcurrencyFlag = 1
const formatter = "junit"
const featurePath = "internal/formatters/formatter-tests/features/with_few_empty_scenarios.feature"
fmtOutputScenarioInitializer := func(ctx *ScenarioContext) {
ctx.Step(`^(?:a )?failing step`, failingStepDef)
ctx.Step(`^(?:a )?pending step$`, pendingStepDef)
ctx.Step(`^(?:a )?passing step$`, passingStepDef)
ctx.Step(`^odd (\d+) and even (\d+) number$`, oddEvenStepDef)
}
expectedStatus, expectedOutput := exitOptionError, ""
dir := filepath.Join(os.TempDir(), t.Name())
file := filepath.Join(dir, "result.xml")
// next test is expected to log: couldn't create file with name: )
actualStatus, actualOutput := testRun(t,
fmtOutputScenarioInitializer,
formatter+":"+file, noConcurrencyFlag,
noRandomFlag, []string{featurePath},
)
assert.Equal(t, expectedStatus, actualStatus)
assert.Equal(t, expectedOutput, actualOutput)
_, err := ioutil.ReadFile(file)
assert.Error(t, err)
}
func Test_AllFeaturesRun(t *testing.T) {
const concurrency = 100
const noRandomFlag = 0
const format = "progress"
const expected = `...................................................................... 70
...................................................................... 140
...................................................................... 210
...................................................................... 280
................................................. 329
86 scenarios (86 passed)
329 steps (329 passed)
0s
`
actualStatus, actualOutput := testRun(t,
InitializeScenario,
format, concurrency,
noRandomFlag, []string{"features"},
)
assert.Equal(t, exitSuccess, actualStatus)
assert.Equal(t, expected, actualOutput)
}
func Test_AllFeaturesRunAsSubtests(t *testing.T) {
const concurrency = 100
const noRandomFlag = 0
const format = "progress"
const expected = `...................................................................... 70
...................................................................... 140
...................................................................... 210
...................................................................... 280
................................................. 329
86 scenarios (86 passed)
329 steps (329 passed)
0s
`
actualStatus, actualOutput := testRunWithOptions(
t,
Options{
Format: format,
Concurrency: concurrency,
Paths: []string{"features"},
Randomize: noRandomFlag,
TestingT: t,
},
InitializeScenario,
)
assert.Equal(t, exitSuccess, actualStatus)
assert.Equal(t, expected, actualOutput)
}
func Test_FormatterConcurrencyRun(t *testing.T) {
formatters := []string{
"progress",
"junit",
"pretty",
"events",
"cucumber",
}
featurePaths := []string{"internal/formatters/formatter-tests/features"}
const concurrency = 100
const noRandomFlag = 0
const noConcurrency = 1
fmtOutputScenarioInitializer := func(ctx *ScenarioContext) {
ctx.Step(`^(?:a )?failing step`, failingStepDef)
ctx.Step(`^(?:a )?pending step$`, pendingStepDef)
ctx.Step(`^(?:a )?passing step$`, passingStepDef)
ctx.Step(`^odd (\d+) and even (\d+) number$`, oddEvenStepDef)
}
for _, formatter := range formatters {
t.Run(
fmt.Sprintf("%s/concurrency/%d", formatter, concurrency),
func(t *testing.T) {
expectedStatus, expectedOutput := testRun(t,
fmtOutputScenarioInitializer,
formatter, noConcurrency,
noRandomFlag, featurePaths,
)
actualStatus, actualOutput := testRun(t,
fmtOutputScenarioInitializer,
formatter, concurrency,
noRandomFlag, featurePaths,
)
assert.Equal(t, expectedStatus, actualStatus)
assertOutput(t, formatter, expectedOutput, actualOutput)
},
)
}
}
func testRun(
t *testing.T,
scenarioInitializer func(*ScenarioContext),
format string,
concurrency int,
randomSeed int64,
featurePaths []string,
) (int, string) {
t.Helper()
opts := Options{
Format: format,
Paths: featurePaths,
Concurrency: concurrency,
Randomize: randomSeed,
}
return testRunWithOptions(t, opts, scenarioInitializer)
}
func testRunWithOptions(
t *testing.T,
opts Options,
scenarioInitializer func(*ScenarioContext),
) (int, string) {
t.Helper()
output := new(bytes.Buffer)
opts.Output = output
opts.NoColors = true
status := TestSuite{
Name: "succeed",
ScenarioInitializer: scenarioInitializer,
Options: &opts,
}.Run()
actual, err := ioutil.ReadAll(output)
require.NoError(t, err)
return status, string(actual)
}
func assertOutput(t *testing.T, formatter string, expected, actual string) {
switch formatter {
case "cucumber", "junit", "pretty", "events":
expectedRows := strings.Split(expected, "\n")
actualRows := strings.Split(actual, "\n")
assert.ElementsMatch(t, expectedRows, actualRows)
case "progress":
expectedOutput := parseProgressOutput(expected)
actualOutput := parseProgressOutput(actual)
assert.Equal(t, expectedOutput.passed, actualOutput.passed)
assert.Equal(t, expectedOutput.skipped, actualOutput.skipped)
assert.Equal(t, expectedOutput.failed, actualOutput.failed)
assert.Equal(t, expectedOutput.undefined, actualOutput.undefined)
assert.Equal(t, expectedOutput.pending, actualOutput.pending)
assert.Equal(t, expectedOutput.noOfStepsPerRow, actualOutput.noOfStepsPerRow)
assert.ElementsMatch(t, expectedOutput.bottomRows, actualOutput.bottomRows)
}
}
func parseProgressOutput(output string) (parsed progressOutput) {
mainParts := strings.Split(output, "\n\n\n")
topRows := strings.Split(mainParts[0], "\n")
parsed.bottomRows = strings.Split(mainParts[1], "\n")
parsed.noOfStepsPerRow = make([]string, len(topRows))
for idx, row := range topRows {
rowParts := strings.Split(row, " ")
stepResults := strings.Split(rowParts[0], "")
parsed.noOfStepsPerRow[idx] = rowParts[1]
for _, stepResult := range stepResults {
switch stepResult {
case ".":
parsed.passed++
case "-":
parsed.skipped++
case "F":
parsed.failed++
case "U":
parsed.undefined++
case "P":
parsed.pending++
}
}
}
return parsed
}
type progressOutput struct {
passed int
skipped int
failed int
undefined int
pending int
noOfStepsPerRow []string
bottomRows []string
}
func passingStepDef() error { return nil }
func oddEvenStepDef(odd, even int) error { return oddOrEven(odd, even) }
func oddOrEven(odd, even int) error {
if odd%2 == 0 {
return fmt.Errorf("%d is not odd", odd)
}
if even%2 != 0 {
return fmt.Errorf("%d is not even", even)
}
return nil
}
func pendingStepDef() error { return ErrPending }
func failingStepDef() error { return fmt.Errorf("step failed") }
func parseSeed(str string) (seed int64) {
re := regexp.MustCompile(`Randomized with seed: (\d*)`)
match := re.FindStringSubmatch(str)
if len(match) > 0 {
var err error
if seed, err = strconv.ParseInt(match[1], 10, 64); err != nil {
seed = 0
}
}
return
}