Code Reference

Testing Basics

Pytest · Reference cheat sheet

Pytest · Reference cheat sheet


📋 Overview

Pytest discovers and runs tests with rich asserts, fixtures, and plugins. Name files test_*.py / *_test.py, functions test_*. Prefer small focused tests; use fixtures for shared setup.

🔧 Core concepts

IdeaPractice
Arrange–Act–AssertSetup → call → assert
Discoverypytest walks the tree
FixturesInject deps via args
MarkersTag slow/integration/unit
IsolationOne behavior per test

Layers: unit (pure functions), integration (DB/HTTP), e2e (browser — Playwright).

💡 Examples

Minimal test:

# test_math.py
def add(a, b):
    return a + b

def test_add():
    assert add(2, 3) == 5

Run:

pytest -q
pytest tests/test_api.py -k auth
pytest -m "not slow"

Fixture sketch:

import pytest

@pytest.fixture
def client():
    return {"token": "test-token"}

def test_uses_client(client):
    assert client["token"]

⚠️ Pitfalls

  • Don't share mutable state between tests without fixtures + scope care.
  • Over-mocking hides real bugs — mock at boundaries.
  • Huge conftest.py becomes hard to reason about — split by package.

On this page