How to mock import (mock AB)?
Module A includes import B at the top.
Just, just mock the library in sys.modules before it is imported:
if wrong_platform(): sys.modules['B'] = mock.MagicMock()
and then, while A does not rely on the specific data types returned from objects B:
import A
must work.
You can also make fun of import AB :
This works even if you have submodules, but you want to mock every module. Say you have this:
from foo import This, That, andTheOtherThing from foo.bar import Yada, YadaYada from foo.baz import Blah, getBlah, boink
To laugh, simply follow below before importing the module that contains the above:
sys.modules['foo'] = MagicMock() sys.modules['foo.bar'] = MagicMock() sys.modules['foo.baz'] = MagicMock()
(My experience: I had a dependency that worked on the same platform, Windows, but didnโt work on Linux, where we run daily tests. So I needed to make fun of the dependency for our tests. Fortunately, it was a black box, so I donโt it was necessary to establish a lot of interaction.)
Wet side effects
Application: Actually, I needed to simulate a side effect, which took some time. So I needed an object method to sleep for a second. This will work as follows:
sys.modules['foo'] = MagicMock() sys.modules['foo.bar'] = MagicMock() sys.modules['foo.baz'] = MagicMock()
And then the code takes some time to run, like the real method.
Aaron Hall May 9 '16 at 10:17 2016-05-09 22:17
source share