| 1 |
======= |
| 2 |
Markers |
| 3 |
======= |
| 4 |
|
| 5 |
.. _reference/markers/asyncio: |
| 6 |
|
| 7 |
``pytest.mark.asyncio`` |
| 8 |
======================= |
| 9 |
A coroutine or async generator with this marker is treated as a test function by pytest. |
| 10 |
The marked function is executed as an asyncio task in the event loop provided by pytest-asyncio. |
| 11 |
|
| 12 |
Multiple async tests in a single class or module can be marked in different ways: |
| 13 |
|
| 14 |
.. tabs:: |
| 15 |
|
| 16 |
.. tab:: decorator |
| 17 |
|
| 18 |
.. include:: function_scoped_loop_strict_mode_example.py |
| 19 |
:code: python |
| 20 |
|
| 21 |
.. tab:: pytestmark |
| 22 |
|
| 23 |
.. include:: function_scoped_loop_pytestmark_strict_mode_example.py |
| 24 |
:code: python |
| 25 |
|
| 26 |
The ``pytest.mark.asyncio`` marker can be omitted entirely in |auto mode|_ where the *asyncio* marker is added automatically to *async* test functions. |
| 27 |
|
| 28 |
By default, each test runs in its own asyncio event loop. |
| 29 |
Multiple tests can share the same event loop by providing a *loop_scope* keyword argument to the *asyncio* mark. |
| 30 |
The supported scopes are *function*, *class*, *module*, *package*, and *session*. |
| 31 |
|
| 32 |
The following code example provides a shared event loop for all tests in ``TestClassScopedLoop``: |
| 33 |
|
| 34 |
.. include:: class_scoped_loop_strict_mode_example.py |
| 35 |
:code: python |
| 36 |
|
| 37 |
Similar to class-scoped event loops, a module-scoped loop is provided when setting mark's scope to *module*: |
| 38 |
|
| 39 |
.. include:: module_scoped_loop_strict_mode_example.py |
| 40 |
:code: python |
| 41 |
|
| 42 |
Subpackages do not share the loop with their parent package. |
| 43 |
|
| 44 |
Tests marked with *session* scope share the same event loop, even if the tests exist in different packages. |
| 45 |
|
| 46 |
The ``pytest.mark.asyncio`` marker also accepts a ``loop_factories`` keyword argument to select a subset of configured event loop factories for a test. If ``loop_factories`` contains names not available from the hook, those test variants are skipped. |
| 47 |
|
| 48 |
.. |auto mode| replace:: *auto mode* |
| 49 |
.. _auto mode: ../../concepts.html#auto-mode |
| 50 |
.. |pytestmark| replace:: ``pytestmark`` |
| 51 |
.. _pytestmark: http://doc.pytest.org/en/latest/example/markers.html#marking-whole-classes-or-modules |