Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

For what 'pytest.mark.asyncio' is used?

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
like image 243
Egor Osokin Avatar asked Aug 12 '19 13:08

Egor Osokin


2 Answers

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()
like image 196
Sławomir Lenart Avatar answered Sep 21 '22 06:09

Sławomir Lenart


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.

like image 23
followben Avatar answered Sep 25 '22 06:09

followben