在线时间:8:00-16:00
迪恩网络APP
随时随地掌握行业动态
扫描二维码
关注迪恩网络微信公众号
开源软件名称:cucumber/godog开源软件地址:https://github.com/cucumber/godog开源编程语言:Go 78.3%开源软件介绍:GodogThe API is likely to change a few times before we reach 1.0.0 Please read the full README, you may find it very useful. And do not forget to peek into the Release Notes and 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. The project was inspired by behat and cucumber. Why Godog/CucumberA single source of truthGodog merges specification and test documentation into one cohesive whole. Living documentationBecause they're automatically tested by Godog, your specifications are always bang up-to-date. Focus on the customerBusiness 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 reworkWhen automated testing is this much fun, teams can easily protect themselves from costly regressions. Read moreContributionsGodog is a community driven Open Source Project within the Cucumber organization. We welcome contributions from everyone, and we're ready to support you if you have the enthusiasm to contribute. See the contributing guide for more detail on how to get started. Getting helpWe have a community Slack where you can chat with other users, developers, and BDD practitioners. Here are some useful channels to try:
ExamplesYou can find a few examples here. Note that if you want to execute any of the examples and have the Git repository checked out in the GodogsThe following example can be found here. Step 1 - Setup a go moduleGiven we create a new go module godogs in your normal go workspace. - From now on, this is our work directory - Initiate the go module - Step 2 - Install godogInstall the Step 3 - Create gherkin featureImagine we have a godog cart to serve godogs for lunch. First of all, we describe our feature in plain text - 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 Step 4 - Create godog step definitionsNOTE: 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. If we run godog inside the module: - You should see that the steps are undefined:
Create and copy the step definitions into a new file - package main
import "github.com/cucumber/godog"
func iEat(arg1 int) error {
return godog.ErrPending
}
func thereAreGodogs(arg1 int) error {
return godog.ErrPending
}
func thereShouldBeRemaining(arg1 int) error {
return godog.ErrPending
}
func InitializeScenario(ctx *godog.ScenarioContext) {
ctx.Step(`^I eat (\d+)$`, iEat)
ctx.Step(`^there are (\d+) godogs$`, thereAreGodogs)
ctx.Step(`^there should be (\d+) remaining$`, thereShouldBeRemaining)
} Our module should now look like this:
Run godog again - You should now see that the scenario is pending with one step pending and two steps skipped:
You may change return godog.ErrPending to return nil in the three step definitions and the scenario will pass successfully. Also, you may omit error return if your step does not fail. func iEat(arg1 int) {
// Eat arg1.
} Step 5 - Create the main program to testWe only need a number of godogs for now. Lets keep it simple. Create and copy the code into a new file - package main
// Godogs available to eat
var Godogs int
func main() { /* usual main func */ } Our module should now look like this:
Step 6 - Add some logic to the step definitionsNow lets implement our step definitions to test our feature requirements: Replace the contents of package main
import (
"context"
"errors"
"fmt"
"testing"
"github.com/cucumber/godog"
)
// godogsCtxKey is the key used to store the available godogs in the context.Context.
type godogsCtxKey struct{}
func thereAreGodogs(ctx context.Context, available int) (context.Context, error) {
return context.WithValue(ctx, godogsCtxKey{}, available), nil
}
func iEat(ctx context.Context, num int) (context.Context, error) {
available, ok := ctx.Value(godogsCtxKey{}).(int)
if !ok {
return ctx, errors.New("there are no godogs available")
}
if available < num {
return ctx, fmt.Errorf("you cannot eat %d godogs, there are %d available", num, available)
}
available -= num
return context.WithValue(ctx, godogsCtxKey{}, available), nil
}
func thereShouldBeRemaining(ctx context.Context, remaining int) error {
available, ok := ctx.Value(godogsCtxKey{}).(int)
if !ok {
return errors.New("there are no godogs available")
}
if available != remaining {
return fmt.Errorf("expected %d godogs to be remaining, but there is %d", remaining, available)
}
return nil
}
func TestFeatures(t *testing.T) {
suite := godog.TestSuite{
ScenarioInitializer: InitializeScenario,
Options: &godog.Options{
Format: "pretty",
Paths: []string{"features"},
TestingT: t, // Testing instance that will run subtests.
},
}
if suite.Run() != 0 {
t.Fatal("non-zero status returned, failed to run feature tests")
}
}
func InitializeScenario(sc *godog.ScenarioContext) {
sc.Step(`^there are (\d+) godogs$`, thereAreGodogs)
sc.Step(`^I eat (\d+)$`, iEat)
sc.Step(`^there should be (\d+) remaining$`, thereShouldBeRemaining)
} In this example we are using When you run godog again with You should see a passing run:
You may hook to 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.
Code of ConductEveryone interacting in this codebase and issue tracker is expected to follow the Cucumber code of conduct. References and Tutorials
DocumentationSee pkg documentation for general API details.
See Circle Config for supported go versions.
See See implementation examples: FAQRunning Godog with go testYou may integrate running godog in your go test command. Subtests of *testing.TYou can run test suite using go Subtests. In this case it is not necessary to have godog command installed. See the following example. package main_test
import (
"testing"
"github.com/cucumber/godog"
)
func TestFeatures(t *testing.T) {
suite := godog.TestSuite{
ScenarioInitializer: func(s *godog.ScenarioContext) {
// Add step definitions here.
},
Options: &godog.Options{
Format: "pretty",
Paths: []string{"features"},
TestingT: t, // Testing instance that will run subtests.
},
}
if suite.Run() != 0 {
t.Fatal("non-zero status returned, failed to run feature tests")
}
} Then you can run suite.
Or a particular scenario.
TestMainYou can run test suite 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 package main
import (
"os"
"testing"
"github.com/cucumber/godog"
"github.com/cucumber/godog/colors"
"github.com/spf13/pflag" // godog v0.11.0 and later
)
var opts = godog.Options{
Output: colors.Colored(os.Stdout),
Format: "progress", // can define default values
}
func init() {
godog.BindFlags("godog.", pflag.CommandLine, &opts) // godog v0.10.0 and earlier
godog.BindCommandLineFlags("godog.", &opts) // godog v0.11.0 and later
}
func TestMain(m *testing.M) {
pflag.Parse()
opts.Paths = pflag.Args()
status := godog.TestSuite{
Name: "godogs",
TestSuiteInitializer: InitializeTestSuite,
ScenarioInitializer: InitializeScenario,
Options: &opts,
}.Run()
// Optional: Run `testing` package's logic besides godog.
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.
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
}
status := godog.TestSuite{
Name: "godogs",
TestSuiteInitializer: InitializeTestSuite,
ScenarioInitializer: InitializeScenario,
Options: &opts,
}.Run()
// Optional: Run `testing` package's logic besides godog.
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"},
}
status := godog.TestSuite{
Name: "godogs",
TestSuiteInitializer: InitializeTestSuite,
ScenarioInitializer: InitializeScenario,
Options: &opts,
}.Run()
// Optional: Run `testing` package's logic besides godog.
if st := m.Run(); st > status {
status = st
}
os.Exit(status)
} Now when running TagsIf you want to filter scenarios by tags, you can use the
Using assertion packages like testify with GodogA 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...)
} |