Behavior-Driven Development in Python with pytest-bdd
Learn behavior-driven development in Python by turning shared booking rules into Gherkin scenarios and executable tests with pytest-bdd.
Article summary
TL;DR
- BDD starts by agreeing on concrete examples of what the software should do. Gherkin records those examples; pytest-bdd connects them to Python.
- Concrete scenarios cover the last seats, sold-out inventory, and a successful request after rejection.
- Step definitions translate the scenario into calls and assertions. Keep the reservation rules in the application code.
- A rejection has 2 outcomes to check: the request fails for the expected reason, and the remaining seats stay available.
- Use feature files when people review the examples together. Keep ordinary pytest tests where the extra representation would add work without helping that conversation.
Code for this article
Open the repository to follow along.
artem-istranin/istranin-dev-code-examples01 / WHY BDD
Behavior-driven development in Python starts with a shared example.
A booking has 3 seats left. A customer asks for 5. Do we reject the request, reserve the 3 available seats, or offer another date?
A passing test cannot settle that decision. Someone has to agree on the rule before we can decide whether the result is correct.
Behavior-driven development (BDD) is a way to develop software through shared examples of expected behavior. People discuss a requirement, agree on concrete outcomes, and use those examples to guide the code and its tests.
We will use a small reservation system to make the process concrete. Its Inventory class tracks available seats and accepts or rejects reservation requests.
In this pytest-bdd tutorial, we will record the examples in Gherkin, connect them to Python, and run them beside the original tests. Then we will introduce a small bug and see which examples catch it.
You need basic Python classes, exceptions, and pytest assertions. The companion includes the complete reservation code and tests; you can follow this tutorial on its own.

