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, 105 flashcards. Below is a complete table-by-table outline of this topic, spanning foundational concepts through advanced details.
A jump-to index of every table row in this cheat sheet.
An interactive map of every table and concept in this topic.
Table 1: Test Types and Strategies
Not all tests are equal, and choosing the right kind is the first design decision in any test suite. These range from tiny, fast unit checks up to slow end-to-end flows, with the test pyramid offering the rule of thumb for how many of each to write—many at the bottom, few at the top.
| 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. | ||
Given I have valid credentialsWhen I log inThen I see the dashboard | • Tests written as human-readable Gherkin scenarios • bridges developers and non-technical stakeholders. | ||
~70% unit / ~20% integration / ~10% e2e | Guideline for test ratio: many fast unit tests at the base, fewer slow e2e tests at the top. | ||
def test_app_starts(): | • Fast sanity check that critical paths work after a deployment • run as a subset of the full suite. | ||
def test_bug_1234(): assert fixed_behavior() | • Verifies a previously fixed bug has not reappeared • every bug fix should have a corresponding test. |