Learn to Code
All tracks
Learn to Code

Free lessons from scratch to pro — every language, databases and DevOps.

AboutContactPrivacy PolicyTerms of Use

Your progress is saved in this browser. © 2026 Learn to Code

PY
Python
0/14 completed
Beginner
Hello PythonVariables and typesWorking with stringsConditions and loopsFunctions
Intermediate
Lists, tuples, dicts and setsFiles and exceptionsModules and the standard library
Advanced
Classes and OOPIterators and generatorsDecorators and context managers
Pro
Async PythonTesting and type hintsVirtual environments, packages and real projects
Tracks / Python / Pro

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

Python · editable

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)

Python · editable

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(). The argv and exit arguments let it run inside this editor.

pytest: the community favourite

Most Python projects use pytest: plain functions and plain assert, with excellent failure messages:

python
# 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)
bash
pip install pytest
pytest              # finds every test_*.py file and runs every test_* function
pytest -x -q        # stop at the first failure, quiet output

Fixtures provide reusable test data and setup:

python
@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.98

What 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:

Python · editable

Type hints

Python is dynamically typed, but you can annotate what types you expect:

Python · editable

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:

python
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)
Python · editable

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:

python
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 message

The 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

  1. Write def fizzbuzz(n: int) -> str and a unittest.TestCase with tests for 3, 5, 15 and 7.
  2. Write def parse_price(text: str) -> float that accepts "$1,299.50", and tests for good input and for invalid input raising ValueError (self.assertRaises(ValueError)).
Python · editable
✎ Check your understanding

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?

← Async Python