如何在Django模型上模拟链式方法
我正在尝试使用Python的mock库来模拟Django模型中的方法,像这样:
# file: tasks.py
def delete_ads(user):
# works fine and return a list of 4 MagicMock objects
ads = Classifieds.objects.filter(
user=user
)
# file: tests.py
def test_delete_ads():
return_list = [MagicMock(name='1'), MagicMock(name='2'), MagicMock(name='3'), MagicMock(name='4')]
with patch('user.tasks.Classifieds') as classified_mock:
classified_mock.objects.filter.return_value = return_value
上面的代码运行得很好,但当我把代码改成这样后,它开始只返回一个MagicMock对象:
# file: tasks.py
def delete_ads(user):
# works fine and return a list of 4 MagicMock objects
ads = Classifieds.objects.filter(
user=user
).order_by('-added')
# file: tests.py
def test_delete_ads():
return_list = [MagicMock(name='1'), MagicMock(name='2'), MagicMock(name='3'), MagicMock(name='4')]
with patch('user.tasks.Classifieds') as classified_mock:
classified_mock.objects.filter.order_by.return_value = return_value
有没有办法让我在对Django模型进行方法链调用时,仍然能正确地做到这一点呢?
1 个回答
1
在模拟一个函数的返回值时,你需要按照代码中调用这个函数的方式来进行模拟。比如,parent.child
这个写法会在 parent
的模拟对象上创建一个叫做 child
的属性。而 parent().child
则是在 parent()
的模拟返回值上创建一个叫做 child
的属性。