Andrew Rosen
Andrew Rosen

Reputation: 101

Monkeypatch an executable in Python pytest

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.

Upvotes: 0

Views: 141

Answers (1)

Laurent
Laurent

Reputation: 13518

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

Upvotes: 1

Related Questions