11

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
Lorenz Walthert
  • 4,414
  • 1
  • 18
  • 24
Egor Osokin
  • 113
  • 1
  • 1
  • 6

2 Answers2

20

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()

Note / Update

As of pytest-asyncio>=0.17 if you add asyncio_mode = auto to your config (pyproject.toml, setup.cfg or pytest.ini) there is no need for the marker, i.e. this behaviour is enabled for async tests automatically.

See https://pytest-asyncio.readthedocs.io/en/latest/reference/configuration.html

smido
  • 771
  • 6
  • 14
Sławomir Lenart
  • 7,543
  • 4
  • 45
  • 61
4

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://pytest-asyncio.readthedocs.io/en/latest/reference/configuration.html

smido
  • 771
  • 6
  • 14
followben
  • 9,067
  • 4
  • 40
  • 42
  • You are correct but I think this should be part of the accepted answer, not a separate answer by itself, as it shouldn't become 'the right answer'. I'll try to merge it into the accepted one – smido Jul 07 '23 at 09:16