如何模拟使用getattr动态调用的请求方法

时间:2017-03-21 16:31:57

标签: python unit-testing mocking python-requests

我有类使用getattr调用请求方法,如下所示:

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)

我正在尝试使用mock和响应lib测试api,如下所示:

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)

有没有更好或正确的方法来测试此方法。 得到此错误:

    message = message.format(**values)
KeyError: 'method'

1 个答案:

答案 0 :(得分:1)

无需使用getattrrequests.getrequests.post等只是requests.request的便捷方法,可让您将HTTP方法作为参数传递:

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

此外: