godog

repository·main·Indexed 25 days ago

https://github.com/cucumber/godog

A BDD (Behavior-Driven Development) framework for Go that provides an implementation of the Cucumber specification. It enables developers to write requirements in Gherkin and verify them through automated Go tests, integrating with the standard go test command. The framework includes a CLI for running and building test suites, support for custom formatters, and capabilities for adding data attachments to JSON reports.

Tokens
4.5K
Snippets
12
Records
43
Agent score
82%

What's inside godog

  1. Understand Cucumber Godog versioning

    main

    Cucumber Godog follows Semantic Versioning (MAJOR.MINOR.PATCH). The meaning of version increments depends on whether the project is currently in the v0.x.x phase or has reached v1.x.x or higher.

    For v0.MINOR.PATCH versions:

    • MINOR: Incompatible API changes.
    • PATCH: Backward-compatible new features and bug fixes.

    After v1.X.X release:

    • MAJOR: Incompatible API changes.
    • MINOR: Backward-compatible new features.
    • PATCH: Backward-compatible bug fixes.
  2. Run the API with DB example

    main

    To run the users.feature test suite in this example, you must have MySQL installed on your system configured with an anonymous root password. The example uses the go-txdb library to wrap every scenario in a database transaction that is rolled back upon completion, ensuring a clean state for subsequent scenarios.

    make test
  3. Test a REST API with godog

    main

    This guide demonstrates how to use godog to describe and test a REST API using Gherkin feature files and Go step definitions. The workflow involves:

    1. Defining Features: Write .feature files in Gherkin syntax to describe API behavior (e.g., successful requests and error handling).
    2. Generating Snippets: Run godog run to identify undefined steps and generate Go function signatures.
    3. Implementing Steps: Create a Go struct to maintain state (like HTTP responses) across steps and implement the logic for each step.
    4. Using Hooks: Use ctx.Before to reset state (e.g., clearing response recorders) before each scenario.
    5. Running Tests: Execute tests using go test -v or godog run to validate the implementation against the feature specifications.
    godog run
    # or
    go test -v
  4. Overview of Godog BDD framework

    main

    Godog is the official Cucumber BDD (Behavior-Driven Development) framework for Golang. It allows you to merge specification and test documentation into a single cohesive whole by using Gherkin feature files to drive tests.

    Key characteristics:

    • Integration with go test: Godog does not interfere with the standard go test command. You can leverage both frameworks by maintaining test-related source code in *_test.go files.
    • Execution Model: Similar to go test, Godog uses the Go compiler and linker to produce a test executable. To work correctly, Godog contexts must be exported in the same manner as standard Go Test functions.
  5. Define API behavior in Gherkin

    main

    Create a .feature file (e.g., features/version.feature) to describe your API requirements. You can use DocString (triple quotes) to define expected JSON bodies for comparison.

    Feature: get version
      In order to know godog version
      As an API user
      I need to be able to request version
    
      Scenario: should get version number
        When I send "GET" request to "/version"
        Then the response code should be 200
        And the response should match json:
          """
          {
            "version": "v0.0.0-dev"
          }
          """
  6. Register step definitions with ScenarioContext

    main

    In your ScenarioInitializer function, use the *godog.ScenarioContext to map Gherkin step regex patterns to your Go implementation methods.

    func InitializeScenario(ctx *godog.ScenarioContext) {
    	api := &apiFeature{}
    
    	ctx.Before(func(ctx context.Context, sc *godog.Scenario) (context.Context, error) {
    		api.resetResponse(sc)
    		return ctx, nil
    	})
    
    	ctx.Step(`^I send "(GET|POST|PUT|DELETE)" request to "([^ "]*)"$`, api.iSendrequestTo)
    	ctx.Step(`^the response code should be (\d+)$`, api.theResponseCodeShouldBe)
    	ctx.Step(`^the response should match json:$`, api.theResponseShouldMatchJSON)
    }
  7. Configure a godog TestSuite in Go

    main

    To integrate godog with Go's testing framework, initialize a godog.TestSuite within a standard TestXxx(t *testing.T) function. Use godog.Options to specify the test format and the paths to your feature files.

    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")
      }
    }
  8. Use Nested Steps with the Steps type

    main

    Instead of returning an error from a step function, you can return godog.Steps to execute multiple steps sequentially. The first step that fails will cause the main step to fail.

    godog.Steps is a slice of strings where each string is a step description.

    func multistep(name string) godog.Steps {
    	return godog.Steps{
    		fmt.Sprintf(`an user named "%s"`, name),
    		fmt.Sprintf(`user "%s" is authenticated`, name),
    	}
    }