Pytest mocker failing to find Path

Question:

I am working with someone else’s testing code, and they make extensive use of mocker. The problem is that I changed the underlying code so it tests for the existence of a file using Path ().is_file.

Now I need to mock Path ().is_file so it returns True. I tried this:

from pathlib import Path
@pytest.fixture(scope="function")
def mock_is_file (mocker):
    # mock the AlignDir existence validation
    mocker.patch ('Path.is_file')
    
    return True

I’m getting this error:

E       ModuleNotFoundError: No module named 'Path'

/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/unittest/mock.py:1161: ModuleNotFoundError

What is the correct way to patch Path.is_file()?

Asked By: Greg Dougherty

||

Answers:

Mock will import the object given the string, so you need to patch with a fully qualified name.

You should probably also set the return_value so that the call returns a boolean, rather than returning another generated mock. The return value in the fixture itself is not needed.

mocker.patch("pathlib.Path.is_file", return_value=True)

You also don’t need to import the thing that you’re mocking at the top of the test module like that, mock itself will import it when patching.

Answered By: wim
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.