I've tried to run the following code snippet with pytest and
pytest-asyncio plugin installed and it "failed"
Actually the test is not going to get run. Even if you have pytest and pytest-asyncio installed, it will be skipped and you'll see a warning like this in output:
================================== warnings summary ====================================
tests.py::test_div
/Users/.../ PytestUnhandledCoroutineWarning: async def functions are not natively supported and have been skipped.
You need to install a suitable plugin for your async framework, for example:
- anyio
- pytest-asyncio
- pytest-tornasync
- pytest-trio
- pytest-twisted
warnings.warn(PytestUnhandledCoroutineWarning(msg.format(nodeid)))
-- Docs: https://docs.pytest.org/en/stable/how-to/capture-warnings.html
============================= 1 skipped, 1 warning in 0.02s =============================
As the documentation says:
A coroutine or async generator with this marker is treated as a test
function by pytest.
So you have to mark your async functions.
The @pytest.mark.asyncio decorator also allows you to specify the scope so that some tests can share the same event loop, otherwise each test will run in it’s own event loop:
import asyncio
import pytest
@pytest.mark.asyncio(scope="class")
class TestClassScopedLoop:
loop: asyncio.AbstractEventLoop
async def test_remember_loop(self):
TestClassScopedLoop.loop = asyncio.get_running_loop()
async def test_this_runs_in_same_loop(self):
assert asyncio.get_running_loop() is TestClassScopedLoop.loop