Intermediate16 min read
Testing & Debugging
Write pytest tests, mock dependencies, and debug with logging and pdb.
Unit Testing with pytest
pytest discovers test_ functions and assert statements with rich failure output. Fixtures inject dependencies and setup/teardown via yield.
Parametrize runs cases across inputs. conftest.py shares fixtures across modules.
Mark slow or integration tests for selective CI runs with -m markers.
- One logical assertion concept per test function
- Use tmp_path fixture for filesystem tests
- Run pytest --cov for coverage trends, not vanity metrics
def test_discount():
assert price_after_discount(100, 0.2) == 80
@pytest.mark.parametrize("n,expected", [(1,1),(2,4)])
def test_square(n, expected):
assert square(n) == expectedMocking and Debugging
unittest.mock.patch replaces functions during tests. pytest-mock provides mocker fixture wrapping pytest style.
logging module configures structured logs better than print for production. pdb.set_trace() or breakpoint() pauses execution in dev.
IDE debuggers integrate breakpoints and variable inspection for complex flows.
- Mock at boundaries: HTTP clients, database, clock
- Use caplog fixture to assert log messages
- Reproduce bugs with minimal failing tests first