Skip to content

resetall does not work when using create_autospec #389

@inikolaev

Description

@inikolaev

Not sure if there exists a different way to achieve what I want, but I use create_autospec extensively and ran into a case where I need to be able to reset it between the tests. I can do this manually, but then I ran into this plugin and noticed resetall, but it turned out that mocks created with create_autospec are not taken into account by resetall.

Consider the following example:

@pytest.fixture(scope="session")
def service_mock():
   ...

@pytest.fixture(scope="session")
def expensive_to_construct_fixture(service_mock):
   ...

I want to avoid creating the expensive fixture on each test run, so I use session scope, but it depends on other mocks which I need to be able to configure and assert in my tests, but then I have to reset them manually.

I would rather create function scope autouse fixture, that would reset all the mocks:

@pytest.fixture(autouse=True)
def reset_all_mocks(session_mocker) -> None:
    session_mocker.resetall()

But unfortunately mocks created with create_autospec are not added to the _patches_and_mocks and thus I cannot use resetall.

Would this be ok to add support for create_autospec? It seems to be pretty straightforward to add it - pretty much something like this would work, but maybe you have some other considerations?

def create_autospec(self, *args, **kwargs):
    m = self.mock_module.create_autospec(*args, **kwargs)
    self._patches_and_mocks.append((None, m))
    return m

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions