Pytest同时使用Fixture与装饰器出现参数缺失错误,求解决方案
Pytest装饰器与Fixture共存时参数注入错误的解决办法
问题根源
你写的自定义装饰器返回的wrapper函数覆盖了原测试函数的签名信息。Pytest是通过函数签名来识别需要注入哪些Fixture的,现在它只能看到wrapper的无参签名,自然不会给测试函数传入sample_data参数,触发了missing required positional argument错误。
修复方案
用functools.wraps装饰wrapper函数,保留原测试函数的元数据(包括签名),让Pytest能正确识别到测试函数依赖的Fixture。同时注意修正脚本入口的拼写错误("main" → "__main__")。
修改后的完整代码:
import pytest import functools @pytest.fixture def sample_data(): return [1, 2, 3, 4, 5] def custom_decorator(func): @functools.wraps(func) # 关键:保留原函数的签名和元数据 def wrapper(*args, **kwargs): print("Decorator: Before test function") result = func(*args, **kwargs) print("Decorator: After test function") return result return wrapper @custom_decorator def test_sum_of_data(sample_data): assert sum(sample_data) == 15 if __name__ == "__main__": # 修正拼写错误 pytest.main()
补充说明
functools.wraps会把原函数的函数名、文档字符串、参数签名等关键信息复制到wrapper上,让Pytest的Fixture注入机制能正常工作。- 原代码里的
if __name__ == "main"是无效的,Python的脚本入口判断必须是__main__(前后各两个下划线),否则直接运行脚本时不会执行测试。
内容的提问来源于stack exchange,提问作者K Ashish
相关产品推荐
相关产品推荐

