Testing Best Practices in Python
Introduction Python's testing tools are lightweight enough that it's easy to write a lot of tests without writing good ones. A suite that mocks every collaborator, duplicates the same assertion ten times with different inputs pasted in by hand, or chases a coverage number will pass in CI and still miss real bugs. pytest gives you fixtures, parametrize , and monkeypatch — the tools that make it just as easy to write the right tests as the wrong ones. This post covers how to use them well. Test at the Right Level: the Pyramid Not every test should look the same. The test pyramid is a rough guide to where your effort should go: Unit tests — the bulk of the suite. Pure functions and classes, no I/O, no real database. Milliseconds each. Integration tests — fewer of these. Verify the seams : does your ORM query actually produce correct SQL against a real database, does your HTTP client actually parse a real response. End-to-end tests — a handful. Cover the critical flows through the whole stack, accepting they're slower and more brittle. # Unit — pure logic, no database, no framework def test_applies_ten_percent_discount_for_orders_over_100 (): calculator = DiscountCalculator () total = calculator . apply ( order_total = 150.0 ) assert total == pytest . approx ( 135.0 ) # Integration — the seam that matters: our query against a real database import pytest @pytest.fixture def db_session ( postgres_container ): # real Postgres in a test container, not mocked with postgres_container . session () as session : yield session def test_finds_orders_placed_in_the_last_week ( db_session ): db_session . add ( Order ( id = " ord-1 " , placed_at = datetime . now ( UTC ))) db_session . commit () recent = order_repository . find_recent ( db_session , within = timedelta ( days = 7 )) assert len ( recent ) == 1 A unit suite that never touches a database runs in seconds and catches most logic bugs. A handful of integration tests catch what only shows up at the boundary — the query that's s