Replace a client library with a mock from a test?
-
27-09-2019 - |
Question
Is there a way to replace a client library (which communicates with a remote server) with a mock object from within a unittest?
Here's a diagram to explain what I'm attempting to do
+---------------+
| tests |----{ mock }
+---------------+ |
| |
v |
+---------------+ |
| model | |
+---------------+ |
| |
v |
+---------------+ |
| client-module |<--{replaces}
+---------------+
^
:
:
v
+---------------+
| service |
+---------------+
Since the tests import the model, which imports the client-module, there doesn't seem to be a way to apply the mock to the model's internals.
Solution
If model.py does an
import client_module
and doesn't use any features of it at import time, you can do
import model
...
model.client_module = MyMockModule()
where MyMockModule
returns suitable mocks for stuff the real client_module
provides. I haven't shown setUp/tearDown stuff to take care of this, but hopefully you get the idea,
If model
does use stuff from client_module
at import time, you'll need to replace sys.modules['client_module']
with the mocked module before importing model
.