【问题标题】:Mocked unit test raises a "stop called on unstarted patcher" error模拟单元测试引发“停止调用未启动的修补程序”错误
【发布时间】:2018-03-17 10:12:02
【问题描述】:

运行下面的测试时,我得到了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())

我在堆栈溢出时阅读了有关此错误的内容,并得出结论认为我应该避免模拟相同的内容(堆叠模拟)。但这不是我在这里做的。我正在嵌套模拟,it seems to be ok.

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

有什么想法吗? 谢谢。

【问题讨论】:

    标签: python django unit-testing mocking


    【解决方案1】:

    简而言之,你不能patch 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 函数:

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

    【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-11-15
    • 2015-04-09
    • 1970-01-01
    • 2016-07-17
    • 2021-10-31
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多