1

我正在使用Mock来替换一个Django Model,它的配置如下:

>>> 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是 Mock 的方法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?

    ...
]

所以我的问题是:你如何断言count()在 Mock Django QuerySet 上被调用?

4

1 回答 1

2

Acall也是 a tuple,因此可以与 a 进行比较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

于 2013-04-17T22:01:13.233 回答