2025-05-05
Python Testing with pytest
Making your code more reliable in 1 hour
Test Early, Test Often
“Code without tests is broken by design.” — Jacob Kaplan-Moss
How much experience do you have with testing Python code?
A. None - I’m completely new to testing
B. Minimal - I’ve written a few basic tests
C. Moderate - I use pytest occasionally
D. Experienced - I practice TDD regularly
Unit tests
- Test individual functions
- Fast, isolated
- Many tests
Integration tests
- Test component interaction
- Fewer, more complex
Advantages
- Simple, Pythonic syntax
- Rich assertion messages
- Powerful fixtures & plugins
- Easy parameterization
Let’s write a test together!
Create calculator.py with basic functions:
Write test_calculator.py:
Run: pytest test_calculator.py -v
Classes in Python
class keywordobject = ClassName()self refers to the instanceArrange → Act → Assert
Before
def test_email_valid():
user = User('Test', 'test@example.com')
assert user.is_valid_email() is True
def test_email_invalid_no_at():
user = User('Test', 'invalid-email')
assert user.is_valid_email() is False
def test_email_invalid_no_dot():
user = User('Test', 'invalid@nodotatall')
assert user.is_valid_email() is FalseWhat are you most interested in testing?
A. Functions with calculations
B. Data validation logic
C. API interactions
D. Database operations
Benefits
- Forces clear requirements
- Prevents over-engineering
- Built-in regression testing
- Improves API design
- Documentation by example
Challenges
- Learning curve
- Requires discipline
- Can slow initial development
- Test maintenance
- “Test-induced design damage”
Tip
Start small and build your testing habit incrementally!
How might TDD change your workflow?
A. Initial slowdown but long-term gain
B. Clarify requirements before coding
C. Improve my code architecture
D. Still not convinced it’s worth it
Questions?
Contact: yangyang.li@northwestern.edu
GitHub: @cauliyang
Python Testing Workshop | Yangyang Li | May 2025