How can I mock an import failure? #11247
-
In the init file for the module I'm testing, it tries to import a version file and throws an error if the file does not exist, letting the user know to create it. I need the file to exist so I can run my other tests. But I want to test that the error is raised when the file isn't there. Is there a way to mock deletion of a file, or another way to force this error to happen during testing?
|
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 1 reply
-
Hi, Mocking things that happen at import time is tricky due to how Python import works. If you can change the original code, one solution would be to split that code into functions: def _import_version() -> str
from module._version import version
return version
def _handle_version() -> str:
"""Return the module._version string, which is generated by setuptools_scm."""
# Note: we use this indirection to be able to test the fallback code.
try:
return _import_version()
except ModuleNotFoundError:
raise FileNotFoundError(
'Install setuptools_scm and run `python setup.py --version` '
'to create version.py'
)
__version__ = _handle_version() With this you can call |
Beta Was this translation helpful? Give feedback.
Hi,
Mocking things that happen at import time is tricky due to how Python import works.
If you can change the original code, one solution would be to split that code into functions: