Introduction to Pytest for Python Testing
Pytest introduction
Pytest is a framework for testing Python code. Pytest allows you to test your functions, methods, and classes with a straight forward syntax. In this tutorial, I’ll go over how to write tests for an async Python application.
Prerequisites
Before you start, make sure you have the following installed on your machine:
- Python 3.7 or greater
- Pytest
You can install Pytest using pip:
pip install pytest
Writing tests
In Pytest, tests are written as functions, methods, or classes. The syntax is very similar to writing your application code. To mark an async function, you need to decorate the function with the @pytest.mark.asyncio
decorator.
import pytest
@pytest.mark.asyncio
async def test_function():
assert 1 == 1
To write a test method, you need to define it inside a class and decorate it with @pytest.mark.asyncio
.
import pytest
class TestClass:
@pytest.mark.asyncio
async def test_method(self):
assert 1 == 1
Run pytests
To run your tests, use pytest from the command line. Pytest searches for tests files that are either prefixed with test_
or the suffix as *_test.py
and pytest will execute the function, method, or class inside these files.
For example, to run all the tests in the current directory, you can use the following command:
pytest .
To run a specific test file, you can pass the file name as an argument to pytest.
pytest test_my_file.py
To run a specific test function, method, or class, you can use the -k
option and specify a keyword to filter the tests by.
pytest -k test_my_function