Use pytest fixture inside mock class

  pytest, python, python-3.x, python-unittest, testing

I need to use a fixture that prepares some data inside a class that will be used to mock a third party library. Right now I have the equivalent to this:

@pytest.fixture(scope="session")
def file(tmpdir_factory):
    """Long process that creates a mock file."""
    ...
    return file_path
    

I need to use this fixture inside the class constructor, something like:

class Mock:

    def __init__(self, file):
        self._file = file

    def get(self, *args, **kwargs):
        return self._file

I need the file fixture to be outside the Mock class since it is used in other places. The Mock class will be used very similar to this:


def my_test():
    with patch("thirdparty.Class", new=Mock):
        ...

I tried using the @pytest.mark.usefixtures("file") decorator but it did not work. How can I inject the fixture to the class?

Source: Python-3x Questions

LEAVE A COMMENT