MCPcopy Index your code
hub / github.com/cucumber/godog

github.com/cucumber/godog @v0.15.1 sqlite

repository ↗ · DeepWiki ↗ · release v0.15.1 ↗
766 symbols 2,618 edges 91 files 270 documented · 35%
README

#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][behat] and [cucumber][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 being 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 Discord where you can chat with other users, developers, and BDD practitioners.

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.

Attachments

An example showing how to make attachments (aka embeddings) to the results is shown in _examples/attachments

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][godoc] 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=ato

Extension points exported contracts — how you extend this code

Formatter (Interface)
Formatter is an interface for feature runner output summary presentation. New formatters may be created to represent su [4 …
formatters/fmt.go
TestingT (Interface)
TestingT is a subset of the public methods implemented by go's testing.T. It allows assertion libraries to be used with [1 …
testingt.go
BeforeScenarioHook (FuncType)
BeforeScenarioHook defines a hook before scenario.
test_context.go
ColorFunc (FuncType)
ColorFunc is a helper type to create colorized strings.
colors/colors.go
FlushFormatter (Interface)
FlushFormatter is a `Formatter` but can be flushed. [1 implementers]
formatters/fmt.go
AfterScenarioHook (FuncType)
AfterScenarioHook defines a hook after scenario.
test_context.go
FormatterFunc (FuncType)
FormatterFunc builds a formatter with given suite name and io.Writer to record output
formatters/fmt.go
BeforeStepHook (FuncType)
BeforeStepHook defines a hook before step.
test_context.go

Core symbols most depended-on inside this repo

Step
called by 150
test_context.go
Errorf
called by 125
testingt.go
Run
called by 68
internal/models/stepdef.go
Fatalf
called by 58
testingt.go
String
called by 37
internal/models/results.go
Error
called by 30
testingt.go
Run
called by 30
run.go
Name
called by 26
testingt.go

Shape

Function 337
Method 309
Struct 87
TypeAlias 19
FuncType 9
Interface 5

Languages

Go100%

Modules by API surface

suite_context_test.go52 symbols
testingt.go36 symbols
internal/formatters/fmt_pretty.go32 symbols
run_test.go31 symbols
test_context.go26 symbols
internal/storage/storage.go25 symbols
internal/models/stepdef_test.go22 symbols
suite.go21 symbols
formatters/fmt.go21 symbols
colors/ansi_windows.go21 symbols
internal/formatters/fmt_cucumber.go20 symbols
internal/formatters/fmt_multi.go19 symbols

Dependencies from manifests, versioned

github.com/DATA-DOG/go-txdbv0.1.6 · 1×
github.com/cucumber/gherkin/go/v26v26.2.0 · 1×
github.com/cucumber/messages/go/v21v21.0.1 · 1×
github.com/hashicorp/go-immutable-radixv1.3.1 · 1×
github.com/hashicorp/go-uuidv1.0.2 · 1×
github.com/kr/prettyv0.3.0 · 1×
github.com/lib/pqv1.10.3 · 1×

For agents

$ claude mcp add godog \
  -- python -m otcore.mcp_server <graph>

⬇ download graph artifact