模拟单元测试引发“停止调用未启动的修补程序";错误 [英] Mocked unit test raises a "stop called on unstarted patcher" error

查看:52
本文介绍了模拟单元测试引发“停止调用未启动的修补程序";错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在运行下面的测试时,我在未启动的修补程序上调用了 stop.

When running the test bellow, I got a stop called on unstarted patcher.

def test_get_subvention_internal_no_triggered_admission(self):
    billing_cluster = BillingClusterFactory()
    subvention = SubventionFactory(billing_cluster=billing_cluster)
    convive_sub = ConviveFactory(subvention=subvention, billing_cluster=billing_cluster)
    order_5 = OrderFactory(beneficiary=convive_sub)
    order_operation_5 = CreationOrderOperationFactory(order=order_5)

    with patch('orders.models.Order.subvention_triggered_same_day', return_value=True):
        with patch('builtins.hasattr', return_value=False):
            self.assertIsNone(order_operation_5._get_subvention())

我在堆栈溢出时阅读了有关此错误的内容,并得出结论,我应该避免模拟相同的内容(堆叠模拟).但这不是我在这里所做的.我正在嵌套模拟,并且 似乎没问题.

I read stuff about this error on stack overflow, and concluded that I should avoid mocking the same stuff (stacked mocks). But it's not what I'm doing here. I'm nesting mocks, and it seems to be ok.

如果我反转返回值(第一个模拟返回 False,第二个返回 True),测试运行良好.

If I invert the return values (first mock returns False, second returns True), the test works well.

有什么想法吗?谢谢.

推荐答案

总之,你不能patch builtins func hasattr

In short, you cannot patch the builtins func hasattr

patch('builtins.hasattr', return_value=False)

原因:被mock.py

if not _is_started(self):
    raise RuntimeError('stop called on unstarted patcher')

def _is_started(patcher):
    # XXXX horrible
    return hasattr(patcher, 'is_local')

重复错误:

@mock.patch('__builtin__.hasattr')
def test_mock_hasattr(self, mocked_hasattr):
    # as long as it is set to False, it will trigger
    mocked_hasattr.return_value = False

模拟 models.py 中的 builtins func:

to mock a builtins func inside models.py:

# narrow the mock scope
@mock.patch('orders.models.hasattr')

这篇关于模拟单元测试引发“停止调用未启动的修补程序";错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