godog

package module
v0.4.3 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Jun 1, 2016 License: BSD-3-Clause Imports: 24 Imported by: 0

README

Build Status GoDoc

Godog

Godog logo

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

Godog is an open source behavior-driven development framework for go programming language. What is behavior-driven development, you ask? It’s the idea that you start by writing human-readable sentences that describe a feature of your application and how it should work, and only then implement this behavior in software.

The project is inspired by behat and cucumber and is based on cucumber gherkin3 parser.

Godog does not intervene with the standard go test command and its 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. It uses a TestMain hook introduced in go1.4 and clones the package sources to a temporary build directory. The only change it does is adding a runner test.go file additionally and ensures to cleanup TestMain func if it was used in tests. Godog uses standard go ast and build utils to generate test suite package and even builds it with go test -c command. It even passes all your environment exported vars.

Godog ships gherkin parser dependency as a subpackage. This will ensure that it is always compatible with the installed version of godog. So in general there are no vendor dependencies needed for installation.

Install
go get github.com/DATA-DOG/godog/cmd/godog
Example

The following example can be found here.

Step 1

Imagine we have a godog cart to serve godogs for dinner. At first, we describe our feature in plain text:

# file: examples/godogs/godog.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

As a developer, your work is done as soon as you’ve made the program behave as described in the Scenario.

Step 2

If you run godog godog.feature inside the examples/godogs directory. You should see that the steps are undefined:

Screenshot

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

Now if you run the tests again you should see that the definition is now pending. 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. Let's define steps.

/* file: examples/godogs/godog.go */
package main

// Godogs to eat
var Godogs int

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

Now let's finish our step implementations in order to test our feature requirements:

/* file: examples/godogs/godog_test.go */
package main

import (
	"fmt"

	"github.com/DATA-DOG/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
}

