Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

resetall does not work when using create_autospec #389

Closed
inikolaev opened this issue Oct 12, 2023 · 2 comments · Fixed by #390
Closed

resetall does not work when using create_autospec #389

inikolaev opened this issue Oct 12, 2023 · 2 comments · Fixed by #390

Comments

@inikolaev
Copy link
Contributor

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
@nicoddemus
Copy link
Member

Hi @inikolaev,

Thanks for the report!

Yeah that sounds reasonable, would you like to open a PR with that feature?

@inikolaev
Copy link
Contributor Author

Hi @inikolaev,

Thanks for the report!

Yeah that sounds reasonable, would you like to open a PR with that feature?

Sure, I can make a PR!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging a pull request may close this issue.

2 participants