Documentation ¶
Overview ¶
Package godog is the official Cucumber BDD framework for Golang, it merges specification and test documentation into one cohesive whole.
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 uses go compiler and linker tool in order to produce test executable. Godog contexts needs to be exported same as Test functions for go test.
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 """
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 Cucumber the above description is taken from it's documentation.
Index ¶
- Constants
- Variables
- func Attach(ctx context.Context, attachments ...Attachment) context.Context
- func AvailableFormatters() map[string]string
- func BindCommandLineFlags(prefix string, opts *Options)
- func BindFlags(prefix string, set *flag.FlagSet, opt *Options)
- func Build(bin string) error
- func FlagSet(opt *Options) *flag.FlagSetdeprecated
- func Format(name, description string, f FormatterFunc)
- func Log(ctx context.Context, args ...interface{})
- func Logf(ctx context.Context, format string, args ...interface{})
- func LoggedMessages(ctx context.Context) []string
- type AfterScenarioHook
- type AfterStepHook
- type Attachment
- type BaseFmt
- type BeforeScenarioHook
- type BeforeStepHook
- type CukeFmt
- type DocString
- type EventsFmt
- type Feature
- type Formatter
- type FormatterFunc
- type GherkinDocument
- type JUnitFmt
- type Options
- type PrettyFmt
- type ProgressFmt
- type Scenario
- type ScenarioContext
- func (ctx ScenarioContext) After(h AfterScenarioHook)
- func (ctx ScenarioContext) AfterScenario(fn func(sc *Scenario, err error))deprecated
- func (ctx ScenarioContext) AfterStep(fn func(st *Step, err error))deprecated
- func (ctx ScenarioContext) Before(h BeforeScenarioHook)
- func (ctx ScenarioContext) BeforeScenario(fn func(sc *Scenario))deprecated
- func (ctx ScenarioContext) BeforeStep(fn func(st *Step))deprecated
- func (ctx ScenarioContext) Given(expr, stepFunc interface{})
- func (ctx ScenarioContext) Step(expr, stepFunc interface{})
- func (ctx ScenarioContext) StepContext() StepContext
- func (ctx ScenarioContext) Then(expr, stepFunc interface{})
- func (ctx ScenarioContext) When(expr, stepFunc interface{})
- type Step
- type StepContext
- type StepDefinition
- type StepResultStatus
- type Steps
- type Table
- type TestSuite
- type TestSuiteContext
- type TestingT
Examples ¶
Constants ¶
const ( // StepPassed indicates step that passed. StepPassed StepResultStatus = models.Passed // StepFailed indicates step that failed. StepFailed = models.Failed // StepSkipped indicates step that was skipped. StepSkipped = models.Skipped // StepUndefined indicates undefined step. StepUndefined = models.Undefined // StepPending indicates step with pending implementation. StepPending = models.Pending // StepAmbiguous indicates step text matches more than one step def StepAmbiguous = models.Ambiguous )
Variables ¶
var ErrAmbiguous = fmt.Errorf("ambiguous step definition")
more than one regex matched the step text
var ErrPending = fmt.Errorf("step implementation is pending")
ErrPending should be returned by step definition if step implementation is pending
var ErrSkip = fmt.Errorf("skipped")
ErrSkip should be returned by step definition or a hook if scenario and further steps are to be skipped.
var ErrUndefined = fmt.Errorf("step is undefined")
ErrUndefined is returned in case if step definition was not found
var Version = "v0.0.0-dev"
Version of package - based on Semantic Versioning 2.0.0 http://semver.org/
Functions ¶
func Attach ¶ added in v0.15.0
func Attach(ctx context.Context, attachments ...Attachment) context.Context
func AvailableFormatters ¶
AvailableFormatters gives a map of all formatters registered with their name as key and description as value
func BindCommandLineFlags ¶ added in v0.11.0
BindCommandLineFlags binds godog flags to given flag set prefixed by given prefix, without overriding usage
func BindFlags ¶ added in v0.7.9
BindFlags binds godog flags to given flag set prefixed by given prefix, without overriding usage
func Build ¶
Build creates a test package like go test command at given target path. If there are no go files in tested directory, then it simply builds a godog executable to scan features.
If there are go test files, it first builds a test package with standard go test command.
Finally, it generates godog suite executable which registers exported godog contexts from the test files of tested package.
Returns the path to generated executable
func Format ¶
func Format(name, description string, f FormatterFunc)
Format registers a feature suite output formatter by given name, description and FormatterFunc constructor function, to initialize formatter with the output recorder.
func Log ¶ added in v0.14.1
Log will log test output. If called in the context of a test and testing.T has been registered, this will log using the step's testing.T, else it will simply log to stdout.
func Logf ¶ added in v0.14.1
Logf will log test output. If called in the context of a test and testing.T has been registered, this will log using the step's testing.T, else it will simply log to stdout.
func LoggedMessages ¶ added in v0.14.1
LoggedMessages returns an array of any logged messages that have been recorded during the test through calls to godog.Log / godog.Logf or via operations against godog.T(ctx)
Types ¶
type AfterScenarioHook ¶ added in v0.12.0
AfterScenarioHook defines a hook after scenario.
type AfterStepHook ¶ added in v0.12.0
type AfterStepHook func(ctx context.Context, st *Step, status StepResultStatus, err error) (context.Context, error)
AfterStepHook defines a hook after step.
type Attachment ¶ added in v0.15.0
func Attachments ¶ added in v0.15.0
func Attachments(ctx context.Context) []Attachment
type BeforeScenarioHook ¶ added in v0.12.0
BeforeScenarioHook defines a hook before scenario.
type BeforeStepHook ¶ added in v0.12.0
BeforeStepHook defines a hook before step.
type CukeFmt ¶ added in v0.12.0
type CukeFmt = internal_fmt.Cuke
CukeFmt exports Cucumber JSON formatter.
type DocString ¶ added in v0.10.0
type DocString = messages.PickleDocString
DocString represents the DocString argument made to a step definition
type EventsFmt ¶ added in v0.12.0
type EventsFmt = internal_fmt.Events
EventsFmt exports Events formatter.
type Formatter ¶
type Formatter = formatters.Formatter
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 FormatterFunc ¶
type FormatterFunc = formatters.FormatterFunc
FormatterFunc builds a formatter with given suite name and io.Writer to record output
func FindFmt ¶ added in v0.7.9
func FindFmt(name string) FormatterFunc
FindFmt searches available formatters registered and returns FormaterFunc matched by given format name or nil otherwise
type GherkinDocument ¶ added in v0.12.0
type GherkinDocument = messages.GherkinDocument
GherkinDocument represents gherkin document.
type JUnitFmt ¶ added in v0.12.0
type JUnitFmt = internal_fmt.JUnit
JUnitFmt exports JUnit formatter.
type Options ¶
Options are suite run options flags are mapped to these options.
It can also be used together with godog.RunWithOptions to run test suite from go source directly
See the flags for more details
type PrettyFmt ¶ added in v0.12.0
type PrettyFmt = internal_fmt.Pretty
PrettyFmt exports Pretty formatter.
type ProgressFmt ¶ added in v0.12.0
type ProgressFmt = internal_fmt.Progress
ProgressFmt exports Progress formatter.
func NewProgressFmt ¶ added in v0.12.0
func NewProgressFmt(suite string, out io.Writer) *ProgressFmt
NewProgressFmt creates a new progress formatter.
type ScenarioContext ¶ added in v0.10.0
type ScenarioContext struct {
// contains filtered or unexported fields
}
ScenarioContext allows various contexts to register steps and event handlers.
When running a scenario, the instance of ScenarioContext 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 (ScenarioContext) After ¶ added in v0.12.0
func (ctx ScenarioContext) After(h AfterScenarioHook)
After registers a function or method to be run after every scenario.
func (ScenarioContext) AfterScenario
deprecated
added in
v0.10.0
func (ctx ScenarioContext) AfterScenario(fn func(sc *Scenario, err error))
AfterScenario registers a function or method to be run after every scenario.
Deprecated: use After.
func (ScenarioContext) AfterStep
deprecated
added in
v0.10.0
func (ctx ScenarioContext) AfterStep(fn func(st *Step, err error))
AfterStep registers a function or method to be run after every step.
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.
Deprecated: use ScenarioContext.StepContext() and StepContext.After.
func (ScenarioContext) Before ¶ added in v0.12.0
func (ctx ScenarioContext) Before(h BeforeScenarioHook)
Before registers a function or method to be run before every scenario.
It is a good practice to restore the default state before every scenario, so it would be isolated from any kind of state.
func (ScenarioContext) BeforeScenario
deprecated
added in
v0.10.0
func (ctx ScenarioContext) BeforeScenario(fn func(sc *Scenario))
BeforeScenario registers a function or method to be run before every scenario.
It is a good practice to restore the default state before every scenario, so it would be isolated from any kind of state.
Deprecated: use Before.
func (ScenarioContext) BeforeStep
deprecated
added in
v0.10.0
func (ctx ScenarioContext) BeforeStep(fn func(st *Step))
BeforeStep registers a function or method to be run before every step.
Deprecated: use ScenarioContext.StepContext() and StepContext.Before.
func (ScenarioContext) Given ¶ added in v0.13.0
func (ctx ScenarioContext) Given(expr, stepFunc interface{})
Given functions identically to Step, but the *StepDefinition will only be matched if the step starts with "Given". "And" and "But" keywords copy the keyword of the last step for the purpose of matching.
func (ScenarioContext) Step ¶ added in v0.10.0
func (ctx ScenarioContext) Step(expr, stepFunc interface{})
Step allows to register a *StepDefinition in the 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.
The expression can be of type: *regexp.Regexp, string or []byte
The stepFunc may accept one or several arguments of type: - int, int8, int16, int32, int64 - float32, float64 - string - []byte - *godog.DocString - *godog.Table
The stepFunc need to return either an error or []string for multistep
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 *StepDefinition is matched, then ErrUndefined error will be returned when running steps.
func (ScenarioContext) StepContext ¶ added in v0.12.0
func (ctx ScenarioContext) StepContext() StepContext
StepContext exposes StepContext of a scenario.
func (ScenarioContext) Then ¶ added in v0.13.0
func (ctx ScenarioContext) Then(expr, stepFunc interface{})
Then functions identically to Step, but the *StepDefinition will only be matched if the step starts with "Then". "And" and "But" keywords copy the keyword of the last step for the purpose of matching.
func (ScenarioContext) When ¶ added in v0.13.0
func (ctx ScenarioContext) When(expr, stepFunc interface{})
When functions identically to Step, but the *StepDefinition will only be matched if the step starts with "When". "And" and "But" keywords copy the keyword of the last step for the purpose of matching.
type StepContext ¶ added in v0.12.0
type StepContext struct {
// contains filtered or unexported fields
}
StepContext allows registering step hooks.
func (StepContext) After ¶ added in v0.12.0
func (ctx StepContext) After(h AfterStepHook)
After registers a function or method to be run after every step.
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 (StepContext) Before ¶ added in v0.12.0
func (ctx StepContext) Before(h BeforeStepHook)
Before registers a function or method to be run before every step.
type StepDefinition ¶ added in v0.9.0
type StepDefinition = formatters.StepDefinition
StepDefinition 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 StepResultStatus ¶ added in v0.12.0
type StepResultStatus = models.StepResultStatus
StepResultStatus describes step result.
type Steps ¶ added in v0.7.1
type Steps []string
Steps allows to nest steps instead of returning an error in step func it is possible to return combined steps:
func multistep(name string) godog.Steps { return godog.Steps{ fmt.Sprintf(`an user named "%s"`, name), fmt.Sprintf(`user "%s" is authenticated`, name), } }
These steps will be matched and executed in sequential order. The first one which fails will result in main step failure.
type Table ¶ added in v0.10.0
type Table = messages.PickleTable
Table represents the Table argument made to a step definition
type TestSuite ¶ added in v0.10.0
type TestSuite struct { Name string TestSuiteInitializer func(*TestSuiteContext) ScenarioInitializer func(*ScenarioContext) Options *Options }
TestSuite allows for configuration of the Test Suite Execution
func (TestSuite) RetrieveFeatures ¶ added in v0.12.0
RetrieveFeatures will parse and return the features based on test suite option Any modification on the parsed features will not have any impact on the next Run of the Test Suite
func (TestSuite) Run ¶ added in v0.10.0
Run will execute the test suite.
If options are not set, it will reads all configuration options from flags.
The exit codes may vary from:
0 - success 1 - failed 2 - command line usage error 128 - or higher, os signal related error exit codes
If there are flag related errors they will be directed to os.Stderr
Example (Subtests) ¶
package main import ( "testing" "github.com/cucumber/godog" ) func main() { var t *testing.T // Comes from your test function, e.g. 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") } }
Output:
type TestSuiteContext ¶ added in v0.10.0
type TestSuiteContext struct {
// contains filtered or unexported fields
}
TestSuiteContext allows various contexts to register event handlers.
When running a test suite, the instance of TestSuiteContext 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
func (*TestSuiteContext) AfterSuite ¶ added in v0.10.0
func (ctx *TestSuiteContext) AfterSuite(fn func())
AfterSuite registers a function or method to be run once after suite runner
func (*TestSuiteContext) BeforeSuite ¶ added in v0.10.0
func (ctx *TestSuiteContext) BeforeSuite(fn 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 (*TestSuiteContext) ScenarioContext ¶ added in v0.12.4
func (ctx *TestSuiteContext) ScenarioContext() *ScenarioContext
ScenarioContext allows registering scenario hooks.
type TestingT ¶ added in v0.14.1
type TestingT interface { // Name returns the name of the current pickle under test Name() string // Log will log to the current testing.T log if set, otherwise it will log to stdout Log(args ...interface{}) // Logf will log a formatted string to the current testing.T log if set, otherwise it will log // to stdout Logf(format string, args ...interface{}) // Error fails the current test and logs the provided arguments. Equivalent to calling Log then // Fail. Error(args ...interface{}) // Errorf fails the current test and logs the formatted message. Equivalent to calling Logf then // Fail. Errorf(format string, args ...interface{}) // Fail marks the current test as failed, but does not halt execution of the step. Fail() // FailNow marks the current test as failed and halts execution of the step. FailNow() // Fatal logs the provided arguments, marks the test as failed and halts execution of the step. Fatal(args ...interface{}) // Fatal logs the formatted message, marks the test as failed and halts execution of the step. Fatalf(format string, args ...interface{}) // Skip logs the provided arguments and marks the test as skipped but does not halt execution // of the step. Skip(args ...interface{}) // Skipf logs the formatted message and marks the test as skipped but does not halt execution // of the step. Skipf(format string, args ...interface{}) // SkipNow marks the current test as skipped and halts execution of the step. SkipNow() // Skipped returns true if the test has been marked as skipped. Skipped() bool }
TestingT is a subset of the public methods implemented by go's testing.T. It allows assertion libraries to be used with godog, provided they depend only on this subset of methods.