pythonpython-3.xpytestpytest-asyncio

What is 'pytest.mark.asyncio' is used for?


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

Solution

  • 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