samedi 2 juillet 2016

Mocking a Python Standard Library function with and without pytest-mock

For testing purposes I would like to mock shutil.which (Python 3.5.1), which is called inside a simplified method find_foo()

def _find_foo(self) -> Path:
foo_exe = which('foo', path=None)
if foo_exe:
    return Path(foo_exe)
else:
    return None

I'm using pytest for implementing my test cases. Because of that I also would like to use the pytest extension pytest-mock. In the following I pasted an example testcase using pytest + pytest-mock:

def test_find_foo(mocker):
mocker.patch('shutil.which', return_value = '/path/foo.exe')

foo_path = find_foo()
assert foo_path is '/path/foo.exe'

This way of mocking with pytest-mock doesn't work. shutil.which is still called instead of the mock.

I tried to directly use the mock package which is now part of Python3:

def test_find_foo():
    with unittest.mock.patch('shutil.which') as patched_which:
        patched_which.return_value = '/path/foo.exe'

        foo_path = find_foo()
        assert foo_path is '/path/foo.exe'

Sadly the result is the same. Also shutil.which is called instead of specified mock.

Which steps of successfully implementing a mock are wrong or missed in my test cases?

Aucun commentaire:

Enregistrer un commentaire