• Stars
    star
    2,193
  • Rank 20,177 (Top 0.5 %)
  • Language
    Go
  • License
    MIT License
  • Created almost 9 years ago
  • Updated 8 days ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

Cucumber for golang

#StandWithUkraine Build Status PkgGoDev codecov pull requests issues

Godog

Godog logo

The 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/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

Contributions

Godog 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.

See the releasing guide for release flow details.

Getting help

We have a community Slack where you can chat with other users, developers, and BDD practitioners.

Here are some useful channels to try:

Examples

You 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 $GOPATH, you need to use: GO111MODULE=off. Issue for reference.

Godogs

The following example can be found here.

Step 1 - Setup a go module

Create a new go module named godogs in your go workspace by running mkdir godogs

From now on, use godogs as your working directory by running cd godogs

Initiate the go module inside the godogs directory by running go mod init godogs

Step 2 - Create gherkin feature

Imagine 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

Run vim features/godogs.feature and add the text above into the vim editor and save the file.

Step 3 - Create godog step definitions

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.

Create and copy the step definitions below into a new file by running vim godogs_test.go:

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(`^there are (\d+) godogs$`, thereAreGodogs)
        ctx.Step(`^I eat (\d+)$`, iEat)
        ctx.Step(`^there should be (\d+) remaining$`, thereShouldBeRemaining)
}

Alternatively, you can also specify the keyword (Given, When, Then...) when creating the step definitions:

func InitializeScenario(ctx *godog.ScenarioContext) {
        ctx.Given(`^there are (\d+) godogs$`, thereAreGodogs)
        ctx.When(`^I eat (\d+)$`, iEat)
        ctx.Then(`^there should be (\d+) remaining$`, thereShouldBeRemaining)
}

Our module should now look like this:

godogs
- features
  - godogs.feature
- go.mod
- go.sum
- godogs_test.go

Run go test in the godogs directory to run the steps you have defined. You should now see that the scenario runs with a warning stating there are no tests to run.

testing: warning: no tests to run
PASS
ok      godogs  0.225s

By adding some logic to these steps, you will be able to thoroughly test the feature you just defined.

Step 4 - Create the main program to test

Let's keep it simple by only requiring an amount of godogs for now.

Create and copy the code below into a new file by running vim godogs.go

package main

// Godogs available to eat
var Godogs int

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

Our module should now look like this:

godogs
- features
  - godogs.feature
- go.mod
- go.sum
- godogs.go
- godogs_test.go

Step 5 - Add some logic to the step definitions

Now lets implement our step definitions to test our feature requirements.

Replace the contents of godogs_test.go with the code below by running vim godogs_test.go.

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 context.Context to pass the state between the steps. Every scenario starts with an empty context and then steps and hooks can add relevant information to it. Instrumented context is chained through the steps and hooks and is safe to use when multiple scenarios are running concurrently.

When you run godog again with go test -v godogs_test.go, you should see a passing run:

=== RUN   TestFeatures
Feature: eat godogs
  In order to be happy
  As a hungry gopher
  I need to be able to eat godogs
=== RUN   TestFeatures/Eat_5_out_of_12

  Scenario: Eat 5 out of 12          # features/godogs.feature:6
    Given there are 12 godogs        # godog_test.go:15 -> command-line-arguments.thereAreGodogs
    When I eat 5                     # godog_test.go:19 -> command-line-arguments.iEat
    Then there should be 7 remaining # godog_test.go:34 -> command-line-arguments.thereShouldBeRemaining

1 scenarios (1 passed)
3 steps (3 passed)
279.917Β΅s
--- PASS: TestFeatures (0.00s)
    --- PASS: TestFeatures/Eat_5_out_of_12 (0.00s)
PASS
ok      command-line-arguments  0.164s

You may hook to ScenarioContext Before event in order to reset or pre-seed the application state before each scenario. You may hook into more events, like sc.StepContext() After 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 piece of 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.

TestFeatures acts as a regular Go test, so you can leverage your IDE facilities to run and debug it.

Code of Conduct

Everyone interacting in this codebase and issue tracker is expected to follow the Cucumber code of conduct.

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.

Subtests of *testing.T

You 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.

go test -test.v -test.run ^TestFeatures$

Or a particular scenario.

go test -test.v -test.run ^TestFeatures$/^my_scenario$

TestMain

You 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 godog in order to prevent flag collisions.

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.

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
	}

	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 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...)
}

Embeds

If you're looking to compile your test binary in advance of running, you can compile the feature files into the binary via go:embed:

//go:embed features/*
var features embed.FS

var opts = godog.Options{
	Paths: []string{"features"},
	FS:    features,
}

Now, the test binary can be compiled with all feature files embedded, and can be ran independently from the feature files:

> go test -c ./test/integration/integration_test.go
> mv integration.test /some/random/dir
> cd /some/random/dir
> ./integration.test

NOTE: godog.Options.FS is as fs.FS, so custom filesystem loaders can be used.

CLI Mode

