Here's a comprehensive guide to getting started with Python testing:
Testing Frameworks
1. unittest (Built-in Standard Library)
import unittest
class TestExample(unittest.TestCase):
def setUp(self):
# Run before each test method
self.value = 10
def test_addition(self):
self.assertEqual(5 + 5, 10)
def test_truth(self):
self.assertTrue(self.value == 10)
def tearDown(self):
# Run after each test method
pass
if __name__ == '__main__':
unittest.main()
2. pytest (Recommended Third-Party Framework)
Installation
pip install pytest
Basic Test Example
def test_addition():
assert 5 + 5 == 10
def test_string_length():
assert len("hello") == 5
Key Testing Concepts
Types of Tests
- Unit Tests: Test individual functions/methods
- Integration Tests: Test interactions between components
- Functional Tests: Test entire system functionality
Best Practices
- Use descriptive test names
- Test one thing per test method
- Cover edge cases
- Use setup and teardown methods
- Aim for high code coverage
Advanced pytest Features
Fixtures
import pytest
@pytest.fixture
def sample_data():
return [1, 2, 3, 4, 5]
def test_list_length(sample_data):
assert len(sample_data) == 5
Parameterized Testing
@pytest.mark.parametrize("input,expected", [
(5, 25),
(4, 16),
(3, 9)
])
def test_square(input, expected):
assert input ** 2 == expected
Mocking and Patching
from unittest.mock import patch
def test_external_call():
with patch('module.external_function') as mock_func:
mock_func.return_value = 42
# Test logic here
Running Tests
unittest
python -m unittest test_file.py
pytest
# Run all tests
pytest
# Run specific file
pytest test_file.py
# Verbose output
pytest -v
# Stop on first failure
pytest -x
Code Coverage
pip install pytest-cov
# Generate coverage report
pytest --cov=your_module
Recommended Tools
- pytest: Most popular testing framework
- coverage.py: Measure code coverage
- hypothesis: Property-based testing
- tox: Test across multiple Python versions
Common Assertions
# unittest assertions
self.assertEqual(a, b)
self.assertTrue(x)
self.assertFalse(x)
self.assertRaises(ErrorType, function)
# pytest assertions
assert condition
assert a == b
assert x in collection
Project Structure
project/
│
├── src/
│ └── my_module.py
│
├── tests/
│ ├── __init__.py
│ ├── test_module1.py
│ └── test_module2.py
│
└── requirements.txt
Quick Start Checklist
- Choose a testing framework (recommend pytest)
- Install framework
- Create test files with
test_ prefix
- Write test methods with
test_ prefix
- Run tests using pytest or unittest runner
- Aim for comprehensive test coverage
Pro Tips
- Write tests before or alongside code (TDD)
- Keep tests independent
- Make tests deterministic
- Use meaningful assertions
- Refactor tests like production code
Remember, good testing is about confidence in your code's behavior across different scenarios. Start simple and gradually increase complexity.