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

后端 未结 2 954
北海茫月
北海茫月 2021-01-01 21:40

I am trying to mock a chained call on the Djangos model.Manager() class. For now I want to mock the values() and filter() method.

相关标签:
2条回答
  • 2021-01-01 22:29

    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)
    
    0 讨论(0)
  • 2021-01-01 22:41

    @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.

    0 讨论(0)
提交回复
热议问题