我正在尝试使用Python模拟库来模拟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模型上链接方法调用,我还能正确地做到这一点吗?
答案 0 :(得分:1)
在模拟模拟函数的返回值时,必须模拟函数,因为它将在代码中调用。 parent.child
在child
模拟上创建了一个名为parent
的属性。鉴于parent().child
在模拟的child
返回值上创建了一个名为parent()
的属性。