Skip to content

Commit 99655f7

Browse files
vearutopmattwynne
andauthoredMay 21, 2022
Update README to reflect current best practices in creating and running tests (cucumber#477)
* Update README to reflect current best practices in creating and running tests * Update CHANGELOG and README Co-authored-by: Matt Wynne <[email protected]>
1 parent d52a4d3 commit 99655f7

File tree

2 files changed

+102
-83
lines changed

2 files changed

+102
-83
lines changed
 

‎CHANGELOG.md

+3
Original file line numberDiff line numberDiff line change
@@ -8,6 +8,9 @@ This document is formatted according to the principles of [Keep A CHANGELOG](htt
88

99
## Unreleased
1010

11+
### Changed
12+
- README example is updated with `context.Context` and `go test` usage. ([477](https://github.com/cucumber/godog/pull/477) - [vearutop](https://github.com/vearutop))
13+
1114
## [v0.12.5]
1215
### Changed
1316
- Changed underlying cobra command setup to return errors instead of calling `os.Exit` directly to enable simpler testing. ([454](https://github.com/cucumber/godog/pull/454) - [mxygem](https://github.com/mxygem))

‎README.md

+99-83
Original file line numberDiff line numberDiff line change
@@ -15,10 +15,6 @@ Please read the full README, you may find it very useful. And do not forget to p
1515

1616
Package godog is the official Cucumber BDD framework for Golang, it merges specification and test documentation into one cohesive whole, using Gherkin formatted scenarios in the format of Given, When, Then.
1717

18-
**Godog** does not intervene with the standard **go test** command behavior. You can leverage both frameworks to functionally test your application while maintaining all test related source code in **_test.go** files.
19-
20-
**Godog** acts similar compared to **go test** command, by using go compiler and linker tool in order to produce test executable. Godog contexts need to be exported the same way as **Test** functions for go tests. Note, that if you use **godog** command tool, it will use `go` executable to determine compiler and linker.
21-
2218
The project was inspired by [behat][behat] and [cucumber][cucumber].
2319

2420
## Why Godog/Cucumber
@@ -44,18 +40,6 @@ When automated testing is this much fun, teams can easily protect themselves fro
4440
- [Behaviour-Driven Development](https://cucumber.io/docs/bdd/)
4541
- [Gherkin Reference](https://cucumber.io/docs/gherkin/reference/)
4642

47-
## Install
48-
```
49-
go install github.com/cucumber/godog/cmd/godog@v0.12.0
50-
```
51-
Adding `@v0.12.0` will install v0.12.0 specifically instead of master.
52-
53-
With `go` version prior to 1.17, use `go get github.com/cucumber/godog/cmd/godog@v0.12.0`.
54-
Running `within the $GOPATH`, you would also need to set `GO111MODULE=on`, like this:
55-
```
56-
GO111MODULE=on go get github.com/cucumber/godog/cmd/godog@v0.12.0
57-
```
58-
5943
## Contributions
6044

6145
Godog is a community driven Open Source Project within the Cucumber organization. We [welcome contributions from everyone](https://cucumber.io/blog/open-source/tackling-structural-racism-(and-sexism)-in-open-so/), and we're ready to support you if you have the enthusiasm to contribute.
@@ -92,13 +76,13 @@ Initiate the go module - `go mod init godogs`
9276

9377
#### Step 2 - Install godog
9478

95-
Install the godog binary - `go get github.com/cucumber/godog/cmd/godog`
79+
Install the `godog` binary - `go install github.com/cucumber/godog/cmd/godog@latest`.
9680

9781
#### Step 3 - Create gherkin feature
9882

9983
Imagine we have a **godog cart** to serve godogs for lunch.
10084

101-
First of all, we describe our feature in plain text - `vim features/godogs.feature`
85+
First of all, we describe our feature in plain text - `vim features/godogs.feature`.
10286

10387
``` gherkin
10488
Feature: eat godogs
@@ -116,7 +100,7 @@ Feature: eat godogs
116100

117101
**NOTE:** same as **go test** godog respects package level isolation. All your step definitions should be in your tested package root directory. In this case: **godogs**.
118102

119-
If we run godog inside the module: - `godog`
103+
If we run godog inside the module: - `godog run`
120104

121105
You should see that the steps are undefined:
122106
```
@@ -190,7 +174,7 @@ godogs
190174
- godogs_test.go
191175
```
192176

193-
Run godog again - `godog`
177+
Run godog again - `godog run`
194178

195179
You should now see that the scenario is pending with one step pending and two steps skipped:
196180
```
@@ -255,101 +239,111 @@ Replace the contents of `godogs_test.go` with the code below - `vim godogs_test.
255239
package main
256240

257241
import (
258-
"context"
259-
"fmt"
242+
"context"
243+
"errors"
244+
"fmt"
245+
"testing"
260246

261-
"github.com/cucumber/godog"
247+
"github.com/cucumber/godog"
262248
)
263249

264-
func thereAreGodogs(available int) error {
265-
Godogs = available
266-
return nil
267-
}
250+
// godogsCtxKey is the key used to store the available godogs in the context.Context.
251+
type godogsCtxKey struct{}
268252

269-
func iEat(num int) error {
270-
if Godogs < num {
271-
return fmt.Errorf("you cannot eat %d godogs, there are %d available", num, Godogs)
272-
}
273-
Godogs -= num
274-
return nil
253+
func thereAreGodogs(ctx context.Context, available int) (context.Context, error) {
254+
return context.WithValue(ctx, godogsCtxKey{}, available), nil
275255
}
276256

277-
func thereShouldBeRemaining(remaining int) error {
278-
if Godogs != remaining {
279-
return fmt.Errorf("expected %d godogs to be remaining, but there is %d", remaining, Godogs)
280-
}
281-
return nil
282-
}
257+
func iEat(ctx context.Context, num int) (context.Context, error) {
258+
available, ok := ctx.Value(godogsCtxKey{}).(int)
259+
if !ok {
260+
return ctx, errors.New("there are no godogs available")
261+
}
262+
263+
if available < num {
264+
return ctx, fmt.Errorf("you cannot eat %d godogs, there are %d available", num, available)
265+
}
283266

284-
func InitializeTestSuite(sc *godog.TestSuiteContext) {
285-
sc.BeforeSuite(func() { Godogs = 0 })
267+
available -= num
268+
269+
return context.WithValue(ctx, godogsCtxKey{}, available), nil
286270
}
287271

288-
func InitializeScenario(sc *godog.ScenarioContext) {
289-
sc.Before(func(ctx context.Context, sc *godog.Scenario) (context.Context, error) {
290-
Godogs = 0 // clean the state before every scenario
272+
func thereShouldBeRemaining(ctx context.Context, remaining int) error {
273+
available, ok := ctx.Value(godogsCtxKey{}).(int)
274+
if !ok {
275+
return errors.New("there are no godogs available")
276+
}
291277

292-
return ctx, nil
293-
})
278+
if available != remaining {
279+
return fmt.Errorf("expected %d godogs to be remaining, but there is %d", remaining, available)
280+
}
294281

295-
sc.Step(`^there are (\d+) godogs$`, thereAreGodogs)
296-
sc.Step(`^I eat (\d+)$`, iEat)
297-
sc.Step(`^there should be (\d+) remaining$`, thereShouldBeRemaining)
282+
return nil
298283
}
299-
```
300284

301-
You can also pass the state between steps and hooks of a scenario using `context.Context`.
302-
Step definitions can receive and return `context.Context`.
285+
func TestFeatures(t *testing.T) {
286+
suite := godog.TestSuite{
287+
ScenarioInitializer: InitializeScenario,
288+
Options: &godog.Options{
289+
Format: "pretty",
290+
Paths: []string{"features"},
291+
TestingT: t, // Testing instance that will run subtests.
292+
},
293+
}
294+
295+
if suite.Run() != 0 {
296+
t.Fatal("non-zero status returned, failed to run feature tests")
297+
}
298+
}
299+
300+
func InitializeScenario(sc *godog.ScenarioContext) {
301+
sc.Step(`^there are (\d+) godogs$`, thereAreGodogs)
302+
sc.Step(`^I eat (\d+)$`, iEat)
303+
sc.Step(`^there should be (\d+) remaining$`, thereShouldBeRemaining)
304+
}
303305

304-
```go
305-
type cntCtxKey struct{} // Key for a particular context value type.
306-
307-
s.Step("^I have a random number of godogs$", func(ctx context.Context) context.Context {
308-
// Creating a random number of godog and storing it in context for future reference.
309-
cnt := rand.Int()
310-
Godogs = cnt
311-
return context.WithValue(ctx, cntCtxKey{}, cnt)
312-
})
313-
314-
s.Step("I eat all available godogs", func(ctx context.Context) error {
315-
// Getting previously stored number of godogs from context.
316-
cnt := ctx.Value(cntCtxKey{}).(uint32)
317-
if Godogs < cnt {
318-
return errors.New("can't eat more than I have")
319-
}
320-
Godogs -= cnt
321-
return nil
322-
})
323306
```
324307

325-
When you run godog again - `godog`
308+
In this example we are using `context.Context` to pass the state between the steps.
309+
Every scenario starts with an empty context and then steps and hooks can add relevant information to it.
310+
Instrumented context is chained through the steps and hooks and is safe to use when multiple scenarios are running concurrently.
311+
312+
When you run godog again with `go test -v godogs_test.go` or with a CLI `godog run`.
326313

327314
You should see a passing run:
328-
```gherkin
315+
```
316+
=== RUN TestFeatures
329317
Feature: eat godogs
330318
In order to be happy
331319
As a hungry gopher
332320
I need to be able to eat godogs
321+
=== RUN TestFeatures/Eat_5_out_of_12
333322
334323
Scenario: Eat 5 out of 12 # features/godogs.feature:6
335-
Given there are 12 godogs # godogs_test.go:10 -> thereAreGodogs
336-
When I eat 5 # godogs_test.go:14 -> iEat
337-
Then there should be 7 remaining # godogs_test.go:22 -> thereShouldBeRemaining
338-
```
339-
```
324+
Given there are 12 godogs # godogs_test.go:14 -> command-line-arguments.thereAreGodogs
325+
When I eat 5 # godogs_test.go:18 -> command-line-arguments.iEat
326+
Then there should be 7 remaining # godogs_test.go:33 -> command-line-arguments.thereShouldBeRemaining
327+
340328
1 scenarios (1 passed)
341329
3 steps (3 passed)
342-
258.302µs
330+
275.333µs
331+
--- PASS: TestFeatures (0.00s)
332+
--- PASS: TestFeatures/Eat_5_out_of_12 (0.00s)
333+
PASS
334+
ok command-line-arguments 0.130s
343335
```
344336

345-
We have hooked to `ScenarioContext` **Before** event in order to reset the application state before each scenario.
337+
You may hook to `ScenarioContext` **Before** event in order to reset or pre-seed the application state before each scenario.
346338
You may hook into more events, like `sc.StepContext()` **After** to print all state in case of an error.
347339
Or **BeforeSuite** to prepare a database.
348340

349341
By now, you should have figured out, how to use **godog**. Another advice is to make steps orthogonal, small and simple to read for a user. Whether the user is a dumb website user or an API developer, who may understand a little more technical context - it should target that user.
350342

351343
When steps are orthogonal and small, you can combine them just like you do with Unix tools. Look how to simplify or remove ones, which can be composed.
352344

345+
`TestFeatures` acts as a regular Go test, so you can leverage your IDE facilities to run and debug it.
346+
353347
## Code of Conduct
354348

355349
Everyone interacting in this codebase and issue tracker is expected to follow the Cucumber [code of conduct](https://github.com/cucumber/cucumber/blob/master/CODE_OF_CONDUCT.md).
@@ -581,17 +575,39 @@ func (a *asserter) Errorf(format string, args ...interface{}) {
581575
}
582576
```
583577

578+
## CLI Mode
579+
580+
Another way to use `godog` is to run it in CLI mode.
581+
582+
In this mode `godog` CLI will use `go` under the hood to compile and run your test suite.
583+
584+
**Godog** does not intervene with the standard **go test** command behavior. You can leverage both frameworks to functionally test your application while maintaining all test related source code in **_test.go** files.
585+
586+
**Godog** acts similar compared to **go test** command, by using go compiler and linker tool in order to produce test executable. Godog contexts need to be exported the same way as **Test** functions for go tests. Note, that if you use **godog** command tool, it will use `go` executable to determine compiler and linker.
587+
588+
### Install
589+
```
590+
go install github.com/cucumber/godog/cmd/godog@latest
591+
```
592+
Adding `@v0.12.0` will install v0.12.0 specifically instead of master.
593+
594+
With `go` version prior to 1.17, use `go get github.com/cucumber/godog/cmd/godog@v0.12.0`.
595+
Running `within the $GOPATH`, you would also need to set `GO111MODULE=on`, like this:
596+
```
597+
GO111MODULE=on go get github.com/cucumber/godog/cmd/godog@v0.12.0
598+
```
599+
584600
### Configure common options for godog CLI
585601

586602
There are no global options or configuration files. Alias your common or project based commands: `alias godog-wip="godog --format=progress --tags=@wip"`
587603

588-
### Concurrency
604+
## Concurrency
589605

590-
When concurrency is configured in options, godog will execute the scenarios concurrently, which is support by all supplied formatters.
606+
When concurrency is configured in options, godog will execute the scenarios concurrently, which is supported by all supplied formatters.
591607

592608
In order to support concurrency well, you should reset the state and isolate each scenario. They should not share any state. It is suggested to run the suite concurrently in order to make sure there is no state corruption or race conditions in the application.
593609

594-
It is also useful to randomize the order of scenario execution, which you can now do with **--random** command option.
610+
It is also useful to randomize the order of scenario execution, which you can now do with `--random` command option or `godog.Options.Randomize` setting.
595611

596612
### Building your own custom formatter
597613
A simple example can be [found here](/_examples/custom-formatter).

0 commit comments

Comments
 (0)
Please sign in to comment.