NOTE: The godog CLI has been deprecated. It is recommended to use go test instead.

Another way to use godog is to run it in CLI mode.

In this mode godog CLI will use go under the hood to compile and run your test suite.

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.

Install

go install github.com/cucumber/godog/cmd/godog@latest

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

With go version prior to 1.17, use go get github.com/cucumber/godog/cmd/[email protected]. Running within the $GOPATH, you would also need to set GO111MODULE=on, like this:

GO111MODULE=on go get github.com/cucumber/godog/cmd/[email protected]

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"

Concurrency

When concurrency is configured in options, godog will execute the scenarios concurrently, which is supported by all supplied formatters.

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 or godog.Options.Randomize setting.

Building your own custom formatter

A simple example can be found here.

License

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

More Repositories

1

cucumber-ruby

Cucumber for Ruby. It's amazing!
Ruby
5,157
star
2

cucumber-js

Cucumber for JavaScript
TypeScript
4,928
star
3

common

A home for issues that are common to multiple cucumber repositories
3,359
star
4

cucumber-jvm

Cucumber for the JVM
Java
2,644
star
5

cucumber-rails

Rails Generators for Cucumber with special support for Capybara and DatabaseCleaner
Ruby
1,008
star
6

aruba

Test command-line applications with Cucumber-Ruby, RSpec or Minitest.
Ruby
948
star
7

cucumber-java-skeleton

This is the simplest possible setup for Cucumber-JVM using Java.
Java
448
star
8

cucumber-cpp

Support for writing Cucumber step definitions in C++
C++
295
star
9

cucumber-eclipse

Eclipse plugin for Cucumber
Java
188
star
10

docs

Cucumber user documentation
CSS
133
star
11

gherkin

A parser and compiler for the Gherkin language.
C
131
star
12

cucumber-expressions

Human friendly alternative to Regular Expressions
Java
129
star
13

cucumber-android

Android support for Cucumber-JVM
Kotlin
124
star
14

cucumber-electron

Run cucumber.js in electron
JavaScript
119
star
15

gherkin-go

[READ-ONLY] Gherkin for Go - subtree of https://github.com/cucumber/gherkin -- moved to https://github.com/cucumber/gherkin
Go
84
star
16

gherkin-javascript

[READ-ONLY] Gherkin for JavaScript - subtree of monorepo https://github.com/cucumber/cucumber -- moved to https://github.com/cucumber/gherkin
TypeScript
80
star
17

gherkin-python

[READ-ONLY] Gherkin for Python - subtree of monorepo https://github.com/cucumber/cucumber -- moved to https://github.com/cucumber/gherkin
Python
75
star
18

vscode

Official Visual Studio Code Extension for Cucumber
TypeScript
55
star
19

gherkin-java

[READ-ONLY] Gherkin for Java - subtree of monorepo https://github.com/cucumber/cucumber -- moved to https://github.com/cucumber/gherkin
Java
50
star
20

screenplay.js

Library to ease implementation of the Screenplay pattern with CucumberJS
TypeScript
50
star
21

gherkin-dotnet

[READ-ONLY] Gherkin for Dotnet - subtree of monorepo https://github.com/cucumber/cucumber Gherkin parser/compiler for .NET
C#
48
star
22

cucumber-jvm-scala

Cucumber Scala
Scala
46
star
23

cucumber-ruby-core

Core library for the Ruby flavour of Cucumber
Ruby
37
star
24

react-components

React components for Cucumber
TypeScript
31
star
25

cucumber-lua

A cucumber wire protocol implementation for Lua step definitions
Lua
29
star
26

language-server

Cucumber Language Server
TypeScript
28
star
27

cucumber.ml

Cucumber for OCaml
OCaml
26
star
28

blockly

Gherkin Editor based on Blockly
TypeScript
23
star
29

cucumber-jvm-groovy

Cucumber Groovy
Java
21
star
30

cucumber-js-examples

Examples of using Cucumber-JS
Makefile
20
star
31

microdata

Extract WHATWG microdata from a DOM
TypeScript
18
star
32

json-formatter

Provides a language-agnostic command-line tool to convert cucumber messages into a JSON document.
Go
18
star
33

cucumber-js-pretty-formatter

Cucumber.js pretty formatter
TypeScript
14
star
34

monaco

Configure Monaco editor to use cucumber-language-service
TypeScript
13
star
35

messages

PHP
12
star
36

html-formatter

HTML formatter for reporting Cucumber results
Java
11
star
37

language-service

Cucumber Language Service
TypeScript
11
star
38

gherkin-c

[READ-ONLY] Gherkin for C - subtree of monorepo https://github.com/cucumber/cucumber -- moved to https://github.com/cucumber/gherkin
C
10
star
39

ci-environment

Detect CI Environment from environment variables
Java
8
star
40

gherkin-ruby

[READ-ONLY] Gherkin for Ruby - subtree of monorepo https://github.com/cucumber/cucumber -- moved to https://github.com/cucumber/gherkin
Ruby
7
star
41

