4

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'
Sunil Kapil
  • 1,020
  • 13
  • 12

1 Answers1

3

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:

ThisSuitIsBlackNot
  • 23,492
  • 9
  • 63
  • 110
  • Thanks @ThisSuitIsBlackNot. Thanks for all the points under 'Also:'. I just made up those Try/Except as couldn't able to find better example to write. In my code I am exactly doing the same thing as you pointed out. Let me try out if that works while I mock the requests using responses. – Sunil Kapil Mar 21 '17 at 19:43