Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 ?

like image 533
leopoodle Avatar asked Oct 22 '16 00:10

leopoodle


People also ask

Can you mock an import in Python?

Rather than hacking on top of Python's import machinery, you can simply add the mocked module into sys. path , and have Python prefer it over the original module. Now, when the test suite is run, the mocked-lib subdirectory is prepended into sys. path and import A uses B from mocked-lib .


1 Answers

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()
like image 174
Brendan Abel Avatar answered Nov 05 '22 08:11

Brendan Abel