Python:mocks上的调用计数无法通过多处理并行执行

时间:2016-10-10 11:42:15

标签: python unit-testing parallel-processing mocking

我正在尝试测试一个简单的并行化模块。该模块提供了一个简单的函数run_tasks(tasks, use_multiprocessing)。我的简单测试包括使用MagicMock类生成任务列表,调用run_tasks并测试是否所有模拟都被调用了一次。

在指定串行运行的情况下,所有模拟都会被调用一次。但是,在并行运行的情况下,模拟的调用计数为零。我认为这是模拟模块的问题,因为如果任务包含一个print语句,那么将对串行和并行运行执行此操作。

以下是测试代码(注意:test_run_tasks_in_parallel失败而test_run_tasks_serially为绿色):

from unittest import TestCase
from mock import mock

from src.stochastic_simulation.util.embarrassing_parallelization import run_tasks
from src.stochastic_simulation.simulation.task import Task


class TestRunTasks(TestCase):
    def setUp(self):
        self.functions_to_run = [mock.MagicMock() for i in range(0, 9)]
        self.test_tasks = [Task(function, None) for function in self.functions_to_run]

    def test_run_tasks_in_parallel(self):
        run_tasks(self.test_tasks, use_multiprocessing=True)
        for function in self.functions_to_run:
            function.assert_called_once()

    def test_run_tasks_serially(self):
        run_tasks(self.test_tasks)
        for function in self.functions_to_run:
            function.assert_called_once()

这是模块

import multiprocessing as mp


def run_task(task):
    task.run()


def run_tasks(tasks, use_multiprocessing=False):
    if use_multiprocessing:
        available_processors = mp.cpu_count() - 1
        print "Distributing tasks among {} processors".format(available_processors)

        pool = mp.Pool(processes=available_processors)
        _ = pool.imap_unordered(run_task, tasks, chunksize=1)

    else:
        print "No multiprocessing"
        for task in tasks:
            task.run()

1 个答案:

答案 0 :(得分:0)

我遇到了类似的问题,请参阅 mock.patch and multiprocessing

解决方案是将 mock.MagicMock() 替换为 SharedMock() https://github.com/elritsch/python-sharedmock