Testing & Debugging
Write robust code with pytest, unit testing, and advanced debugging techniques.
Why Test?
Tests prevent regressions, document behavior, and make refactoring safer. Python's standard tool is pytest.
Writing Tests with pytest
# app.py
def add(a, b):
return a + b
# test_app.py
from app import add
def test_add():
assert add(2, 3) == 5
assert add(-1, 1) == 0
def add(a, b):
return a + b
# test_app.py
from app import add
def test_add():
assert add(2, 3) == 5
assert add(-1, 1) == 0
Running Tests
$ pytest
======= test session starts =======
collected 1 item
test_app.py . [100%]
======= test session starts =======
collected 1 item
test_app.py . [100%]
Fixtures and Parameterization
import pytest
@pytest.mark.parametrize("a, b, expected", [(1,2,3), (0,5,5)])
def test_add_parameterized(a, b, expected):
assert add(a, b) == expected
@pytest.mark.parametrize("a, b, expected", [(1,2,3), (0,5,5)])
def test_add_parameterized(a, b, expected):
assert add(a, b) == expected
Debugging with pdb
The Python Debugger (pdb) lets you pause execution and inspect state.
import pdb
x = 10
pdb.set_trace() # Breakpoint
y = x * 2
x = 10
pdb.set_trace() # Breakpoint
y = x * 2
โ Practice (30 minutes)
- Install pytest:
pip install pytest. - Write tests for a function that checks if a string is a palindrome.
- Use a pytest fixture to provide a mock database connection to your tests.
- Learn common pdb commands:
n(next),s(step),c(continue),p variable(print).