Archives Feb. 11, 2021

Mocking a failing module import in Python

Published: Feb. 11, 2021

When testing Python code, one sometimes has to imitate a broken or missing module. In a specific example, the pywin32 package requires running a post-installation script with administrator privileges after initial installation. Importing, for example, the win32security module of pywin32 may throw an ImportError if the postinstallation script wasn't executed. Packages that depend on pywin32 may want to handle this situation gracefully so that users who just pip install mypackage get only a soft failure or at least a helpful error message. If one wants to test this behavior in continuous integration and get code coverage, the ImportError has to be triggered even if pywin32 is installed correctly. Here is a short example that mimicks a broken or missing package with pytest and monkeypatch, since I didn't find this elsewhere:

Continue reading

Comments: Be first to comment!

Previous day

Jan. 26, 2019