leopoodle
leopoodle

Reputation: 2492

How to mock the existence of a particular file in python unit test?

I am writing a unit test for embedded software code in python.

One of the files require a specific file to exist. (e.g. "/dir_name/file_name.txt") otherwise it raises an error.

Normally, this file exists on hardware device and my python code reads this file. When writing unit tests for python code, how can I mock the existence of the file?

tempfile.mkstemp() does not seem to generate the exact path/file name I want, which is/dir_name/file_name.txt. It always adds some random letters.

This is with Python3.4. Is it possible to accomplish this with unittest.mock ?

Upvotes: 9

Views: 4220

Answers (3)

Tomas
Tomas

Reputation: 1094

If your function call (eg. your_function_call) uses Path("/dir_name/file_name.txt").exists() to test for the existence of the file then a simple way is:

with patch("pathlib.Path.exists", autospec=True): your_function_call( )

Upvotes: 0

LondonRob
LondonRob

Reputation: 78993

This is one of the examples given in unittest's "getting started" page.

For posterity, here's a copy/paste from that page:

DEFAULT = "default"
data_dict = {"file1": "data1",
             "file2": "data2"}

def open_side_effect(name):
    return mock_open(read_data=data_dict.get(name, DEFAULT))()

with patch("builtins.open", side_effect=open_side_effect):
    with open("file1") as file1:
        assert file1.read() == "data1"

    with open("file2") as file2:
        assert file2.read() == "data2"

    with open("file3") as file2:
        assert file2.read() == "default"

Upvotes: 0

Brendan Abel
Brendan Abel

Reputation: 37599

You could create a context manager that creates and deletes the file.

from contextlib import contextmanager

@contextmanager
def mock_file(filepath, content=''):
    with open(filepath, 'w') as f:
        f.write(content)
    yield filepath
    try:
        os.remove(filepath)
    except Exception:
        pass


def test_function():
    with mock_file(r'/dirname/filename.txt'):
        function()

Upvotes: 2

Related Questions