█
LastWrite
  • > Curriculum
  • > Pricing
  • > For Educators
  • > About
  • > Contact
Log InGet Started

Questions, concerns, bug reports, or suggestions? We read every message, write to us at [email protected].

More ways to reach us →
LastWrite

Structured computer science lessons for aspiring developers and security professionals.

[email protected]

(201) 785-7951

Mon–Fri, 9 AM–5 PM EST

Learn

  • Curriculum
  • Pricing

Company

  • About
  • For Educators & Schools
  • Contact Us

Legal

  • Terms of Service
  • Privacy Policy
© 2026 LastWrite. All rights reserved.
Curriculum/Programming Languages/Python (Professional)/Testing in Python with pytest
50 minIntermediate

Testing in Python with pytest

After this lesson, you will be able to: Write tests with pytest: fixtures, parametrize, mocking, and coverage.

Tests are how you ship without fear. pytest is the standard.

Prerequisites:Python Standard Library

pytest in 30 lines

Drop test_*.py files alongside your code.

python
# test_math.py
import pytest
from mymodule import add, divide
def test_add():
assert add(2, 3) == 5
def test_divide_by_zero():
with pytest.raises(ZeroDivisionError):
divide(10, 0)
@pytest.mark.parametrize("a,b,expected", [
(1, 1, 2),
(0, 0, 0),
(-1, 1, 0),
])
def test_add_cases(a, b, expected):
assert add(a, b) == expected
# Run: pytest
# Run with coverage: pytest --cov=mymodule

Fixtures + mocking

Fixtures = setup helpers. Mocks = replace dependencies during tests.

python
import pytest
from unittest.mock import patch, MagicMock
@pytest.fixture
def sample_user():
return {"name": "Alex", "email": "[email protected]"}
def test_uses_fixture(sample_user):
assert sample_user["name"] == "Alex"
# Mock external API
@patch("mymodule.requests.get")
def test_fetch(mock_get):
mock_get.return_value = MagicMock(
status_code=200,
json=lambda: {"ok": True},
)
from mymodule import fetch
assert fetch("http://x")["ok"] is True
mock_get.assert_called_once_with("http://x")

Coverage + CI

pip install pytest-cov. `pytest --cov=mypackage --cov-report=term-missing` shows uncovered lines. Aim for 60-80% on logic code (not getters/types). In CI: fail builds when coverage drops by more than X%. Use pytest + coverage.py + codecov.

Common mistakes only experienced Python devs avoid

Test files in src/ folder rather than tests/. Mixes prod + test code. Mocking everything until tests pass but real system is broken. Mock at the boundary only. Skipping pytest.raises. Catching with try/except in tests loses the pytest assertion. Hardcoded sleep() in tests. Use freezegun or pytest-asyncio properly.

Quick Check

What's the cleanest way to test a function with many input/output cases?

Pick the canonical pytest pattern.

Sign in and purchase access to unlock this lesson.

Sign in to purchase
←Python Standard Library Deep Dive
Back to Python (Professional)
Python for Scripting and Automation→