Search code examples
pythonpython-3.xpytestfixtures

pytest fixture 'dog' not found


Say, for instance, I'm calling the following code using 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)

I'm getting an error saying

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.


Solution

  • To make this clearer: pytest basically works by collecting all tests it finds, applying all fixtures and hooks that are defined and executing the tests.

    In your case, your test would look something like:

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

    And you would call pytest at the command line to exceute the test. You can also call it with the specific test file, say pytest test_dog.py.

    Any parameter you add to the test function is handled as a test fixture, and if no fixture is found with that name (fixtures are looked up by name only), you get the mentioned error.