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
?
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 .
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()
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With