1pytest-asyncio: pytest support for asyncio
2==========================================
3
4.. image:: https://img.shields.io/pypi/v/pytest-asyncio.svg
5    :target: https://pypi.python.org/pypi/pytest-asyncio
6.. image:: https://travis-ci.org/pytest-dev/pytest-asyncio.svg?branch=master
7    :target: https://travis-ci.org/pytest-dev/pytest-asyncio
8.. image:: https://coveralls.io/repos/pytest-dev/pytest-asyncio/badge.svg
9    :target: https://coveralls.io/r/pytest-dev/pytest-asyncio
10.. image:: https://img.shields.io/pypi/pyversions/pytest-asyncio.svg
11    :target: https://github.com/pytest-dev/pytest-asyncio
12    :alt: Supported Python versions
13
14pytest-asyncio is an Apache2 licensed library, written in Python, for testing
15asyncio code with pytest.
16
17asyncio code is usually written in the form of coroutines, which makes it
18slightly more difficult to test using normal testing tools. pytest-asyncio
19provides useful fixtures and markers to make testing easier.
20
21.. code-block:: python
22
23    @pytest.mark.asyncio
24    async def test_some_asyncio_code():
25        res = await library.do_something()
26        assert b'expected result' == res
27
28pytest-asyncio has been strongly influenced by pytest-tornado_.
29
30.. _pytest-tornado: https://github.com/eugeniy/pytest-tornado
31
32Features
33--------
34
35- fixtures for creating and injecting versions of the asyncio event loop
36- fixtures for injecting unused tcp ports
37- pytest markers for treating tests as asyncio coroutines
38- easy testing with non-default event loops
39- support for `async def` fixtures and async generator fixtures
40
41Installation
42------------
43
44To install pytest-asyncio, simply:
45
46.. code-block:: bash
47
48    $ pip install pytest-asyncio
49
50This is enough for pytest to pick up pytest-asyncio.
51
52Fixtures
53--------
54
55``event_loop``
56~~~~~~~~~~~~~~
57Creates and injects a new instance of the default asyncio event loop. By
58default, the loop will be closed at the end of the test (i.e. the default
59fixture scope is ``function``).
60
61Note that just using the ``event_loop`` fixture won't make your test function
62a coroutine. You'll need to interact with the event loop directly, using methods
63like ``event_loop.run_until_complete``. See the ``pytest.mark.asyncio`` marker
64for treating test functions like coroutines.
65
66Simply using this fixture will not set the generated event loop as the
67default asyncio event loop, or change the asyncio event loop policy in any way.
68Use ``pytest.mark.asyncio`` for this purpose.
69
70.. code-block:: python
71
72    def test_http_client(event_loop):
73        url = 'http://httpbin.org/get'
74        resp = event_loop.run_until_complete(http_client(url))
75        assert b'HTTP/1.1 200 OK' in resp
76
77This fixture can be easily overridden in any of the standard pytest locations
78(e.g. directly in the test file, or in ``conftest.py``) to use a non-default
79event loop. This will take effect even if you're using the
80``pytest.mark.asyncio`` marker and not the ``event_loop`` fixture directly.
81
82.. code-block:: python
83
84    @pytest.fixture
85    def event_loop():
86        loop = MyCustomLoop()
87        yield loop
88        loop.close()
89
90If the ``pytest.mark.asyncio`` marker is applied, a pytest hook will
91ensure the produced loop is set as the default global loop.
92Fixtures depending on the ``event_loop`` fixture can expect the policy to be properly modified when they run.
93
94``unused_tcp_port``
95~~~~~~~~~~~~~~~~~~~
96Finds and yields a single unused TCP port on the localhost interface. Useful for
97binding temporary test servers.
98
99``unused_tcp_port_factory``
100~~~~~~~~~~~~~~~~~~~~~~~~~~~
101A callable which returns a different unused TCP port each invocation. Useful
102when several unused TCP ports are required in a test.
103
104.. code-block:: python
105
106    def a_test(unused_tcp_port_factory):
107        port1, port2 = unused_tcp_port_factory(), unused_tcp_port_factory()
108        ...
109
110Async fixtures
111~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
112Asynchronous fixtures are defined just like ordinary pytest fixtures, except they should be coroutines or asynchronous generators.
113
114.. code-block:: python3
115
116    @pytest.fixture
117    async def async_gen_fixture():
118        await asyncio.sleep(0.1)
119        yield 'a value'
120
121    @pytest.fixture(scope='module')
122    async def async_fixture():
123        return await asyncio.sleep(0.1)
124
125All scopes are supported, but if you use a non-function scope you will need
126to redefine the ``event_loop`` fixture to have the same or broader scope.
127Async fixtures need the event loop, and so must have the same or narrower scope
128than the ``event_loop`` fixture.
129
130If you want to do this with Python 3.5, the ``yield`` statement must be replaced with ``await yield_()`` and the coroutine
131function must be decorated with ``@async_generator``, like so:
132
133.. code-block:: python3
134
135    from async_generator import yield_, async_generator
136
137    @pytest.fixture
138    @async_generator
139    async def async_gen_fixture():
140        await asyncio.sleep(0.1)
141        await yield_('a value')
142
143
144Markers
145-------
146
147``pytest.mark.asyncio``
148~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
149Mark your test coroutine with this marker and pytest will execute it as an
150asyncio task using the event loop provided by the ``event_loop`` fixture. See
151the introductory section for an example.
152
153The event loop used can be overriden by overriding the ``event_loop`` fixture
154(see above).
155
156In order to make your test code a little more concise, the pytest |pytestmark|_
157feature can be used to mark entire modules or classes with this marker.
158Only test coroutines will be affected (by default, coroutines prefixed by
159``test_``), so, for example, fixtures are safe to define.
160
161.. code-block:: python
162
163    import asyncio
164    import pytest
165
166    # All test coroutines will be treated as marked.
167    pytestmark = pytest.mark.asyncio
168
169    async def test_example(event_loop):
170        """No marker!"""
171        await asyncio.sleep(0, loop=event_loop)
172
173.. |pytestmark| replace:: ``pytestmark``
174.. _pytestmark: http://doc.pytest.org/en/latest/example/markers.html#marking-whole-classes-or-modules
175
176Changelog
177---------
1780.13.0 (2020-06-24)
179~~~~~~~~~~~~~~~~~~~
180- Fix `#162 <https://github.com/pytest-dev/pytest-asyncio/issues/162>`_, and ``event_loop`` fixture behavior now is coherent on all scopes.
181  `#164 <https://github.com/pytest-dev/pytest-asyncio/pull/164>`_
182
1830.12.0 (2020-05-04)
184~~~~~~~~~~~~~~~~~~~
185- Run the event loop fixture as soon as possible. This helps with fixtures that have an implicit dependency on the event loop.
186  `#156 <https://github.com/pytest-dev/pytest-asyncio/pull/156>`_
187
1880.11.0 (2020-04-20)
189~~~~~~~~~~~~~~~~~~~
190- Test on 3.8, drop 3.3 and 3.4. Stick to 0.10 for these versions.
191  `#152 <https://github.com/pytest-dev/pytest-asyncio/pull/152>`_
192- Use the new Pytest 5.4.0 Function API. We therefore depend on pytest >= 5.4.0.
193  `#142 <https://github.com/pytest-dev/pytest-asyncio/pull/142>`_
194- Better ``pytest.skip`` support.
195  `#126 <https://github.com/pytest-dev/pytest-asyncio/pull/126>`_
196
1970.10.0 (2019-01-08)
198~~~~~~~~~~~~~~~~~~~~
199- ``pytest-asyncio`` integrates with `Hypothesis <https://hypothesis.readthedocs.io>`_
200  to support ``@given`` on async test functions using ``asyncio``.
201  `#102 <https://github.com/pytest-dev/pytest-asyncio/pull/102>`_
202- Pytest 4.1 support.
203  `#105 <https://github.com/pytest-dev/pytest-asyncio/pull/105>`_
204
2050.9.0 (2018-07-28)
206~~~~~~~~~~~~~~~~~~
207- Python 3.7 support.
208- Remove ``event_loop_process_pool`` fixture and
209  ``pytest.mark.asyncio_process_pool`` marker (see
210  https://bugs.python.org/issue34075 for deprecation and removal details)
211
2120.8.0 (2017-09-23)
213~~~~~~~~~~~~~~~~~~
214- Improve integration with other packages (like aiohttp) with more careful event loop handling.
215  `#64 <https://github.com/pytest-dev/pytest-asyncio/pull/64>`_
216
2170.7.0 (2017-09-08)
218~~~~~~~~~~~~~~~~~~
219- Python versions pre-3.6 can use the async_generator library for async fixtures.
220  `#62 <https://github.com/pytest-dev/pytest-asyncio/pull/62>`
221
222
2230.6.0 (2017-05-28)
224~~~~~~~~~~~~~~~~~~
225- Support for Python versions pre-3.5 has been dropped.
226- ``pytestmark`` now works on both module and class level.
227- The ``forbid_global_loop`` parameter has been removed.
228- Support for async and async gen fixtures has been added.
229  `#45 <https://github.com/pytest-dev/pytest-asyncio/pull/45>`_
230- The deprecation warning regarding ``asyncio.async()`` has been fixed.
231  `#51 <https://github.com/pytest-dev/pytest-asyncio/pull/51>`_
232
2330.5.0 (2016-09-07)
234~~~~~~~~~~~~~~~~~~
235- Introduced a changelog.
236  `#31 <https://github.com/pytest-dev/pytest-asyncio/issues/31>`_
237- The ``event_loop`` fixture is again responsible for closing itself.
238  This makes the fixture slightly harder to correctly override, but enables
239  other fixtures to depend on it correctly.
240  `#30 <https://github.com/pytest-dev/pytest-asyncio/issues/30>`_
241- Deal with the event loop policy by wrapping a special pytest hook,
242  ``pytest_fixture_setup``. This allows setting the policy before fixtures
243  dependent on the ``event_loop`` fixture run, thus allowing them to take
244  advantage of the ``forbid_global_loop`` parameter. As a consequence of this,
245  we now depend on pytest 3.0.
246  `#29 <https://github.com/pytest-dev/pytest-asyncio/issues/29>`_
247
248
2490.4.1 (2016-06-01)
250~~~~~~~~~~~~~~~~~~
251- Fix a bug preventing the propagation of exceptions from the plugin.
252  `#25 <https://github.com/pytest-dev/pytest-asyncio/issues/25>`_
253
2540.4.0 (2016-05-30)
255~~~~~~~~~~~~~~~~~~
256- Make ``event_loop`` fixtures simpler to override by closing them in the
257  plugin, instead of directly in the fixture.
258  `#21 <https://github.com/pytest-dev/pytest-asyncio/pull/21>`_
259- Introduce the ``forbid_global_loop`` parameter.
260  `#21 <https://github.com/pytest-dev/pytest-asyncio/pull/21>`_
261
2620.3.0 (2015-12-19)
263~~~~~~~~~~~~~~~~~~
264- Support for Python 3.5 ``async``/``await`` syntax.
265  `#17 <https://github.com/pytest-dev/pytest-asyncio/pull/17>`_
266
2670.2.0 (2015-08-01)
268~~~~~~~~~~~~~~~~~~
269- ``unused_tcp_port_factory`` fixture.
270  `#10 <https://github.com/pytest-dev/pytest-asyncio/issues/10>`_
271
272
2730.1.1 (2015-04-23)
274~~~~~~~~~~~~~~~~~~
275Initial release.
276
277
278Contributing
279------------
280Contributions are very welcome. Tests can be run with ``tox``, please ensure
281the coverage at least stays the same before you submit a pull request.
282