Skip to content Skip to sidebar Skip to footer

Mock.patch And Multiprocessing

I'm struggling to use mock.patch in a multiprocessing environment while without multiprocessing mock.patch works fine. Filename: test_mp.py import multiprocessing import mock def

Solution 1:

Finally, I got it working.

SharedMock is not that flexible like Mock, eg. missing assert_called_once_with, ..., but you can set returned value or check the number of calls or its arguments.

import multiprocessing
import mock
from sharedmock.mock import SharedMock


def inner():
    return sub(x="xxx")

def sub(x=""):
    return f"abc"

def fun_under_test():
    with multiprocessing.Pool() as pool:
        assert pool.apply(inner,args=[])=='xyz'

def test_final():
    sm=SharedMock()
    sm.return_value="xyz"
    with mock.patch('test_mp.sub', sm) as xx:
        fun_under_test()
        assert xx.call_count == 1 #number of calls of sub function
        assert xx.mock_calls[0][2]['x']=="xxx" # value of parameters ie sub(x="xxx")

Post a Comment for "Mock.patch And Multiprocessing"