I don't understand for which purposes the decorator @pytest.mark.asyncio
can be used.
I've tried to run the following code snippet with pytest
and pytest-asyncio
plugin installed and it failed, so I concluded that pytest collects test coroutines without the decorator. Why it exists so?
async def test_div():
return 1 / 0
When your tests are marked with @pytest.mark.asyncio
, they become coroutines, together with the keyword await
in body
pytest
will execute it as an asyncio task using the event loop provided by the event_loop
fixture:
This code with decorator
@pytest.mark.asyncio
async def test_example(event_loop):
do_stuff()
await asyncio.sleep(0.1, loop=event_loop)
is equal to writing this:
def test_example():
loop = asyncio.new_event_loop()
try:
do_stuff()
asyncio.set_event_loop(loop)
loop.run_until_complete(asyncio.sleep(0.1, loop=loop))
finally:
loop.close()
Sławomir Lenart's answer is still correct, but note that as of pytest-asyncio>=0.17
if you add asyncio_mode = auto
to your pyproject.toml
or pytest.ini
there is no need for the marker, i.e. this behaviour is enabled for async tests automatically.
See https://github.com/pytest-dev/pytest-asyncio#modes.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With