Testing and type hints
Professional Python code comes with two safety nets: tests, which prove the code does what it should (and keeps doing so after changes), and type hints, which let tools catch mistakes before the code even runs.
Why test?
Without tests, every change is a gamble: you fix one bug and silently create another. With a good test suite, you run one command and know within seconds whether everything still works. That's what lets teams change code confidently.
assert: the simplest test
The last assertion is wrong (60, not 61), so it fails with our message. Good tests are small, specific, and check one behaviour each.
unittest (built in)
Now break the function on purpose (say, delete bool(user) and) and run again: one test fails and points straight at the problem.
On your computer you'd normally just call
unittest.main(). Theargvandexitarguments let it run inside this editor.
pytest: the community favourite
Most Python projects use pytest: plain functions and plain assert, with excellent failure messages:
# test_pricing.py
import pytest
from pricing import apply_discount
def test_ten_percent_off():
assert apply_discount(100, 10) == 90
@pytest.mark.parametrize("price, percent, expected", [
(100, 0, 100),
(100, 50, 50),
(80, 25, 60),
])
def test_many_cases(price, percent, expected):
assert apply_discount(price, percent) == expected
def test_rejects_negative_percent():
with pytest.raises(ValueError):
apply_discount(100, -5)pip install pytest
pytest # finds every test_*.py file and runs every test_* function
pytest -x -q # stop at the first failure, quiet outputFixtures provide reusable test data and setup:
@pytest.fixture
def cart():
c = ShoppingCart()
c.add("mug", price=8.99, qty=2)
return c
def test_total(cart): # pytest passes the fixture in by name
assert cart.total() == 17.98What to test
- The happy path (normal input), the edge cases (empty, zero, huge, negative), and the error cases (bad input should raise the right exception).
- Behaviour, not implementation details: test what a function returns, not how it computes it.
- When you fix a bug, first write a test that reproduces it. It stays fixed forever.
Mocking
Tests should be fast and repeatable, so replace slow or unpredictable things (network, time, randomness) with mocks:
Type hints
Python is dynamically typed, but you can annotate what types you expect:
Python doesn't enforce hints at run time: they're documentation that tools check. A type checker like mypy or pyright (built into VS Code's Pylance) reads them and catches bugs without running anything:
def greet(name: str) -> str:
return "Hello " + name
greet(42)
# mypy: error: Argument 1 to "greet" has incompatible type "int"; expected "str"Common annotations
| Hint | Meaning |
|---|---|
int, str, float, bool |
The basic types |
list[str], dict[str, int], set[int], tuple[int, int] |
Collections and their contents |
str | None |
Either a string or None (an optional value) |
Callable[[int], str] |
A function taking an int and returning a str (from collections.abc) |
Any |
Opt out of checking (from typing) |
Validating data at run time
Hints aren't checked at run time, so data from outside (JSON, forms, APIs) still needs validation. Pydantic turns type hints into real validation, and it's what FastAPI is built on:
from pydantic import BaseModel, EmailStr # pip install "pydantic[email]"
class SignUp(BaseModel):
email: EmailStr
age: int
SignUp(email="asha@example.com", age="31") # OK: "31" is converted to 31
SignUp(email="not-an-email", age=31) # ValidationError with a clear messageThe professional setup
- pytest for tests, run automatically in CI on every pull request
- mypy or pyright for type checking
- ruff for linting and formatting (fast, replaces flake8, isort and black)
- coverage (
pytest --cov) to see which lines your tests never execute
Practice
- Write
def fizzbuzz(n: int) -> strand aunittest.TestCasewith tests for 3, 5, 15 and 7. - Write
def parse_price(text: str) -> floatthat accepts"$1,299.50", and tests for good input and for invalid input raisingValueError(self.assertRaises(ValueError)).
1.Does Python stop you from calling greet(42) when name: str is annotated?
2.Why use a mock in a test?
3.You just fixed a bug. What's the best next step?