def test_raw_body_cache_returns_same_result(): demo = app.Chalice('app-name') @demo.route('/index') def index_view(): # The first raw_body decodes base64, # the second value should return the cached value. # Both should be the same value return {'rawbody': demo.current_request.raw_body, 'rawbody2': demo.current_request.raw_body} event = create_event('/index', 'GET', {}) event['base64-body'] = base64.b64encode('{"hello": "world"}') result = demo(event, context=None) assert result['rawbody'] == result['rawbody2']
def test_can_base64_encode_binary_media_types_bytes(): demo = app.Chalice('demo-app') @demo.route('/index') def index_view(): return app.Response( status_code=200, body=b'\u2713', headers={'Content-Type': 'application/octet-stream'}) event = create_event('/index', 'GET', {}) event['headers']['Accept'] = 'application/octet-stream' response = demo(event, context=None) assert response['statusCode'] == 200 assert response['isBase64Encoded'] is True assert response['body'] == 'XHUyNzEz' assert response['headers']['Content-Type'] == 'application/octet-stream'
def test_can_handle_builtin_auth(): demo = app.Chalice('builtin-auth') @demo.authorizer() def my_auth(auth_request): pass @demo.route('/', authorizer=my_auth) def index_view(): return {} assert len(demo.builtin_auth_handlers) == 1 authorizer = demo.builtin_auth_handlers[0] assert isinstance(authorizer, app.BuiltinAuthConfig) assert authorizer.name == 'my_auth' assert authorizer.handler_string == 'app.my_auth' assert my_auth.name == 'my_auth'
def sample_app(): demo = app.Chalice('demo-app') demo.debug = True @demo.route('/index', methods=['GET']) def index(): return {'hello': 'world'} @demo.route('/names/{name}', methods=['GET']) def name(name): return {'provided-name': name} @demo.route('/put', methods=['PUT']) def put(): return {'body': demo.current_request.json_body} @demo.route('/cors', methods=['GET', 'PUT'], cors=True) def cors(): return {'cors': True} @demo.route('/options', methods=['OPTIONS']) def options(): return {'options': True} @demo.route('/delete', methods=['DELETE']) def delete(): return {'delete': True} @demo.route('/patch', methods=['PATCH']) def patch(): return {'patch': True} @demo.route('/badrequest') def badrequest(): raise BadRequestError('bad-request') @demo.route('/decimals') def decimals(): return decimal.Decimal('100') @demo.route('/query-string') def query_string(): return demo.current_request.query_params return demo
def test_can_return_response_object(): demo = app.Chalice('app-name') @demo.route('/index') def index_view(): return app.Response(status_code=200, body={'foo': 'bar'}, headers={'Content-Type': 'application/json'}) event = create_event('/index', 'GET', {}) response = demo(event, context=None) assert response == { 'statusCode': 200, 'body': '{"foo": "bar"}', 'headers': { 'Content-Type': 'application/json' } }
def test_can_call_method_without_auth(self, lambda_context_args, create_event): demo = app.Chalice('app-name') @demo.route('/index') def index_view(): return {} path = '/index' authorizer = LocalGatewayAuthorizer(demo) original_event = create_event(path, 'GET', {}) original_context = LambdaContext(*lambda_context_args) event, context = authorizer.authorize( path, original_event, original_context) # Assert that when the authorizer.authorize is called and there is no # authorizer defined for a particular route that it is a noop. assert original_event == event assert original_context == context
def test_can_receive_binary_data(): content_type = 'application/octet-stream' demo = app.Chalice('demo-app') @demo.route('/bincat', methods=['POST'], content_types=[content_type]) def bincat(): raw_body = demo.current_request.raw_body return app.Response(raw_body, headers={'Content-Type': content_type}, status_code=200) body = 'L3UyNzEz' event = create_event_with_body(body, '/bincat', 'POST', content_type) event['headers']['Accept'] = content_type event['isBase64Encoded'] = True response = demo(event, context=None) assert response['statusCode'] == 200 assert response['body'] == body
def test_builtin_auth_can_transform_event(): event = { 'type': 'TOKEN', 'authorizationToken': 'authtoken', 'methodArn': 'arn:aws:execute-api:...:foo', } auth_app = app.Chalice('builtin-auth') request = [] @auth_app.authorizer() def builtin_auth(auth_request): request.append(auth_request) builtin_auth(event, None) assert len(request) == 1 transformed = request[0] assert transformed.auth_type == 'TOKEN' assert transformed.token == 'authtoken' assert transformed.method_arn == 'arn:aws:execute-api:...:foo'
def test_can_have_views_of_same_route_but_different_methods(create_event): demo = app.Chalice('app-name') @demo.route('/index', methods=['GET']) def get_view(): return {'method': 'GET'} @demo.route('/index', methods=['PUT']) def put_view(): return {'method': 'PUT'} assert demo.routes['/index']['GET'].view_function == get_view assert demo.routes['/index']['PUT'].view_function == put_view event = create_event('/index', 'GET', {}) result = demo(event, context=None) assert json_response_body(result) == {'method': 'GET'} event = create_event('/index', 'PUT', {}) result = demo(event, context=None) assert json_response_body(result) == {'method': 'PUT'}
def test_json_body_available_on_multiple_content_types(): demo = app.Chalice('demo-app') @demo.route('/', methods=['POST'], content_types=['application/xml', 'application/json']) def index(): return (demo.current_request.json_body, demo.current_request.raw_body) event = create_event_with_body('<Message>hello</Message>', content_type='application/xml') json_body, raw_body = demo(event, context=None) assert json_body is None assert raw_body == '<Message>hello</Message>' # Now if we create an event with JSON, we should be able # to access .json_body as well. event = create_event_with_body({'foo': 'bar'}, content_type='application/json') json_body, raw_body = demo(event, context=None) assert json_body == {'foo': 'bar'} assert raw_body == '{"foo": "bar"}'
def demo_app_auth(): demo = app.Chalice('app-name') @demo.authorizer() def auth_with_explicit_policy(auth_request): token = auth_request.token if token == 'allow': return { 'context': {}, 'principalId': 'user', 'policyDocument': { 'Version': '2012-10-17', 'Statement': [ { 'Action': 'execute-api:Invoke', 'Effect': 'Allow', 'Resource': ["arn:aws:execute-api:mars-west-1:123456789012:" "ymy8tbxw7b/api/GET/explicit"] } ] } } else: return { 'context': {}, 'principalId': '', 'policyDocument': { 'Version': '2012-10-17', 'Statement': [ { 'Action': 'execute-api:Invoke', 'Effect': 'Deny', 'Resource': ["arn:aws:execute-api:mars-west-1:123456789012:" "ymy8tbxw7b/api/GET/explicit"] } ] } } @demo.authorizer() def demo_authorizer_returns_none(auth_request): return None @demo.authorizer() def demo_auth(auth_request): token = auth_request.token if token == 'allow': return app.AuthResponse(routes=['/index'], principal_id='user') else: return app.AuthResponse(routes=[], principal_id='user') @demo.authorizer() def resource_auth(auth_request): token = auth_request.token if token == 'allow': return app.AuthResponse(routes=['/resource/foobar'], principal_id='user') else: return app.AuthResponse(routes=[], principal_id='user') @demo.authorizer() def all_auth(auth_request): token = auth_request.token if token == 'allow': return app.AuthResponse(routes=['*'], principal_id='user') else: return app.AuthResponse(routes=[], principal_id='user') @demo.authorizer() def landing_page_auth(auth_request): token = auth_request.token if token == 'allow': return app.AuthResponse(routes=['/'], principal_id='user') else: return app.AuthResponse(routes=[], principal_id='user') iam_authorizer = IAMAuthorizer() @demo.route('/', authorizer=landing_page_auth) def landing_view(): return {} @demo.route('/index', authorizer=demo_auth) def index_view(): return {} @demo.route('/secret', authorizer=demo_auth) def secret_view(): return {} @demo.route('/resource/{name}', authorizer=resource_auth) def single_value(name): return {'resource': name} @demo.route('/secret/{value}', authorizer=all_auth) def secret_view_value(value): return {'secret': value} @demo.route('/explicit', authorizer=auth_with_explicit_policy) def explicit(): return {} @demo.route('/iam', authorizer=iam_authorizer) def iam_route(): return {} @demo.route('/none', authorizer=demo_authorizer_returns_none) def none_auth(): return {} return demo
def test_logs_can_be_disabled(): handlers_before = logging.getLogger('log_app').handlers[:] app.Chalice('log_app', configure_logs=False) handlers_after = logging.getLogger('log_app').handlers[:] new_handlers = set(handlers_after) - set(handlers_before) assert len(new_handlers) == 0
def test_debug_mode_changes_log_level(): test_app = app.Chalice('logger-test-4', debug=False) test_app.debug = True assert test_app.debug is True assert test_app.log.getEffectiveLevel() == logging.DEBUG
def test_can_set_debug_mode_in_initialzier(): test_app = app.Chalice('logger-test-3', debug=True) assert test_app.debug is True assert test_app.log.getEffectiveLevel() == logging.DEBUG
def test_aws_execution_env_set(): env = {'AWS_EXECUTION_ENV': 'AWS_Lambda_python2.7'} app.Chalice('app-name', env=env) assert env['AWS_EXECUTION_ENV'] == ( 'AWS_Lambda_python2.7 aws-chalice/%s' % chalice_version )
def sample_app(): demo = app.Chalice('demo-app') demo.debug = True @demo.route('/index', methods=['GET']) def index(): return {'hello': 'world'} @demo.route('/names/{name}', methods=['GET']) def name(name): return {'provided-name': name} @demo.route('/put', methods=['PUT']) def put(): return {'body': demo.current_request.json_body} @demo.route('/cors', methods=['GET', 'PUT'], cors=True) def cors(): return {'cors': True} @demo.route('/custom_cors', methods=['GET', 'PUT'], cors=CORSConfig( allow_origin='https://foo.bar', allow_headers=['Header-A', 'Header-B'], expose_headers=['Header-A', 'Header-B'], max_age=600, allow_credentials=True )) def custom_cors(): return {'cors': True} @demo.route('/options', methods=['OPTIONS']) def options(): return {'options': True} @demo.route('/delete', methods=['DELETE']) def delete(): return {'delete': True} @demo.route('/patch', methods=['PATCH']) def patch(): return {'patch': True} @demo.route('/badrequest') def badrequest(): raise BadRequestError('bad-request') @demo.route('/decimals') def decimals(): return decimal.Decimal('100') @demo.route('/query-string') def query_string(): return demo.current_request.query_params @demo.route('/custom-response') def custom_response(): return Response(body='text', status_code=200, headers={'Content-Type': 'text/plain'}) @demo.route('/binary', methods=['POST'], content_types=['application/octet-stream']) def binary_round_trip(): return Response(body=demo.current_request.raw_body, status_code=200, headers={'Content-Type': 'application/octet-stream'}) return demo
def test_can_explicitly_set_debug_false_in_initializer(): test_app = app.Chalice('logger-test-2', debug=False) assert test_app.debug is False assert test_app.log.getEffectiveLevel() == logging.ERROR
def sample_app(): demo = app.Chalice('app-name') return demo