Django ORM - mock values().filter() chain

我是研究僧i 提交于 2019-11-30 17:39:43

Try this:

import mock
from mocktest.mockme.models import MyModel

class SimpleTest(TestCase):
    def test_chained_query(self):
        my_model_value_mock = mock.patch(MyModel.objects, 'value')
        my_model_value_mock.return_value.filter.return_value.count.return_value = 10000
        self.assertTrue(my_model_value_mock.return_value.filter.return_value.count.called)

@Gin's answer got me most of the way there, but in my case I'm patching MyModel.objects, and the query I'm mocking looks like this:

MyModel.objects.filter(arg1=user, arg2=something_else).order_by('-something').first()

so this worked for me:

@patch('MyModel.objects')
def test_a_function(mock, a_fixture):
    mock.filter.return_value.order_by.return_value.first.return_value = a_fixture
    result = the_func_im_testing(arg1, arg2)
    assert result == 'value'

Also, the order of the patched attributes matters, and must match the order you're calling them within the tested function.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!