Mock a package that survives from ... import

Viewed 79

In a test case, I want to mock the keras package where I will not know how the user will going to import that package. This means I need to support

import keras
from keras import something
from keras.backend import otherthings
from keras.sub.subsub....module  import somethingelse

I tried to use a Mock object to do the following:

from unittest.mock import Mock
m = Mock()
sys.modules['keras'] = m

import keras                # Success
from keras import backend   # Success
from keras.backend import a # Failed: ModuleNotFoundError: No module named 'keras.backend'; 'keras' is not a package

I can certainly add a line like

sys.modules['keras.backend'] = m

to bypass this error, but I would not know if a user would want another module tomorrow - and I will just have to add in the list of modules, which does not seem to be a good choice.

Is there any approach that I can mock this module recursively ?

0 Answers
Related