Implementing a Pytest Plugin

Guide for implementing your first Pytest plugin

Oliver Lövström
Internet of Technology
2 min readJan 26, 2024

--

Today is the fourth day of the 30-day Python challenge. This guide will introduce you to the basics of Pytest plugins.

Photo by Thomas Jensen on Unsplash

Let’s start by building a basic Pytest plugin. Our goal is to print “Hello World!” before Pytest starts running tests.

Project Structure

First, we set up the project structure for our plugin:


your_plugin_name/
├─ src/
│ ├─ __init__.py
│ ├─ plugin_code.py

Replace your_project_name and plugin_code.py with names relevant to your plugin.

In the src folder, the __init__.py file marks the directory as a Python package. We'll keep this file empty for now.

Creating the Plugin

In plugin_code.py, we'll write a simple plugin:

print("Hello World!")

This line will display “Hello World!” when we run Pytest.

Running the Plugin

First, we need to add the plugin to your Python path:

export PYTHONPATH=/path/to/your_plugin_name:/path/to/bin/python

To test our plugin, navigate to the directory containing your_plugin_name/ and run Pytest with this command:

$ pytest -p src.plugin_code test/test.py
Hello World!
============================================================================ test session starts ============================================================================
platform darwin -- Python 3.11.7, pytest-7.4.0, pluggy-1.0.0 -- /Users/oliverl/anaconda3/bin/python
cachedir: .pytest_cache
rootdir: /Users/oliverl/Git/python-projects
plugins: anyio-3.5.0
collected 1 item

The -p flag will preload the plugin. For further details, refer to the Pytest documentation in the Pytest Writing Plugins Guide.

Beyond the Basics

Typically, plugins are developed, packaged, and sometimes published on PyPI, the Python Package Index. This process is a great opportunity to learn about packaging and publishing Python projects. For a guide, see:

Tomorrow, we’ll continue our work with Pytest plugins, focusing on creating a plugin that ensures Pytest properly registers assertion rewrites before any modules are imported. All the code for these projects is available on Python Projects on GitHub.

Further Reading

If you want to learn more about programming and, specifically, Python and Java, see the following course:

Note: If you use my links to order, I’ll get a small kickback. So, if you’re inclined to order anything, feel free to click above.

--

--