Testing in Python encompasses a rich ecosystem of frameworks, tools, and methodologies for verifying code correctness through unit tests, integration tests, and functional tests. The landscape is dominated by pytest (the modern standard with powerful fixtures and plugins) and unittest (the built-in framework following xUnit patterns), though both share the fundamental goal of catching bugs before production. The key insight: testing isn't just about running assertions—it's about structuring tests for maintainability, isolation, and speed, using fixtures to manage setup/teardown, mocks to control dependencies, and parametrization to test multiple scenarios without code duplication.
What This Cheat Sheet Covers
This topic spans 17 focused tables and 131 indexed concepts. Below is a complete table-by-table outline of this topic, spanning foundational concepts through advanced details.
Table 1: Test Types and Strategies
| Type | Example | Description |
|---|---|---|
def test_add(): assert add(2, 3) == 5 | • Tests a single function or class in complete isolation • fastest and most numerous tests in a well-structured suite. | |
def test_user_repo(): repo = UserRepo(db) assert repo.find(1) is not None | • Tests multiple components working together • slower than unit tests but catches interaction bugs between layers. | |
page.goto("/login")page.fill("#user", "admin")page.click("button[type=submit]") | • Tests the full user workflow through the UI • slowest and fewest, typically powered by Playwright or Selenium. | |
# 1. write failing test (red)# 2. minimal code to pass (green)# 3. improve code (refactor) | • Write a failing test first, make it pass with minimal code, then refactor • drives design through tests. |