def test_request_params_works_correctly(self): config = Configuration(timeout=15, verify=False, api_key='test') request_params = config.request_params() assert type(request_params) is dict assert 'timeout' in request_params assert 'verify' in request_params assert 'headers' in request_params
def __init__(self, **configuration_overrides): super().__init__() self.configuration = Configuration(**configuration_overrides) self.on( "request", lambda req: self.configuration.logger.debug('Request: %s', req)) self.on( "response", lambda res: self.configuration.logger.debug('Request: %s', res)) self.on("error", lambda err: self.configuration.logger.error(err))
class Client(Events, Operations): configuration = None user_agent = 'Firstclasspostcodes/python@{}'.format(VERSION) def __init__(self, **configuration_overrides): super().__init__() self.configuration = Configuration(**configuration_overrides) self.on( "request", lambda req: self.configuration.logger.debug('Request: %s', req)) self.on( "response", lambda res: self.configuration.logger.debug('Request: %s', res)) self.on("error", lambda err: self.configuration.logger.error(err)) def request(self, path, query_params, method): url = self.build_request_url(path) request_params = { 'params': query_params, **self.configuration.request_params() } self.emit('request', {'url': url, **request_params}) response = self.call_request(url, method, request_params) data = response.json() self.emit('response', data) return data def call_request(self, url, method, params={}): try: request = getattr(requests, method) response = request(url, **params) if response.status_code == requests.codes.ok: return response try: raise ResponseError(**response.json()) except json.decoder.JSONDecodeError: raise ResponseError(response, type='network-error') except requests.exceptions.Timeout: raise ResponseError('Connection timed out', type='timeout') except requests.exceptions.RequestException as e: raise ResponseError(str(e), type='liberror') def build_request_url(self, path): request_url = self.configuration.base_url() + path safe_request_url = re.sub(r"(?<!:)\/\/", '/', request_url) return safe_request_url
class GetPostcodeStub(GetPostcode): configuration = Configuration(protocol=URL.scheme, host=URL.netloc, base_path=URL.path, api_key=KEY) emit = Mock() request = Mock()
def test_base_url_works_correctly(self): config = Configuration(protocol='http', host='example.com', base_path='/test') assert config.base_url() == 'http://example.com/test'
def test_it_sets_base_path_correctly(self): assert self.configuration_key_is_not_empty( Configuration().base_path) is True
def test_it_sets_protocol_correctly(self): assert self.configuration_key_is_not_empty( Configuration().protocol) is True
def test_it_sets_content_correctly(self): assert self.configuration_key_is_not_empty( Configuration().content) is True
def test_it_sets_keys_correctly(self): assert Configuration().api_key is None assert Configuration(api_key='test').api_key == 'test'