func featureContext(s *godog.Suite) {
	s.Step(`^there are (\d+) godogs$`, thereAreGodogs)
	s.Step(`^I eat (\d+)$`, iEat)
	s.Step(`^there should be (\d+) remaining$`, thereShouldBeRemaining)

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

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

Screenshot

Note: we have hooked to BeforeScenario event in order to reset state. You may hook into more events, like AfterStep to test against an error and print more details about the error or state before failure. Or BeforeSuite to prepare a database.

Documentation

See godoc for general API details. See .travis.yml for supported go versions. See godog -h for general command options.

See implementation examples:

Changes

2016-06-01

  • parse flags in main command, to show version and help without needing to compile test package and buildable go sources.

2016-05-28

  • show nicely formatted called step func name and file path

2016-05-26

  • pack gherkin dependency in a subpackage to prevent compatibility conflicts in the future. If recently upgraded, probably you will need to reference gherkin as github.com/DATA-DOG/godog/gherkin instead.

2016-05-25

  • refactored test suite build tooling in order to use standard go test tool. Which allows to compile package with godog runner script in go idiomatic way. It also supports all build environment options as usual.
  • godog.Run now returns an int exit status. It was not returning anything before, so there is no compatibility breaks.

2016-03-04

  • added junit compatible output formatter, which prints xml results to os.Stdout
  • fixed #14 which skipped printing background steps when there was scenario outline in feature.

2015-07-03

  • changed godog.Suite from interface to struct. Context registration should be updated accordingly. The reason for change: since it exports the same methods and there is no need to mock a function in tests, there is no obvious reason to keep an interface.
  • in order to support running suite concurrently, needed to refactor an entry point of application. The Run method now is a func of godog package which initializes and run the suite (or more suites). Method New is removed. This change made godog a little cleaner.
  • renamed RegisterFormatter func to Format to be more consistent.
FAQ

Q: Where can I configure common options globally? A: You can't. Alias your common or project based commands: alias godog-wip="godog --format=progress --tags=@wip"

Contributions

Feel free to open a pull request. Note, if you wish to contribute an extension to public (exported methods or types) - please open an issue before to discuss whether these changes can be accepted. All backward incompatible changes are and will be treated cautiously.

License

All package dependencies are MIT or BSD licensed.

Godog is licensed under the three clause BSD license

Documentation

Overview

Package godog is a behavior-driven development framework, a tool to describe your application based on the behavior and run these specifications. The features are described by a human-readable gherkin language.

Godog does not intervene with the standard "go test" command and it's 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. It builds all package sources to a single main package file and replaces main func with it's own and runs the build to test described application behavior in feature files. Production builds remains clean without any overhead.

For example, imagine you’re about to create the famous UNIX ls command. Before you begin, you describe how the feature should work, see the example below..

Example:

Feature: ls
  In order to see the directory structure
  As a UNIX user
  I need to be able to list the current directory's contents

  Scenario:
	Given I am in a directory "test"
	And I have a file named "foo"
	And I have a file named "bar"
	When I run ls
	Then I should get output:
	  """
	  bar
	  foo
	  """

As a developer, your work is done as soon as you’ve made the ls command behave as described in the Scenario.

Now, wouldn’t it be cool if something could read this sentence and use it to actually run a test against the ls command? Hey, that’s exactly what this package does! As you’ll see, Godog is easy to learn, quick to use, and will put the fun back into tests.

Godog was inspired by Behat and the above description is taken from it's documentation.

Index

Constants

View Source
const Version = "v0.4.3"

Version of package - based on Semantic Versioning 2.0.0 http://semver.org/

Variables

View Source
var ErrPending = fmt.Errorf("step implementation is pending")

ErrPending should be returned by step definition if step implementation is pending

View Source
var ErrUndefined = fmt.Errorf("step is undefined")

ErrUndefined is returned in case if step definition was not found

Functions

func Build

func Build(dir string) error

Build scans clones current package into a temporary godog suite test package.

If there is a TestMain func in any of test.go files it removes it and all necessary unused imports related to this function.

It also looks for any godog suite contexts and registers them in order to call them on execution.

The test entry point which uses go1.4 TestMain func is generated from the template above.

func FlagSet added in v0.4.3

func FlagSet(format, tags *string, defs, sof, vers *bool, cl *int) *flag.FlagSet

FlagSet allows to manage flags by external suite runner

func Format added in v0.2.1

func Format(name, description string, f Formatter)

Format registers a feature suite output Formatter as the name and descriptiongiven. Formatter is used to represent suite output

func Run added in v0.2.1

func Run(contextInitializer func(suite *Suite)) int

Run creates and runs the feature suite. uses contextInitializer to register contexts

the concurrency option allows runner to initialize a number of suites to be run separately. Only progress formatter is supported when concurrency level is higher than 1

contextInitializer must be able to register the step definitions and event handlers.

Types

type Formatter

type Formatter interface {
	Feature(*gherkin.Feature, string)
	Node(interface{})
	Failed(*gherkin.Step, *StepDef, error)
	Passed(*gherkin.Step, *StepDef)
	Skipped(*gherkin.Step)
	Undefined(*gherkin.Step)
	Pending(*gherkin.Step, *StepDef)
	Summary()
}

Formatter is an interface for feature runner output summary presentation.

New formatters may be created to represent suite results in different ways. These new formatters needs to be registered with a godog.Format function call

type StepDef

type StepDef struct {
	Expr    *regexp.Regexp
	Handler interface{}
	// contains filtered or unexported fields
}

StepDef is a registered step definition contains a StepHandler and regexp which is used to match a step. Args which were matched by last executed step

This structure is passed to the formatter when step is matched and is either failed or successful

type Suite

type Suite struct {
	// contains filtered or unexported fields
}

Suite allows various contexts to register steps and event handlers.

When running a test suite, the instance of Suite is passed to all functions (contexts), which have it as a first and only argument.

Note that all event hooks does not catch panic errors in order to have a trace information. Only step executions are catching panic error since it may be a context specific error.

func (*Suite) AfterScenario

func (s *Suite) AfterScenario(f func(interface{}, error))

AfterScenario registers an function or method to be run after every scenario or scenario outline

The interface argument may be *gherkin.Scenario or *gherkin.ScenarioOutline

func (*Suite) AfterStep

func (s *Suite) AfterStep(f func(*gherkin.Step, error))

AfterStep registers an function or method to be run after every scenario

It may be convenient to return a different kind of error in order to print more state details which may help in case of step failure

In some cases, for example when running a headless browser, to take a screenshot after failure.

func (*Suite) AfterSuite

func (s *Suite) AfterSuite(f func())

AfterSuite registers a function or method to be run once after suite runner

func (*Suite) BeforeScenario

func (s *Suite) BeforeScenario(f func(interface{}))

BeforeScenario registers a function or method to be run before every scenario or scenario outline.

The interface argument may be *gherkin.Scenario or *gherkin.ScenarioOutline

It is a good practice to restore the default state before every scenario so it would be isolated from any kind of state.

func (*Suite) BeforeStep

func (s *Suite) BeforeStep(f func(*gherkin.Step))

BeforeStep registers a function or method to be run before every scenario

func (*Suite) BeforeSuite

func (s *Suite) BeforeSuite(f func())

BeforeSuite registers a function or method to be run once before suite runner.

Use it to prepare the test suite for a spin. Connect and prepare database for instance...

func (*Suite) Step

func (s *Suite) Step(expr interface{}, stepFunc interface{})

Step allows to register a *StepDef in Godog feature suite, the definition will be applied to all steps matching the given Regexp expr.

It will panic if expr is not a valid regular expression or stepFunc is not a valid step handler.

Note that if there are two definitions which may match the same step, then only the first matched handler will be applied.

If none of the *StepDef is matched, then ErrUndefined error will be returned when running steps.

Directories

Path Synopsis
cmd
api
Example - demonstrates REST API server implementation tests.
Example - demonstrates REST API server implementation tests.
db

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL