我正在使用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()
?
答案 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