我要测试我的电报机器人。要做到这一点,我需要创建客户端用户来询问我的机器人。我找到了电传子库,可以做到这一点。首先,我编写了一个代码示例,以确保授权和连接工作正常,并向自己发送测试消息(省略导入):
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())
@某个用户(我)成功地接收到消息。好了,现在我根据上面的代码创建了一个带有固定装置的测试:
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']
我把“右”客户对象从夹具中的生成器放哪儿了?
发布于 2022-07-18 08:11:04
根据文档@pytest_asyncio.fixture
https://pypi.org/project/pytest-asyncio/#async-fixtures,在异步夹具中使用https://pypi.org/project/pytest-asyncio/#async-fixtures装饰器。
如下所示:
import pytest_asyncio
@pytest_asyncio.fixture(scope="session")
async def client():
...
发布于 2022-07-15 16:19:42
我宁愿使用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://stackoverflow.com/questions/72996818
复制相似问题