Behave API Reference¶
This reference is meant for people actually writing step implementations for feature tests. It contains way more information than a typical step implementation will need: most implementations will only need to look at the basic implementation of step functions and maybe environment file functions.
The model stuff is for people getting really serious about their step implementations.
Note
Anywhere this document says “string” it means “unicode string” in Python 2.x
behave works exclusively with unicode strings internally.
Step Functions¶
Step functions are implemented in the Python modules present in your “steps” directory. All Python files (files ending in “.py”) in that directory will be imported to find step implementations. They are all loaded before behave starts executing your feature tests.
Step functions are identified using step decorators. All step implementations should normally start with the import line:
from behave import *
This line imports several decorators defined by behave to allow you to identify your step functions. These are available in both PEP-8 (all lowercase) and traditional (title case) versions: “given”, “when”, “then” and the generic “step”. See the full list of variables imported in the above statement.
The decorators all take a single string argument: the string to match against the feature file step text exactly. So the following step implementation code:
@given(u'some known state')
def step_impl(context):
setup_something(some, state)
will match the “Given” step from the following feature:
Scenario: test something
Given some known state
Then some observed outcome.
You don’t need to import the decorators: they’re automatically available to your step implementation modules as global variables.
Steps beginning with “and” or “but” in the feature file are renamed to take the name of their preceding keyword, so given the following feature file:
Given some known state
And some other known state
When some action is taken
Then some outcome is observed
But some other outcome is not observed.
the first “and” step will be renamed internally to “given” and behave will look for a step implementation decorated with either “given” or “step”:
@given(u'some other known state')
def step_impl(context):
setup_something(some, other, state)
and similarly the “but” would be renamed internally to “then”. Multiple “and” or “but” steps in a row would inherit the non-“and” or “but” keyword.
The function decorated by the step decorator will be passed at least one
argument. The first argument is always the Context
variable. Additional arguments come from step parameters, if any.
Step Parameters¶
You may additionally use parameters in your step names. These will be
handled by either the default simple parser (parse),
its extension “cfparse” or by regular expressions
if you invoke use_step_matcher()
.
- behave.use_step_matcher(name)¶
Changes the step-matcher class to use while parsing step definitions. This allows to use multiple step-matcher classes:
in the same steps module
in different step modules
There are several step-matcher classes available in behave:
parse (the default, based on: parse):
cfparse (extends: parse, requires: parse_type)
re (using regular expressions)
- Parameters
name – Name of the step-matcher class.
- Returns
Current step-matcher class that is now in use.
You may add new types to the default parser by invoking
register_type()
.
- behave.register_type(**kwargs)¶
Registers one (or more) custom type that will be available by some matcher classes, like the
ParseMatcher
and its derived classes, for type conversion during step matching.Converters should be supplied as
name=callable
arguments (or as dict). A type converter should follow the rules of itsMatcher
class.
You may define a new parameter matcher by subclassing
behave.matchers.Matcher
and registering it with
behave.matchers.matcher_mapping
which is a dictionary of “matcher
name” to Matcher
class.
- class behave.matchers.Matcher(func, pattern, step_type=None)¶
Pull parameters out of step names.
- pattern¶
The match pattern attached to the step function.
- func¶
The step function the pattern is being attached to.
- check_match(step)¶
Match me against the “step” name supplied.
Return None, if I don’t match otherwise return a list of matches as
Argument
instances.The return value from this function will be converted into a
Match
instance by behave.
- describe(schema=None)¶
Provide a textual description of the step function/matcher object.
- Parameters
schema – Text schema to use.
- Returns
Textual description of this step definition (matcher).
- property regex_pattern¶
Return the used textual regex pattern.
- classmethod register_type(**kwargs)¶
Register one (or more) user-defined types used for matching types in step patterns of this matcher.
- class behave.model_core.Argument(start, end, original, value, name=None)¶
An argument found in a feature file step name.
The attributes are:
- original¶
The actual text matched in the step name.
- value¶
The potentially type-converted value of the argument.
- name¶
The name of the argument. This will be None if the parameter is anonymous.
- start¶
The start index in the step name of the argument. Used for display.
- end¶
The end index in the step name of the argument. Used for display.
Step Macro: Calling Steps From Other Steps¶
If you find you’d like your step implementation to invoke another step you
may do so with the Context
method
execute_steps()
.
This function allows you to, for example:
@when(u'I do the same thing as before with the {color:w} button')
def step_impl(context, color):
context.execute_steps(u'''
When I press the big {color} button
And I duck
'''.format(color=color))
This will cause the “when I do the same thing as before with the red button” step to execute the other two steps as though they had also appeared in the scenario file.
from behave import *¶
The import statement:
from behave import *
is written to introduce a restricted set of variables into your code:
Name |
Kind |
Description |
---|---|---|
given, when, then, step |
Decorator |
Decorators for step implementations. |
use_step_matcher(name) |
Function |
Selects current step matcher (parser). |
register_type(Type=func) |
Function |
Registers a type converter. |
See also the description in step parameters.
Environment File Functions¶
The environment.py module may define code to run before and after certain events during your testing:
- before_all(context), after_all(context)
These run before and after the whole shooting match.
- before_feature(context, feature), after_feature(context, feature)
These run before and after each feature is executed. The feature object, that is passed in, is an instance of
Feature
.- before_rule(context, rule), after_rule(context, rule)
These run before and after each rule is execured. The rule object, that is passed in, is an instance of
Rule
.- before_scenario(context, scenario), after_scenario(context, scenario)
These run before and after each scenario is run. The scenario object, that is passed in, is an instance of
Scenario
.- before_step(context, step), after_step(context, step)
These run before and after every step. The step object, that is passed in, is an instance of
Step
.- before_tag(context, tag), after_tag(context, tag)
These run before and after a section tagged with the given name. They are invoked for each tag encountered in the order they’re found in the feature file. See Controlling Things With Tags.
Taggable statements are: Feature, Rule, Scenario, ScenarioOutline, Examples.
The tag, that is passed in, is an instance of
Tag
and because it’s a subclass of string you can do simple tests like:# -- ASSUMING: tags @browser.chrome or @browser.any are used. # BETTER: Use Fixture for this example. def before_tag(context, tag): if tag.startswith("browser."): browser_type = tag.replace("browser.", "", 1) if browser_type == "chrome": context.browser = webdriver.Chrome() else: context.browser = webdriver.PlainVanilla()
Some Useful Environment Ideas¶
Here’s some ideas for things you could use the environment for.
Logging Setup¶
The following recipe works in all cases (log-capture on or off). If you want to use/configure logging, you should use the following snippet:
# -- FILE:features/environment.py
def before_all(context):
# -- SET LOG LEVEL: behave --logging-level=ERROR ...
# on behave command-line or in "behave.ini".
context.config.setup_logging()
# -- ALTERNATIVE: Setup logging with a configuration file.
# context.config.setup_logging(configfile="behave_logging.ini")
Capture Logging in Hooks¶
If you wish to capture any logging generated during an environment
hook function’s invocation, you may use the
capture()
decorator, like:
# -- FILE:features/environment.py
from behave.log_capture import capture
@capture
def after_scenario(context):
...
This will capture any logging done during the call to after_scenario and print it out.
Detecting that user code overwrites behave Context attributes¶
The context variable in all cases is an instance of
behave.runner.Context
.
- class behave.runner.Context(runner)¶
Hold contextual information during the running of tests.
This object is a place to store information related to the tests you’re running. You may add arbitrary attributes to it of whatever value you need.
During the running of your tests the object will have additional layers of namespace added and removed automatically. There is a “root” namespace and additional namespaces for features and scenarios.
Certain names are used by behave; be wary of using them yourself as behave may overwrite the value you set. These names are:
- feature¶
This is set when we start testing a new feature and holds a
Feature
. It will not be present outside of a feature (i.e. within the scope of the environment before_all and after_all).
- scenario¶
This is set when we start testing a new scenario (including the individual scenarios of a scenario outline) and holds a
Scenario
. It will not be present outside of the scope of a scenario.
- tags¶
The current set of active tags (as a Python set containing instances of
Tag
which are basically just glorified strings) combined from the feature and scenario. This attribute will not be present outside of a feature scope.
- aborted¶
This is set to true in the root namespace when the user aborts a test run (
KeyboardInterrupt
exception). Initially: False.
- failed¶
This is set to true in the root namespace as soon as a step fails. Initially: False.
- text¶
This is set at the step level and holds any multiline text associated with the step.
- config¶
The configuration of behave as determined by configuration files and command-line options. The attributes of this object are the same as the configuration file section names.
- active_outline¶
This is set for each scenario in a scenario outline and references the
Row
that is active for the current scenario. It is present mostly for debugging, but may be useful otherwise.
- captured¶
If any output capture is enabled, provides access to a
Captured
object that contains a snapshot of all captured data (stdout/stderr/log).New in version 1.3.0.
A
behave.runner.ContextMaskWarning
warning will be raised if user code attempts to overwrite one of these variables, or if behave itself tries to overwrite a user-set variable.You may use the “in” operator to test whether a certain value has been set on the context, for example:
"feature" in context
checks whether there is a “feature” value in the context.
Values may be deleted from the context using “del” but only at the level they are set. You can’t delete a value set by a feature at a scenario level but you can delete a value set for a scenario in that scenario.
- abort(reason=None)¶
Abort the test run.
This sets the
aborted
attribute to true. Any test runner evaluates this attribute to abort a test run.New in version 1.2.7.
- add_cleanup(cleanup_func, *args, **kwargs)¶
Adds a cleanup function that is called when
Context._pop()
is called. This is intended for user-cleanups.- Parameters
cleanup_func – Callable function
args – Args for cleanup_func() call (optional).
kwargs – Kwargs for cleanup_func() call (optional).
Note
RESERVED
layer
: optional-stringThe keyword argument
layer="LAYER_NAME"
can to be used to assign thecleanup_func
to specific a layer on the context stack (instead of the current layer).Known layer names are: “testrun”, “feature”, “rule”, “scenario”
See also
Context.LAYER_NAMES
- attach(mime_type, data)¶
Embeds data (e.g. a screenshot) in reports for all formatters that support it, such as the JSON formatter.
- Parameters
mime_type – MIME type of the binary data.
data – Bytes-like object to embed.
- execute_steps(steps_text)¶
The steps identified in the “steps” text string will be parsed and executed in turn just as though they were defined in a feature file.
If the execute_steps call fails (either through error or failure assertion) then the step invoking it will need to catch the resulting exceptions.
- Parameters
steps_text – Text with the Gherkin steps to execute (as string).
- Returns
True, if the steps executed successfully.
- Raises
AssertionError, if a step failure occurs.
- Raises
ValueError, if invoked without a feature context.
- use_or_assign_param(name, value)¶
Use an existing context parameter (aka: attribute) or assign a value to new context parameter (if it does not exist yet).
- Parameters
name – Context parameter name (as string)
value – Parameter value for new parameter.
- Returns
Existing or newly created parameter.
New in version 1.2.7.
- use_or_create_param(name, factory_func, *args, **kwargs)¶
Use an existing context parameter (aka: attribute) or create a new parameter if it does not exist yet.
- Parameters
name – Context parameter name (as string)
factory_func – Factory function, used if parameter is created.
args – Positional args for
factory_func()
on create.kwargs – Named args for
factory_func()
on create.
- Returns
Existing or newly created parameter.
New in version 1.2.7.
- use_with_user_mode()¶
Provides a context manager for using the context in USER mode.
- class behave.runner.ContextMaskWarning¶
Raised if a context variable is being overwritten in some situations.
If the variable was originally set by user code then this will be raised if behave overwrites the value.
If the variable was originally set by behave then this will be raised if user code overwrites the value.
Fixtures¶
Provide a Fixture¶
- behave.fixture.fixture(func=None, name=None, pattern=None)¶
Fixture decorator (currently mostly syntactic sugar).
# -- FILE: features/environment.py # CASE FIXTURE-GENERATOR-FUNCTION (like @contextlib.contextmanager): @fixture def foo(context, *args, **kwargs): the_fixture = setup_fixture_foo(*args, **kwargs) context.foo = the_fixture yield the_fixture cleanup_fixture_foo(the_fixture) # CASE FIXTURE-FUNCTION: No cleanup or cleanup via context-cleanup. @fixture(name="fixture.bar") def bar(context, *args, **kwargs): the_fixture = setup_fixture_bar(*args, **kwargs) context.bar = the_fixture context.add_cleanup(cleanup_fixture_bar, the_fixture.cleanup) return the_fixture
- Parameters
name – Specifies the fixture tag name (as string).
See also
contextlib.contextmanager()
decorator
Use Fixtures¶
- behave.fixture.use_fixture(fixture_func, context, *fixture_args, **fixture_kwargs)¶
Use fixture (function) and call it to perform its setup-part.
The fixture-function is similar to a
contextlib.contextmanager()
(and contains a yield-statement to seperate setup and cleanup part). If it contains a yield-statement, it registers a context-cleanup function to the context object to perform the fixture-cleanup at the end of the current scoped when the context layer is removed (and all context-cleanup functions are called).Therefore, fixture-cleanup is performed after scenario, feature or test-run (depending when its fixture-setup is performed).
# -- FILE: behave4my_project/fixtures.py (or: features/environment.py) from behave import fixture from somewhere.browser import FirefoxBrowser @fixture(name="fixture.browser.firefox") def browser_firefox(context, *args, **kwargs): # -- SETUP-FIXTURE PART: context.browser = FirefoxBrowser(*args, **kwargs) yield context.browser # -- CLEANUP-FIXTURE PART: context.browser.shutdown()
# -- FILE: features/environment.py from behave import use_fixture from behave4my_project.fixtures import browser_firefox def before_tag(context, tag): if tag == "fixture.browser.firefox": use_fixture(browser_firefox, context, timeout=10)
- Parameters
fixture_func – Fixture function to use.
context – Context object to use
fixture_kwargs – Positional args, passed to the fixture function.
fixture_kwargs – Additional kwargs, passed to the fixture function.
- Returns
Setup result object (may be None).
- behave.fixture.use_fixture_by_tag(tag, context, fixture_registry)¶
Process any fixture-tag to perform
use_fixture()
for its fixture. If the fixture-tag is known, the fixture data is retrieved from the fixture registry.# -- FILE: features/environment.py from behave.fixture import use_fixture_by_tag from behave4my_project.fixtures import browser_firefox, browser_chrome # -- SCHEMA 1: fixture_func fixture_registry1 = { "fixture.browser.firefox": browser_firefox, "fixture.browser.chrome": browser_chrome, } # -- SCHEMA 2: fixture_func, fixture_args, fixture_kwargs fixture_registry2 = { "fixture.browser.firefox": (browser_firefox, (), dict(timeout=10)), "fixture.browser.chrome": (browser_chrome, (), dict(timeout=12)), } def before_tag(context, tag): if tag.startswith("fixture."): return use_fixture_by_tag(tag, context, fixture_registry1): # -- MORE: Tag processing steps ...
- Parameters
tag – Fixture tag to process.
context – Runtime context object, used for
use_fixture()
.fixture_registry – Registry maps fixture-tag to fixture data.
- Returns
Fixture-setup result (same as: use_fixture())
- Raises
LookupError – If fixture-tag/fixture is unknown.
ValueError – If fixture data type is not supported.
- behave.fixture.use_composite_fixture_with(context, fixture_funcs_with_params)¶
Helper function when complex fixtures should be created and safe-cleanup is needed even if an setup-fixture-error occurs.
This function ensures that fixture-cleanup is performed for every fixture that was setup before the setup-error occured.
# -- BAD-EXAMPLE: Simplistic composite-fixture # NOTE: Created fixtures (fixture1) are not cleaned up. @fixture def foo_and_bad0(context, *args, **kwargs): the_fixture1 = setup_fixture_foo(*args, **kwargs) the_fixture2 = setup_fixture_bar_with_error("OOPS-HERE") yield (the_fixture1, the_fixture2) # NOT_REACHED. # -- NOT_REACHED: Due to fixture2-setup-error. the_fixture1.cleanup() # NOT-CALLED (SAD). the_fixture2.cleanup() # OOPS, the_fixture2 is None (if called).
# -- GOOD-EXAMPLE: Sane composite-fixture # NOTE: Fixture foo.cleanup() occurs even after fixture2-setup-error. @fixture def foo(context, *args, **kwargs): the_fixture = setup_fixture_foo(*args, **kwargs) yield the_fixture cleanup_fixture_foo(the_fixture) @fixture def bad_with_setup_error(context, *args, **kwargs): raise RuntimeError("BAD-FIXTURE-SETUP") # -- SOLUTION 1: With use_fixture() @fixture def foo_and_bad1(context, *args, **kwargs): the_fixture1 = use_fixture(foo, context, *args, **kwargs) the_fixture2 = use_fixture(bad_with_setup_error, context, "OOPS") return (the_fixture1, the_fixture2) # NOT_REACHED # -- SOLUTION 2: With use_composite_fixture_with() @fixture def foo_and_bad2(context, *args, **kwargs): the_fixture = use_composite_fixture_with(context, [ fixture_call_params(foo, *args, **kwargs), fixture_call_params(bad_with_setup_error, "OOPS") ]) return the_fixture
- Parameters
context – Runtime context object, used for all fixtures.
fixture_funcs_with_params – List of fixture functions with params.
- Returns
List of created fixture objects.
Runner Operation¶
The execution of code is based on the Gherkin description in *.feature files. The following section provides a short overview of the hierarchical containment that is possible in the Gherkin grammer:
# -- SIMPLIFIED GHERKIN GRAMMAR (for Gherkin v6):
# CARDINALITY DECORATOR: '*' means 0..N (many), '?' means 0..1 (optional)
# EXAMPLE: Feature
# A Feature can have many Tags (as TaggableStatement: zero or more tags before its keyword).
# A Feature can have an optional Background.
# A Feature can have many Scenario(s), meaning zero or more Scenarios.
# A Feature can have many ScenarioOutline(s).
# A Feature can have many Rule(s).
Feature(TaggableStatement):
Background?
Scenario*
ScenarioOutline*
Rule*
Background:
Step* # Background steps are injected into any Scenario of its scope.
Scenario(TaggableStatement):
Step*
ScenarioOutline(ScenarioTemplateWithPlaceholders):
Scenario* # Rendered Template by using ScenarioOutline.Examples.rows placeholder values.
Rule(TaggableStatement):
Background? # Behave-specific extension (after removal from final Gherkin v6).
Scenario*
ScenarioOutline*
Given all the code that could be run by behave, this is the order in which that code is invoked (if they exist.)
# -- PSEUDO-CODE:
# HOOK: before_tag(), after_tag() is called for Feature, Rule, Scenario
ctx = createContext()
call-optional-hook before_all(ctx)
for feature in all_features:
for tag in feature.tags: call-optional-hook before_tag(ctx, tag)
call-optional-hook before_feature(ctx, feature)
for run_item in feature.run_items: # CAN BE: Rule, Scenario, ScenarioOutline
execute_run_item(run_item, ctx)
call-optional-hook after_feature(ctx, feature)
for tag in feature.tags: call-optional-hook after_tag(ctx, tag)
call-optional-hook after_all(ctx)
function execute_run_item(run_item, ctx):
if run_item isa Rule:
# -- CASE: Rule
rule = run_item
for tag in rule.tags: call-optional-hook before_tag(ctx, tag)
call-optional-hook before_rule(ctx, rule)
for run_item in rule.run_items: # CAN BE: Scenario, ScenarioOutline
execute_run_item(run_item, ctx)
call-optional-hook after_rule(ctx, rule)
for tag in rule.tags: call-optional-hook after_tag(ctx, tag)
else if run_item isa ScenarioOutline:
# -- CASE: ScenarioOutline
# HINT: All Scenarios are already created from Example(s) rows.
scenario_outline = run_item
for scenario in scenario_outline.scenarios:
execute_run_item(scenario, ctx)
else if run_item isa Scenario:
# -- CASE: Scenario
# HINT: Background steps are injected before scenario steps.
scenario = run_item
for tag in scenario.tags: call-optional-hook before_tag(ctx, tag)
call-optional-hook before_scenario(ctx, scenario)
for step in scenario.steps:
call-optional-hook before_step(ctx, step)
step.run(ctx)
call-optional-hook after_step(ctx, step)
call-optional-hook after_scenario(ctx, scenario)
for tag in scenario.tags: call-optional-hook after_tag(ctx, tag)
Model Objects¶
The feature, scenario and step objects represent the information parsed from the feature file. They have a number of common attributes:
- keyword
“Feature”, “Scenario”, “Given”, etc.
- name
The name of the step (the text after the keyword.)
- filename and line
The file name (or “<string>”) and line number of the statement.
The structure of model objects parsed from a feature file will typically be:
Tag
(asFeature.tags
)Feature
: TaggableModelElement Description (asFeature.description
)Background
Step
Table
(asStep.table
) MultiLineText (asStep.text
)Tag
(asScenario.tags
)Scenario
: TaggableModelElement Description (asScenario.description
)Step
Table
(asStep.table
) MultiLineText (asStep.text
)Tag
(asScenarioOutline.tags
)ScenarioOutline
: TaggableModelElement Description (asScenarioOutline.description
)Step
Table
(asStep.table
) MultiLineText (asStep.text
)Examples
Table
- class behave.model.Feature(filename, line, keyword, name, tags=None, description=None, scenarios=None, background=None, language=None)¶
A feature parsed from a feature file.
The attributes are:
- keyword¶
This is the keyword as seen in the feature file. In English this will be “Feature”.
- name¶
The name of the feature (the text after “Feature”.)
- description¶
The description of the feature as seen in the feature file. This is stored as a list of text lines.
- background¶
The
Background
for this feature, if any.
- tags¶
A list of @tags (as
Tag
which are basically glorified strings) attached to the feature. See Controlling Things With Tags.
- status¶
Read-Only. A summary status of the feature’s run. If read before the feature is fully tested it will return “untested” otherwise it will return one of:
- Status.untested
The feature was has not been completely tested yet.
- Status.skipped
One or more steps of this feature was passed over during testing.
- Status.passed
The feature was tested successfully.
- Status.failed
One or more steps of this feature failed.
Changed in version 1.2.6: Use Status enum class (was: string).
- hook_failed¶
Indicates if a hook failure occured while running this feature.
New in version 1.2.6.
- duration¶
The time, in seconds, that it took to test this feature. If read before the feature is tested it will return 0.0.
- filename¶
The file name (or “<string>”) of the feature file where the feature was found.
- line¶
The line number of the feature file where the feature was found.
- language¶
Indicates which spoken language (English, French, German, ..) was used for parsing the feature file and its keywords. The I18N language code indicates which language is used. This corresponds to the language tag at the beginning of the feature file.
New in version 1.2.6.
- class behave.model.Rule(filename, line, keyword, name, tags=None, description=None, scenarios=None, background=None, parent=None)¶
A rule parsed from a feature file.
# -- FILE: *.feature Feature: ... Description.... Background? Scenario* ScenarioOutline* @tag1 @tag2 Rule: Some Rule Title Description? # CARDINALITY: 0..1 (optional). Background? # CARDINALITY: 0..1 (optional). Scenario* # CARDINALITY: 0..N (many) ScenarioOutline* # CARDINALITY: 0..N (many)
The attributes are:
- keyword¶
This is the keyword as seen in the feature file. In English this will be “Feature”.
- name¶
The name of the feature (the text after “Feature”.)
- description¶
The description of the feature as seen in the feature file. This is stored as a list of text lines.
- background¶
The
Background
for this feature, if any.
- tags¶
A list of @tags (as
Tag
which are basically glorified strings) attached to the feature. See Controlling Things With Tags.
- status¶
Read-Only. A summary status of the feature’s run. If read before the feature is fully tested it will return “untested” otherwise it will return one of:
- Status.untested
The feature was has not been completely tested yet.
- Status.skipped
One or more steps of this feature was passed over during testing.
- Status.passed
The feature was tested successfully.
- Status.failed
One or more steps of this feature failed.
Changed in version 1.2.6: Use Status enum class (was: string).
- hook_failed¶
Indicates if a hook failure occured while running this feature.
New in version 1.2.6.
- duration¶
The time, in seconds, that it took to test this feature. If read before the feature is tested it will return 0.0.
- filename¶
The file name (or “<string>”) of the feature file where the feature was found.
- line¶
The line number of the feature file where the feature was found.
- language¶
Indicates which spoken language (English, French, German, ..) was used for parsing the feature file and its keywords. The I18N language code indicates which language is used. This corresponds to the language tag at the beginning of the feature file.
New in version 1.2.7.
- class behave.model.Background(filename, line, keyword='Background', name='', steps=None, description=None)¶
A background parsed from a feature file.
Behaviour:
Each scenario of a scenario container (Feature, Rule) inherits the Background of its scenario container
Background steps in a scenario are executed before scenario steps
Rule Background inherits the Feature Background (outer background) if any
Inherited Background steps are used/executed first
Optionally, background inheritance can be disabled (normally: by using a fixture/fixture-tag)
The attributes are:
- keyword¶
This is the keyword as seen in the feature file. In English this will typically be “Background”.
- name¶
The name of the background (the text after “Background:”.)
- duration¶
The time, in seconds, that it took to run this background. If read before the background is run it will return 0.0.
- filename¶
The file name (or “<string>”) of the feature file where the background was found.
- line¶
The line number of the feature file where the background was found.
- description¶
Optional description (text, as list of lines).
New in version 1.2.7: (supported since Gherkin v6 or earlier)
- class behave.model.Scenario(filename, line, keyword, name, tags=None, steps=None, description=None, parent=None)¶
A scenario parsed from a feature file.
The attributes are:
- keyword¶
This is the keyword as seen in the feature file. In English this will typically be “Scenario”.
- name¶
The name of the scenario (the text after “Scenario:”.)
- description¶
The description of the scenario as seen in the feature file. This is stored as a list of text lines.
- tags¶
A list of @tags (as
Tag
which are basically glorified strings) attached to the scenario. See Controlling Things With Tags.
- status¶
Read-Only. A summary status of the scenario’s run. If read before the scenario is fully tested it will return “untested” otherwise it will return one of:
- Status.untested
The scenario was has not been completely tested yet.
- Status.skipped
One or more steps of this scenario was passed over during testing.
- Status.passed
The scenario was tested successfully.
- Status.failed
One or more steps of this scenario failed.
Changed in version 1.2.6: Use Status enum class (was: string)
- hook_failed¶
Indicates if a hook failure occured while running this scenario.
New in version 1.2.6.
- duration¶
The time, in seconds, that it took to test this scenario. If read before the scenario is tested it will return 0.0.
- filename¶
The file name (or “<string>”) of the feature file where the scenario was found.
- line¶
The line number of the feature file where the scenario was found.
- parent¶
Points to parent entity that contains this scenario (Feature, Rule, …).
New in version 1.2.7.
- class behave.model.ScenarioOutline(filename, line, keyword, name, tags=None, steps=None, examples=None, description=None)¶
A scenario outline parsed from a feature file.
A scenario outline extends the existing
Scenario
class with the addition of theExamples
tables of data from the feature file.The attributes are:
- keyword¶
This is the keyword as seen in the feature file. In English this will typically be “Scenario Outline”.
- name¶
The name of the scenario (the text after “Scenario Outline:”.)
- description¶
The description of the scenario outline as seen in the feature file. This is stored as a list of text lines.
- tags¶
A list of @tags (as
Tag
which are basically glorified strings) attached to the scenario. See Controlling Things With Tags.
- status¶
Read-Only. A summary status of the scenario outlines’s run. If read before the scenario is fully tested it will return “untested” otherwise it will return one of:
- Status.untested
The scenario was has not been completely tested yet.
- Status.skipped
One or more scenarios of this outline was passed over during testing.
- Status.passed
The scenario was tested successfully.
- Status.failed
One or more scenarios of this outline failed.
Changed in version 1.2.6: Use Status enum class (was: string)
- duration¶
The time, in seconds, that it took to test the scenarios of this outline. If read before the scenarios are tested it will return 0.0.
- filename¶
The file name (or “<string>”) of the feature file where the scenario was found.
- line¶
The line number of the feature file where the scenario was found.
- class behave.model.Examples(filename, line, keyword, name, tags=None, table=None)¶
A table parsed from a scenario outline in a feature file.
The attributes are:
- keyword¶
This is the keyword as seen in the feature file. In English this will typically be “Example”.
- name¶
The name of the example (the text after “Example:”.)
- filename¶
The file name (or “<string>”) of the feature file where the example was found.
- line¶
The line number of the feature file where the example was found.
- class behave.model.Tag(name, line)¶
Tags appear may be associated with Features or Scenarios.
They’re a subclass of regular strings (unicode pre-Python 3) with an additional
line
number attribute (where the tag was seen in the source feature file.
- class behave.model.Step(filename, line, keyword, step_type, name, text=None, table=None)¶
A single step parsed from a feature file.
The attributes are:
- keyword¶
This is the keyword as seen in the feature file. In English this will typically be “Given”, “When”, “Then” or a number of other words.
- name¶
The name of the step (the text after “Given” etc.)
- step_type¶
The type of step as determined by the keyword. If the keyword is “and” then the previous keyword in the feature file will determine this step’s step_type.
- status¶
Read-Only. A summary status of the step’s run. If read before the step is tested it will return “untested” otherwise it will return one of:
- Status.untested
This step was not run (yet).
- Status.skipped
This step was skipped during testing.
- Status.passed
The step was tested successfully.
- Status.failed
The step failed.
- Status.undefined
The step has no matching step implementation.
Changed in version Use: Status enum class (was: string).
- hook_failed¶
Indicates if a hook failure occured while running this step.
New in version 1.2.6.
- duration¶
The time, in seconds, that it took to test this step. If read before the step is tested it will return 0.0.
- error_message¶
If the step failed then this will hold any error information, as a single string. It will otherwise be None.
Changed in version 1.2.6: (moved to base class)
- filename¶
The file name (or “<string>”) of the feature file where the step was found.
- line¶
The line number of the feature file where the step was found.
Tables may be associated with either Examples or Steps:
- class behave.model.Table(headings, line=None, rows=None)¶
A table extracted from a feature file.
Table instance data is accessible using a number of methods:
- iteration
Iterating over the Table will yield the
Row
instances from the .rows attribute.- indexed access
Individual rows may be accessed directly by index on the Table instance; table[0] gives the first non-heading row and table[-1] gives the last row.
The attributes are:
- headings¶
The headings of the table as a list of strings.
Tables are also comparable, for what that’s worth. Headings and row data are compared.
- class behave.model.Row(headings, cells, line=None, comments=None)¶
One row of a table parsed from a feature file.
Row data is accessible using a number of methods:
- iteration
Iterating over the Row will yield the individual cells as strings.
- named access
Individual cells may be accessed by heading name; row[“name”] would give the cell value for the column with heading “name”.
- indexed access
Individual cells may be accessed directly by index on the Row instance; row[0] gives the first cell and row[-1] gives the last cell.
The attributes are:
- cells¶
The list of strings that form the cells of this row.
- headings¶
The headings of the table as a list of strings.
Rows are also comparable, for what that’s worth. Only the cells are compared.
And Text may be associated with Steps:
Logging Capture¶
The logging capture behave uses by default is implemented by the class
LoggingCapture
. It has methods
- class behave.log_capture.LoggingCapture(config, level=None)¶
Capture logging events in a memory buffer for later display or query.
Captured logging events are stored on the attribute
buffer
:- buffer¶
This is a list of captured logging events as logging.LogRecords.
By default the format of the messages will be:
'%(levelname)s:%(name)s:%(message)s'
This may be overridden using standard logging formatter names in the configuration variable
logging_format
.The level of logging captured is set to
logging.NOTSET
by default. You may override this using the configuration settinglogging_level
(which is set to a level name.)Finally there may be filtering of logging events specified by the configuration variable
logging_filter
.- abandon()¶
Turn off logging capture.
If other handlers were removed by
inveigle()
then they are reinstated.
- any_errors()¶
Search through the buffer for any ERROR or CRITICAL events.
Returns boolean indicating whether a match was found.
- find_event(pattern)¶
Search through the buffer for a message that matches the given regular expression.
Returns boolean indicating whether a match was found.
- flush()¶
Override to implement custom flushing behaviour.
This version just zaps the buffer to empty.
The log_capture module also defines a handy logging capture decorator that’s intended to be used on your environment file functions.
- behave.log_capture.capture(*args, **kw)¶
Decorator to wrap an environment file function in log file capture.
It configures the logging capture using the behave context, the first argument to the function being decorated (so don’t use this to decorate something that doesn’t have context as the first argument).
The basic usage is:
The function prints any captured logging (at the level determined by the
log_level
configuration setting) directly to stdout, regardless of error conditions.It is mostly useful for debugging in situations where you are seeing a message like:
No handlers could be found for logger "name"
The decorator takes an optional “level” keyword argument which limits the level of logging captured, overriding the level in the run’s configuration:
This would limit the logging captured to just ERROR and above, and thus only display logged events if they are interesting.