How Can I Mock Any Function Which Is Not Being Called Directly?
TL;DR How can I patch or mock 'any functions that are not being called/used directly'? Sceneario I have a simple unit-test snippet as # utils/functions.py def get_user_agents():
Solution 1:
It does not matter that you call the function indirectly - important is to patch it as it is imported. In your example you import the function to be patched locally inside the tested function, so it will only be imported at function run time. In this case you have to patch the function as imported from its module (e.g. 'utils.functions.get_user_agents'
):
classTestFooKlass(unittest.TestCase):
defsetUp(self):
self.patcher = mock.patch('utils.functions.get_user_agents',
return_value='foo') # whatever it shall return in the test
self.patcher.start() # this returns the patched object, i case you need it
create_foo()
deftearDown(self):
self.patcher.stop()
deftest_foo(self):
...
If you had imported the function instead at module level like:
from utils.functions import get_user_agents
defcreate_foo():
value = get_user_agents()
...
you should have patched the imported instance instead:
self.patcher = mock.patch('my_module.tasks.get_user_agents',
return_value='foo')
As for patching the module for all tests: you can start patching in setUp
as shown above, and stop it in tearDown
.
Post a Comment for "How Can I Mock Any Function Which Is Not Being Called Directly?"