使用pytest+asyncio编写fixture时出现AttributeError问题
问题分析与解决
错误原因
你遇到的AttributeError: 'async_generator' object has no attribute 'conversation',核心原因是pytest没有正确解析异步fixture的返回值,导致测试用例拿到的是async生成器对象,而非实际的TelegramClient实例。常见触发场景有两个:
- 使用了普通的
@pytest.fixture装饰器,而非pytest-asyncio提供的异步fixture装饰器; - fixture实现中没有通过
yield(或return)正确返回TelegramClient实例。
正确的异步Fixture写法
首先确保安装pytest-asyncio:
pip install pytest-asyncio
然后编写session级的异步fixture:
import pytest import pytest_asyncio from telethon import TelegramClient from telethon.sessions import StringSession # 替换为你的测试环境API信息 API_ID = 123456 API_HASH = "your_api_hash_here" TEST_PHONE = "+1234567890" @pytest_asyncio.fixture(scope="session") async def telegram_client(): # 初始化Telegram客户端 client = TelegramClient(StringSession(), API_ID, API_HASH) await client.start(phone=TEST_PHONE) # 将客户端实例传递给测试用例 yield client # Session结束后清理资源 await client.disconnect()
测试用例示例
async def test_bot_interaction(telegram_client): # 此时telegram_client是正确的TelegramClient实例 async with telegram_client.conversation("@your_test_bot") as conv: await conv.send_message("/start") response = await conv.get_response() assert "欢迎" in response.text
关键注意事项
- 必须使用
@pytest_asyncio.fixture替代普通@pytest.fixture,pytest-asyncio会专门处理异步生成器,解析出yield返回的实例; - session级fixture要保证客户端在整个测试会话结束后正确断开,避免残留连接;
- 敏感信息(API_ID、API_HASH等)建议通过环境变量导入,不要硬编码在代码中。
内容的提问来源于stack exchange,提问作者Andrei Alekseev
相关产品推荐
相关产品推荐

