How to skip method call in the DRF unit-test?

Viewed 850

I am not clear on how to properly use unittest.mock. I need to test APIView using rest_framework.test.APITestCase.client. But I don't need to call one of methods.

class MyClass(MyMixin):
    def do_some_stuff(self, request):
        self.should_be_called_in_the_test()
        self.should_not_be_called_in_the_test()

class MyView(views.APIView):
    def post(self, request):
        my_object = MyClass()
        my_object.do_some_stuff(request)
        return Response(status=status.HTTP_200_OK)

#test.py:
class MyViewTest(APITestCase):
    def test_post_request(self):
        url = reverse('my-view-url')
        # How properly skip call of "should_not_be_called_in_the_test()" ?
        response = self.client.post(url, data)
        # some asserts...
1 Answers

You'll need to use the patch instead of mock. You can do it with something like this,

#views.py
class MyClass(MyMixin):
    def do_some_stuff(self, request):
        self.should_be_called_in_the_test()
        self.should_not_be_called_in_the_test()

class MyView(views.APIView):
    def post(self, request):
        my_object = MyClass()
        my_object.do_some_stuff(request)
        return Response(status=status.HTTP_200_OK)

#test.py:
class MyViewTest(APITestCase):
    def test_post_request(self):
        url = reverse('my-view-url')
        with patch('app.views.MyClass.should_not_be_called_in_the_test'):
            response = self.client.post(url, data)
        # some asserts...

When using patch you'll usually have to be careful where to patch which is explained here

Related