Home > database >  mocking multiprocessing.Process target in unit tests
mocking multiprocessing.Process target in unit tests

Time:04-20

I want to test if a mocked method is called by multiprocessing.Process. I am aware that a subprocess call makes a fork of the current process and that the information can only be available in the subprocess. However, I would like to know if there is a clean way to test such a usecase anyway.

One possibility would certainly be to simply not use a mock but, for example, to call a function that simply writes a file somewhere and use it to verify that the method has run through successfully. However, a "clean" solution with mocking would definitely be preferable to me.

Minimal example:

#!/usr/bin/env python3
# -*- coding: utf-8 -*-

import multiprocessing
from unittest.mock import MagicMock

# Create mock method
mocked_target: MagicMock = MagicMock()

# Make sure that the call counter works
assert 0 == mocked_target.call_count
mocked_target()
assert 1 == mocked_target.call_count

# Call the method via multiprocessing
process: multiprocessing.Process = multiprocessing.Process(target=mocked_target)
process.start()
process.join()
assert 2 == mocked_target.call_count  # Does not work, call counter is still 1

Possible related question:

Edit:

This package actually provides this functionality. Unfortunately, it is neither available on pypi nor actively maintained.

CodePudding user response:

As mentioned, https://github.com/elritsch/python-sharedmock does the job pretty well.

  • Related