XenonStack

DevOps

XenonStack Blog TDD in Python: pytest, unittest and BDD Guide

and | Published | Updated

TDD in Python: pytest, unittest and BDD Guide
14:31

Key takeaway

  • Test-driven development in Python: red-green-refactor with pytest and unittest, mocking with unittest.mock, BDD tools, and why nose is no longer advised.

Test-driven development (TDD) in Python means writing a failing test, adding the smallest code that makes it pass, then refactoring with the tests green. For most teams the practical stack in 2026 is pytest for day-to-day tests, the standard-library unittest and unittest.mock where no extra dependency is wanted, and a BDD layer only where business stakeholders read the scenarios. The older nose runner is now a poor choice for new work.

This guide is the Python companion to our general guide to test-driven development, which covers the method itself, TDD against BDD and ATDD, and AI coding agents. Here we cover the Python tools, a worked example you can run, mocking without hollow tests, and the adoption sequence we would use for an engineering organisation.

Which Python test tool should a team standardise on?

Pick one runner for the whole organisation and let the rest be libraries. The table below shows what each tool is for and its status on the project's own documentation, as read on 11 November 2026.

ToolWhat it doesWhen it fitsCurrent status
pytestPlain assert statements with detailed failure output, fixtures, automatic test discovery, and it runs existing unittest suitesDefault for new services and for teams moving off older runnersDocumentation shows the 9.x line; needs Python 3.10 or later, or PyPy 3
unittestThe standard-library framework: TestCase classes, setUp and tearDown, assertRaises, discovery with python -m unittest discoverLibraries and locked-down environments that cannot add dependenciesPart of Python; current documentation covers Python 3.15
unittest.mockMock, MagicMock and patch() to replace collaborators and assert how they were calledIsolating code from networks, databases, clocks and third-party servicesPart of the standard library; works under pytest as well
noseOlder test runnerExisting suites onlyIts own page says it has been in maintenance mode for several years and may cease without new maintainers
nose2Extends unittest with plugins and a params decoratorSuites that already depend on itVersion 0.16.0; its documentation encourages considering pytest for new projects
behaveBDD in Python with scenarios in natural language backed by Python step codeTeams where product or QA staff write and read scenariosDocumentation is for 1.4.0.dev0, a development build
pytest-bddGherkin .feature files bound to Python steps, run as ordinary pytest testsBDD without a second runnerDocumentation lists Python 3.10 to 3.14

Sources: pytest, unittest, unittest.mock, nose, nose2, behave and pytest-bdd.

How do you run red, green, refactor in Python?

We use a small banking example. The business has added a credit and debit facility, so before writing any code we write the tests that describe it. Use this layout: an app/banking_app.py module, a tests/ folder and an empty __init__.py in both, run from the project root.

Two-column diagram mapping needs to Python tools: runner to pytest or unittest, setup to fixtures, external calls to unittest.mock patch, readable scenarios to pytest-bdd or behave

Red: write one failing test

# tests/test_banking.py
import pytest
from app.banking_app import Banking


def test_credit_returns_new_balance():
    bank = Banking(balance=1000)
    assert bank.credit(500) == 1500

Run pytest. It fails with an import error because Banking does not exist yet. That failure is useful: it proves the test can fail, so a later pass means something.

Green: write the smallest code that passes

# app/banking_app.py
class Banking:
    def __init__(self, balance=0):
        self.balance = balance

    def credit(self, amount):
        self.balance += amount
        return self.balance

Add the next behaviours as tests first

The old version of this tutorial rejected only strings. A real ledger must also reject None, booleans (which Python treats as integers), zero, negative amounts and overdrafts. Write each rule as a test before the code, using pytest.mark.parametrize so one test function runs once per input.

@pytest.fixture
def bank():
    return Banking(balance=1000)


def test_debit_returns_new_balance(bank):
    assert bank.debit(700) == 300


@pytest.mark.parametrize("bad", ["two", None, True, -5, 0])
def test_credit_rejects_invalid_amounts(bank, bad):
    with pytest.raises(ValueError):
        bank.credit(bad)


def test_debit_rejects_overdraft(bank):
    with pytest.raises(ValueError):
        bank.debit(1001)

Refactor with the tests green

from numbers import Real


