编写异步函数装饰器遇问题:断言未触发,求排查错误
问题分析与修复
你的代码有两个关键问题导致断言未触发:
1. 缺少functools模块导入
代码中使用了@functools.wraps(func)来保留原函数的元信息,但没有导入functools模块。这会导致运行时抛出NameError,装饰器的逻辑根本无法执行,断言代码自然不会被触发。
2. pytest.approx公差参数使用不当(可选修正)
pytest.approx的第二个参数默认是相对公差(百分比),比如你传入的10代表允许目标值±10%的误差。如果你的需求是允许绝对误差不超过10,需要显式指定abs参数,否则当相对误差的计算不符合预期时,可能出现断言逻辑不符合你预期的情况。
修正后的代码
import asyncio import pytest import functools # 新增导入 def tmi_freq_check(needed_value: int, tmi_freq_tolerance: int, tmi_freq_critical: bool, info_message: str = ""): def decorator(func): @functools.wraps(func) async def wrapper(*args, **kwargs): result = await func(*args, **kwargs) if tmi_freq_critical: # 如果需要绝对公差,使用abs参数;如果是相对公差,保留原写法即可 assert needed_value == pytest.approx(result, abs=tmi_freq_tolerance) return result return wrapper return decorator @tmi_freq_check(600, 10, True) async def my_function(): return 500 async def main(): await my_function() asyncio.run(main())
运行修正后的代码,会直接抛出AssertionError,因为500和600的绝对差是100,远大于设置的10,断言逻辑正常触发。
内容的提问来源于stack exchange,提问作者roman
相关产品推荐
相关产品推荐

