0

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 ?

  • 1
    You'll be more likely to get better help if you create a [Minimal, Reproducible Example](https://stackoverflow.com/help/minimal-reproducible-example) – one that people can copy, paste into a `.py` file, and run. – FMc Feb 15 '21 at 07:02

1 Answers1

2

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.

D Hudson
  • 1,004
  • 5
  • 12
  • Thanks for getting back. I have a follow up question, so the function fn2 remains mocked even when its called in subprocess context; however the main process does not get to know that the mocked fn2 got called in the subprocess context? – user1522160 Feb 15 '21 at 21:32
  • Yes - give this code a go to see the mocked function running in the new process. https://tio.run/##rZGxbsQgDIZ3nsJbiFQhJWOkPELVquqOEIHUbTAIyNCnT@FK1cvdVtWT9Rv7s/nDZ37zNBwHuuBjBrdvGUP02qSEtDLG9KZSgleT8sQYlFiMBUsDT2az/XSRaoQB5tt28fyd8qziavJcW4Slsb/qEqkUMz9J7x6pKFe48Q4XkTLvniKuSGoDu5PO6EnAy05U2IAEbZOpe7jbTO8xGsqySbwXAZeCrDjn9YdZ5M9I3rAN@Xip/huQoQUpSTkjJcwzdFI6hSRld6aqP42vE1QxpvrX/liJ6t5vPlbfbi8@vTyOLw – D Hudson Feb 16 '21 at 09:48