FastAPI、SQLAlchemy、pytest,无法获得100%覆盖率,没有正确收集

Ili*_*iev 11 python sqlalchemy python-asyncio pytest-asyncio fastapi

我正在尝试构建FastAPI完全覆盖测试的应用程序python 3.9 为此目的,我选择了堆栈:FastAPI、uvicorn、SQLAlchemy、asyncpg、pytest(+ async、cov 插件)、覆盖范围和 httpx AsyncClient

这是我的最低要求.txt

所有测试都运行顺利,我得到了预期的结果。但我遇到了问题,覆盖范围没有正确收集。await当协程将控制权返回到事件循环时,它会在第一个关键字之后中断

以下是关于如何重现此行为的最小集合(也可以在 GitHub 上找到)。

应用代码main.py

import sqlalchemy as sa
from fastapi import FastAPI
from sqlalchemy.ext.asyncio import AsyncSession, create_async_engine
from starlette.requests import Request

app = FastAPI()
DATABASE_URL = 'sqlite+aiosqlite://?cache=shared'


@app.on_event('startup')
async def startup_event():
    engine = create_async_engine(DATABASE_URL, future=True)
    app.state.session = AsyncSession(engine, expire_on_commit=False)
    app.state.engine = engine


@app.on_event('shutdown')
async def shutdown_event():
    await app.state.session.close()


@app.get('/', name="home")
async def get_home(request: Request):
    res = await request.app.state.session.execute(sa.text('SELECT 1'))
    # after this line coverage breaks
    row = res.first()
    assert str(row[0]) == '1'
    return {"message": "OK"}
Run Code Online (Sandbox Code Playgroud)

测试设置conftest.py如下所示:

import asyncio

import pytest
from asgi_lifespan import LifespanManager
from httpx import AsyncClient


@pytest.fixture(scope='session')
async def get_app():
    from main import app
    async with LifespanManager(app):
        yield app


@pytest.fixture(scope='session')
async def get_client(get_app):
    async with AsyncClient(app=get_app, base_url="http://testserver") as client:
        yield client


@pytest.fixture(scope="session")
def event_loop():
    loop = asyncio.new_event_loop()
    yield loop
    loop.close()
Run Code Online (Sandbox Code Playgroud)

测试很简单(只需检查状态代码是否为 200)test_main.py

import pytest
from starlette import status


@pytest.mark.asyncio
async def test_view_health_check_200_ok(get_client):
    res = await get_client.get('/')
    assert res.status_code == status.HTTP_200_OK
Run Code Online (Sandbox Code Playgroud)
pytest -vv --cov=. --cov-report term-missing --cov-report html
Run Code Online (Sandbox Code Playgroud)

结果我得到了:

Name           Stmts   Miss  Cover   Missing
--------------------------------------------
conftest.py       18      0   100%
main.py           20      3    85%   26-28
test_main.py       6      0   100%
--------------------------------------------
TOTAL             44      3    93%
Run Code Online (Sandbox Code Playgroud)

在此输入图像描述

  1. 上面的示例代码使用aiosqlite代替,asyncpg但覆盖失败也会持续重现
  2. 我得出的结论是这个问题是SQLAlchemy,因为这个例子asyncpg没有使用SQLAlchemy像 charm 这样的作品

r-m*_*m-n 11

这是覆盖率中 SQLAlchemy 1.4 的问题:https://github.com/nedbat/coveragepy/issues/1082https://github.com/nedbat/coveragepy/issues/1012

你可以尝试使用--concurrency==greenlet选项


rfe*_*rov 6

这就是对我的帮助:

您可以将覆盖并发greenlet设置添加到您的配置setup.cfg.coveragerc文件中:

[coverage:run]
branch = True
concurrency =
    greenlet
    thread
Run Code Online (Sandbox Code Playgroud)