Part 11 / Stage 2
Testing and code quality
Goal: Find bugs with a debugger, prove your code works with pytest, and keep it clean with logging, type hints, Ruff and Git. Time: ~1 hour
What you will learn
- Why we test, and manual vs automated testing
- Debugging: reading tracebacks,
breakpoint()and pdb, the VS Code debugger assertand its limits- pytest basics: install, naming, running, reading results,
-q,-k,-x - pytest features:
pytest.raises,parametrize, fixtures,tmp_path,pytest.approx - What to test: happy path, edge cases, errors; Arrange-Act-Assert
unittestanddoctestfrom the standard library- Logging instead of
print - Type hints in depth, and checking them with mypy
- PEP 8, Ruff, pre-commit and Google-style docstrings
- Git and GitHub basics
- Putting it together: fully testing a grade calculator
Folder map
part-11-testing-and-code-quality/
├── examples/ shop.py and grade_calculator.py (code under test) + 01_…07_ demos
├── tests/ conftest.py, test_shop.py, test_grade_calculator.py
├── exercises.md
└── solutions/ ex01.py … ex07.py (each has the function AND its tests)
Topics in this part
Practice
Python workbench — write and run code here
Press Run and Python 3.14 loads right in your browser (a one-time download of about 15 MB; after that it works offline). Your code never leaves this page. input() opens a small prompt window.
How to work: put each function and its tests in one file, for example ex03.py. Add a main() demo under if __name__ == "__main__":. Then the file runs two ways:
python ex03.py # the demo: prints the Sample output below
python -m pytest -q ex03.py # pytest runs the test_ functions in the file
(macOS/Linux: python3.) pytest collects a file you name on the command line even if it does not start with test_. For a real project, keep tests in a tests/ folder like this part does.
The last line of pytest output (for example 4 passed in 0.01s) shows the time, which changes on every run. Only the number of tests must match.
Exercise 1: First tests for a PIN code checker
Scenario: A delivery app must reject wrong Indian PIN codes (6 digits, the first digit is not 0). What to do:
- Copy
is_valid_pinfrom the starting data. - Write four tests:
test_valid_pin,test_too_short_pin,test_pin_with_letters,test_pin_starting_with_zero. - In
main(), print each sample PIN and its result.
Starting data:
def is_valid_pin(pin: str) -> bool:
return len(pin) == 6 and pin.isdigit() and pin[0] != "0"
SAMPLE_PINS = ["560001", "5600", "56A001", "012345"]
Sample output:
560001 -> True
5600 -> False
56A001 -> False
012345 -> False
pytest: 4 passed
💡 Hint: Each test is one line, like assert is_valid_pin("560001") is True. Print with f"{pin:<7} -> {is_valid_pin(pin)}".
Show the solution to Exercise 1
"""Exercise 1: First pytest tests for a PIN code checker.
The function and its tests live in the same file, so it can be run two ways:
Run: python ex01.py quick demo (macOS/Linux: python3 ex01.py)
Run: python -m pytest -q ex01.py runs the test_ functions
"""
def is_valid_pin(pin: str) -> bool:
"""Return True for an Indian PIN code: exactly 6 digits, not starting with 0."""
return len(pin) == 6 and pin.isdigit() and pin[0] != "0"
SAMPLE_PINS = ["560001", "5600", "56A001", "012345"]
# ---------- Tests ----------
def test_valid_pin():
assert is_valid_pin("560001") is True
def test_too_short_pin():
assert is_valid_pin("5600") is False
def test_pin_with_letters():
assert is_valid_pin("56A001") is False
def test_pin_starting_with_zero():
assert is_valid_pin("012345") is False
def main() -> None:
for pin in SAMPLE_PINS:
print(f"{pin:<7} -> {is_valid_pin(pin)}")
if __name__ == "__main__":
main()
Exercise 2: Let a test find the bug
Scenario: A food app shows the average star rating of a restaurant. Customers say the stars look too high. What to do:
- Copy the buggy
average_rating. Writetest_average_of_three_ratingsthat expectsaverage_rating([4, 5, 3]) == 4.0. Run pytest and read the failure: what number did you get? - Fix the bug. Add
test_average_of_one_rating([5]→5.0) andtest_average_is_rounded([5, 4, 4]→4.3). - Make an empty list raise
ValueError("no ratings yet")and test it withpytest.raises. - In
main(), print the three averages, then try[]and print the error.
Starting data:
def average_rating(ratings: list[int]) -> float:
return round(sum(ratings) / (len(ratings) - 1), 1)
Sample output:
4.0
5.0
4.3
Error: no ratings yet
pytest: 4 passed
💡 Hint: The first run shows assert 6.0 == 4.0. Divide by len(ratings). Check if not ratings: first.
Show the solution to Exercise 2
"""Exercise 2: Let a test find the bug, then fix it.
The old version divided by `len(ratings) - 1`, so [4, 5, 3] gave 6.0.
The fixed version divides by len(ratings) and refuses an empty list.
Run: python ex02.py quick demo (macOS/Linux: python3 ex02.py)
Run: python -m pytest -q ex02.py runs the test_ functions
"""
import pytest
def average_rating(ratings: list[int]) -> float:
"""Return the average star rating, rounded to 1 decimal.
Raises:
ValueError: If there are no ratings.
"""
if not ratings:
raise ValueError("no ratings yet")
return round(sum(ratings) / len(ratings), 1) # fixed: was len(ratings) - 1
# ---------- Tests ----------
def test_average_of_three_ratings():
assert average_rating([4, 5, 3]) == 4.0
def test_average_of_one_rating():
assert average_rating([5]) == 5.0
def test_average_is_rounded():
assert average_rating([5, 4, 4]) == 4.3
def test_empty_ratings_raise():
with pytest.raises(ValueError, match="no ratings"):
average_rating([])
def main() -> None:
print(average_rating([4, 5, 3]))
print(average_rating([5]))
print(average_rating([5, 4, 4]))
try:
average_rating([])
except ValueError as error:
print("Error:", error)
if __name__ == "__main__":
main()
Exercise 3: Ticket price boundaries with parametrize
Scenario: A museum charges by age: under 5 free, 5 to 17 ₹100, 18 to 59 ₹200, 60 and over ₹120. What to do:
- Write
ticket_price(age)that returns the price as anint. A negative age raisesValueError. - Write one test
test_ticket_price(age, expected)with@pytest.mark.parametrizethat checks both sides of every boundary: 0, 4, 5, 17, 18, 59, 60, 85. - Write
test_negative_age_raises. - In
main(), print the price for ages 4, 5, 17, 18, 59, 60.
Sample output:
age 4: ₹0
age 5: ₹100
age 17: ₹100
age 18: ₹200
age 59: ₹200
age 60: ₹120
pytest: 9 passed (8 rows + 1 error test)
💡 Hint: @pytest.mark.parametrize(("age", "expected"), [(0, 0), (4, 0), (5, 100), ...]). Format the age with {age:>2}.
Show the solution to Exercise 3
"""Exercise 3: Test every age boundary of a ticket price with parametrize.
Run: python ex03.py quick demo (macOS/Linux: python3 ex03.py)
Run: python -m pytest -q ex03.py runs the test_ functions
"""
import pytest
def ticket_price(age: int) -> int:
"""Return the museum ticket price in rupees for this age.
Under 5: free. 5-17: ₹100. 18-59: ₹200. 60 and over: ₹120.
Raises:
ValueError: If age is negative.
"""
if age < 0:
raise ValueError(f"age cannot be negative: {age}")
if age < 5:
return 0
if age < 18:
return 100
if age < 60:
return 200
return 120
# ---------- Tests ----------
@pytest.mark.parametrize(
("age", "expected"),
[
(0, 0),
(4, 0),
(5, 100),
(17, 100),
(18, 200),
(59, 200),
(60, 120),
(85, 120),
],
)
def test_ticket_price(age, expected):
assert ticket_price(age) == expected
def test_negative_age_raises():
with pytest.raises(ValueError):
ticket_price(-1)
def main() -> None:
for age in [4, 5, 17, 18, 59, 60]:
print(f"age {age:>2}: ₹{ticket_price(age)}")
if __name__ == "__main__":
main()
Exercise 4: Test the errors of a bank withdrawal
Scenario: A bank app must refuse a zero or negative withdrawal, and a withdrawal bigger than the balance. What to do:
- Create
class InsufficientFundsError(Exception). - Write
withdraw(balance, amount)that returns the new balance. RaiseValueError(f"amount must be positive, got {amount}")whenamount <= 0. RaiseInsufficientFundsError(f"balance ₹{balance:,} is less than ₹{amount:,}")whenamount > balance. - Tests:
test_withdraw_reduces_balance,test_withdraw_whole_balance_leaves_zero, a parametrizedtest_zero_or_negative_amount_raises(amounts0and-100), andtest_too_much_raises_insufficient_fundsthat usesmatch="less than ₹6,000". - In
main(), withdraw 1200 from 5000, then try 0 and 6000 and print the error type and message.
Sample output:
New balance: 3800
ValueError: amount must be positive, got 0
InsufficientFundsError: balance ₹5,000 is less than ₹6,000
pytest: 5 passed
💡 Hint: Catch both with except (ValueError, InsufficientFundsError) as error: and print type(error).__name__.
Show the solution to Exercise 4
"""Exercise 4: Test the errors of a bank withdrawal with pytest.raises.
Run: python ex04.py quick demo (macOS/Linux: python3 ex04.py)
Run: python -m pytest -q ex04.py runs the test_ functions
"""
import pytest
class InsufficientFundsError(Exception):
"""Raised when a withdrawal is bigger than the balance."""
def withdraw(balance: float, amount: float) -> float:
"""Return the new balance after taking out amount.
Raises:
ValueError: If amount is 0 or negative.
InsufficientFundsError: If amount is more than balance.
"""
if amount <= 0:
raise ValueError(f"amount must be positive, got {amount}")
if amount > balance:
raise InsufficientFundsError(f"balance ₹{balance:,} is less than ₹{amount:,}")
return balance - amount
# ---------- Tests ----------
def test_withdraw_reduces_balance():
assert withdraw(5000, 1200) == 3800
def test_withdraw_whole_balance_leaves_zero():
assert withdraw(5000, 5000) == 0
@pytest.mark.parametrize("amount", [0, -100])
def test_zero_or_negative_amount_raises(amount):
with pytest.raises(ValueError, match="must be positive"):
withdraw(5000, amount)
def test_too_much_raises_insufficient_funds():
with pytest.raises(InsufficientFundsError, match="less than ₹6,000"):
withdraw(5000, 6000)
def main() -> None:
print("New balance:", withdraw(5000, 1200))
for amount in [0, 6000]:
try:
withdraw(5000, amount)
except (ValueError, InsufficientFundsError) as error:
print(f"{type(error).__name__}: {error}")
if __name__ == "__main__":
main()
Exercise 5: Fixtures and tmp_path for a contacts file
Scenario: A phone book app saves contacts to a JSON file and finds people by city. What to do:
- Write
save_contacts(path, contacts)andload_contacts(path)(JSON,encoding="utf-8").load_contactsreturns[]if the file does not exist. - Write
find_by_city(contacts, city)that returns the names in that city, ignoring upper/lower case. - Write a fixture
contactsthat returns the starting data. - Tests:
test_save_then_load_gives_same_contacts(usetmp_path),test_load_missing_file_gives_empty_list,test_find_by_city_ignores_case("pune"),test_find_by_unknown_city("Delhi"). - In
main(), save todemo_contacts.jsonnext to your file, load it, print the count and the Pune names, delete the file, then load again.
Starting data:
contacts = [
{"name": "Asha", "city": "Pune"},
{"name": "Ravi", "city": "Chennai"},
{"name": "Neha", "city": "Pune"},
]
Sample output:
Loaded 3 contacts
In Pune: ['Asha', 'Neha']
After delete: []
pytest: 4 passed
💡 Hint: path = tmp_path / "contacts.json". Compare with c["city"].lower() == city.lower(). Delete with path.unlink().
Show the solution to Exercise 5
"""Exercise 5: A fixture and tmp_path to test saving and loading contacts.
Run: python ex05.py quick demo (macOS/Linux: python3 ex05.py)
Run: python -m pytest -q ex05.py runs the test_ functions
"""
import json
from pathlib import Path
import pytest
def save_contacts(path: Path, contacts: list[dict]) -> None:
path.write_text(json.dumps(contacts, indent=2), encoding="utf-8")
def load_contacts(path: Path) -> list[dict]:
"""Return the saved contacts, or an empty list if the file does not exist."""
if not path.exists():
return []
return json.loads(path.read_text(encoding="utf-8"))
def find_by_city(contacts: list[dict], city: str) -> list[str]:
"""Return the names of contacts in this city (case does not matter)."""
return [c["name"] for c in contacts if c["city"].lower() == city.lower()]
# ---------- Tests ----------
@pytest.fixture
def contacts() -> list[dict]:
return [
{"name": "Asha", "city": "Pune"},
{"name": "Ravi", "city": "Chennai"},
{"name": "Neha", "city": "Pune"},
]
def test_save_then_load_gives_same_contacts(tmp_path, contacts):
path = tmp_path / "contacts.json"
save_contacts(path, contacts)
assert load_contacts(path) == contacts
def test_load_missing_file_gives_empty_list(tmp_path):
assert load_contacts(tmp_path / "nothing.json") == []
def test_find_by_city_ignores_case(contacts):
assert find_by_city(contacts, "pune") == ["Asha", "Neha"]
def test_find_by_unknown_city(contacts):
assert find_by_city(contacts, "Delhi") == []
def main() -> None:
path = Path(__file__).parent / "demo_contacts.json"
data = [
{"name": "Asha", "city": "Pune"},
{"name": "Ravi", "city": "Chennai"},
{"name": "Neha", "city": "Pune"},
]
save_contacts(path, data)
loaded = load_contacts(path)
print(f"Loaded {len(loaded)} contacts")
print("In Pune:", find_by_city(loaded, "pune"))
path.unlink() # clean up the demo file
print("After delete:", load_contacts(path))
if __name__ == "__main__":
main()
Exercise 6: Loan EMI with pytest.approx and logging
Scenario: A loan app shows the EMI (equated monthly instalment: the fixed amount paid every month). What to do:
- Write
monthly_emi(principal, yearly_rate, months)using the formula below. Ifmonths < 1, raiseValueError. If the rate is 0, the EMI isprincipal / months. - Use
logger = logging.getLogger(__name__). Log an INFO message for a normal EMI and a WARNING for a 0% rate (see the output). Do not useprintinside the function. - Tests with
pytest.approx(..., abs=0.01): ₹5,00,000 at 9% for 60 months → 10,379.18; ₹25,00,000 at 8.5% for 240 months → 21,695.58; ₹1,20,000 at 0% for 12 months → 10,000. Plustest_zero_months_raises. - In
main(), calllogging.basicConfig(level=logging.INFO, format="%(levelname)s: %(message)s")and print the three EMIs.
Starting data:
# EMI = P * r * (1 + r)**n / ((1 + r)**n - 1)
# P = loan amount, r = yearly_rate / 12 / 100, n = months
Sample output:
INFO: EMI for ₹500,000 at 9% for 60 months
Car loan EMI: ₹10,379.18
INFO: EMI for ₹2,500,000 at 8.5% for 240 months
Home loan EMI: ₹21,695.58
WARNING: Rate is 0%, EMI is just the loan split into 12 parts
Zero-rate EMI: ₹10,000.00
pytest: 4 passed
💡 Hint: Python's , format groups digits in thousands (500,000), not the Indian way (5,00,000). In a log message, write %% to show one %. Logs go to stderr and prints to stdout; in a terminal they appear in this order.
Show the solution to Exercise 6
"""Exercise 6: Test a loan EMI with pytest.approx, and log instead of print.
EMI (equated monthly instalment) = P * r * (1 + r)**n / ((1 + r)**n - 1)
P = loan amount, r = monthly rate (yearly % / 12 / 100), n = number of months.
Run: python ex06.py quick demo (macOS/Linux: python3 ex06.py)
Run: python -m pytest -q ex06.py runs the test_ functions
"""
import logging
import pytest
logger = logging.getLogger(__name__)
def monthly_emi(principal: float, yearly_rate: float, months: int) -> float:
"""Return the monthly instalment for a loan.
Raises:
ValueError: If months is less than 1.
"""
if months < 1:
raise ValueError(f"months must be at least 1, got {months}")
if yearly_rate == 0:
logger.warning("Rate is 0%%, EMI is just the loan split into %d parts", months)
return principal / months
r = yearly_rate / 12 / 100
growth = (1 + r) ** months
emi = principal * r * growth / (growth - 1)
logger.info(
"EMI for ₹%s at %s%% for %d months", f"{principal:,}", yearly_rate, months
)
return emi
# ---------- Tests ----------
def test_car_loan_emi():
assert monthly_emi(500_000, 9, 60) == pytest.approx(10_379.18, abs=0.01)
def test_home_loan_emi():
assert monthly_emi(2_500_000, 8.5, 240) == pytest.approx(21_695.58, abs=0.01)
def test_zero_rate_splits_evenly():
assert monthly_emi(120_000, 0, 12) == pytest.approx(10_000)
def test_zero_months_raises():
with pytest.raises(ValueError, match="at least 1"):
monthly_emi(100_000, 9, 0)
def main() -> None:
logging.basicConfig(level=logging.INFO, format="%(levelname)s: %(message)s")
print(f"Car loan EMI: ₹{monthly_emi(500_000, 9, 60):,.2f}")
print(f"Home loan EMI: ₹{monthly_emi(2_500_000, 8.5, 240):,.2f}")
print(f"Zero-rate EMI: ₹{monthly_emi(120_000, 0, 12):,.2f}")
if __name__ == "__main__":
main()
Exercise 7: Fully test an order-line parser
Scenario: A wholesale shop gets orders as text lines like "Pen, 3, 20.50" (item, quantity, price). Some lines are typed wrongly.
What to do:
- Write
parse_order_line(line)that returns{"item": str, "qty": int, "price": float}. Strip spaces around each part. RaiseValueErrorif there are not exactly 3 parts, the item is empty, a number is not valid, or qty is less than 1. - Write
order_total(lines)that addsqty * pricefor every valid line, rounded to 2 decimals. For a bad line, log a WARNING"Skipping bad line: <error>"and go on. - Tests:
- parametrized
test_parse_valid_linefor"Pen, 3, 20.50","Notebook,2,45"and" Glue stick , 4 , 12.25 " - parametrized
test_parse_bad_line_raisesfor"Stapler, 1","Pen, 3, 20, extra","Eraser, two, 5",", 2, 10","Pen, 0, 20" - a fixture
order_lines(the starting data) andtest_order_total_skips_bad_lineswithpytest.approx(200.50) test_order_total_of_no_lines_is_zero
- parametrized
- In
main(), set up logging like Exercise 6, print the parsed first line, then the total. - Bonus: add type hints and run
mypy ex07.pyandruff check ex07.py.
Starting data:
lines = [
"Pen, 3, 20.50",
"Notebook, 2, 45",
"Eraser, two, 5",
"Stapler, 1",
"Glue stick, 4, 12.25",
]
Sample output:
{'item': 'Pen', 'qty': 3, 'price': 20.5}
WARNING: Skipping bad line: invalid literal for int() with base 10: 'two'
WARNING: Skipping bad line: expected 3 parts, got 2: 'Stapler, 1'
Order total: ₹200.50
pytest: 10 passed
💡 Hint: parts = [part.strip() for part in line.split(",")], then item, qty_text, price_text = parts. int("two") raises ValueError for you. Use {line!r} in messages to show the line in quotes.
Show the solution to Exercise 7
"""Exercise 7: Fully test an order-line parser.
Uses parametrize + raises + a fixture + logging, all in one file.
Run: python ex07.py quick demo (macOS/Linux: python3 ex07.py)
Run: python -m pytest -q ex07.py runs the test_ functions
"""
import logging
import pytest
logger = logging.getLogger(__name__)
def parse_order_line(line: str) -> dict:
"""Turn "Pen, 3, 20.50" into {"item": "Pen", "qty": 3, "price": 20.5}.
Raises:
ValueError: If the line does not have 3 parts, a number is not valid,
the item name is empty, or qty is less than 1.
"""
parts = [part.strip() for part in line.split(",")]
if len(parts) != 3:
raise ValueError(f"expected 3 parts, got {len(parts)}: {line!r}")
item, qty_text, price_text = parts
if not item:
raise ValueError(f"item name is empty: {line!r}")
qty = int(qty_text) # int("three") raises ValueError by itself
price = float(price_text)
if qty < 1:
raise ValueError(f"qty must be at least 1: {line!r}")
return {"item": item, "qty": qty, "price": price}
def order_total(lines: list[str]) -> float:
"""Add up all valid lines. Bad lines are logged as warnings and skipped."""
total = 0.0
for line in lines:
try:
order = parse_order_line(line)
except ValueError as error:
logger.warning("Skipping bad line: %s", error)
continue
total += order["qty"] * order["price"]
return round(total, 2)
# ---------- Tests ----------
@pytest.fixture
def order_lines() -> list[str]:
return [
"Pen, 3, 20.50",
"Notebook, 2, 45",
"Eraser, two, 5", # bad qty
"Stapler, 1", # missing price
"Glue stick, 4, 12.25",
]
@pytest.mark.parametrize(
("line", "expected"),
[
("Pen, 3, 20.50", {"item": "Pen", "qty": 3, "price": 20.5}),
("Notebook,2,45", {"item": "Notebook", "qty": 2, "price": 45.0}),
(" Glue stick , 4 , 12.25 ", {"item": "Glue stick", "qty": 4, "price": 12.25}),
],
)
def test_parse_valid_line(line, expected):
assert parse_order_line(line) == expected
@pytest.mark.parametrize(
"line",
["Stapler, 1", "Pen, 3, 20, extra", "Eraser, two, 5", ", 2, 10", "Pen, 0, 20"],
)
def test_parse_bad_line_raises(line):
with pytest.raises(ValueError):
parse_order_line(line)
def test_order_total_skips_bad_lines(order_lines):
# 3 x 20.50 + 2 x 45 + 4 x 12.25 = 61.50 + 90 + 49 = 200.50
assert order_total(order_lines) == pytest.approx(200.50)
def test_order_total_of_no_lines_is_zero():
assert order_total([]) == 0
def main() -> None:
logging.basicConfig(level=logging.INFO, format="%(levelname)s: %(message)s")
lines = [
"Pen, 3, 20.50",
"Notebook, 2, 45",
"Eraser, two, 5",
"Stapler, 1",
"Glue stick, 4, 12.25",
]
print(parse_order_line(lines[0]))
print(f"Order total: ₹{order_total(lines):,.2f}")
if __name__ == "__main__":
main()
Common mistakes
| Mistake | Why it is wrong | Fix |
|---|---|---|
Test function named check_total() |
pytest only collects names starting with test_ |
def test_total(): |
assert 0.1 + 0.2 == 0.3 |
Float rounding makes it False |
== pytest.approx(0.3) |
Using assert to check user input in app code |
python -O removes every assert |
if …: raise ValueError(...) |
pytest.raises around many lines |
You cannot tell which line raised | Put only the one failing call inside with |
| Tests that share one list and change it | One test spoils the next | Use a fixture: fresh data for every test |
Leaving print/breakpoint() in code |
Noise, or the program pauses for users | Remove them; use logging for real messages |
Calling basicConfig inside a module |
Takes the choice away from the program | Module: getLogger(__name__); program: basicConfig |
Running pytest from the wrong venv |
"No module named pytest" or old version | Activate the venv, use python -m pytest |
Committing .venv/ or __pycache__/ |
Huge, machine-specific files in Git | Add them to .gitignore |
Quick recap
- Automated tests catch bugs early and let you refactor safely.
- Read tracebacks bottom-up; use
breakpoint()(pdb:n,s,c,p,q) or the VS Code debugger to step through code. - pytest finds
test_*.pyfiles andtest_*functions; run withpython -m pytest -q, filter with-k, stop early with-x. pytest.raisestests errors,parametrizeruns one test on many inputs, fixtures andtmp_pathgive fresh data,pytest.approxcompares floats.- Test the happy path, edge cases and errors; use Arrange-Act-Assert and one idea per test.
- Use
loggingwith levels instead ofprint;basicConfigonce in the program,getLogger(__name__)in modules. - Type hints (
list[str],float | None,Callable,TypedDict) are checked by mypy, not by Python. - Ruff lints and formats; Git saves snapshots; pull requests let a team review changes.
Checklist
- I can read a traceback and step through code with
breakpoint(). - I can write and run pytest tests and read a failure report.
- I can test errors with
pytest.raisesand many inputs withparametrize. - I can write a fixture and use
tmp_pathandpytest.approx. - I can pick happy-path, edge-case and error tests for a function.
- I can set up logging with a level, a format and a log file.
- I can add type hints with generics and
X | None, and run mypy and Ruff. - I can init a Git repo, commit, branch, push and explain a pull request.