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
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).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With