【问题标题】:Python 3 Mocking Thread Target not working in UnittestPython 3 模拟线程目标在 Unittest 中不起作用
【发布时间】:2018-04-23 20:44:49
【问题描述】:

我有以下代码并存储在一个名为run_thread.py的文件中

from mymodule import Builder 

def run_thread(): 
    threads = []
    for chunk in chunks:
        thread = threading.Thread(target=Builder.work, args=(a, b, c))
        threads.append(thread)

        try:
            thread.start()
        except:
            pass

    for thread in threads:
        try:
            thread.join()
        except:
            pass

当我尝试在我的单元测试中模拟/修补 Builder.work 时,原来的 Builder.work 仍在运行,这不是我所期望的。

import unittest
from ddt import ddt, data, unpack
from mock import patch

@ddt
class TestRunThread(unittest.TestCase):
    @patch('run_thread.Builder.work')
    def test_run_thread(self, mock_work):
        run_thread()

【问题讨论】:

  • 我也试过了,还是一样的问题。
  • 好的,试试@patch('mymodule.Builder.work')而不是@patch('run_thread.Builder.work')
  • 带有mock_work.return_value = sth 或mock_work.side_effect=[],@patch.object 被测试工作

标签: python unit-testing mocking


【解决方案1】:

它对我不起作用,因为 Builder.work() 是一个静态方法。

【讨论】:

【解决方案2】:

当patch一个类函数、属性、类属性时,这个根据文档使用

@patch.object(Builder, 'work')
def test_run_thread(self, mock_work):
    # this is tested to work with static method
    mock_work.return_value = ['a', 'bbbb']

类属性和类属性(不是实例成员)也可以使用

@patch('mymodule.Builder.class_attribute_or_property')
def test_mock_cls_attribute_or_property(mock_attribute):
    # this patch method tested not working for static method

【讨论】:

  • 它对我不起作用,因为 Builder.work() 是一个静态方法。所以还是用@patch.object?
猜你喜欢
  • 2010-11-22
  • 2022-01-22
  • 1970-01-01
  • 2021-04-12
  • 2011-03-26
  • 1970-01-01
  • 1970-01-01
  • 2015-05-10
相关资源
最近更新 更多