0

In Python 3.10, I have a function like:

from shutil import which
def my_func():
    if which('myexecutable.sh'):
       # do stuff
    else:
       # do other stuff

I would like to write a unit test with Pytest that runs the first part code even though the executable is not present. What is the best way to do this?

I know that I can use monkeypatch.setenv() to set an environment variable, but that's not going to make the which() check pass. There's also the added challenge of making sure this is compatible on Windows and Linux.

1 Answer 1

1

You could try like this:

# in script file
from shutil import which

def myfunc():
    if which("myexecutable.sh"):
        return "OK"
    else:
        ...
# in test file
import pytest
from script import myfunc


@pytest.fixture
def which(mocker):
    return mocker.patch("script.which", autospec=True)


def test_myfunc(which):
    assert myfunc() == "OK"

Running pytest outputs: 1 passed

Sign up to request clarification or add additional context in comments.

1 Comment

Now this is a neat trick!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.