The conversation in the illustration comes before the test automation. Installing pytest-bdd gives us a way to run agreed examples; it does not decide what a customer should be allowed to do.
02 / HOW BDD WORKS
Turn a shared decision into an executable example.
A rule such as “reservations cannot exceed availability” still leaves questions. Can a customer reserve the last seats? Does a rejected request leave them available for someone else?
BDD brings people who understand the product, its users, and its implementation together to answer those questions with concrete examples.
Cucumber describes BDD through 3 activities: discovery, formulation, and automation. We explore a rule, express its examples clearly, and connect them to executable checks.
| Practice | What it contributes here |
|---|---|
| BDD | A shared decision about which reservations should succeed or fail |
| TDD | Small red-green-refactor cycles that help implement those decisions |
pytest-bdd is the Python plugin we use to run the Gherkin scenarios through pytest.
For a new rule, those examples can guide the implementation. In this tutorial, the inventory already works. We are making existing behavior explicit and adding examples the first tests did not cover.
Our scenarios call a Python object directly. They do not need a browser just because a customer appears in the story.
If you want to explore how tests can guide the implementation, the related TDD tutorial builds this same inventory through small failing tests.
03 / DISCOVER THE RULES
Resolve the booking decisions before writing scenarios.
Start with the story: “As a customer, I want to reserve available seats so that I can attend the event.”
Now ask what happens at its boundaries. For this example, a reservation is all or nothing: a request for 5 seats cannot quietly become a booking for 3.
A short discussion should include product, development, and testing perspectives. This is often called the Three Amigos. The name describes the perspectives to cover, not a requirement to invite exactly 3 people.
Keep the story, rules, examples, and unanswered questions separate. This simple form of example mapping helps us notice when a decision is still missing.
The inventory has 3 rules: requests must be positive, cannot exceed availability, and must leave availability unchanged when rejected.
| Seats before | Requested | Decision | Seats after |
|---|---|---|---|
| 3 | 2 | Accept | 1 |
| 3 | 3 | Accept the last seats | 0 |
| 2 | 3 | Reject: not enough seats | 2 |
| 0 | 1 | Reject: not enough seats | 0 |
| 3 | 0 | Reject: quantity must be positive | 3 |
| 3 | -1 | Reject: quantity must be positive | 3 |
The last-seats row makes an easy-to-miss decision explicit: equality is allowed. Each rejection row also answers what remains available afterward.
Practice choosing useful examples and testing their outcomes in the Pytest course.
View courseAdd one short sequence: reserve 2 of 3 seats, reject a request for 2 more, then accept a request for the last seat. That checks whether a failed request leaves the inventory usable.
We are discussing integer requests against an in-memory seat count. Payment, cancellation, simultaneous customers, and database transactions need separate decisions and tests.
These examples are useful even if they never become Gherkin. For more on making testing a shared habit, see onboarding a Python team to testing.
04 / RUN THE COMPANION
Run the working example before tracing its parts.
Use Git, Python 3.13 or newer, and uv. Clone the companion and open the BDD project:
git clone https://github.com/artem-istranin/istranin-dev-code-examples.git
cd istranin-dev-code-examples/behavior-driven-development-python-pytest-bdd
uv sync --locked
uv run pytest -v
If you already cloned the repository, open that directory and run the last 2 commands. uv sync --locked installs the recorded dependencies. uv run pytest -v runs the tests and shows each case by name.
The result is 11 passed: 4 original pytest cases and 7 BDD cases. This walkthrough was checked with Python 3.13.12, pytest 8.4.2, and pytest-bdd 8.1.0 from the companion’s lockfile.
Keep your terminal in this directory. The following sections read files that already exist; the snippets are excerpts, not replacement files.
inventory.py
tests/
features/
reservations.feature
test_inventory.py
test_reservations.py
pyproject.toml
uv.lock
inventory.py contains the reservation logic. It checks the request before changing the count. Its public method does just 2 things:
def reserve(self, quantity: int) -> None:
self._validate_reservation(quantity)
self.available -= quantity
The validation helper rejects non-positive quantities with ValueError and oversized requests with OutOfStockError. No BDD-specific code has been added to this class.
test_inventory.py holds the original tests. reservations.feature holds the shared examples. test_reservations.py connects those examples to the inventory. The included pytest configuration finds the tests and makes inventory.py importable.
Both test groups exercise the same Inventory class.
05 / READ GHERKIN
Read a Gherkin scenario before introducing placeholders.
Gherkin gives examples a small, consistent structure. Here is the last-seats case written out without placeholders:
Scenario: Reserve the last seats
Given a booking has 3 seats available
When a customer requests 3 seats
Then the reservation is accepted
And 0 seats remain available
Given establishes the starting situation. When describes the action. Then checks the outcome. And continues the previous kind of step; here, it adds another outcome check.
Notice that the scenario says nothing about private methods or Python exception handling. It describes a booking decision and its result.
The companion expresses this case as a row in a Scenario Outline. Open tests/features/reservations.feature and read its first outline:
Scenario Outline: Reserve a quantity that is available
Given a booking has <available> seats available
When a customer requests <quantity> seats
Then the reservation is accepted
And <remaining> seats remain available
Examples:
| available | quantity | remaining |
| 3 | 2 | 1 |
| 3 | 3 | 0 |
Each row supplies the values in angle brackets and becomes a separate case. The second row gives us the concrete scenario above. A Feature groups these related reservation scenarios under one name.
The next 2 outlines cover oversized and non-positive requests. For example, the oversized-request outline checks:
Then the reservation is rejected because there are not enough seats
And <available> seats remain available
Those are 2 promises: rejection for the expected reason, and an unchanged seat count. The word “rejected” alone would leave the second promise unchecked.
The 3 outlines each have 2 rows, producing 6 cases. The final sequence scenario adds the seventh. It reserves seats, observes a rejection, then makes another valid request on the same inventory.
Use outlines when the same rule needs several concrete inputs. Keep different rules separate so a failure still tells you which decision broke. The Gherkin reference explains the remaining language features when you need them.
06 / CONNECT THE STEPS
Connect Gherkin steps to Python with pytest-bdd.
A step definition is a Python function attached to a Gherkin sentence. pytest-bdd matches each sentence, runs its function, and passes the values that function needs.
Open tests/test_reservations.py. We will follow the last-seats example through its setup, request, and assertions.
Load the scenarios
The file begins with these imports and registration:
from pytest_bdd import given, parsers, scenarios, then, when
from inventory import Inventory, OutOfStockError
scenarios("features/reservations.feature")
scenarios(...) makes the feature’s scenarios available as pytest tests. Here, the feature path is relative to test_reservations.py. Pytest collects that Python module, which loads the feature file.
Given: create the starting inventory
@given(
parsers.parse("a booking has {available:d} seats available"),
target_fixture="inventory",
)
def available_inventory(available: int) -> Inventory:
return Inventory(available=available)
parsers.parse matches the sentence. The {available:d} part captures its number as an integer. For our example, available is 3.
The function returns an Inventory. A fixture is a named value pytest supplies to a test or step. target_fixture="inventory" makes this returned object available under that name.
Later functions request the same object by declaring an inventory parameter. Each scenario creates its own inventory; only steps inside that scenario share it.
When: make the request
@when(
parsers.parse("a customer requests {quantity:d} seats"),
target_fixture="reservation_error",
)
def request_seats(
inventory: Inventory, quantity: int
) -> OutOfStockError | ValueError | None:
try:
inventory.reserve(quantity)
except (OutOfStockError, ValueError) as error:
return error
return None
This function calls the real reserve method. For the last-seats example, it calls reserve(3) on an inventory containing 3 seats.
The method succeeds, so the step returns None. If the method raises one of the 2 expected rejection exceptions, the step returns that exception instead. An unexpected exception still fails the scenario immediately.
The | symbols in the return annotation mean “one of these types.” They document the possible results; they do not catch or validate exceptions.
target_fixture="reservation_error" gives the next steps access to that result. We capture expected rejections here because they are outcomes the scenarios need to inspect.
Then: check the decision and the remaining seats
@then("the reservation is accepted")
def reservation_accepted(
reservation_error: OutOfStockError | ValueError | None,
) -> None:
assert reservation_error is None
@then(parsers.parse("{remaining:d} seats remain available"))
def remaining_seats(inventory: Inventory, remaining: int) -> None:
assert inventory.available == remaining
For our example, the first assertion confirms success. The second compares the actual count with the scenario’s expected value, 0.
The rejection steps in the same file check the exception type: OutOfStockError for insufficient seats and ValueError for a non-positive quantity. They also run the remaining-seats check.
The adapter does not decide whether a request is valid or calculate the expected remaining count. The application owns the rule, and the scenario supplies the expected outcome. Duplicating the subtraction in the test would risk repeating the same mistake.
In the final sequence scenario, a Given step makes the earlier reservation through reserve(2). Each later When step supplies a fresh reservation_error, so the assertions inspect the latest request.
We now have a complete route from a reviewable sentence to a real operation and an assertion. The ordinary pytest tests reach that same operation directly.

