python - 模拟单元测试引发 "stop called on unstarted patcher"错误

标签 python django unit-testing mocking

运行下面的测试时,我在未启动的修补程序上调用了一个停止

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),则测试效果良好。

有什么想法吗? 谢谢。

最佳答案

简而言之,您无法修补 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')

关于python - 模拟单元测试引发 "stop called on unstarted patcher"错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49334774/

相关文章:

Angular2 测试组件是否有正确的选择器

python - SQL 查询显示结果比 Python 表中存储的结果多或少 30 分钟

django - 为什么 save_model 方法在 admin.StackedInline 中不起作用?

objective-c - 为什么当我测试一个方法抛出异常并且该方法抛出异常时,测试会停止?

c# - 为什么我的单元测试在不运行测试的情况下成功完成?

python - VSCode 调试 Celery Worker

python - 如何在 django-import-export 中导入 django-taggit 标签

python - 如何制作非数值列的散点图?

python - 'UserCreationForm' 对象没有属性 'get_username' django 1.8

python - Django 查找图中两个顶点之间的路径