相关疑难解决方法(0)

在固定装置中包含代码后,使用 asyncio 进行 pytest 时出现 AttributeError

我需要测试我的电报机器人。为此,我需要创建客户端用户来询问我的机器人。我找到了可以做到这一点的电视马拉松图书馆。首先,我编写了一个代码示例以确保授权和连接正常工作并向自己发送测试消息(省略导入):

api_id = int(os.getenv("TELEGRAM_APP_ID"))
api_hash = os.getenv("TELEGRAM_APP_HASH")
session_str = os.getenv("TELETHON_SESSION")

async def main():
    client = TelegramClient(
        StringSession(session_str), api_id, api_hash,
        sequential_updates=True
    )
    await client.connect()
    async with client.conversation("@someuser") as conv:
        await conv.send_message('Hey, what is your name?')


if __name__ == "__main__":
    asyncio.run(main())
Run Code Online (Sandbox Code Playgroud)

@someuser(我)成功收到消息。好的,现在我根据上面的代码使用固定装置创建一个测试:

api_id = int(os.getenv("TELEGRAM_APP_ID"))
api_hash = os.getenv("TELEGRAM_APP_HASH")
session_str = os.getenv("TELETHON_SESSION")

@pytest.fixture(scope="session")
async def client():
    client = TelegramClient(
        StringSession(session_str), api_id, api_hash,
        sequential_updates=True
    )
    await client.connect()
    yield client
    await client.disconnect()


@pytest.mark.asyncio
async def test_start(client: TelegramClient):
    async with client.conversation("@someuser") as conv:
        await …
Run Code Online (Sandbox Code Playgroud)

python pytest python-asyncio telethon

16
推荐指数
2
解决办法
1万
查看次数

异步方法的 Python 覆盖范围

我使用 aiohttp、pytest 和 pytest-cov 来覆盖我的代码。我想要获得更好的覆盖率<但现在我有点卡住了,因为事件简单代码没有显示 100% cov。比如这段代码:

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

在覆盖率报告中,它显示返回的行未被覆盖。

我已阅读此链接异步方法的代码覆盖率。但这是针对 C# 的,我无法理解:

如果您正在等待的操作在等待之前已完成,则最常发生这种情况。

我的运行测试的代码:

python3.9 -m pytest -vv --cov --cov-report xml --cov-report term-missing
Run Code Online (Sandbox Code Playgroud)

我对上面代码的测试

async def test_healthz_page(test_client):
    response = await test_client.get("/healthz")
    assert response.status == HTTPStatus.OK
Run Code Online (Sandbox Code Playgroud)

python pytest python-3.x python-asyncio aiohttp

9
推荐指数
1
解决办法
2221
查看次数

标签 统计

pytest ×2

python ×2

python-asyncio ×2

aiohttp ×1

python-3.x ×1

telethon ×1