def api_test ( method = 'GET' , * * response_kwargs ) : method = method . lower ( ) def api_test_factory ( fn ) : @ functools . wraps ( fn ) @ mock . patch ( 'requests.{}' . format ( method ) ) def execute_test ( method_func , * args , * * kwargs ) : method_func . return_value = MockResponse ( * * response_kwargs ) expected_url , response = fn ( * args , * * kwargs ) method_func . assert_called_once ( ) assert_valid_api_call ( method_func , expected_url ) assert isinstance ( response , JSONAPIParser ) assert response . json_data is method_func . return_value . data return execute_test return api_test_factory
mock api response in python unit test
Decorator to ensure API calls are made and return expected data .
def api_test(method='GET', **response_kwargs):
    """ Decorator to ensure API calls are made and return expected data. """

    method = method.lower()

    def api_test_factory(fn):
        @functools.wraps(fn)
        @mock.patch('requests.{}'.format(method))
        def execute_test(method_func, *args, **kwargs):
            method_func.return_value = MockResponse(**response_kwargs)

            expected_url, response = fn(*args, **kwargs)

            method_func.assert_called_once()
            assert_valid_api_call(method_func, expected_url)
            assert isinstance(response, JSONAPIParser)
            assert response.json_data is method_func.return_value.data

        return execute_test

    return api_test_factory