07 / PROVE THE EXAMPLES
See which example catches a broken boundary.
Run just the BDD cases:
uv run pytest tests/test_reservations.py -v
The result is 7 passed. They pass immediately because the inventory already implements these rules. We have added executable examples of existing behavior, not demonstrated a new feature being built test-first.
Now introduce one temporary mistake. In inventory.py, change the availability check from:
if quantity > self.available:
to:
if quantity >= self.available:
Leave everything else unchanged. The new check wrongly rejects a request for exactly the remaining seats.
Run the BDD test file again:
uv run pytest tests/test_reservations.py -v
The result is 2 failed, 5 passed. The last-seats row fails, and so does the final valid request in the sequence scenario. Both try to reserve all the remaining seats.
With the mistake still present, run the original tests:
uv run pytest tests/test_inventory.py -v
They still report 4 passed. None of those cases requests exactly the available quantity. This is why discussing the boundary added value.
An ordinary pytest test for the last seats would catch the same bug. The useful addition is the chosen example; Gherkin gives the team another way to read and review it.
Restore > in inventory.py, then run the full suite:
uv run pytest -v
Confirm 11 passed before continuing.
For a future rule, agree on its example before changing the implementation. Run it and inspect the failure. A missing step definition or import error needs a wiring fix; a failed expectation can guide the implementation once the test reaches the behavior.
These tests exercise a real inventory in memory. A green result does not establish that a booking page, database transaction, or simultaneous reservation works.
08 / USE BDD DELIBERATELY
Common questions about behavior-driven development.
BDD is useful when a requirement can mean different things to different people. Booking policies, eligibility rules, permissions, and pricing often benefit from concrete examples reviewed together.
Feature files also need maintenance. Similar sentences can become confusing, bindings must stay in sync, and old scenarios can preserve a decision the product no longer wants. Review the example and its outcome when the rule changes.
Is pytest a BDD framework?
Pytest is a Python testing framework. The pytest-bdd plugin connects Gherkin scenarios to pytest tests and fixtures. BDD itself is the practice of discussing and developing shared examples; installing the plugin provides its automation tool.
Does BDD replace unit tests?
No. Keep tests that protect useful behavior at an appropriate level. This companion retains the original tests so you can compare the two forms. A production suite does not need every unit test translated into Gherkin.
Use a few shared scenarios to explain the rule. Ordinary pytest tests can cover further technical cases without making the feature file harder to review.
Do you need Gherkin or Cucumber to practice BDD?
No. Start with a conversation and concrete examples. Gherkin helps when the people responsible for the requirement can read and review those examples. Cucumber and pytest-bdd are tools for automating them.
If only developers read a feature file and it repeats an already-clear Python test, consider whether that extra representation is helping.
Why use pytest-bdd instead of Behave?
Our example already uses pytest, so pytest-bdd lets both test groups share its runner and fixture system. Behave is another Python BDD framework with its own runner and conventions.
Choose around the project’s tools and the team’s review process. Either framework still needs people to agree on the behavior.
What makes a scenario brittle?
A scenario is harder to maintain when it describes incidental details, such as a private helper or a particular button selector, rather than the behavior that matters.
For our inventory, request seats and observe the decision and remaining count. Use browser details when the interaction itself is the requirement being tested.
Takeaway: start your next change with a shared example
We turned booking rules into shared scenarios, connected them to Python, and proved that the last-seats example catches a gap in the original suite.
For your next rule, discuss one normal example, one boundary, and one rejection. Agree on the results, automate them where they can be observed, and use smaller TDD cycles when they help implement the change.
Continue with the Pytest course to practice useful test cases, fixtures, and test automation.
View courseMore field notes
Keep reading.
Test-Driven Development in Python with pytest: A Practical Guide
Build a seat-reservation rule one failing test at a time. Use pytest to see what is missing, protect rejected requests, and refactor with 4 passing cases.
Test-driven developmentpytestHow to Onboard a Python Team to Testing with Pytest
Learn how a 15-developer Python team used shared practice, legacy-code pinch points, and CI to turn pytest into an everyday engineering habit.
pytestPython testingPython Unit Testing Best Practices: 10 pytest Rules
Write Python unit tests that survive refactoring. Use pytest to protect behavior, choose useful cases, control dependencies, and keep the suite fast.
Python unit testingpytest