Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to mock requests methods called dynamically using getattr

I have class which called requests method using getattr like this:

import requests

class CustomRequests(object):
     def __init__(self):
         pass

     def _do_requests(self, method='GET', url='', expected_status=200):
         make_request = getattr(requests, method.lower())
         url = url if url else 'http://example.com'

         try:
            response = make_request(method, url=url)
            except response.exceptions.RequestException as exception:
                raise exception
         if response.status_code != expected_status:
            raise ValueError

    def get(self, *args, **kwargs):
        self._do_requests(method='GET', *args, **kwargs)

I am trying to test the api using mock and responses lib like this:

import responses

@responses.activate
def test_get_method(self):
    responses.add('GET', url='http://test_this_api.com', status=200)
    custom_request = CustomRequest()
    response_data = custom_request.get(method='GET')
    AssertIsNotNone(response_data)

Is there any better or right way to test this method. Getting this error:

    message = message.format(**values)
KeyError: 'method'
like image 825
Sunil Kapil Avatar asked Sep 20 '25 04:09

Sunil Kapil


1 Answers

There's no need to use getattr. requests.get, requests.post, etc. are just convenience methods for requests.request, which lets you pass the HTTP method as a parameter:

requests.request('GET', url) # equivalent to requests.get(url)

Also:

  • Your try/except is pointless, since all you do is re-raise the exception.
  • It doesn't make sense to raise a ValueError when the response status doesn't match what you expected. ValueError is for "when a built-in operation or function receives an argument that has the right type but an inappropriate value." Create your own exception class, e.g. UnexpectedHTTPStatusError.
  • Since the whole point of your CustomRequests class seems to be to raise an exception when the status code of the response doesn't match what the user expected, your tests should assert that an exception was actually raised with assertRaises().
like image 175
ThisSuitIsBlackNot Avatar answered Sep 22 '25 18:09

ThisSuitIsBlackNot