cucumber-eclipse-update-site-snapshot

Cucumber Eclipse Update Site Snapshots
CSS
7
star
42

gherkin-objective-c

[READ-ONLY] Gherkin for Objective C - subtree of monorepo https://github.com/cucumber/cucumber -- moved to https://github.com/cucumber/gherkin
Objective-C
7
star
43

cucumber-ruby-wire

Wire protocol plugin for Cucumber
Gherkin
7
star
44

screenplay.js.examples

Examples using @cucumber/screenplay
TypeScript
6
star
45

gherkin-utils

API for working with Gherkin documents
TypeScript
6
star
46

cucumber-json-converter

Parse Cucumber JSON from most Cucumber implementations and versions
TypeScript
6
star
47

tag-expressions

Cucumber tag expression parser
Python
5
star
48

polyglot-release

Make polyglot releases with a single command
Shell
5
star
49

todo-react-typescript-subsecond

Tiny Todo app in React and TypeScript demonstrating sub-second test feedback
TypeScript
4
star
50

action-retire-inactive-contributors

Retire inactive contributors from one team to another
TypeScript
4
star
51

cucumber-json-schema

JSON Schemas for Cucumber JSON output
Ruby
4
star
52

messages-go

[READ ONLY] Cucumber Messages for Go - subtree of monorepo https://github.com/cucumber/messages -- moved to https://github.com/cucumber/messages
Go
3
star
53

try-cucumber-expressions

Try Cucumber Expressions in your browser
TypeScript
3
star
54

cucumber-eclipse-update-site

Cucumber Eclipse Update Site
3
star
55

gherkin-perl

[READ-ONLY] Gherkin for Perl - subtree of monorepo https://github.com/cucumber/cucumber -- moved to https://github.com/cucumber/gherkin
Perl
2
star
56

github-settings

Pulumi scripts to automatically configure our GitHub org/repo settings
TypeScript
2
star
57

gherkin-php

[READ ONLY] Cucumber Gherkin for PHP - subtree of https://github.com/cucumber/gherkin
PHP
2
star
58

cucumber-junit-xml-formatter

JUnit XML formatter for reporting Cucumber results
Java
2
star
59

oselvar-github-metrics

Oselvar GitHub Metrics for the Cucumber Organisation
Shell
2
star
60

gherkin-streams

Stream utilities to read Gherkin parser output.
TypeScript
2
star
61

build

Docker image used to build the Cucumber Project
Shell
2
star
62

fake-cucumber

Tool to generate test data for cucumber
TypeScript
2
star
63

messages-javascript

[READ ONLY] Cucumber Messages for JavaScript (Protocol Buffers) - subtree of monorepo https://github.com/cucumber/cucumber -- moved to https://github.com/cucumber/messages
TypeScript
2
star
64

commitbit

Microservice that hands out commit bit to everyone who gets a pull request merged
JavaScript
2
star
65

aruba-getting-started

Getting started with aruba
Ruby
2
star
66

action-changelog

GitHub Action for changelog tool
Shell
1
star
67

release-announcement-banner

For blog posts where we announce a new version of a Cucumber tool
JavaScript
1
star
68

split-java

A Cucumber plugin to toggle Split features from Cucumber scenarios
Java
1
star
69

cucumber-js-package-upgrade

package to point users to the new @cucumber/cucumber
JavaScript
1
star
70

messages-java

[READ ONLY] Cucumber Messages for Java (Protocol Buffers) - subtree of monorepo https://github.com/cucumber/cucumber
Java
1
star
71

action-publish-subrepo-test-monorepo-a-subfolder

target for tests for https://github.com/cucumber/action-publish-subrepo
1
star
72

cucumber-parent

Parent `pom.xml` for all Cucumber Java modules
1
star
73

action-publish-rubygem

GitHub Action to publish a Ruby Gem
Ruby
1
star
74

compatibility-kit

Platform-agnostic set of acceptance tests for validating cucumber implementations
TypeScript
1
star
75

action-publish-subrepo-test-monorepo

Test repo for testing the action-publish-subrepo GitHub Action
1
star
76

messages-ruby

[READ ONLY] Cucumber Messages for Ruby (Protocol Buffers) - subtree of monorepo https://github.com/cucumber/cucumber -- moved to https://github.com/cucumber/messages
Ruby
1
star
77

action-publish-mvn

GitHub Action to publish Maven artefacts
Java
1
star
78

message-streams

Stream utilities to read and write Cucumber Message objects to/from streams.
TypeScript
1
star
79

action-publish-npm

GitHub Action to publish an NPM module
1
star
80

query

A query API for https://github.com/cucumber/messages
TypeScript
1
star
81

messages-dotnet

[READ ONLY] Cucumber Messages for .NET (Protocol Buffers) - subtree of monorepo https://github.com/cucumber/cucumber -- moved to https://github.com/cucumber/messages
Makefile
1
star
82

.github

πŸ‘©β€βš•οΈ Default community health files for the Cucumber organisation on GitHub.
Shell
1
star