Godog - приёмочные тесты по-человечески (форк https://github.com/cucumber/godog)
Найти файл
Fredrik Lönnblad 18a045f989
Merge pull request #305 from cucumber/store-results-in-storage
Added Pickle and PickleStep results to the in-mem storage
2020-06-13 06:43:16 +02:00
.circleci Moved the fmt tests to a godog_test pkg and restructured the fmt output tests 2020-05-22 12:52:27 +02:00
.github/ISSUE_TEMPLATE Update issue templates 2020-03-14 08:44:56 -03:00
_examples Readded some legacy doc for FeatureContext 2020-05-23 08:51:23 +02:00
cmd/godog Change data-dog/godog references to cucumber/godog 2020-02-06 08:38:28 -07:00
colors Updated linting checks in circleci config and fixed linting issues 2020-05-03 12:09:51 +02:00
features Added a missed test file and updated the CHANGELOG 2020-04-30 14:32:13 +02:00
formatter-tests Copied the SuiteContext for testing of TestSuite{}.Run() 2020-06-06 16:12:19 +02:00
release-notes Fixed final release doc for v0.9.0 2020-03-22 18:08:17 +01:00
screenshots update godog usage example with more details 2016-06-17 10:06:52 +03:00
.gitignore <fix>(PRETIFIER): Fix s method to not have errors on negative entry 2020-03-09 10:39:20 +01:00
ast.go Added the new TestSuiteInitializer and ScenarioInitializer 2020-05-18 09:48:06 +02:00
ast_test.go Added the new TestSuiteInitializer and ScenarioInitializer 2020-05-18 09:48:06 +02:00
builder.go Added the new TestSuiteInitializer and ScenarioInitializer 2020-05-18 09:48:06 +02:00
builder_go112_test.go Made the builder tests run in parallel 2020-05-24 19:05:08 +02:00
builder_go113_test.go Made the builder tests run in parallel 2020-05-24 19:05:08 +02:00
builder_go_module_test.go Made the builder tests run in parallel 2020-05-24 19:05:08 +02:00
builder_test.go Made the builder tests run in parallel 2020-05-24 19:05:08 +02:00
CHANGELOG.md Update CHANGELOG.md 2020-05-23 09:11:49 +02:00
CHANGELOG_OLD.md Switch to new CHANGELOG and bump version to 0.8.0 2020-02-06 08:45:44 -07:00
CONTRIBUTING.md Merge branch 'master' into release/v0.9.0 2020-03-16 08:04:07 -03:00
flags.go Change data-dog/godog references to cucumber/godog 2020-02-06 08:38:28 -07:00
flags_test.go Change data-dog/godog references to cucumber/godog 2020-02-06 08:38:28 -07:00
fmt.go Added Pickle and PickleStep results to the in-mem storage 2020-06-10 21:45:23 +02:00
fmt_color_tag_test.go Moved the fmt tests to a godog_test pkg and restructured the fmt output tests 2020-05-22 12:52:27 +02:00
fmt_cucumber.go Added Pickle and PickleStep results to the in-mem storage 2020-06-10 21:45:23 +02:00
fmt_events.go Added Pickle and PickleStep results to the in-mem storage 2020-06-10 21:45:23 +02:00
fmt_junit.go Added Pickle and PickleStep results to the in-mem storage 2020-06-10 21:45:23 +02:00
fmt_output_test.go Copied the SuiteContext for testing of TestSuite{}.Run() 2020-06-06 16:12:19 +02:00
fmt_pretty.go Added Pickle and PickleStep results to the in-mem storage 2020-06-10 21:45:23 +02:00
fmt_progress.go Added Pickle and PickleStep results to the in-mem storage 2020-06-10 21:45:23 +02:00
fmt_progress_test.go Added an in-mem storage for pickles 2020-06-09 13:30:32 +02:00
fmt_test.go Moved the fmt tests to a godog_test pkg and restructured the fmt output tests 2020-05-22 12:52:27 +02:00
go.mod Added an in-mem storage for pickles 2020-06-09 13:30:32 +02:00
go.sum Added an in-mem storage for pickles 2020-06-09 13:30:32 +02:00
godog.go Fixed final release doc for v0.9.0 2020-03-22 18:08:17 +01:00
LICENSE Fix typo 2020-02-04 11:59:44 +00:00
logo.png Replaced loco.png with better quality image and added a vector logo 2018-12-19 19:19:45 +01:00
logo.svg Replaced loco.png with better quality image and added a vector logo 2018-12-19 19:19:45 +01:00
Makefile Rename examples to _examples 2020-02-10 09:31:52 +08:00
options.go adds --strict flag to fail suite when there are pending or undefined steps 2017-05-04 20:25:29 +03:00
README.md Updated the README.md 2020-06-10 21:24:54 +02:00
run.go Added Pickle and PickleStep results to the in-mem storage 2020-06-10 21:45:23 +02:00
run_test.go Added an in-mem storage for pickles 2020-06-09 13:30:32 +02:00
stacktrace.go fixes stack trace test 2017-04-28 10:54:24 +03:00
stacktrace_test.go Made progress formatter verification a bit more accurate 2020-03-24 09:56:59 +01:00
stepdef.go Upgraded gherkin-go and messages-go to latest 2020-03-12 15:16:43 -03:00
stepdef_test.go Upgraded gherkin-go and messages-go to latest 2020-03-12 15:16:43 -03:00
storage.go Added Pickle and PickleStep results to the in-mem storage 2020-06-10 21:45:23 +02:00
suite.go Added Pickle and PickleStep results to the in-mem storage 2020-06-10 21:45:23 +02:00
suite_context.go Added Pickle and PickleStep results to the in-mem storage 2020-06-10 21:45:23 +02:00
suite_context_test.go Added Pickle and PickleStep results to the in-mem storage 2020-06-10 21:45:23 +02:00
suite_test.go Remove TestMain call 2020-03-04 22:16:20 -07:00
tag_filter.go Broke out the tag filtering logic to its own file 2020-06-07 09:10:56 +02:00
tag_filter_test.go Broke out the tag filtering logic to its own file 2020-06-07 09:10:56 +02:00
test_context.go Added the new TestSuiteInitializer and ScenarioInitializer 2020-05-18 09:48:06 +02:00
test_context_test.go Added Pickle and PickleStep results to the in-mem storage 2020-06-10 21:45:23 +02:00
undefined_snippets_gen.go Added sorting for undefined snippets on method name 2020-03-24 10:05:05 +01:00
utils.go Clean change on pretty. Make test on new TC meaningfull again. 2020-03-09 20:54:10 +01:00
utils_test.go tests junit formatter 2017-04-28 15:46:11 +03:00

CircleCI GoDoc codecov

Godog

Godog logo

The API is likely to change a few times before we reach 1.0.0

Please read all the README, you may find it very useful. And do not forget to peek into the CHANGELOG from time to time.

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.

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.

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.

The project was inspired by behat and cucumber.

Why Godog/Cucumber

A single source of truth

Godog merges specification and test documentation into one cohesive whole.

Living documentation

Because they're automatically tested by Godog, your specifications are always bang up-to-date.

Focus on the customer

Business and IT don't always understand each other. Godog's executable specifications encourage closer collaboration, helping teams keep the business goal in mind at all times.

Less rework

When automated testing is this much fun, teams can easily protect themselves from costly regressions.

Read more

Install

go get github.com/cucumber/godog/cmd/godog@v0.9.0

Adding @v0.9.0 will install v0.9.0 specifically instead of master.

Running within the $GOPATH, you would also need to set GO111MODULE=on, like this:

GO111MODULE=on go get github.com/cucumber/godog/cmd/godog@v0.9.0

Contributions

Godog is a community driven Open Source Project within the Cucumber organization, it is maintained by a handfull of developers, but we appreciate contributions from everyone.

If you are interested in developing Godog, we suggest you to visit one of our slack channels.

Feel free to open a pull request. Note, if you wish to contribute larger changes or an extension to the exported methods or types, please open an issue before and visit us in slack to discuss the changes.

Reach out to the community on our Cucumber Slack Community. Join here.

Example

The following example can be found here.

Step 1

Given we create a new go package $GOPATH/src/godogs. From now on, this is our work directory cd $GOPATH/src/godogs.

Imagine we have a godog cart to serve godogs for lunch. First of all, we describe our feature in plain text - vim $GOPATH/src/godogs/features/godogs.feature:

# file: $GOPATH/src/godogs/features/godogs.feature
Feature: eat godogs
  In order to be happy
  As a hungry gopher
  I need to be able to eat godogs

  Scenario: Eat 5 out of 12
    Given there are 12 godogs
    When I eat 5
    Then there should be 7 remaining

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 - $GOPATH/src/godogs

Step 2

If godog is installed in your GOPATH. We can run godog inside the $GOPATH/src/godogs directory. You should see that the steps are undefined:

Undefined step snippets

If we wish to vendor godog dependency, we can do it as usual, using tools you prefer:

git clone https://github.com/cucumber/godog.git $GOPATH/src/godogs/vendor/github.com/cucumber/godog

It gives you undefined step snippets to implement in your test context. You may copy these snippets into your godogs_test.go file.

Our directory structure should now look like:

Directory layout

If you copy the snippets into our test file and run godog again. We should see the step definition is now pending:

Pending step definition

You may change ErrPending to nil and the scenario will pass successfully.

Since we need a working implementation, we may start by implementing only what is necessary.

Step 3

We only need a number of godogs for now. Lets keep it simple.

package main

// Godogs available to eat
var Godogs int

func main() { /* usual main func */ }

Step 4

Now lets implement our step definitions, which we can copy from generated console output snippets in order to test our feature requirements:

package main

import (
	"fmt"
	
	messages "github.com/cucumber/messages-go/v10" // needed for godog v0.9.0 (latest) and earlier

	"github.com/cucumber/godog"
)

func thereAreGodogs(available int) error {
	Godogs = available
	return nil
}

func iEat(num int) error {
	if Godogs < num {
		return fmt.Errorf("you cannot eat %d godogs, there are %d available", num, Godogs)
	}
	Godogs -= num
	return nil
}

func thereShouldBeRemaining(remaining int) error {
	if Godogs != remaining {
		return fmt.Errorf("expected %d godogs to be remaining, but there is %d", remaining, Godogs)
	}
	return nil
}

// godog v0.9.0 (latest) and earlier
func FeatureContext(s *godog.Suite) {
	s.BeforeSuite(func() { Godogs = 0 })

	s.BeforeScenario(func(*messages.Pickle) {
		Godogs = 0 // clean the state before every scenario
	})

	s.Step(`^there are (\d+) godogs$`, thereAreGodogs)
	s.Step(`^I eat (\d+)$`, iEat)
	s.Step(`^there should be (\d+) remaining$`, thereShouldBeRemaining)
}

// godog v0.10.0 (coming release)
func InitializeTestSuite(ctx *godog.TestSuiteContext) {
	ctx.BeforeSuite(func() { Godogs = 0 })
}

func InitializeScenario(ctx *godog.ScenarioContext) {
	ctx.BeforeScenario(func(*godog.Scenario) {
		Godogs = 0 // clean the state before every scenario
	})

	ctx.Step(`^there are (\d+) godogs$`, thereAreGodogs)
	ctx.Step(`^I eat (\d+)$`, iEat)
	ctx.Step(`^there should be (\d+) remaining$`, thereShouldBeRemaining)
}

Now when you run the godog again, you should see:

Passed suite

We have hooked to BeforeScenario event in order to reset application state before each scenario. You may hook into more events, like AfterStep to print all state in case of an error. Or BeforeSuite to prepare a database.

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.

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.

References and Tutorials

Documentation

See pkg documentation for general API details. See Circle Config for supported go versions. See godog -h for general command options.

See implementation examples:

FAQ

Running Godog with go test

You may integrate running godog in your go test command. You can run it using go TestMain func available since go 1.4. In this case it is not necessary to have godog command installed. See the following examples.

The following example binds godog flags with specified prefix godog in order to prevent flag collisions.

var opts = godog.Options{
	Output: colors.Colored(os.Stdout),
	Format: "progress", // can define default values
}

func init() {
	godog.BindFlags("godog.", flag.CommandLine, &opts)
}

func TestMain(m *testing.M) {
	flag.Parse()
	opts.Paths = flag.Args()

	// godog v0.9.0 (latest) and earlier
	status := godog.RunWithOptions("godogs", func(s *godog.Suite) {
		FeatureContext(s)
	}, opts)

	// godog v0.10.0 (coming release)
	status := godog.TestSuite{
		Name: "godogs",
		TestSuiteInitializer: InitializeTestSuite,
		ScenarioInitializer:  InitializeScenario,
		Options: &opts,
	}.Run()

	if st := m.Run(); st > status {
		status = st
	}
	os.Exit(status)
}

Then you may run tests with by specifying flags in order to filter features.

go test -v --godog.random --godog.tags=wip
go test -v --godog.format=pretty --godog.random -race -coverprofile=coverage.txt -covermode=atomic

The following example does not bind godog flags, instead manually configuring needed options.

func TestMain(m *testing.M) {
	opts := godog.Options{
		Format:    "progress",
		Paths:     []string{"features"},
		Randomize: time.Now().UTC().UnixNano(), // randomize scenario execution order
	}

	// godog v0.9.0 (latest) and earlier
	status := godog.RunWithOptions("godogs", func(s *godog.Suite) {
		FeatureContext(s)
	}, opts)

	// godog v0.10.0 (coming release)
	status := godog.TestSuite{
		Name: "godogs",
		TestSuiteInitializer: InitializeTestSuite,
		ScenarioInitializer:  InitializeScenario,
		Options: &opts,
	}.Run()

	if st := m.Run(); st > status {
		status = st
	}
	os.Exit(status)
}

You can even go one step further and reuse go test flags, like verbose mode in order to switch godog format. See the following example:

func TestMain(m *testing.M) {
	format := "progress"
	for _, arg := range os.Args[1:] {
		if arg == "-test.v=true" { // go test transforms -v option
			format = "pretty"
			break
		}
	}

	opts := godog.Options{
		Format: format,
		Paths:     []string{"features"},
	}

	// godog v0.9.0 (latest) and earlier
	status := godog.RunWithOptions("godogs", func(s *godog.Suite) {
		FeatureContext(s)
	}, opts)

	// godog v0.10.0 (coming release)
	status := godog.TestSuite{
		Name: "godogs",
		TestSuiteInitializer: InitializeTestSuite,
		ScenarioInitializer:  InitializeScenario,
		Options: &opts,
	}.Run()

	if st := m.Run(); st > status {
		status = st
	}
	os.Exit(status)
}

Now when running go test -v it will use pretty format.

Tags

If you want to filter scenarios by tags, you can use the -t=<expression> or --tags=<expression> where <expression> is one of the following:

  • @wip - run all scenarios with wip tag
  • ~@wip - exclude all scenarios with wip tag
  • @wip && ~@new - run wip scenarios, but exclude new
  • @wip,@undone - run wip or undone scenarios

Using assertion packages like testify with Godog

A more extensive example can be found here.

func thereShouldBeRemaining(remaining int) error {
	return assertExpectedAndActual(
		assert.Equal, Godogs, remaining,
		"Expected %d godogs to be remaining, but there is %d", remaining, Godogs,
	)
}

// assertExpectedAndActual is a helper function to allow the step function to call
// assertion functions where you want to compare an expected and an actual value.
func assertExpectedAndActual(a expectedAndActualAssertion, expected, actual interface{}, msgAndArgs ...interface{}) error {
	var t asserter
	a(&t, expected, actual, msgAndArgs...)
	return t.err
}

type expectedAndActualAssertion func(t assert.TestingT, expected, actual interface{}, msgAndArgs ...interface{}) bool

// asserter is used to be able to retrieve the error reported by the called assertion
type asserter struct {
	err error
}

// Errorf is used by the called assertion to report an error
func (a *asserter) Errorf(format string, args ...interface{}) {
	a.err = fmt.Errorf(format, args...)
}

Configure common options for godog CLI

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

Testing browser interactions

godog does not come with builtin packages to connect to the browser. You may want to look at selenium and probably phantomjs. See also the following components:

  1. browsersteps - provides basic context steps to start selenium and navigate browser content.
  2. You may wish to have goquery in order to work with HTML responses like with JQuery.

Concurrency

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.

It is also useful to randomize the order of scenario execution, which you can now do with --random command option.

NOTE: if suite runs with concurrency option, it concurrently runs every feature, not scenario per different features. This will be updated in release v0.10.0 to run every scenario concurrently.

License

Godog and Gherkin are licensed under the MIT and developed as a part of the cucumber project