pytest场景中,使用夹具创建测试资源时,装饰器@pytest.fixture报错:fixture ‘xxx‘ not found
·
最近在看《Python从入门到实践》
项目场景:
来源:第11章习题
“练习 11.3:雇员 编写一个名为 Employee 的类,其__init__() 方法接受名、姓和年薪,并将它们都存储在属性中。编写一个名为 give_raise() 的方法,它默认将年薪增加5000 美元,同时能够接受其他的年薪增加量。为 Employee 类编写一个测试文件,其中包含两个测试函数:test_give_default_raise() 和test_give_custom_raise()。在不使用夹具的情况下编写这两个测试,并确保它们都通过了。然后,编写一个夹具,以免在每个测试函数中都创建一个 Employee 对象。重新运行测试,确认两个测试都通过了。”
类已写好:
class Employee:
"""雇员"""
def __init__(self, last_name, first_name, salary):
self.last_name = last_name
self.first_name = first_name
self.salary = salary
def give_raise(self, increment=5000):
"""默认将年薪增加5000 美元,同时能够接受其他的年薪增加量"""
self.salary += increment
两个测试函数如下(使用夹具版):
@pytest.fixture
def employee_info():
"""一个可供所有测试函数使用的Employee实例"""
employee = Employee('zhong', 'qu', 100)
return employee
def test_give_default_raise(employee):
assert employee.salary == 100
def test_give_custom_raise(employee):
employee.give_raise()
assert employee.salary == 5100
问题描述
打开终端Terminal,输入命令进行测试(.py文件右键——Open In——Terminal)
python -m pytest
报错:无法找到对应fixture

解决方案:
使装饰器@pytest.fixture定义的函数名,与测试函数中引用的参数名保持一致
比如这里,def的是employee_info,则以test_开头命名的测试函数中引用的参数也设置成employee_info,因此第一个函数的返回值也是employee_info

再运行,即可成功

原因分析:
Pytest 严格匹配装饰器定义的名称。
Pytest 的查找逻辑是基于“函数名”(Function Name),而不是“返回值”(Return Value)。
更多推荐

所有评论(0)