你怎么断言Django的QuerySet.count()方法是在Mock上调用的?

时间:2013-04-07 16:54:26

标签: python django mocking

我正在使用Mock替换Django模型,它配置如下:

>>> config = {'objects.filter.return_value.count.return_value': 1}
>>> MockModel = Mock(**config)

我可以查询一些值,然后在结果上调用.count()

>>> # This works as expected
>>> MockModel.objects.filter(foo='bar').count()
1

但是,当我声称这些方法被调用时,Mock会引发TypeError因为。{ count是模拟call的方法:

>>> MockModel.assert_has_calls([
        call.objects.filter(foo='bar'),
        call.objects.filter().count(),
    ])
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-78-bf4e954d856f> in <module>()
      1 MockModel.assert_has_calls([
      2         call.objects.filter(foo='bar'),
----> 3         call.objects.filter().count()
      4 ])

TypeError: count() takes exactly one argument (0 given)

但是,您可以看到此调用确实存在于mock_calls

>>> MockModel.mock_calls
[
    call.trait_names(),
    call._getAttributeNames(),
    call.objects.filter(foo='bar'),
    call.objects.filter().count(),    # How do you test for this?

    ...
]

所以我的问题是:你怎么断言在模拟Django QuerySet上调用了count()

1 个答案:

答案 0 :(得分:2)

call也是tuple,因此可以与tuple进行比较:

>>> MockModel.assert_has_calls([
        call.objects.filter(foo='bar'),
        ('objects.filter().count',),
    ])

您可以确认:

>>> map(tuple, MockModel.mock_calls)
  > [('objects.filter', (), {'foo': 'bar'}), ('objects.filter().count', (), {})]

来源:https://code.google.com/p/mock/source/browse/mock.py#1988