admin管理员组

文章数量:1315310

)

I am struggeling with a teardown scenario of monkeypatch'ed functions.

Setup:

Windows 11, Python 3.10, pytest 8.3.4

Observation

On a high level first:

  • There is a testfunction test_non_e2e that relies on a fixture monkeypatch_context where monkeypatching is going on.
  • There is a testfunction test_e2e that does not use the fixture monkeypatch_context.

If I run each test on its own then everything works.

If I run both tests together in one testrun (not in parallel but sequential in the same run by calling pytest . is what I mean) than the test_e2e fails because the patches are still present.

What I've done so far

So I checked if there is a hidden connection from test_e2e to the fixture by printing the calling function within this fixture. Here is the real fixture:

@pytest.fixture(scope="function", name="monkeypatch_context", autouse=False)
def get_monkeypatch_context(monkeypatch, request):
    # some temporary debugging stuff to see who slurps in the this fixture
    caller_name = request.node.name
    print(f"Fixture called by: {caller_name}")
    # the actual code
    with monkeypatch.context() as monkeypatch_context:
        monkeypatch_context.setattr(
            fat_device_mount,
            "get_mount_path",
            lambda _path: "tests/test_assets",
        )
        # [...] more patching happening here but with the affected patch visible above
        yield monkeypatch_context
        
# I also used this pattern before:

try:
    # do the monkeypatching
    monkeypatch.setattr(...)
finally: 
    monkeypatch.undo()

The output is that test_non_e2e calls this fixture as expected and test_e2e does not, also as expected.

Up to this point I would say that the issue is more about the patch that is not teared down/undone after test_non_e2e ended rather then some kind of hidden slurping the fixture around three corners and other fixtures.

If that helps I can absolutely share the the link to the github repo but I don't know if this is allowed here in the first place :)

The open issues regarding monkeypatch do not look familiar to my observation I would say.

Questions:

Is there somehting more I can do to check if it is an orphaned patch?

Am I using the monkeypatch framework in a wrong manner?

本文标签: monkeypatchingpytest monkeypatch39ed function used in a fixture not undone after each testStack Overflow