V
V
Vladimir Kuts2020-01-17 15:08:12
Django
Vladimir Kuts, 2020-01-17 15:08:12

What is the correct way to make a mockup to test a request?

Let's say I have some API (greatly simplified):
api.py :

from some.app import some_external_check

class SomeViewSet(GenericViewSet):
    ...
    @action(detail=False, methods=['POST'], permission_classes=(permissions.IsAuthenticated, ))
    def somefunc(self, request, *args, **kwargs):
        serializer = self.get_serializer(data=request.data)
        serializer.is_valid(raise_exception=True)
        result = some_external_check(serializer.validated_data)   # <-- вот тут надо пропатчить результат вызова на определенное значение
        ...
        # какие-то вычисления дальше
        return Response(someresult)

And I make a test for it:
tests.py :
from unittest.mock import Mock, patch
from rest_framework import status
from rest_framework.test import APITestCase, APIClient

class SomeAPITest(APITestCase):
    ...
    def test_somefunc(self):
        my_client = APIClient()
        my_client.credentials(HTTP_AUTHORIZATION=f'Token {SOMETOKEN}') 
        ...
        response = my_client.post(reverse('some-url-for-somefunc-api'), data=data, format='json')
        self.assertEqual(response.status_code, status.HTTP_200_OK)
        # тут тестирую результат вызова
        ...

So, how to write a test using Mock or any other library without embedding in the code itself, so that the call to the some_external_check function is patched with the return of some specific value for the purpose of further testing?
And how is it generally done correctly?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
V
Vladimir Kuts, 2020-01-27
@fox_12 Asker

In general - since there are no answers - I will describe one of the options used, maybe it will help someone:
On the test run, in addition to working containers, a wiremock container was also raised , which simulated the operation of an external REST service, and the main project was connected to it based on the settings derived from environment variables.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question