Registry / testing / pytest-bdd

pytest-bdd

JSON →
library8.1.0pypypi✓ verified 28d ago

Pytest-bdd is a pytest plugin that implements a subset of the Gherkin language to enable automating project requirements testing and facilitate Behavior-Driven Development (BDD). It integrates seamlessly with pytest, allowing reuse of fixtures and plugins, unifying unit and functional tests, and simplifying continuous integration server configuration. The library is actively maintained, with version 8.1.0 currently available, and often releases updates to ensure compatibility with the latest Gherkin specification.

pip install pytest-bdd
INSTALL
IMPORT
SIG · PYTEST-BDD
P
pytest-bdd
testingpythonv8.1.0
Install
3.1s avg
Import
518ms
Disk
32MB
Pass rate
10/ 10
Env Coverage10 / 10
glibc
3.9–3.13
musl
3.9–3.13
Install & Compatibility
Where this runs
tested against v8.1.0 · pip install
no network on importno background threads
Install × environment matrix
Each cell = how many times install + import succeeded across repeated harness runs. Partial = flaky.
glibc = Debian/Ubuntu slim · musl = Alpine Linux
musl
py 3.10–3.95 runs
installs and imports cleanly · install 0.0s · import 0.536s · 33.2MB
glibc
py 3.10–3.95 runs
installs and imports cleanly · install 3.1s · import 0.500s · 34MB
32MB installed
● package 32MB
Code
Verified usage

Verified import paths — ran on the pinned version, not inferred.

scenario
✓ from pytest_bdd import scenario
given
✓ from pytest_bdd import given
when
✓ from pytest_bdd import when
then
✓ from pytest_bdd import then
parsers
✓ from pytest_bdd import parsers
✗ from pytest_bdd.steps import parsers
While parsers were previously accessible via `pytest_bdd.steps`, the direct import from `pytest_bdd` is the current and recommended path.

This quickstart demonstrates a basic pytest-bdd setup. It involves creating a Gherkin `.feature` file to define a scenario and a corresponding Python test file (`test_example.py`) where the scenario is linked using `@scenario` and step definitions (`@given`, `@when`, `@then`) are implemented. Pytest fixtures are used for sharing state between steps.

