如何修复「Coroutine object is not callable」类型提示警告?
Async Pytest Fixtures 类型提示问题
我在给异步pytest fixture添加类型提示时遇到了问题,PyCharm在第二个fixture和测试函数中弹出警告,尝试查阅资料后仍未解决。
相关Fixture代码
Fixture 1: create_raw_user
@pytest.fixture(scope='function') async def create_raw_user(asyncpg_pool) -> Callable[[str, str, str], Awaitable[None]]: async def create_raw_user(email: str, name: str, password: str) -> None: auth = AuthHandler() hashed_password = auth.get_password_hash(password) async with asyncpg_pool.acquire() as connection: return await connection.execute( "INSERT INTO users (email, name, password, registered_at, auth0_registered) VALUES ('%s', '%s', '%s', '%s', '%s')" % (email, name, hashed_password, datetime.utcnow(), False) ) return create_raw_user
Fixture 2: create_user_instance
@pytest.fixture(scope="function") async def create_user_instance(create_raw_user) -> Callable[[str, str, str], Awaitable[dict[str, Any]]]: async def create_user_instance(email: str = "test@email.com", name: str = "ilya", password: str = "password123") -> dict[str, Any]: await create_raw_user(email=email, name=name, password=password) return { "email": email, "name": name, "password": password } return create_user_instance
修复方案
1. 给依赖参数添加明确类型提示
第二个fixture中的create_raw_user参数未标注类型,PyCharm无法推断其类型,需要补充:
# 先确保导入所需类型 from collections.abc import Callable, Awaitable from typing import Any @pytest.fixture(scope="function") async def create_user_instance( create_raw_user: Callable[[str, str, str], Awaitable[int]] # 与第一个fixture的返回类型匹配 ) -> Callable[[str, str, str], Awaitable[dict[str, Any]]]: # 原有代码不变
2. 修正第一个fixture的类型不匹配问题
第一个fixture内部函数返回的是connection.execute的结果(受影响行数,int类型),但类型提示写的是-> None,存在矛盾,需要修正:
async def create_raw_user(email: str, name: str, password: str) -> int: # 原有代码不变
对应的fixture返回类型也要同步修改:
async def create_raw_user(asyncpg_pool) -> Callable[[str, str, str], Awaitable[int]]:
3. 适配带默认参数的函数类型(可选)
内部的create_user_instance函数有默认参数,如果想让类型提示更精准,Python 3.10+可以用ParamSpec处理:
from typing import ParamSpec, TypeVar P = ParamSpec('P') R = TypeVar('R') # 将fixture返回类型改为 Callable[P, Awaitable[dict[str, Any]]]
4. 修复SQL注入风险(额外优化)
当前SQL语句用字符串格式化拼接参数,存在注入风险,建议改用asyncpg的参数化查询:
await connection.execute( "INSERT INTO users (email, name, password, registered_at, auth0_registered) VALUES ($1, $2, $3, $4, $5)", email, name, hashed_password, datetime.utcnow(), False )
内容的提问来源于stack exchange,提问作者TeraBasedProgrammer
相关产品推荐
相关产品推荐

