Beispiel #1
0
 def __init__(self, **kwargs):
     self.event = kwargs['event']
     self.context = kwargs['context']
     self.handler_path = kwargs['handler_path']
     self.base_path = kwargs['base_path']
     self.schema_path = kwargs.get('schema_path')
     self.before_all = kwargs.get('before_all')
     self.router_response = ResponseClient()
 def test_compress(self):
     response = ResponseClient()
     response.body = {'unit-test': True}
     response.compress = True
     apigateway_response = response.response.copy()
     decoded = json.loads(
         gzip.decompress(base64.b64decode(apigateway_response['body'])))
     self.assertEqual(apigateway_response['isBase64Encoded'], True)
     self.assertEqual(apigateway_response['headers']['Content-Encoding'],
                      'gzip')
     self.assertDictEqual(decoded, {'unit-test': True})
 def test_base64_encoded(self):
     response = ResponseClient()
     response.base64_encoded = True
     self.assertEqual(True, response.base64_encoded)
     self.assertDictEqual(
         response.response, {
             'headers': {
                 'Access-Control-Allow-Origin': '*',
                 'Access-Control-Allow-Headers': '*'
             },
             'statusCode': 204,
             'isBase64Encoded': True,
             'body': '{}'
         })
 def test_check_body_for_errors_pass(self):
     request = RequestClient(mock_data.apigateway_event(), None)
     response = ResponseClient()
     validator = RequestValidator(request, response, self.OPENAPI)
     validator._check_body_for_errors('v1-test-request',
                                      mock_data.valid_request())
     self.assertFalse(response.has_errors)
 def test_validate_params_fail(self):
     request = RequestClient(mock_data.apigateway_event(), None)
     response = ResponseClient()
     validator = RequestValidator(request, response, self.OPENAPI)
     validator._available_fields(['test_path'],
                                 {'test_path_fail': 'test_value'}, 'params')
     self.assertTrue(response.has_errors)
 def test_validate_path_params_pass(self):
     request = RequestClient(mock_data.apigateway_event(), None)
     response = ResponseClient()
     validator = RequestValidator(request, response, self.OPENAPI)
     validator._required_fields(['test_path'], {'test_path': 'test_value'},
                                'path parameters')
     self.assertFalse(response.has_errors)
 def test_validate_headers_fail(self):
     request = RequestClient(mock_data.apigateway_event(), None)
     response = ResponseClient()
     validator = RequestValidator(request, response, self.OPENAPI)
     validator._required_fields(['test-key'], {'test-key-fail': '123456'},
                                'headers')
     self.assertTrue(response.has_errors)
 def wrapper(event, context, schema_path = ''):
     request = RequestClient(event, context)
     response = ResponseClient()
     validator = RequestValidator(request, response, schema_path)
     validator.validate_request(**kwargs)
     if not response.has_errors:
         func(request, response)
     return response.response
 def test_defaults(self):
     response = ResponseClient()
     self.assertEqual(False, response.has_errors)
     self.assertDictEqual(
         response.response, {
             'headers': {
                 'Access-Control-Allow-Origin': '*',
                 'Access-Control-Allow-Headers': '*'
             },
             'statusCode': 204,
             'isBase64Encoded': False,
             'body': '{}'
         })
 def test_get_schema(self):
     request = RequestClient(mock_data.apigateway_event(), None)
     response = ResponseClient()
     validator = RequestValidator(request, response, self.OPENAPI)
     schema = validator._get_combined_schema('v1-test-request')
     self.assertDictEqual(schema, mock_data.request_schema())
Beispiel #11
0
class Router:
    def __init__(self, **kwargs):
        self.event = kwargs['event']
        self.context = kwargs['context']
        self.handler_path = kwargs['handler_path']
        self.base_path = kwargs['base_path']
        self.schema_path = kwargs.get('schema_path')
        self.before_all = kwargs.get('before_all')
        self.router_response = ResponseClient()

    def route(self):
        try:
            return self._route_request()
        except BeforeAllException as b_error:
            self.router_response.code = b_error.code
            self.router_response.set_error(b_error.key_path, b_error.message)
            return self.router_response.response
        except:
            return self.router_response.response

    def _route_request(self):
        handler_module = self._get_route()
        handler_function = self._get_method(handler_module)
        if self.before_all and callable(self.before_all):
            self.before_all(self.event, self.context, self.schema_path)
        return self._run_endpoint(handler_module, handler_function)

    def _get_route(self):
        import_path = self._get_import_path()
        file_path = self._get_file_path()
        if os.path.exists(file_path):
            spec = importlib.util.spec_from_file_location(
                import_path, file_path)
            handler_module = importlib.util.module_from_spec(spec)
            spec.loader.exec_module(handler_module)
            return handler_module
        return self._set_error(404, 'url', 'path not found')

    def _get_method(self, handler_module):
        method = self.event['httpMethod'].lower()
        if hasattr(handler_module, method):
            return method
        return self._set_error(403, 'method', 'method not allowed')

    def _run_endpoint(self, handler_module, method):
        try:
            return getattr(handler_module, method)(self.event, self.context,
                                                   self.schema_path)
        except Exception as error:
            return self._set_error(500, 'server', 'internal server error',
                                   error)

    def _clean_path(self, path):
        if path[0] == '/':
            path = path[1:]
        if path[-1] == '/':
            path = path[:-1]
        return path

    def _get_import_path(self):
        event_path = self._clean_path(self.event['path'])
        base_path = self._clean_path(self.base_path)
        endpoint_import = event_path.replace('{}'.format(base_path),
                                             '').replace('-', '_')
        return '{}.{}'.format(self.handler_path, endpoint_import)

    def _get_file_path(self):
        event_path = self._clean_path(self.event['path'])
        base_path = self._clean_path(self.base_path)
        endpoint_file = event_path.replace('{}'.format(base_path),
                                           '').replace('-', '_')
        if not endpoint_file:
            endpoint_file = '__init__'
        return '{}/{}.py'.format(self.handler_path.replace('.', '/'),
                                 endpoint_file)

    def _set_error(self, code, key_path, message, error=None):
        self.router_response.code = code
        self.router_response.set_error(key_path, message)
        if error and not os.getenv('UNITTEST'):
            logger.log(level='ERROR', log=error, trace=True)
        raise Exception(message)