import pytest from pytest_bdd import scenario, given, when, then # --- content of features/example.feature --- # Feature: Basic feature # Scenario: Run a simple scenario # Given I have a value of 10 # When I add 5 to it # Then the value should be 15 # --- content of tests/test_example.py --- @scenario('../features/example.feature', 'Run a simple scenario') def test_simple_scenario(): pass @pytest.fixture def initial_value(): return {} @given('I have a value of 10') def i_have_value_10(initial_value): initial_value['value'] = 10 @when('I add 5 to it') def i_add_5(initial_value): initial_value['value'] += 5 @then('the value should be 15') def the_value_should_be_15(initial_value): assert initial_value['value'] == 15 # To run this example: # 1. Create a directory structure: project_root/features/ and project_root/tests/ # 2. Save the .feature content into features/example.feature # 3. Save the Python code into tests/test_example.py # 4. Run `pytest` from `project_root`
pytest --version
Debug
Known issues
breakingStep arguments are no longer fixtures since version 6.0.0 and 8.0.0. In previous versions, parsed step arguments automatically became pytest fixtures. This behavior was removed to align with official Gherkin specifications and avoid conflicts with actual fixtures.
fix
Explicitly define fixtures or use the `target_fixture` parameter in step decorators if you need to expose a step's return value as a fixture. For example, `@given(parsers.parse('I have a {fruit}'), target_fixture='my_fruit')`.
affects: >=6.0.0
breakingFeature-level and vertical example tables are no longer supported since version 6.0.0 and 8.0.0. Pytest-bdd now strictly adheres to Gherkin's specification, which only supports example tables within `Scenario Outline` sections.
fix
Migrate feature-level and vertical examples into `Scenario Outline` blocks using `Examples` tables. Ensure all variable templates `<variable>` are used within `Scenario Outline` steps only.
affects: >=6.0.0
breakingThe behavior of parsing variable templates (`<variable>`) in steps changed significantly in versions 6.0.0 and 8.0.0. Previously, these were parsed in both `Scenario` and `Scenario Outline`. Now, they are only parsed for `Scenario Outline` steps.
fix
Ensure that steps containing variable templates like `<variable>` are exclusively used within `Scenario Outline` scenarios. For regular `Scenario` steps that need parameters, use `pytest_bdd.parsers.parse` or other explicit parsers.
affects: >=6.0.0
gotchaBy default, `pytest-bdd` uses the current module's path to find feature files. This can lead to issues if feature files are organized in a different directory structure.
fix
Configure the `bdd_features_base_dir` key in your `pytest.ini` (or `tox.ini`, `setup.cfg`) to specify the base directory for feature files, relative to the pytest root directory. Alternatively, provide `features_base_dir` directly to the `@scenario` decorator for per-scenario overrides.
affects: all
gotchaWhen using tags in `.feature` files, if `pytest` is run with the `--strict-markers` option, these tags must also be explicitly declared in the `markers` setting of your `pytest.ini` file. Tag names should also be Python-compatible variable names.
fix
Add all Gherkin tags to the `markers` section in `pytest.ini`. E.g., `[pytest]
markers = my_tag: description of my_tag`. Ensure tags use alphanumeric characters and underscores, starting with a non-number.
affects: all (especially with pytest >= 5.0 and --strict-markers)
breakingSince version 8.0.0, `pytest-bdd` uses the official Gherkin parser. This introduced several strictness changes: multiline steps must use triple-quotes, all feature files must start with `Feature:`, and tags can no longer contain spaces.
fix
Update `.feature` files to comply with the official Gherkin specification. Ensure multiline steps are enclosed in triple quotes, every feature file begins with `Feature:`, and tags like `@tag one` are changed to `@tag_one` or separate tags.
affects: >=8.0.0
Errors
Common errors & fixes
pytest_bdd.exceptions.StepDefinitionNotFoundError: Step definition is not found for step 'I have a clean database'
A step defined in the Gherkin feature file does not have a corresponding Python step implementation function (decorated with @given, @when, or @then) that matches its text.
fix
Define a Python function with the appropriate `pytest_bdd` decorator (`@given`, `@when`, or `@then`) matching the exact text of the Gherkin step.

```python
from pytest_bdd import given

@given('I have a clean database')
def clean_database():
    # Implement database setup here
    pass
```
gherkin.parser.ParserError: Parse error at /path/to/feature_file.feature:3: Expected one of: #EOF, #TableRow, #DocString, #Step, #Tag, #Comment, #Empty, #Background, #Scenario, #ScenarioOutline, #Rule. Got 'Invalid Line'
The Gherkin `.feature` file contains a syntax error or an incorrectly formatted line at the specified location, preventing the parser from understanding the file structure.
fix
Correct the syntax in the `.feature` file to adhere to the Gherkin specification, ensuring correct keywords, indentation, or table formatting.

```gherkin
Feature: User login

  Scenario: Successful login
    Given I am on the login page
    When I enter valid credentials
    Then I should be logged in
```
_pytest.fixtures.FixtureLookupError: Unknown fixture 'my_fixture' (scenario: 'My Scenario')
A pytest fixture referenced by a `pytest-bdd` step or scenario is either not defined, not imported, or not discoverable by pytest in the test file or a `conftest.py`.
fix
Ensure the referenced fixture is correctly defined using `@pytest.fixture` and is available in a scope accessible to the test (e.g., in the test file itself or in a `conftest.py` file in a parent directory).

```python
# In conftest.py or your test file
import pytest

@pytest.fixture
def my_fixture():
    return "some_value"

# In your steps file, use the fixture as an argument
from pytest_bdd import given

@given('I use a fixture')
def use_the_fixture(my_fixture):
    print(f"Using: {my_fixture}")
```
ModuleNotFoundError: No module named 'pytest_bdd'
The `pytest-bdd` library has not been installed in the current Python environment or the active environment is not the one where it was installed.
fix
Install the `pytest-bdd` package using pip: `pip install pytest-bdd`
Upgrade
Version history
8.1.0latest on PyPI · released Dec 5, 2024
Audit
Dependencies
pytestrequiredpytest-bdd is a plugin for the pytest testing framework.
Agent activity
5 hits · last 30 days
node
4
Resources
pytest-bdd — pip install pytest-bdd · libregistry