behave (BDD Framework)
behave is a behavior-driven development (BDD) framework for Python, enabling teams to write executable specifications in Gherkin feature files. It supports Gherkin v6, Cucumber-Expressions, and async-steps, allowing for clear, human-readable tests. The current stable version is 1.3.3, with releases typically focusing on bug fixes and incremental feature enhancements, sometimes with pre-releases for larger changes.
Warnings
- breaking Recursive discovery and import of steps directories is disabled by default starting from v1.3.2. Nested `steps` directories under the primary `steps` directory will no longer be automatically scanned.
- gotcha Python 2.7 support was temporarily broken in `v1.3.2` due to an oversight.
- gotcha ImportError for `asynccontextmanager` in Python 3.6 could occur with `v1.3.0` and `v1.3.1`.
- breaking Version 1.3.0 introduced Gherkin v6, native Cucumber-Expressions, and native async-steps support.
Install
-
pip install behave
Imports
- given, when, then
from behave import given, when, then
- step
from behave import step
- before_all, after_all, before_scenario, after_scenario, etc.
from behave import * # in environment.py (common practice, but specific imports are also fine)
- use_step_matcher
from behave import use_step_matcher
Quickstart
# Create the following file structure in your project root:
#
# ./
# ├── features/
# │ ├── example.feature
# │ └── steps/
# │ └── example_steps.py
# └── (run 'behave' from this root directory)
# --- features/example.feature ---
# Feature: Basic addition
# As a calculator user
# I want to be able to add numbers
# So that I can get the sum
#
# Scenario: Add two numbers
# Given I have the numbers 5 and 3
# When I add them
# Then the result should be 8
# --- features/steps/example_steps.py ---
from behave import given, when, then
@given('I have the numbers {num1:d} and {num2:d}')
def step_impl(context, num1, num2):
context.num1 = num1
context.num2 = num2
@when('I add them')
def step_impl(context):
context.result = context.num1 + context.num2
@then('the result should be {expected_result:d}')
def step_impl(context, expected_result):
assert context.result == expected_result
# To run this example:
# 1. Create the files as shown above.
# 2. Navigate to your project's root directory (containing the 'features' folder) in your terminal.
# 3. Execute the behave command:
# $ behave