testing with missing modules

Sometimes we need to test our code that uses some third party API which is only available in certain environments. Building special environment to test is cumbersome and often slow. If we try to test in isolation that pytest complains about missing imports and refuses to run the tests. How can we mock the third party module to run our tests? The standard patching doesn’t work as the modules are collected before the code is executed. There is however a not very well known feature of pytest that allows you to execute the code earlier. Welcome to conftest.py

https://docs.pytest.org/en/latest/explanation/pythonpath.html

lets say you relay on a module called tde4 but you do not actually need it to test your code as you are going to patch the function from it anyway. The only thing you need to do is to fake the module entry in sys.modules. To do so create a file called conftest.py and add the following code to it:

import sys

module = type(sys)('tde4')
sys.modules['tde4'] = module

this makes sure that import tde4 in your code will not raise ImportError anymore and you will be able to patch it in the tests with mocker:

mocker.patch('tde4.someFunction', return_value=1, create=True)