PyTest
PyTest is a widely used testing framework for Python.
Tests are typically written as functions, using assert statements to check whether the actual results match the expected results.
This tutorial does not cover advanced features and focuses only on basic usage. The BlueBase project uses PyTest to verify whether your implementation works correctly.
Key Features
Simple syntax: Writing tests does not require classes or complex structures.
Automatic test discovery: Automatically detects functions and files that follow
test_naming conventions.Powerful assertions: Uses Python’s built-in
assertstatement while providing readable error messages when a test fails.Plugin support: Can be extended with various plugins for features such as coverage and mocking.
Core Concepts
test function: A function in the form
def test_*that serves as the basic unit for verifying expected behavior.fixture: A reusable mechanism for preparing and cleaning up resources before and after tests.
marker: Used to categorize tests or run them conditionally, such as
@pytest.mark.slow.test discovery: Automatically finds tests, by default, in files matching the
test_*.pypattern.
Usage Examples
1. Environment setup
PyTest is not part of the Python standard library, so it must be installed separately.
uv add pytest
For more information about uv, refer to the corresponding tutorial.
2. Write tests
Test-driven development, commonly known as TDD, recommends writing tests before implementing the actual code.
As an example, let’s write tests for functions add and sub, which add and subtract two integers.
Example: test_utils.py
from utils import add, sub
def test_add():
assert add(2, 3) == 5
def test_sub():
assert sub(3, 2) == 1
3. Implement the functions
Now implement the actual functions.
Example: utils.py
def add(a, b):
return a + b
def sub(a, b):
return a - b
4. Run the tests
Run the tests from the terminal with:
uv run pytest
The output shows whether each test function passed or failed. When a test fails, PyTest provides detailed information about which input produced an unexpected result.
5. Run a specific test
By default, pytest collects and runs all tests under the current directory.
To run only a specific test, provide the file name and test function as an argument.
uv run pytest test_utils.py::test_sub