Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python coverage for async methods

I use aiohttp, pytest and pytest-cov to get coverage of my code. I want to get better coverage< but now I am a little bit stuck, because event simple code does not show 100% cov. For example this piece of code:

@session_decorator()
async def healthcheck(session, request):
    await session.scalar("select pg_is_in_recovery();")
    return web.json_response({"status": "ok"})

in coverage report it shows that line with return is not covered.

I have read this link Code coverage for async methods. But this is for C# and I can not understand:

This can happen most commonly if the operation you're awaiting is completed before it's awaited.

My code to run tests:

python3.9 -m pytest -vv --cov --cov-report xml --cov-report term-missing

My test for code above

async def test_healthz_page(test_client):
    response = await test_client.get("/healthz")
    assert response.status == HTTPStatus.OK
like image 608
Anton Pomieshchenko Avatar asked Feb 26 '26 14:02

Anton Pomieshchenko


1 Answers

I had the same issue when testing FastAPI code using asyncio. The fix is to create or edit a .coveragerc at the root of your project with the following content:

[run]
concurrency = gevent

If you use a pyproject.toml you can also include this section in that file instead:

[tool.coverage.run]
concurrency = ["gevent"]

In addition, you have to pip install gevent. If using Poetry, run poetry add --group dev gevent.

If the above doesn’t work, try using concurrency = thread,gevent instead (see this comment. Note it says to use --concurrency but this option is not available when you use pytest-cov; you must use .coveragerc).

like image 158
bfontaine Avatar answered Feb 28 '26 05:02

bfontaine