pytest-subprocess icon indicating copy to clipboard operation
pytest-subprocess copied to clipboard

conflict with mock.patch

Open mpagot opened this issue 2 years ago • 2 comments

I have a script that internally is using subproccess.run to call some external executable (e.g dosomething). So for example

$ python myscript.py do

It internally results in a subprocess call of dosomething /tmp Test about this base functionality is like

def test_main(fp):
    fp.register(['dosomething', '/tmp'])
    main(['do'])

Some of the script configurations (sort of hidden) are using env variables. So for example

$ MYSCRIPT_TMP_FOLDER=/mytmp  python myscript.py do

It internally results in a subprocess call of dosomething /mytmp

My attempt to test it is like

def test_main(fp):
    fp.register(['dosomething', '/mytmp'])
    with mock.patch.dict(os.environ, {'MYSCRIPT_TMP_FOLDER': 'mytmp'}):
        main(['do'])

Unfortunately the with mock (or something else) seems to interfere with fp. As result the true subprocess and so the dosomething executable is called during the test.

Expected behavior is that fp to keep to be able to intercept submodule call and not to perform it.

mpagot avatar May 31 '22 12:05 mpagot

Thanks for reporting, I'll try to reproduce this error during the weekend, but I'm not sure if I'll have enough time for that. If you can, please prepare a complete example, where this behavior could be reproduced. That would help me a lot with getting to the point.

aklajnert avatar May 31 '22 14:05 aklajnert

Sorry @mpagot, but I'm not able to reproduce this issue. Here's how I've tried it:

COMMAND = ["dosomething", "/mytmp"]


def subprocess_calling_function(command):
    subprocess.call(command)


def test_mock_interference(fp):

    fp.allow_unregistered(False)

    fp.register(COMMAND)
    with mock.patch.dict(os.environ, {"MYSCRIPT_TMP_FOLDER": "mytmp"}):
        subprocess_calling_function(COMMAND)

    assert fp.call_count(COMMAND) == 1

Please provide a minimal example that reproduces the problem, otherwise, I cannot fix this.

aklajnert avatar Jun 16 '22 07:06 aklajnert

Closing this issue as it cannot be reproduced. Feel free to reopen when you'll be able to provide a method to reproduce this problem.

aklajnert avatar Oct 02 '22 07:10 aklajnert