如何在Django模型上模拟链式方法

时间:2014-07-13 10:00:49

标签: python unit-testing django-models mocking python-mock

我正在尝试使用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模型上链接方法调用,我还能正确地做到这一点吗?

1 个答案:

答案 0 :(得分:1)

在模拟模拟函数的返回值时,必须模拟函数,因为它将在代码中调用。 parent.childchild模拟上创建了一个名为parent的属性。鉴于parent().child在模拟的child返回值上创建了一个名为parent()的属性。