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

后端 未结 2 1004
北海茫月
北海茫月 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: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.

提交回复
热议问题