[Python] Pytest fixture(autouse=True) that uses monkeypatch is seen by a test that shouldn't...

Discussão em 'Python' iniciado por Stack, Abril 18, 2025.

  1. Stack

    Stack Membro Participativo

    I have the following structure

    /tests/test_permissions.py
    /tests/test_types.py


    test_permissions.py has a fixture:

    @pytest.fixture(autouse=True)
    def patch_some_func(monkeypatch):
    monkeypatch.setattr(SomeClass,"some_func", OtherClass.some_other_func)


    This works fine where it is needed. However, in test_types.py the tests where I want to test some_func also use this fixture, even though it is only available in the sibling file and according to my thought process therefore shouldn't be. There are no imports of either the test_permissions.py file higher up in the conftest.py file (or in any other file for that matter).

    Is my understanding wrong (very much possible, please enlighten me)? Or is the fixture not tearing down properly somehow?

    I tried using a monkeypatch.context() with block and did a manual .undo() after yielding to the test, to check if the teardown of the monkeypatch was somehow failing, but this didn't work.

    Using the method in the accepted answer here ensures that the test doesn't patch stuff, but this is not something I would want to add to every test outside of test_permissions.py, plus I am really looking for understanding why it is performing the way it does.

    [Edit] I also tried putting test_permissions.py in its own subfolder and even then the tests in test_types.py are using the fixture.

    Continue reading...

Compartilhe esta Página