Module 30 - Testing with pytest
pytest is a powerful testing framework that makes it easy to write simple and scalable test cases.
1. Installation
pip install pytest
2. Basic Tests
test_example.py:
def add(a, b):
return a + b
def test_add():
assert add(2, 3) == 5
assert add(-1, 1) == 0
assert add(0, 0) == 0
def test_add_negative():
assert add(-5, -3) == -8
Run tests:
pytest test_example.py
3. Test Organization
# test_math.py
class TestMath:
def test_addition(self):
assert 1 + 1 == 2
def test_subtraction(self):
assert 5 - 3 == 2
def test_multiplication(self):
assert 2 * 3 == 6
4. Fixtures
import pytest
@pytest.fixture
def sample_data():
return [1, 2, 3, 4, 5]
def test_sum(sample_data):
assert sum(sample_data) == 15
def test_len(sample_data):
assert len(sample_data) == 5
5. Parameterized Tests
import pytest
@pytest.mark.parametrize("input,expected", [
(2, 4),
(3, 9),
(4, 16),
(5, 25)
])
def test_square(input, expected):
assert input ** 2 == expected
6. Exception Testing
import pytest
def divide(a, b):
if b == 0:
raise ValueError("Cannot divide by zero")
return a / b
def test_divide_by_zero():
with pytest.raises(ValueError):
divide(10, 0)
def test_divide_success():
assert divide(10, 2) == 5
7. Mocking
from unittest.mock import Mock, patch
def fetch_data():
# Imagine this makes an API call
return {"status": "success"}
def test_fetch_data():
with patch('module.fetch_data') as mock_fetch:
mock_fetch.return_value = {"status": "mocked"}
result = fetch_data()
assert result["status"] == "mocked"
Summary
✅ pytest makes testing easy
✅ Fixtures provide reusable test data
✅ Parameterize for multiple test cases
✅ Mock external dependencies
✅ Test exceptions and edge cases
Next Steps
In Module 31, you'll learn:
- Logging module
- Debugging with pdb
- Error tracking
- Best practices
Practice Exercises
- Write tests for a calculator module
- Create fixtures for database testing
- Test API endpoints with mock requests
- Implement parameterized tests for validation functions
- Write integration tests for a complete application :::