Unit Testing
Unit testing is a crucial part of software development, and pytest is one of the most popular testing frameworks for Python.
Basic Python Unit Testing
Python includes a built-in unittest
module, but pytest has become very popular due to its simplicity and powerful features.
Why Unit Test?
- Validates that code works as expected
- Makes refactoring safer by catching regressions
- Serves as documentation for how your code should be used
- Encourages modular, testable code design
pytest Framework
pytest is a more advanced testing framework that simplifies test writing:
# Simple pytest example
def test_addition():
assert 1 + 1 == 2
Key pytest Features:
-
Simple Assertions: Just use Python's
assert
statement - no need for special assertion methods. -
Test Discovery: Automatically finds test files and functions (named with
test_
prefix). -
Fixtures: For setting up test environments and sharing resources between tests:
import pytest
@pytest.fixture
def example_data():
return {'key': 'value'}
def test_with_fixture(example_data):
assert example_data['key'] == 'value'
- Parameterized Tests: Test multiple input combinations easily:
@pytest.mark.parametrize("input,expected", [
(1, 1),
(2, 4),
(3, 9),
])
def test_square(input, expected):
assert input * input == expected
- Powerful Output: Detailed error reports and test results.
Getting Started
- Install pytest:
pip install pytest
-
Create test files (named
test_*.py
) in your project. -
Write test functions (named
test_*
) in those files. -
Run tests with the command:
pytest