Getting Started with pytest: Features, Installation, and Example Tests
This article introduces pytest, a popular Python testing framework, outlining its key features, installation steps, how to write and run basic, parameterized, and parallel tests, generate HTML reports, and integrate with CI/CD pipelines, providing code examples throughout.
pytest is one of the most popular and widely used unit testing frameworks in the Python community, offering more flexibility and ease of use than other frameworks such as unittest, making test writing and execution simpler.
Key features of pytest include concise and easy-to-understand syntax, a powerful plugin system, no need to import specific test modules, automatic assertion rewriting for detailed error messages, support for parameterized and dynamically generated tests, parallel test execution, HTML report generation, support for various test types (unit, functional, integration), and seamless integration with CI/CD tools like Jenkins and GitLab CI.
Installation is straightforward using pip:
pip install pytestExample: a simple add function and its test case.
# File: mylib.py
def add(a, b):
return a + b # File: test_mylib.py
def test_add():
assert add(1, 2) == 3
assert add(-1, 1) == 0
assert add(0, 0) == 0Test files should start with test_ . Run tests with:
pytest test_mylib.pyOr simply pytest to execute all tests in the current directory and subdirectories that follow the test_ naming convention.
pytest rewrites assertions to provide detailed failure information, e.g.:
assert 1 + 1 == 3When this assertion fails, pytest displays a clear error message to help locate the issue.
Parameterized testing using @pytest.mark.parametrize :
import pytest
@pytest.mark.parametrize("a, b, expected", [
(1, 2, 3),
(-1, 1, 0),
(0, 0, 0),
(100, 200, 300)
])
def test_add(a, b, expected):
assert add(a, b) == expectedDynamic test generation can be achieved by providing a function that returns test cases:
import pytest
def get_test_cases():
return [(1, 2, 3), (-1, 1, 0), (0, 0, 0), (100, 200, 300)]
@pytest.mark.parametrize("a, b, expected", get_test_cases())
def test_add(a, b, expected):
assert add(a, b) == expectedParallel test execution can be accelerated with the -n option, e.g., pytest -n 4 runs tests using four processes.
HTML test reports can be generated using the pytest-html plugin:
pip install pytest-html
pytest --html=test_report.htmlThis creates a test_report.html file containing the test results.
In summary, pytest provides concise syntax, a robust plugin ecosystem, detailed assertion messages, easy parameterization, dynamic test generation, parallel execution, and HTML reporting, making it a powerful tool for Python testing and CI/CD integration.
Test Development Learning Exchange
Test Development Learning Exchange
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.