fatf.utils.testing.imports.module_import_tester(module_name: str, when_missing: bool = True) → Iterator[None][source]

Provides a context for testing imports of installed and missing modules.

This context can be used to get an environment where a particular module (module_name) is either not installed – when_missing=True – or installed – when_missing=False. The example below demonstrates a possible use case:

>>> import fatf.utils.testing.imports as futi
>>> with futi.module_import_tester('a_module', when_missing=True):
...     try:
...         import a_module
...     except ImportError:
...         print('Module not found!')
Module not found!
>>> with futi.module_import_tester('a_module', when_missing=False):
...     import a_module

In the first example we are making sure that the import will fail by providing when_missing=True. On the other hand, the second call ensures that the import succeeds.


Python 3.6 and later will result in ModuleNotFoundError, however Python 3.5 will raise ImportError.


A module name that we want to test given as a string.


A boolean parameter specifying whether the module named above should be available for import or not. Defaults to True.

A context with the selected module either missing or present.