| 1 |
.. _plugins: |
| 2 |
.. _`writing-plugins`: |
| 3 |
|
| 4 |
Writing plugins |
| 5 |
=============== |
| 6 |
|
| 7 |
It is easy to implement `local conftest plugins`_ for your own project |
| 8 |
or `pip-installable plugins`_ that can be used throughout many projects, |
| 9 |
including third party projects. Please refer to :ref:`using plugins` if you |
| 10 |
only want to use but not write plugins. |
| 11 |
|
| 12 |
A plugin contains one or multiple hook functions. :ref:`Writing hooks <writinghooks>` |
| 13 |
explains the basics and details of how you can write a hook function yourself. |
| 14 |
``pytest`` implements all aspects of configuration, collection, running and |
| 15 |
reporting by calling :ref:`well specified hooks <hook-reference>` of the following plugins: |
| 16 |
|
| 17 |
* builtin plugins: loaded from pytest's internal ``_pytest`` directory. |
| 18 |
|
| 19 |
* :ref:`external plugins <extplugins>`: installed third-party modules discovered |
| 20 |
through :ref:`entry points <pip-installable plugins>` in their packaging metadata |
| 21 |
|
| 22 |
* `conftest.py plugins`_: modules auto-discovered in test directories |
| 23 |
|
| 24 |
In principle, each hook call is a ``1:N`` Python function call where ``N`` is the |
| 25 |
number of registered implementation functions for a given specification. |
| 26 |
All specifications and implementations follow the ``pytest_`` prefix |
| 27 |
naming convention, making them easy to distinguish and find. |
| 28 |
|
| 29 |
.. _`pluginorder`: |
| 30 |
|
| 31 |
Plugin discovery order at tool startup |
| 32 |
-------------------------------------- |
| 33 |
|
| 34 |
``pytest`` loads plugin modules at tool startup in the following way: |
| 35 |
|
| 36 |
1. by scanning the command line for the ``-p no:name`` option |
| 37 |
and *blocking* that plugin from being loaded (even builtin plugins can |
| 38 |
be blocked this way). This happens before normal command-line parsing. |
| 39 |
|
| 40 |
2. by loading all builtin plugins. |
| 41 |
|
| 42 |
3. by scanning the command line for the ``-p name`` option |
| 43 |
and loading the specified plugin. This happens before normal command-line parsing. |
| 44 |
|
| 45 |
4. by loading all plugins registered through installed third-party package |
| 46 |
:ref:`entry points <pip-installable plugins>`, unless the |
| 47 |
:envvar:`PYTEST_DISABLE_PLUGIN_AUTOLOAD` environment variable is set. |
| 48 |
|
| 49 |
5. by loading all plugins specified through the :envvar:`PYTEST_PLUGINS` environment variable. |
| 50 |
|
| 51 |
6. by loading all "initial" :file:`conftest.py` files: |
| 52 |
|
| 53 |
- determine the test paths: specified on the command line, otherwise in |
| 54 |
:confval:`testpaths` if defined and running from the rootdir, otherwise the |
| 55 |
current dir |
| 56 |
- for each test path, load ``conftest.py`` and ``test*/conftest.py`` relative |
| 57 |
to the directory part of the test path, if exist. Before a ``conftest.py`` |
| 58 |
file is loaded, load ``conftest.py`` files in all of its parent directories. |
| 59 |
After a ``conftest.py`` file is loaded, recursively load all plugins specified |
| 60 |
in its :globalvar:`pytest_plugins` variable if present. |
| 61 |
|
| 62 |
|
| 63 |
.. _`conftest.py plugins`: |
| 64 |
.. _`localplugin`: |
| 65 |
.. _`local conftest plugins`: |
| 66 |
|
| 67 |
conftest.py: local per-directory plugins |
| 68 |
---------------------------------------- |
| 69 |
|
| 70 |
Local ``conftest.py`` plugins contain directory-specific hook |
| 71 |
implementations. Hook Session and test running activities will |
| 72 |
invoke all hooks defined in ``conftest.py`` files closer to the |
| 73 |
root of the filesystem. Example of implementing the |
| 74 |
``pytest_runtest_setup`` hook so that is called for tests in the ``a`` |
| 75 |
sub directory but not for other directories:: |
| 76 |
|
| 77 |
a/conftest.py: |
| 78 |
def pytest_runtest_setup(item): |
| 79 |
# called for running each test in 'a' directory |
| 80 |
print("setting up", item) |
| 81 |
|
| 82 |
a/test_sub.py: |
| 83 |
def test_sub(): |
| 84 |
pass |
| 85 |
|
| 86 |
test_flat.py: |
| 87 |
def test_flat(): |
| 88 |
pass |
| 89 |
|
| 90 |
Here is how you might run it:: |
| 91 |
|
| 92 |
pytest test_flat.py --capture=no # will not show "setting up" |
| 93 |
pytest a/test_sub.py --capture=no # will show "setting up" |
| 94 |
|
| 95 |
.. note:: |
| 96 |
If you have ``conftest.py`` files which do not reside in a |
| 97 |
python package directory (i.e. one containing an ``__init__.py``) then |
| 98 |
"import conftest" can be ambiguous because there might be other |
| 99 |
``conftest.py`` files as well on your ``PYTHONPATH`` or ``sys.path``. |
| 100 |
It is thus good practice for projects to either put ``conftest.py`` |
| 101 |
under a package scope or to never import anything from a |
| 102 |
``conftest.py`` file. |
| 103 |
|
| 104 |
See also: :ref:`pythonpath`. |
| 105 |
|
| 106 |
.. note:: |
| 107 |
Some hooks cannot be implemented in conftest.py files which are not |
| 108 |
:ref:`initial <pluginorder>` due to how pytest discovers plugins during |
| 109 |
startup. See the documentation of each hook for details. |
| 110 |
|
| 111 |
Writing your own plugin |
| 112 |
----------------------- |
| 113 |
|
| 114 |
If you want to write a plugin, there are many real-life examples |
| 115 |
you can copy from: |
| 116 |
|
| 117 |
* a custom collection example plugin: :ref:`yaml plugin` |
| 118 |
* builtin plugins which provide pytest's own functionality |
| 119 |
* many :ref:`external plugins <plugin-list>` providing additional features |
| 120 |
|
| 121 |
All of these plugins implement :ref:`hooks <hook-reference>` and/or :ref:`fixtures <fixture>` |
| 122 |
to extend and add functionality. |
| 123 |
|
| 124 |
.. note:: |
| 125 |
Make sure to check out the excellent |
| 126 |
`cookiecutter-pytest-plugin <https://github.com/pytest-dev/cookiecutter-pytest-plugin>`_ |
| 127 |
project, which is a `cookiecutter template <https://github.com/audreyr/cookiecutter>`_ |
| 128 |
for authoring plugins. |
| 129 |
|
| 130 |
The template provides an excellent starting point with a working plugin, |
| 131 |
tests running with tox, a comprehensive README file as well as a |
| 132 |
pre-configured entry-point. |
| 133 |
|
| 134 |
Also consider :ref:`contributing your plugin to pytest-dev<submitplugin>` |
| 135 |
once it has some happy users other than yourself. |
| 136 |
|
| 137 |
|
| 138 |
.. _`setuptools entry points`: |
| 139 |
.. _`pip-installable plugins`: |
| 140 |
|
| 141 |
Making your plugin installable by others |
| 142 |
---------------------------------------- |
| 143 |
|
| 144 |
If you want to make your plugin externally available, you |
| 145 |
may define a so-called entry point for your distribution so |
| 146 |
that ``pytest`` finds your plugin module. Entry points are |
| 147 |
a feature that is provided by :std:doc:`packaging tools |
| 148 |
<packaging:specifications/entry-points>`. |
| 149 |
|
| 150 |
pytest looks up the ``pytest11`` entrypoint to discover its |
| 151 |
plugins, thus you can make your plugin available by defining |
| 152 |
it in your ``pyproject.toml`` file. |
| 153 |
|
| 154 |
.. sourcecode:: toml |
| 155 |
|
| 156 |
# sample ./pyproject.toml file |
| 157 |
[build-system] |
| 158 |
requires = ["hatchling"] |
| 159 |
build-backend = "hatchling.build" |
| 160 |
|
| 161 |
[project] |
| 162 |
name = "myproject" |
| 163 |
classifiers = [ |
| 164 |
"Framework :: Pytest", |
| 165 |
] |
| 166 |
|
| 167 |
[project.entry-points.pytest11] |
| 168 |
myproject = "myproject.pluginmodule" |
| 169 |
|
| 170 |
If a package is installed this way, ``pytest`` will load |
| 171 |
``myproject.pluginmodule`` as a plugin which can define |
| 172 |
:ref:`hooks <hook-reference>`. Confirm registration with ``pytest --trace-config`` |
| 173 |
|
| 174 |
.. note:: |
| 175 |
|
| 176 |
Make sure to include ``Framework :: Pytest`` in your list of |
| 177 |
`PyPI classifiers <https://pypi.org/classifiers/>`_ |
| 178 |
to make it easy for users to find your plugin. |
| 179 |
|
| 180 |
|
| 181 |
.. _assertion-rewriting: |
| 182 |
|
| 183 |
Assertion Rewriting |
| 184 |
------------------- |
| 185 |
|
| 186 |
One of the main features of ``pytest`` is the use of plain assert |
| 187 |
statements and the detailed introspection of expressions upon |
| 188 |
assertion failures. This is provided by "assertion rewriting" which |
| 189 |
modifies the parsed AST before it gets compiled to bytecode. This is |
| 190 |
done via a :pep:`302` import hook which gets installed early on when |
| 191 |
``pytest`` starts up and will perform this rewriting when modules get |
| 192 |
imported. However, since we do not want to test different bytecode |
| 193 |
from what you will run in production, this hook only rewrites test modules |
| 194 |
themselves (as defined by the :confval:`python_files` configuration option), |
| 195 |
and any modules which are part of plugins. |
| 196 |
Any other imported module will not be rewritten and normal assertion behaviour |
| 197 |
will happen. |
| 198 |
|
| 199 |
If you have assertion helpers in other modules where you would need |
| 200 |
assertion rewriting to be enabled you need to ask ``pytest`` |
| 201 |
explicitly to rewrite this module before it gets imported. |
| 202 |
|
| 203 |
.. autofunction:: pytest.register_assert_rewrite |
| 204 |
:noindex: |
| 205 |
|
| 206 |
This is especially important when you write a pytest plugin which is |
| 207 |
created using a package. The import hook only treats ``conftest.py`` |
| 208 |
files and any modules which are listed in the ``pytest11`` entrypoint |
| 209 |
as plugins. As an example consider the following package:: |
| 210 |
|
| 211 |
pytest_foo/__init__.py |
| 212 |
pytest_foo/plugin.py |
| 213 |
pytest_foo/helper.py |
| 214 |
|
| 215 |
With the following typical ``setup.py`` extract: |
| 216 |
|
| 217 |
.. code-block:: python |
| 218 |
|
| 219 |
setup(..., entry_points={"pytest11": ["foo = pytest_foo.plugin"]}, ...) |
| 220 |
|
| 221 |
In this case only ``pytest_foo/plugin.py`` will be rewritten. If the |
| 222 |
helper module also contains assert statements which need to be |
| 223 |
rewritten it needs to be marked as such, before it gets imported. |
| 224 |
This is easiest by marking it for rewriting inside the |
| 225 |
``__init__.py`` module, which will always be imported first when a |
| 226 |
module inside a package is imported. This way ``plugin.py`` can still |
| 227 |
import ``helper.py`` normally. The contents of |
| 228 |
``pytest_foo/__init__.py`` will then need to look like this: |
| 229 |
|
| 230 |
.. code-block:: python |
| 231 |
|
| 232 |
import pytest |
| 233 |
|
| 234 |
pytest.register_assert_rewrite("pytest_foo.helper") |
| 235 |
|
| 236 |
|
| 237 |
Requiring/Loading plugins in a test module or conftest file |
| 238 |
----------------------------------------------------------- |
| 239 |
|
| 240 |
You can require plugins in a test module or a ``conftest.py`` file using :globalvar:`pytest_plugins`: |
| 241 |
|
| 242 |
.. code-block:: python |
| 243 |
|
| 244 |
pytest_plugins = ["name1", "name2"] |
| 245 |
|
| 246 |
When the test module or conftest plugin is loaded the specified plugins |
| 247 |
will be loaded as well. Any module can be blessed as a plugin, including internal |
| 248 |
application modules: |
| 249 |
|
| 250 |
.. code-block:: python |
| 251 |
|
| 252 |
pytest_plugins = "myapp.testsupport.myplugin" |
| 253 |
|
| 254 |
:globalvar:`pytest_plugins` are processed recursively, so note that in the example above |
| 255 |
if ``myapp.testsupport.myplugin`` also declares :globalvar:`pytest_plugins`, the contents |
| 256 |
of the variable will also be loaded as plugins, and so on. |
| 257 |
|
| 258 |
.. _`requiring plugins in non-root conftests`: |
| 259 |
|
| 260 |
.. note:: |
| 261 |
Requiring plugins using :globalvar:`pytest_plugins` variable in non-root |
| 262 |
``conftest.py`` files is deprecated. |
| 263 |
|
| 264 |
This is important because ``conftest.py`` files implement per-directory |
| 265 |
hook implementations, but once a plugin is imported, it will affect the |
| 266 |
entire directory tree. In order to avoid confusion, defining |
| 267 |
:globalvar:`pytest_plugins` in any ``conftest.py`` file which is not located in the |
| 268 |
tests root directory is deprecated, and will raise a warning. |
| 269 |
|
| 270 |
This mechanism makes it easy to share fixtures within applications or even |
| 271 |
external applications without the need to create external plugins using the |
| 272 |
:std:doc:`entry point packaging metadata |
| 273 |
<packaging:guides/creating-and-discovering-plugins>` technique. |
| 274 |
|
| 275 |
Plugins imported by :globalvar:`pytest_plugins` will also automatically be marked |
| 276 |
for assertion rewriting (see :func:`pytest.register_assert_rewrite`). |
| 277 |
However for this to have any effect the module must not be |
| 278 |
imported already; if it was already imported at the time the |
| 279 |
:globalvar:`pytest_plugins` statement is processed, a warning will result and |
| 280 |
assertions inside the plugin will not be rewritten. To fix this you |
| 281 |
can either call :func:`pytest.register_assert_rewrite` yourself before |
| 282 |
the module is imported, or you can arrange the code to delay the |
| 283 |
importing until after the plugin is registered. |
| 284 |
|
| 285 |
|
| 286 |
Accessing another plugin by name |
| 287 |
-------------------------------- |
| 288 |
|
| 289 |
If a plugin wants to collaborate with code from |
| 290 |
another plugin it can obtain a reference through |
| 291 |
the plugin manager like this: |
| 292 |
|
| 293 |
.. sourcecode:: python |
| 294 |
|
| 295 |
plugin = config.pluginmanager.get_plugin("name_of_plugin") |
| 296 |
|
| 297 |
If you want to look at the names of existing plugins, use |
| 298 |
the :option:`--trace-config` option. |
| 299 |
|
| 300 |
|
| 301 |
.. _registering-markers: |
| 302 |
|
| 303 |
Registering custom markers |
| 304 |
-------------------------- |
| 305 |
|
| 306 |
If your plugin uses any markers, you should register them so that they appear in |
| 307 |
pytest's help text and do not :ref:`cause spurious warnings <unknown-marks>`. |
| 308 |
For example, the following plugin would register ``cool_marker`` and |
| 309 |
``mark_with`` for all users: |
| 310 |
|
| 311 |
.. code-block:: python |
| 312 |
|
| 313 |
def pytest_configure(config): |
| 314 |
config.addinivalue_line("markers", "cool_marker: this one is for cool tests.") |
| 315 |
config.addinivalue_line( |
| 316 |
"markers", "mark_with(arg, arg2): this marker takes arguments." |
| 317 |
) |
| 318 |
|
| 319 |
|
| 320 |
Testing plugins |
| 321 |
--------------- |
| 322 |
|
| 323 |
pytest comes with a plugin named ``pytester`` that helps you write tests for |
| 324 |
your plugin code. The plugin is disabled by default, so you will have to enable |
| 325 |
it before you can use it. |
| 326 |
|
| 327 |
You can do so by adding the following line to a ``conftest.py`` file in your |
| 328 |
testing directory: |
| 329 |
|
| 330 |
.. code-block:: python |
| 331 |
|
| 332 |
# content of conftest.py |
| 333 |
|
| 334 |
pytest_plugins = ["pytester"] |
| 335 |
|
| 336 |
Alternatively you can invoke pytest with the ``-p pytester`` command line |
| 337 |
option. |
| 338 |
|
| 339 |
This will allow you to use the :py:class:`pytester <pytest.Pytester>` |
| 340 |
fixture for testing your plugin code. |
| 341 |
|
| 342 |
Let's demonstrate what you can do with the plugin with an example. Imagine we |
| 343 |
developed a plugin that provides a fixture ``hello`` which yields a function |
| 344 |
and we can invoke this function with one optional parameter. It will return a |
| 345 |
string value of ``Hello World!`` if we do not supply a value or ``Hello |
| 346 |
{value}!`` if we do supply a string value. |
| 347 |
|
| 348 |
.. code-block:: python |
| 349 |
|
| 350 |
import pytest |
| 351 |
|
| 352 |
|
| 353 |
def pytest_addoption(parser): |
| 354 |
group = parser.getgroup("helloworld") |
| 355 |
group.addoption( |
| 356 |
"--name", |
| 357 |
action="store", |
| 358 |
dest="name", |
| 359 |
default="World", |
| 360 |
help='Default "name" for hello().', |
| 361 |
) |
| 362 |
|
| 363 |
|
| 364 |
@pytest.fixture |
| 365 |
def hello(request): |
| 366 |
name = request.config.getoption("name") |
| 367 |
|
| 368 |
def _hello(name=None): |
| 369 |
if not name: |
| 370 |
name = request.config.getoption("name") |
| 371 |
return f"Hello {name}!" |
| 372 |
|
| 373 |
return _hello |
| 374 |
|
| 375 |
|
| 376 |
Now the ``pytester`` fixture provides a convenient API for creating temporary |
| 377 |
``conftest.py`` files and test files. It also allows us to run the tests and |
| 378 |
return a result object, with which we can assert the tests' outcomes. |
| 379 |
|
| 380 |
.. code-block:: python |
| 381 |
|
| 382 |
def test_hello(pytester): |
| 383 |
"""Make sure that our plugin works.""" |
| 384 |
|
| 385 |
# create a temporary conftest.py file |
| 386 |
pytester.makeconftest( |
| 387 |
""" |
| 388 |
import pytest |
| 389 |
|
| 390 |
@pytest.fixture(params=[ |
| 391 |
"Brianna", |
| 392 |
"Andreas", |
| 393 |
"Floris", |
| 394 |
]) |
| 395 |
def name(request): |
| 396 |
return request.param |
| 397 |
""" |
| 398 |
) |
| 399 |
|
| 400 |
# create a temporary pytest test file |
| 401 |
pytester.makepyfile( |
| 402 |
""" |
| 403 |
def test_hello_default(hello): |
| 404 |
assert hello() == "Hello World!" |
| 405 |
|
| 406 |
def test_hello_name(hello, name): |
| 407 |
assert hello(name) == "Hello {0}!".format(name) |
| 408 |
""" |
| 409 |
) |
| 410 |
|
| 411 |
# run all tests with pytest |
| 412 |
result = pytester.runpytest() |
| 413 |
|
| 414 |
# check that all 4 tests passed |
| 415 |
result.assert_outcomes(passed=4) |
| 416 |
|
| 417 |
|
| 418 |
Additionally it is possible to copy examples to the ``pytester``'s isolated environment |
| 419 |
before running pytest on it. This way we can abstract the tested logic to separate files, |
| 420 |
which is especially useful for longer tests and/or longer ``conftest.py`` files. |
| 421 |
|
| 422 |
Note that for ``pytester.copy_example`` to work we need to set `pytester_example_dir` |
| 423 |
in our configuration file to tell pytest where to look for example files. |
| 424 |
|
| 425 |
.. code-block:: toml |
| 426 |
|
| 427 |
# content of pytest.toml |
| 428 |
[pytest] |
| 429 |
pytester_example_dir = "." |
| 430 |
|
| 431 |
|
| 432 |
.. code-block:: python |
| 433 |
|
| 434 |
# content of test_example.py |
| 435 |
|
| 436 |
|
| 437 |
def test_plugin(pytester): |
| 438 |
pytester.copy_example("test_example.py") |
| 439 |
pytester.runpytest("-k", "test_example") |
| 440 |
|
| 441 |
|
| 442 |
def test_example(): |
| 443 |
pass |
| 444 |
|
| 445 |
.. code-block:: pytest |
| 446 |
|
| 447 |
$ pytest |
| 448 |
=========================== test session starts ============================ |
| 449 |
platform linux -- Python 3.x.y, pytest-9.x.y, pluggy-1.x.y |
| 450 |
rootdir: /home/sweet/project |
| 451 |
configfile: pytest.toml |
| 452 |
collected 2 items |
| 453 |
|
| 454 |
test_example.py .. [100%] |
| 455 |
|
| 456 |
============================ 2 passed in 0.12s ============================= |
| 457 |
|
| 458 |
For more information about the result object that ``runpytest()`` returns, and |
| 459 |
the methods that it provides please check out the :py:class:`RunResult |
| 460 |
<_pytest.pytester.RunResult>` documentation. |