Pytest asyncio not launching simple async test

Viewed 1299

Using Pytest and asyncio I am trying to execute an async test:

async def count(self):
    return "2"

async def test_foo(self):
    x = []
    x.append(await asyncio.gather(self.count(), self.count(), self.count()))
    print(x)

If this code is launched without using pytest, it returns this:

[['2', '2', '2']]

With Pytest it does not seem to be executing anything inside the funcion. It returns this warning:

 RuntimeWarning: coroutine 'TestClass.test_foo' was never awaited
    method()

Any idea?

1 Answers

You should use pytest.mark.asyncio marker.

Mark your test coroutine with this marker and pytest will execute it as an asyncio task using the event loop provided by the event_loop fixture.

E.g.

import asyncio
import pytest


class TestClass:
    async def count(self):
        return "2"

    @pytest.mark.asyncio
    async def test_foo(self):
        x = []
        x.append(await asyncio.gather(self.count(), self.count(), self.count()))
        print(x)
        assert x == [['2', '2', '2']]

unit test result:

⚡  coverage run -m pytest -s /Users/dulin/workspace/github.com/mrdulin/python-codelab/src/stackoverflow/66546652/test_example.py && coverage report -m --include="src/*"
============================================================================================================================================ test session starts ============================================================================================================================================
platform darwin -- Python 3.9.2, pytest-5.3.1, py-1.8.0, pluggy-0.13.1
rootdir: /Users/dulin/workspace/github.com/mrdulin/python-codelab
plugins: asyncio-0.10.0
collected 1 item                                                                                                                                                                                                                                                                                            

src/stackoverflow/66546652/test_example.py [['2', '2', '2']]
.

============================================================================================================================================= 1 passed in 0.03s =============================================================================================================================================
Name                                         Stmts   Miss  Cover   Missing
--------------------------------------------------------------------------
src/stackoverflow/66546652/test_example.py      11      0   100%
Related