验证在Python单元测试中创建模拟对象

时间:2017-09-28 15:21:23

标签: python unit-testing mocking

我正在尝试测试一个可选择接受像对象一样的多处理池的函数。如果提供了一个,那么将使用该池,如果不是,它将创建一个ThreadPool来使用。

我想测试一下这种行为。具体来说,在适当的时候调用ThreadPool,而不是其他。

在下面的最小示例中,我正在尝试验证ThreadPool创建的调用状态。我使用MockThreadPool,因为在测试环境中我需要验证一些下游的东西,只能在串行操作中检查。

目前在TempTest.test_pool_created中失败。如何验证是否已调用ThreadPool

除了下面的例子,我试图模仿__init__ ThreadPool而没有任何运气。

temp.py

from multiprocessing.pool import ThreadPool


def run(execution_pool=None):

    values = [1, 2]

    if execution_pool:
        out = execution_pool.map(lambda x: x+1, values)
    else:
        with ThreadPool(2) as p:
            out = p.map(lambda x: x+1, values)

    return out


if __name__ == "__main__":
    out = run()
    print(out)

temp_test.py

import unittest
import unittest.mock as mock

from multiprocessing.pool import ThreadPool

from temp import run

# Mock ThreadPool for diverting parallel code to serial
class MockThreadPool:
    def map(self, run_simulation, all_inputs, chunksize=1):
        map(run_simulation, all_inputs)


class TempTest(unittest.TestCase):


    def test_check_runs(self):
        self.assertTrue(True)


    # Want to test:
    # - ThreadPool is created when no execution pool is passed to run()
    # - ThreadPool is not created when an execution pool is passed to run()

    @mock.patch('multiprocessing.pool.ThreadPool', return_value=MockThreadPool())
    def test_pool_created(self, fcn_pool):
        out = run(None)
        self.assertTrue(fcn_pool.called)

    @mock.patch('multiprocessing.pool.ThreadPool', return_value=MockThreadPool())
    def test_pool_not_created(self, fcn_pool):
        out = run(execution_pool=MockThreadPool())
        self.assertFalse(fcn_pool.called)

1 个答案:

答案 0 :(得分:0)

之前我遇到过同样的问题。您正在修补multiprocessing.pool.ThreadPool,但temp模块中的代码正在直接调用ThreadPool。如果您将patch()来电更改为

,我相信它会有效
@mock.patch('temp.ThreadPool', return_value=MockThreadPool())