Introduction to pytest
pytest is a popular Python testing framework used for writing simple to complex test cases efficiently. It is widely used for unit testing, functional testing, and integration testing.
Key Features
Simple Syntax - Easy to write tests using functions without the need for classes.
Auto Discovery - Automatically finds test files and functions by following naming conventions (
test_*.pyor*_test.py).Fixtures - Supports setup and teardown operations via fixtures (
@pytest.fixture).Parameterization - Allows running tests with multiple sets of data using
@pytest.mark.parametrize.Assertions - Uses standard Python
assertstatements with improved error reporting.Plugins - A rich ecosystem of plugins for coverage, mocking, parallel execution (
pytest-xdist), etc.Test Skipping & Expected Failures - Mark tests to skip or expect failure using decorators like
@pytest.mark.skipand@pytest.mark.xfail.
Installation
To install pytest, run:
pip install pytest
Example Usage
Here is a simple example demonstrating pytest in action:
import pytest
# Function to be tested
def add(x, y):
return x + y
# Test function
def test_add():
assert add(2, 3) == 5
assert add(-1, 1) == 0
assert add(0, 0) == 0
To execute tests, run:
pytest test_file.py
In the next chapters, we will explore the various features of pytest in detail.