I have a class like the below:
Class a:
def fn1(self):
p1=multiprocessing.Process(self.fn2, (arg1,)
p1.start()
p1.join()
def fn2(self, arg1):
…
I am trying to test it and I have mocked the self.fn2 call:
Test:
Class aTest(unittest.TestCase):
def testfn1(self):
a obj1
obj1.fn2 = MagicMock.mock()
obj1.fn1()
obj1.fn2.assert_called_once_with(arg1)
When I run the test, I notice that the function fn2 ( I don’t see debugs I have there) has been mocked. However, the call_count is 0. How to debug this further ?
The function is being run in a separate process to the main process. Therefore, your main process has no record of self.fn2
being called.
If you want to continue on this route, this library may work for you. It synchronises the state of the mock between processes. https://github.com/elritsch/python-sharedmock
However: I encourage you to adopt a "GIVEN, THEN, WHEN" approach to write your test - this may make it a bit easier to see what an appropriate test could be and mean that you no longer have a need for a multiprocessing-safe MagicMock
implementation. What is the actual behaviour of your code that you are trying to verify and how could that be translated into an assert?
To test the desired behaviour here, perhaps you can assert against a different set of criteria. For example, is the calling on self.fn2
supposed to have an effect on something in the main process or file system? If so, you could assert against that instead.