繁体   English   中英

在夹具中包含代码后,带有异步的 pytest 中的 AttributeError

[英]AttributeError in pytest with asyncio after include code in fixtures

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

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

@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 conv.send_message("Hey, what is your name?")

运行pytest后收到错误:

AttributeError: 'async_generator' object has no attribute 'conversation'

似乎client对象在“错误”条件下从client夹具返回。 这是print(dir(client))

['__aiter__', '__anext__', '__class__', '__class_getitem__', '__del__', '__delattr__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__le__', '__lt__', '__name__', '__ne__', '__new__', '__qualname__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', 'aclose', 'ag_await', 'ag_code', 'ag_frame', 'ag_running', 'asend', 'athrow']

我在哪里从夹具中的生成器中释放“正确”的客户端对象?

我宁愿使用anyio而不是pytest-asyncio

  • pip install anyio

尝试这个:

import pytest

@pytest.fixture(scope="session")
def anyio_backend():
    return "asyncio"

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

@pytest.mark.anyio
async def test_start(conv):
    await conv.send_message("Hey, what is your name?")

根据文档https://pypi.org/project/pytest-asyncio/#async-fixtures在异步夹具中使用@pytest_asyncio.fixture装饰器。

像这样:

import pytest_asyncio

@pytest_asyncio.fixture(scope="session")
async def client():
    ...

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM