An instance of class A starts a sub-process that calls a method of an instance of class B. It works as expected in real-life, but unit tests fail because the mock object replacing the object of class B does not report being called.
Minimal code:
from multiprocessing import Process
class Main:
def __init__(self, mock):
self._mock = mock
process = Process(target=self.task)
process.start()
process.join()
def task(self):
self._mock.method()
Tests:
from unittest.mock import Mock
from MinimalCode import Main
mock = Mock(unsafe=True)
def test_process():
main = Main(mock)
mock.method.assert_called()
Pytest result:
_____________________________________________________________ ERROR collecting test_Process.py ______________________________________________________________
test_Process.py:9: in <module>
test_process()
test_Process.py:7: in test_process
mock.method.assert_called()
/usr/lib/python3.11/unittest/mock.py:902: in assert_called
raise AssertionError(msg)
E AssertionError: Expected 'method' to have been called.
How should I write tests for mocks called in subprocesses ?
multiprocessingorsubprocess? Can you make the concurrency layer pluggable so that you can use a direct function call in tests?