class Banking:
    def __init__(self, balance=0):
        self.balance = balance

    @staticmethod
    def _check(amount):
        if isinstance(amount, bool) or not isinstance(amount, Real):
            raise ValueError("amount must be a number")
        if amount <= 0:
            raise ValueError("amount must be positive")

    def credit(self, amount):
        self._check(amount)
        self.balance += amount
        return self.balance

    def debit(self, amount):
        self._check(amount)
        if amount > self.balance:
            raise ValueError("insufficient funds")
        self.balance -= amount
        return self.balance

The duplicated type check from the first two methods moved into one helper, and the suite stayed green throughout. We ran this exact code on Python 3.13 with pytest; all tests passed. The same tests written with unittest.TestCase use setUp to build the fixture and with self.assertRaises(ValueError): for the error cases, and can be run with python -m unittest from the project root.

How do pytest fixtures and parametrize keep tests short?

A fixture is a function that prepares data or state. A test asks for it by naming it as an argument, and each test gets its own result, which keeps tests isolated. The default scope is function; class, module, package and session keep the value for longer. For cleanup, use yield instead of return and put the teardown after it. Use wide scopes only for expensive, read-only resources such as a test database schema, because shared mutable state is the most common source of order-dependent failures.

@pytest.mark.parametrize runs one test once for each set of arguments, and stacked decorators produce every combination. Treat the parameter list as the specification table for a rule.

How do you mock dependencies without writing hollow tests?

unittest.mock.patch() replaces an object for the length of a test and restores it afterwards. The rule that causes most confusion is where to patch: the documentation says you patch where an object is looked up, which is not necessarily where it is defined. If alerts.py does import requests and calls requests.post, patch app.alerts.requests.post.

# app/alerts.py
import requests


def notify_if_low(bank, threshold, url):
    if bank.balance < threshold:
        requests.post(url, json={"balance": bank.balance}, timeout=5)
        return True
    return False


# tests/test_alerts.py
from unittest.mock import patch
from app.alerts import notify_if_low
from app.banking_app import Banking


@patch("app.alerts.requests.post")
def test_low_balance_sends_alert(post):
    assert notify_if_low(Banking(50), 100, "https://example.test/hook") is True
    post.assert_called_once()

Two cautions. First, never patch the function you are testing: the older version of this post patched Banking.credit and then called it, which proves nothing about the real code. Mock only the boundary, such as the network call. Second, pass autospec=True to patch() where you can, so the mock enforces the real call signature and a wrong call fails as it would in production. For database-backed code, see our guide to database unit testing.

Where does BDD fit with TDD in Python?

TDD tests are written by developers to drive design. BDD scenarios describe behaviour in plain language so that product owners and testers can read them. In Python there are two routes. behave is a dedicated BDD tool with its own runner. pytest-bdd binds Gherkin .feature files to Python step functions with @given, @when and @then and runs them as ordinary pytest tests, so fixtures work inside steps.

Our recommendation is to keep BDD for a small set of business-critical journeys and to write everything else as pytest unit tests. A scenario is only worth its upkeep if someone outside engineering reads it. Acceptance-level scenarios can sit on top of the unit suite without replacing it.

What has changed since the nose-era approach?

Older practiceCurrent practiceWhy it matters
pip install nose and nosetestspytest, or the standard-library unittestnose describes itself as in maintenance mode and its documentation recommends pytest or unittest for new projects
Python 2 and early Python 3 test outputPython 3.10 or later for current pytestSupported tooling follows supported Python versions
assertEqual and a long list of assert methodsPlain assert with pytest introspectionShorter tests and more readable failures
Hand-written setup in each testFixtures with explicit scopeLess duplication and clearer isolation
Tests written by people onlyTests as the specification for AI coding agentsAgents need a failing test to turn green; people must still own and review the tests

Inside XenonStack, our engineering teams have adopted an agentic TDD practice on internal platform work: a shared skills file defines the steps, and the team enabled it on one repository first before extending it to others. The point we would pass on is the sequencing: prove the workflow on one codebase, then roll it out.

