Introduction
Testing is a crucial skill for professional developers. Python's pytest framework makes writing tests simple and enjoyable. In this lesson, you'll learn the fundamentals of test-driven development (TDD).
Writing tests with pytest
# calculator.py
def add(a, b):
return a + b
def divide(a, b):
if b == 0:
raise ValueError("Cannot divide by zero")
return a / b
# test_calculator.py
import pytest
from calculator import add, divide
def test_add():
assert add(2, 3) == 5
assert add(-1, 1) == 0
assert add(0, 0) == 0
def test_divide():
assert divide(10, 2) == 5
assert divide(7, 2) == 3.5
def test_divide_by_zero():
with pytest.raises(ValueError):
divide(10, 0)
# Run with: pytest test_calculator.py -vThe TDD workflow
- Red: Write a failing test.
- Green: Write the minimum code to make it pass.
- Refactor: Clean up the code while keeping tests green.
Assignment
- Install pytest:
pip install pytest. - Write tests for a
StringCalculatorclass that can add comma-separated numbers. - Use TDD to build a simple
Stackclass.