Level: Advanced | Prerequisite: Week 5
Learning Goals
- Basic usage of pytest
- Various cases with
parametrize - Common setup with
fixture - Isolate external dependencies using mock
1. Why test?
- Prevent regression (ensure functionality when code changes)
- Serve as specification (document intent)
- Safety net for refactoring
2. pytest basics
pip install pytest
Test files are test_*.py or *_test.py.
# test_calc.py
def add(a, b): return a + b
def test_add():
assert add(2, 3) == 5
assert add(-1, 1) == 0
pytest #Run All
pytest test_calc.py #Single File
pytest -v # verbose
pytest -k "add" #Name Matching
3. parametrize
Run the same test with multiple inputs.
import pytest
@pytest.mark.parametrize("a,b,expected", [
(1, 2, 3),
(-1, 1, 0),
(0, 0, 0),
(100, 200, 300),
])
def test_add(a, b, expected):
assert add(a, b) == expected
4. fixture
Common setup code.
@pytest.fixture
def sample_users():
return [{"name": "Alice"}, {"name": "Bob"}]
def test_first(sample_users):
assert sample_users[0]["name"] == "Alice"
def test_count(sample_users):
assert len(sample_users) == 2
Scope (session, module, function):
@pytest.fixture(scope="module")
def expensive():
print("Setup just once")
return ...
5. Exception validation
def divide(a, b):
if b == 0:
raise ValueError("0 division")
return a / b
def test_divide_by_zero():
with pytest.raises(ValueError, match="0 division"):
divide(10, 0)
6. mock
Fake external dependencies (API, DB).
from unittest.mock import patch, MagicMock
def get_weather(city):
import requests
return requests.get(f"https://api/{city}").json()
def test_get_weather():
with patch("requests.get") as mock_get:
mock_get.return_value.json.return_value = {"temp": 20}
assert get_weather("seoul") == {"temp": 20}
7. Coverage
pip install pytest-cov
pytest --cov=mypackage --cov-report=term-missing
Key Examples (examples/)
| File | Content |
|---|---|
01_basic_test.py |
Basic assert |
02_parametrize.py |
parametrize |
03_fixture.py |
fixture |
04_mock.py |
unittest.mock |
⚠️ Common Mistakes
- Test function does not start with
test_— pytest cannot find it - Dependency between tests — fails if execution order changes. Should be independent
- Changing global state — setup/teardown with fixture
- Calling real external API — slow and unstable. Use mock
❓ FAQ
Q1. unittest or pytest? A. Standard is unittest. For new projects, pytest is overwhelmingly recommended (concise, powerful).
Q2. Do we have to do TDD? A. Not necessarily, but recommended. At minimum, test the core functionalities.
Q3. What about UI testing? A. Separate tools like Selenium, Playwright, etc.
📝 Exercises (exercises/)
exercise1.md— Intermediate OOP code testingexercise2.md— Parameterize various casesexercise3.md— Test API calls with mocks
Next Week
Week 7. Web Scraping