PyTest: Python Testing Framework for Backend Engineers
Comprehensive pytest tutorial for beginners: install pytest, write unit tests, use fixtures, understand test discovery rules (test_ and _test), run tests from command line, and basic pytest.ini configuration.
Drake Nguyen
Founder · System Architect
Introduction
This pytest tutorial explains how to use pytest, a popular python testing framework, to write reliable unit tests and automate backend testing in Python. Whether you are a backend engineer, QA automation engineer, or just starting with unit testing in python, this guide covers installation, test discovery rules, writing tests, fixtures, running tests from the command line, and a basic pytest configuration example.
Prerequisites
Python installed on your system (check with
python --versionorpython3 --version).Pip available to install packages. Confirm with
python -m pip --versionorpython3 -m pip --version.
Installing pytest
To use pytest, install it with pip. This installs the testing framework and its dependencies.
pip install pytest
Or, when using a specific Python interpreter:
python -m pip install pytest
Writing your first tests (pytest tutorial for beginners)
Pytest discovers tests automatically and encourages simple test functions using the assert statement. Create a file named test_backend.py and add a few basic tests to learn how to write unit tests with pytest.
def test_addition():
assert 3 + 3 == 6
def test_subtraction():
assert 5 - 4 == 1
def test_multiplication():
assert 4 * 4 == 16
def test_division():
assert 10 / 2 == 5
The assert statement is used for pytest assertions and exception testing. If an assertion fails, pytest prints a helpful assertion error example showing the expression and values.
How to run pytest tests from command line
Run all tests in the current directory with:
pytest
Or explicitly use the Python module flag:
python -m pytest
The difference between python -m pytest and pytest is minor but useful when you want to ensure the tests run with a specific interpreter or virtual environment.
Running specific tests
To run one file or a single test function, use the node id pattern:
pytest test_backend.py::test_division
Or use -k to run tests by keyword expression:
pytest -k "division or add"
Test discovery rules
By default, pytest test discovery rules recognise files that start with test_ or end with _test. It will collect functions that start with test_ inside those files. You can point pytest at a specific directory:
pytest tests/
This makes it easy to follow pytest tests directory structure best practice by keeping tests under a tests/ folder.
Test output and failure example
When tests pass, pytest shows a summary like "4 passed". On failure, pytest prints the failing assertion and a short test summary. This clear output helps with debugging and continuous test automation in Python.
pytest fixtures tutorial with examples
Fixtures provide setup and teardown for tests and are one of pytest's most powerful features. Use the @pytest.fixture decorator to define reusable resources. This example shows a fixture that sets up a resource and uses yield to perform teardown.
import pytest
@pytest.fixture
def db():
# setup: create a database connection or test client
connection = create_db()
yield connection
# teardown: close connection
connection.close()
def test_query(db):
results = db.query("SELECT * FROM users")
assert len(results) == 12
This pattern is a pytest fixture yield teardown example and illustrates pytest setup and teardown using fixtures. Fixtures can also have scopes such as function, module, class, or session to control lifetime:
@pytest.fixture(scope="module")
def resource():
# expensive setup
yield
# module-level teardown
Advanced assertions and exception testing
Besides plain assert statements, pytest provides helpers such as pytest.raises for testing exceptions:
import pytest
def test_zero_division():
with pytest.raises(ZeroDivisionError):
1 / 0
Using these tools improves clarity when writing python test cases that must validate error handling.
pytest configuration (pytest.ini example configuration)
For larger projects, add a pytest.ini to configure collection and reporting. A minimal example:
[pytest]
minversion = 6.0
addopts = -ra -q
testpaths = tests
python_files = test_*.py *_test.py
This pytest configuration centralises options and can help with test discovery, verbosity, and plugin settings. See how to set up pytest.ini configuration to match your repo conventions.
How to test python backend with pytest
When testing backend services, combine pytest fixtures for database or API clients, parametrize for multiple input cases, and use mocks for external dependencies. Organize tests by feature or module and run them in CI to catch regressions early—this is core to professional software testing and QA automation python workflows.
pytest vs unittest: which is better?
Pytest and unittest both enable unit testing in Python. Unittest is part of the standard library and uses classes, while pytest offers a more concise syntax, powerful fixtures, rich plugins, and better assertion introspection. For most modern projects, pytest improves developer ergonomics and speeds up writing tests.
Best practices and tips
Keep tests small and focused on one behavior.
Use fixtures for repeatable setup/teardown and avoid global state.
Name files and functions to follow pytest test discovery rules test_ and _test.
Run tests with
python -m pytestin CI to pin the interpreter.Use
-kor node ids to run specific tests during development.
Conclusion
This pytest tutorial covered how to install and use pytest for python unit testing, how test discovery works, writing tests and fixtures, running tests from the command line, and setting up a basic pytest.ini. Adopting pytest for test automation in Python helps catch bugs early, improves code quality, and supports robust backend testing python workflows. Continue exploring pytest plugins, parametrization, and advanced fixtures to level up your testing strategy.