pytest is a powerful testing framework for Python that simplifies unit testing and integration testing. 🧪 Here's a quick guide to get started:
1. Installation
Install pytest via pip:
pip install pytest
🚀 For more on Python package management, check our Python Best Practices guide.
2. Basic Usage
Writing a Test
Create a file test_example.py
with:
def test_addition():
assert 1 + 1 == 2
💡 Run tests using: pytest test_example.py
Test Discovery
pytest automatically finds tests in files named test_*.py
or *_test.py
.
📂 Example: test_*.py Pattern
3. Advanced Features
- Parameterized Tests
@pytest.mark.parametrize("a,b,expected", [(1,2,3), (4,5,9)]) def test_multiplication(a, b, expected): assert a * b == expected
- Fixtures
Use fixtures to setup test dependencies:
🛠️ Learn more: pytest Fixtures
4. Tips & Tricks
- Add
pytest.ini
for configuration - Use
--verbose
for detailed output - Enable
--color
for colored test reports
📸 Visualize test structure:
For a deeper dive into testing strategies, explore our Python Testing Guide. 📚