Tech With Galvan
Back to Articles
TechNov 8, 2026 • 5 min read

Python Testing with pytest: From Zero to Confident

Learn pytest from scratch — fixtures, parametrize, mocking, coverage, and the patterns that make Python tests actually useful.

Galvan
Galvan

Founder & Creator

Introduction

Untested code is legacy code. pytest is Python’s de-facto testing framework — simple, powerful, and the standard in 2026. This post takes you from your first test to fixtures, mocking, and coverage.

Setup

pip install pytest pytest-cov

Step 1: Your first test

Create test_math.py:

def add(a, b):
    return a + b

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

def test_add_negative():
    assert add(-1, 1) == 0

Run:

pytest
# collected 2 items
# test_math.py ..                                          [100%]
# 2 passed in 0.01s

pytest auto-discovers files named test_*.py or *_test.py and functions starting with test_.

Step 2: Assertions (no boilerplate)

pytest uses plain assert — no self.assertEqual:

def test_list():
    items = [1, 2, 3]
    assert 2 in items
    assert len(items) == 3
    assert items == [1, 2, 3]

def test_exception():
    import pytest
    with pytest.raises(ValueError):
        int("abc")

On failure, pytest shows a detailed diff. No extra imports needed.

Step 3: Fixtures (setup/teardown)

import pytest

@pytest.fixture
def sample_user():
    return {"name": "Galvan", "age": 30}

def test_user_name(sample_user):
    assert sample_user["name"] == "Galvan"

def test_user_age(sample_user):
    assert sample_user["age"] == 30

Fixtures are injected by name. They run before each test that uses them.

Teardown with yield

@pytest.fixture
def db_connection():
    conn = create_connection()
    yield conn          # test runs here
    conn.close()        # teardown after test

yield separates setup (before) from teardown (after).

Scope

@pytest.fixture(scope="module")   # once per module
def expensive_resource():
    return load_big_data()

Scopes: function (default), class, module, package, session.

Step 4: Parametrize (test many cases)

import pytest

@pytest.mark.parametrize("a,b,expected", [
    (2, 3, 5),
    (0, 0, 0),
    (-1, 1, 0),
    (100, 200, 300),
])
def test_add(a, b, expected):
    assert add(a, b) == expected

One test function, 4 test cases. Failures show which case failed.

Step 5: Mocking

from unittest.mock import patch, MagicMock

def fetch_user(user_id):
    import requests
    r = requests.get(f"https://api.example.com/users/{user_id}")
    return r.json()

def test_fetch_user():
    with patch("requests.get") as mock_get:
        mock_get.return_value.json.return_value = {"name": "Galvan"}
        result = fetch_user(1)
        assert result["name"] == "Galvan"
        mock_get.assert_called_once_with("https://api.example.com/users/1")

patch replaces the function during the test. Use pytest-mock for a cleaner mocker fixture.

Step 6: Testing exceptions

import pytest

def divide(a, b):
    if b == 0:
        raise ValueError("Cannot divide by zero")
    return a / b

def test_divide_by_zero():
    with pytest.raises(ValueError, match="Cannot divide"):
        divide(10, 0)

match checks the error message with regex.

Step 7: Coverage

pytest --cov=myapp --cov-report=term-missing

Output shows which lines aren’t tested. Aim for 80%+ on business logic; 100% is often impractical.

Step 8: conftest.py (shared fixtures)

Create conftest.py in your test directory — fixtures there are auto-available to all tests:

# conftest.py
import pytest

@pytest.fixture
def client():
    from fastapi.testclient import TestClient
    from main import app
    return TestClient(app)

# test_api.py
def test_health(client):
    r = client.get("/health")
    assert r.status_code == 200

Step 9: Markers

import pytest

@pytest.mark.slow
def test_big_data():
    ...

@pytest.mark.skip(reason="not implemented")
def test_future():
    ...

@pytest.mark.skipif(sys.version_info < (3, 11), reason="needs 3.11+")
def test_new_feature():
    ...

Run only fast tests: pytest -m "not slow".

Step 10: Testing FastAPI/Streamlit

# FastAPI
from fastapi.testclient import TestClient
from main import app

client = TestClient(app)

def test_create_note():
    r = client.post("/notes", json={"title": "Hi", "body": "Hello"})
    assert r.status_code == 201
    assert r.json()["title"] == "Hi"

For Streamlit, use streamlit.testing.v1.AppTest:

from streamlit.testing.v1 import AppTest

def test_app():
    at = AppTest.from_file("app.py")
    at.run()
    assert at.title[0].value == "My App"

Common mistakes

  • Testing implementation, not behavior — test what the function does, not how. Refactoring shouldn’t break tests.
  • No isolation — tests sharing state (global variables, files) cause flaky failures. Use fixtures + teardown.
  • Ignoring failures — pytest with --cov-fail-under=80 fails CI if coverage drops.
  • Slow tests in the main suite — mark slow tests and run them separately in CI.
  • Mocking everything — over-mocking tests the mock, not the code. Mock external services, not your own logic.

Key Concepts

  • pytest = test discovery + assertions + fixtures
  • Fixture = reusable setup/teardown
  • Parametrize = one test, many cases
  • Mock = replace dependencies in tests
  • Coverage = measure what’s tested

What to Try Next

  • Add tests to your FastAPI backend.
  • Test your Streamlit app with AppTest.
  • Add pytest to CI (GitHub Actions) — run on every PR.
  • Combine with type hints — mypy + pytest = strong safety net.

FAQ

pytest vs unittest?

unittest is built-in but verbose (classes, self.assertEqual). pytest is simpler (functions, plain assert), has better output, and a richer plugin ecosystem. For new projects, pytest is the default.

Do I need 100% coverage?

No. 80% on business logic is a good target. 100% is often impractical and tests trivial code. Focus on critical paths and edge cases.

How do I test async code?

Use pytest-asyncio:

import pytest

@pytest.mark.asyncio
async def test_fetch():
    result = await fetch_data()
    assert result is not None