13

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
8
  • How did your unittest invoke the healthcheck function? You may need to adapt your test case methods such that they execute as intended, please take a look at this thread on how this may be done. Commented Aug 18, 2021 at 5:24
  • added in the post Commented Aug 18, 2021 at 5:33
  • You will need to mark your test correctly with pytest, see thread and thread and thread for examples. Commented Aug 18, 2021 at 5:54
  • Pytest doesn't have built-in support for async tests. What plugin do you use for that, pytest-asyncio or something else? Commented Aug 18, 2021 at 6:09
  • 3
    To clarify: the code after the first await is never shown as covered. Commented Apr 11, 2023 at 14:45

1 Answer 1

13

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).

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.