1

I need to write a unit test case for my Django server, where I have the structure like following code snippet. This is just a pseudo-code because I just want to get the idea about the approach.

# views.py
class UserView(ViewSet):

    def get_info_from_multiple_sources(self, request):
        # assume url for this action is /users/:id/info
        user_id = get_parameters(request)
        info = info_service.get_info(user_id)
        return Response(info)

# user_info_service.py
class UserInfoService:

    def get_info(user_id):
        user_fb_info = fb_service.get_user_info(user_id)
        user_twitter_info = twitter_service.get_user_info(user_id)
        merged_info = merge_info(user_fb_info, user_twitter_info)
        return merged_info

# fb_service.py
class FbService:

    def _manipulate_data(response):
        user_info = None
        # do some processing here, to convert data from fb format to 
        # project format. Assign formatted response to user_info variable.
        return user_info

    def get_user_info(user_id):
        # lets say this imaginary urls gives user info somehow magically.
        response = requests.request('http://fb.com/users/{0}'.format(user_id))
        return self._manipulate_data(response)

# twitter_Service.py
class TwitterService:

    def _manipulate_data(response):
        user_info = None
        # do some processing here, to convert data from twitter format to 
        # project format. Assign formatted response to user_info variable.
        return user_info

    def get_user_info(user_id):
        response  = requests.request('http://twitter.com/users/{0}'.format(user_id))
        return self._manipulate_data(response)

# test_user_info_endpoint.py
class TestUserInfoViewEndpoint(APITestCase):

    def test_user_info(self):
        # how to write a unit test function where
        # I will be mocking only requests.request call. i.e outgoing call to external APIs

I am using unittests framework, and I am open to using any standard library for it.

Gaurav Gupta
  • 4,586
  • 4
  • 39
  • 72
  • 1
    what about monkey-patching requests.request to return a response similar to that of the api you're calling – m0etaz Oct 16 '18 at 08:12
  • @m0etaz How? Can you provide small pseudo-code – Gaurav Gupta Oct 16 '18 at 08:20
  • have a look at this library https://pypi.org/project/requests-staticmock/ – m0etaz Oct 16 '18 at 08:24
  • Possible duplicate of [Unittest Django: Mock external API, what is proper way?](https://stackoverflow.com/questions/50157543/unittest-django-mock-external-api-what-is-proper-way) – aasmpro Oct 16 '18 at 08:51

0 Answers0