pytest 夹具 'dog' 未找到

pytest fixture 'dog' not found

例如,我正在使用 pytest

调用以下代码
class Dog:
   def __init__(self, name, age, breed):
        self.name = name
        self.age = age
        self.breed = breed

def test_dog_age(dog):
    dog_age = dog.age
    assert dog_age == 7
    
if __name__ == '__main__':
    dog1 = Dog('rex', 7, 'labrador')
    test_dog_age(dog1)

我收到一条错误消息

E fixture 'dog' not found available fixtures: cache, capfd, capfdbinary, caplog, capsys, capsysbinary, doctest_namespace, monkeypatch, pytestconfig, record_property, record_testsuite_property, record_xml_attribute, recwarn, tmp_path, tmp_path_factory, tmpdir, tmpdir_factory use 'pytest --fixtures [testpath]' for help on them.

第 1 行出现意外缩进。

为了使这一点更清楚:pytest 基本上通过收集它找到的所有测试、应用所有定义的固定装置和挂钩并执行测试来工作。

在你的例子中,你的测试看起来像:

def test_dog_age():
    dog = Dog('rex', 7, 'labrador')
    assert dog.age == 7

并且您将在命令行调用 pytest 来执行测试。您也可以使用特定的测试文件调用它,例如 pytest test_dog.py.

您添加到测试函数的任何参数都作为测试夹具处理,如果找不到具有该名称的夹具(仅按名称查找夹具),您将收到上述错误。

def 函数不应以“test”或“test_”开头。 def test_dog_age(dog): -->def dog_age_test(dog):