pytest-bdd

8.1.0 · active · verified Fri Apr 10

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.

Warnings

Install

Imports

Quickstart

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`

view raw JSON →