What are the governance, cost and trade-offs?

  • Cost: expect slower first deliveries while the team learns the habit. Published studies of industrial teams report a defect reduction alongside extra development time; we cover the figures in our TDD guide.
  • Governance: treat tests as the specification. Require review of any change that deletes an assertion, skips a test or edits an expected value, whether the author is a person or an agent. For AI-built systems, quality checks on agent workflows belong in the pipeline: AgentQA is the ElixirData agent for automated quality assurance of AI, and ElixirClaw is an agentic OS platform to build, orchestrate and govern AI agents and automation workflows while keeping humans in control.
  • Security: never put real credentials or production data in fixtures; mock the boundary instead.
  • When not to use strict TDD: throwaway scripts, exploratory data analysis, and UI layout work where the feedback comes from looking at the screen. Test these after the design settles. For data science code, see unit testing of machine learning.

What adoption sequence works for an engineering organisation?

  • Weeks 1 to 2: choose pytest, set the Python version, and add the runner to continuous integration so failing tests block a merge.
  • Weeks 3 to 4: run red, green, refactor on new code in one service. Review tests in pull requests as closely as code.
  • Next: add fixtures and parametrised tables for shared rules, and add mocks only at the boundaries.
  • Then: add pytest-bdd or behave for a handful of business journeys, if stakeholders will read them.
  • Finally: migrate legacy nose suites file by file, since pytest runs unittest-style tests unchanged.

The week numbers are a suggested pace, not a benchmark. For the wider testing picture, read our guide to unit testing techniques and best practices. Other languages are covered in TDD for Java with JUnit and TDD with React and Jest.

To map one release decision your teams and AI agents make, and the tests, context and policy it depends on, book a Context Workshop. See what happens in the workshop.

Frequently asked questions

What is test-driven development in Python?

It is a cycle of writing a failing test, writing the smallest code that passes it, then refactoring while the tests stay green. In Python it is usually done with pytest or the standard-library unittest module.

Should we use pytest or unittest for TDD?

Use pytest for new work: it uses plain assert statements, has fixtures and runs existing unittest tests. Use unittest where you cannot add dependencies, since it ships with Python.

Is nose still a good choice?

No for new projects. The nose documentation says it has been in maintenance mode for several years and may stop without new maintainers, and it recommends pytest or unittest. nose2 is a separate project that also points readers to pytest.

Where should we patch with unittest.mock?

Patch where the object is looked up, not where it is defined. If your module imports requests and calls requests.post, patch that name inside your module.

When should a Python team use BDD tools?

Use behave or pytest-bdd when product owners or testers will read the scenarios. pytest-bdd runs Gherkin scenarios as ordinary pytest tests; keep unit tests in plain pytest.

Next Steps towards Test-driven Development

Connect with our experts to learn how Test Driven Development (TDD) boosts code quality and efficiency. By adopting a test-first approach, teams can build stronger systems, reduce bugs, and automate testing for smoother development. TDD fosters faster feedback, continuous integration, and optimized workflows, ensuring better software and faster delivery

Follow XenonStack on LinkedIn: XenonStack on LinkedIn for new guides on agentic AI, data and platform engineering.

Table of Contents

navdeep-singh-gill

Navdeep Singh Gill

Global CEO and Founder of XenonStack

LinkedIn profile

Navdeep Singh Gill is serving as Chief Executive Officer and Product Architect at XenonStack. He holds expertise in building SaaS Platform for Decentralised Big Data management and Governance, AI Marketplace for Operationalising and Scaling. His incredible experience in AI Technologies and Big Data Engineering thrills him to write about different use cases and its approach to solutions.

Get the latest articles in your inbox

Subscribe Now

Interested in Solving your Challenges with XenonStack Team
Get Started

Get Started with your requirements and primary focus, that will help us to make your solution

Please Select your Industry
Banking
Fintech
Payment Providers
Wealth Management
Discrete Manufacturing
Semiconductor
Machinery Manufacturing / Automation
Appliances / Electrical / Electronics
Elevator Manufacturing
Defense & Space Manufacturing
Computers & Electronics / Industrial Machinery
Motor Vehicle Manufacturing
Food and Beverages
Distillery & Wines
Beverages
Shipping
Logistics
Mobility (EV / Public Transport)
Energy & Utilities
Hospitality
Digital Gaming Platforms
SportsTech with AI
Public Safety - Explosives
Public Safety - Firefighting
Public Safety - Surveillance
Public Safety - Others
Media Platforms
City Operations
Airlines & Aviation
Defense Warfare & Drones
Robotics Engineering
Drones Manufacturing
AI Labs for Colleges
AI MSP / Quantum / AGI Institutes
Retail Apparel and Fashion

Proceed Next