def test_wrong_body(run_from_file_directory):
    environ._load_config_from_file("api_response_wrapper_config.json")

    from aws_serverless_wrapper.serverless_handler import (
        LambdaHandlerOfFunction, )

    event = load_single(
        f"../schema_validation/test_data/api/request_basic.json")
    from json import dumps

    event["body"] = loads(event["body"])
    event["body"]["body_key1"] = 123
    event["body"] = dumps(event["body"])

    response = LambdaHandlerOfFunction(api_basic).wrap_lambda(event, context)

    assert response == {
        "statusCode":
        400,
        "body":
        "123 is not of type 'string'\n\n"
        "Failed validating 'type' in "
        "schema['properties']['body']['properties']['body_key1']:\n"
        "    {'description': 'containing only a string', 'type': 'string'}\n\n"
        "On instance['body']['body_key1']:\n"
        "    123",
        "headers": {
            "Content-Type": "text/plain"
        },
    }
def test_logging_of_event_and_response(run_from_file_directory, caplog,
                                       log_config, expected_part_in_logging,
                                       stated_log_level):
    environ._load_config_from_file("api_response_wrapper_config.json")
    caplog.set_level(logging.INFO)
    from aws_serverless_wrapper.serverless_handler import (
        LambdaHandlerOfFunction, )

    def returning_api(_):
        return {
            "statusCode": 200,
            "body": test_body,
            "headers": {
                "Content-Type": "application/json"
            }
        }

    event = compose_ReST_event(
        httpMethod="POST",
        resource="/test_request_resource/{path_level1}/{path_level2}",
        pathParameters={
            "path_level1": "path_value1",
            "path_level2": "path_value2"
        },
        body=test_body)

    response = LambdaHandlerOfFunction(returning_api,
                                       **log_config).wrap_lambda(
                                           event.copy(), context)

    assert len(caplog.messages) == 1
    assert expected_part_in_logging in caplog.text
    assert caplog.text.startswith(stated_log_level)
    assert response["statusCode"] == 200
def test_parsing_config(caplog, run_from_file_directory, parse_config,
                        response_components, event_body, return_body,
                        raised_exception):
    def test_func(_):
        return {
            "statusCode": 200,
            "body": return_body,
            "headers": {
                "Content-Type": "application/json"
            }
        }

    from aws_serverless_wrapper._environ_variables import environ
    environ._load_config_from_file("api_response_wrapper_config.json")

    from aws_serverless_wrapper.serverless_handler import LambdaHandlerOfFunction

    event = compose_ReST_event(httpMethod="POST",
                               resource="/test_request_no_verification",
                               header={"Content-Type": "application/json"})
    event["body"] = event_body

    if not raised_exception:
        response = LambdaHandlerOfFunction(test_func,
                                           **parse_config).wrap_lambda(
                                               event, fake_context)
        for key in response_components:
            assert response[key] == response_components[key]
    else:
        with raises(raised_exception):
            LambdaHandlerOfFunction(test_func, **parse_config).wrap_lambda(
                event, fake_context)
def test_wrong_method_with_error_response(run_from_file_directory):
    environ._load_config_from_file("api_response_wrapper_config.json")

    environ["API_INPUT_VERIFICATION"]["LOG_ERRORS"]["API_RESPONSE"] = True

    from aws_serverless_wrapper.serverless_handler import (
        LambdaHandlerOfFunction, )

    event = {"httpMethod": "WRONG", "resource": "/test_request_resource"}

    response = LambdaHandlerOfFunction(api_basic).wrap_lambda(event, context)
    response["body"] = loads(response["body"])
    assert response == {
        "statusCode": 501,
        "body": {
            "basic": "API is not defined",
            "error_log_item": {
                "body": "API is not defined",
                "lambda_name": "test_function",
                "service_name": "group",
                "function_version": "$LATEST",
                "headers": {
                    "Content-Type": "text/plain"
                },
                "aws_log_group": "test/log/group",
                "aws_request_id": "uuid",
                "statusCode": 501,
                "timestamp": 1577836800.0,
            },
        },
        "headers": {
            "Content-Type": "application/json"
        },
    }
def test_basic_function_run_through(run_from_file_directory):
    environ._load_config_from_file("api_response_wrapper_config.json")
    from aws_serverless_wrapper.serverless_handler import (
        LambdaHandlerOfFunction, )

    event = load_single(
        f"../schema_validation/test_data/api/request_basic.json")

    def api_basic(event_data):
        assert event_data == event

    LambdaHandlerOfFunction(api_basic).wrap_lambda(event, context)
def test_basic_class_run_through(run_from_file_directory):
    class api_basic(ServerlessBaseClass):
        def main(self) -> dict:
            pass

    environ._load_config_from_file("api_response_wrapper_config.json")
    from aws_serverless_wrapper.serverless_handler import LambdaHandlerOfClass

    event = load_single(
        f"../schema_validation/test_data/api/request_basic.json")
    response = LambdaHandlerOfClass(api_basic).wrap_lambda(event, context)
    assert response["statusCode"] == 200
def test_different_named_class_run_through(run_from_file_directory):
    class EventHandler(ServerlessBaseClass):
        def main(self) -> dict:
            pass

    environ._load_config_from_file("api_response_wrapper_config.json")
    environ["API_INPUT_VERIFICATION"][
        "SCHEMA_DIRECTORY"] = "../schema_validation/test_data/api/test_request_resource||{path_level1}||{path_level2}.json"
    from aws_serverless_wrapper.serverless_handler import LambdaHandlerOfClass

    event = load_single(
        f"../schema_validation/test_data/api/request_basic.json")
    response = LambdaHandlerOfClass(EventHandler).wrap_lambda(event, context)
    assert response["statusCode"] == 200
예제 #8
0
def test_function_run_through(run_from_file_directory):
    from aws_serverless_wrapper import aws_serverless_wrapper

    environ._load_config_from_file("api_response_wrapper_config.json")

    event = load_single(
        f"../schema_validation/test_data/api/request_basic.json")

    @aws_serverless_wrapper
    def api_basic(event_data):
        assert event_data == event

    response = api_basic(event, context)
    assert response["statusCode"] == 200
def test_nested_api_resource(run_from_file_directory):
    environ._load_config_from_file("api_response_wrapper_config.json")

    from aws_serverless_wrapper.serverless_handler import (
        LambdaHandlerOfFunction, )

    event = compose_ReST_event(
        httpMethod="POST",
        resource="/test_request_resource/specific_resource/{some_id}",
        pathParameters={"some_id": "test_id"},
    )

    response = LambdaHandlerOfFunction(api_basic).wrap_lambda(event, context)

    assert response == {"statusCode": 200}
예제 #10
0
def test_class_run_through(run_from_file_directory):
    from aws_serverless_wrapper import aws_serverless_wrapper, ServerlessBaseClass

    environ._load_config_from_file("api_response_wrapper_config.json")

    event = load_single(
        f"../schema_validation/test_data/api/request_basic.json")

    @aws_serverless_wrapper
    class api_basic(ServerlessBaseClass):
        def main(self):
            assert self.event == event
            assert self.context == context

    response = api_basic(event, context)
    assert response["statusCode"] == 200
예제 #11
0
def test_wrapper_with_charset_utf8_content_type(run_from_file_directory):
    from aws_serverless_wrapper import aws_serverless_wrapper

    environ._load_config_from_file("api_response_wrapper_config.json")

    event = load_single(
        f"../schema_validation/test_data/api/request_basic.json")

    event["headers"]["Content-Type"] += "; charset=utf-8"

    @aws_serverless_wrapper
    def api_basic(event_data):
        assert event_data == event

    response = api_basic(event, context)
    assert response["statusCode"] == 200
def test_wrong_method(run_from_file_directory):
    environ._load_config_from_file("api_response_wrapper_config.json")

    from aws_serverless_wrapper.serverless_handler import (
        LambdaHandlerOfFunction, )

    event = {"httpMethod": "WRONG", "resource": "/test_request_resource"}

    response = LambdaHandlerOfFunction(api_basic).wrap_lambda(event, context)

    assert response == {
        "statusCode": 501,
        "body": "API is not defined",
        "headers": {
            "Content-Type": "text/plain"
        },
    }
def test_invalid_logging_config(run_from_file_directory, caplog, log_config):
    environ._load_config_from_file("api_response_wrapper_config.json")
    from aws_serverless_wrapper.serverless_handler import (
        LambdaHandlerOfFunction, )

    event = compose_ReST_event(
        httpMethod="POST",
        resource="/test_request_resource/{path_level1}/{path_level2}",
        pathParameters={
            "path_level1": "path_value1",
            "path_level2": "path_value2"
        },
        body=test_body)

    from jsonschema.exceptions import ValidationError
    with raises(ValidationError):
        LambdaHandlerOfFunction(api_basic, **log_config).wrap_lambda(
            event.copy(), context)
def test_unexpected_exception(run_from_file_directory):
    environ._load_config_from_file("api_response_wrapper_config.json")

    from aws_serverless_wrapper.serverless_handler import LambdaHandlerOfClass

    event = load_single(
        f"../schema_validation/test_data/api/request_basic.json")

    response = LambdaHandlerOfClass(RaiseUnexpectedException).wrap_lambda(
        event, context)

    assert response == {
        "statusCode": 500,
        "body": "internal server error",
        "headers": {
            "Content-Type": "text/plain"
        },
    }
def test_function_occurring_exception(run_from_file_directory):
    def api_basic():
        raise Exception("test")

    environ._load_config_from_file("api_response_wrapper_config.json")
    from aws_serverless_wrapper.serverless_handler import (
        LambdaHandlerOfFunction, )

    event = load_single(
        f"../schema_validation/test_data/api/request_basic.json")

    response = LambdaHandlerOfFunction(api_basic).wrap_lambda(event, context)

    assert response == {
        "statusCode": 500,
        "body": "internal server error",
        "headers": {
            "Content-Type": "text/plain"
        },
    }
def test_missing_headers(run_from_file_directory):
    environ._load_config_from_file("api_response_wrapper_config.json")

    from aws_serverless_wrapper.serverless_handler import (
        LambdaHandlerOfFunction, )

    event = {
        "httpMethod": "POST",
        "resource": "/test_request_resource/{path_level1}/{path_level2}"
    }

    response = LambdaHandlerOfFunction(api_basic).wrap_lambda(event, context)

    assert response == {
        "statusCode": 400,
        "body": "'headers' is a required property",
        "headers": {
            "Content-Type": "text/plain"
        },
    }
예제 #17
0
def test_class_run_through_with_response(run_from_file_directory):
    from aws_serverless_wrapper import aws_serverless_wrapper, ServerlessBaseClass

    @aws_serverless_wrapper
    class api_basic(ServerlessBaseClass):
        def main(self):
            return {
                "statusCode": 400,
                "body": "some response text",
                "headers": {
                    "Content-Type": "text/plain"
                },
            }

    environ._load_config_from_file("api_response_wrapper_config.json")

    event = load_single(
        f"../schema_validation/test_data/api/request_basic.json")
    response = api_basic(event, context)
    assert response["statusCode"] == 400
    assert response["body"] == "some response text"
    assert response["headers"] == {"Content-Type": "text/plain"}
def test_basic_function_run_through_no_verification(run_from_file_directory,
                                                    caplog):
    environ._load_config_from_file("api_response_wrapper_config.json")
    from aws_serverless_wrapper.serverless_handler import (
        LambdaHandlerOfFunction, )

    event = load_single(
        f"../schema_validation/test_data/api/request_basic.json")

    def api_basic(event_data):
        assert event_data == event
        return {
            "statusCode": 200,
            "body": "Faulty Data",
            "headers": {
                "Content-Type": "text/plain"
            }
        }

    event["body"] = "wrong_body"
    assert LambdaHandlerOfFunction(api_basic).wrap_lambda(
        event, context)["statusCode"] != 200
    assert len(caplog.messages) == 0
    assert LambdaHandlerOfFunction(api_basic,
                                   PARSE_BODY=False,
                                   API_INPUT_VERIFICATION=False).wrap_lambda(
                                       event, context)["statusCode"] == 200
    assert len(caplog.messages) == 1
    assert "no specified response schema available" in caplog.text
    caplog.clear()
    environ._load_config_from_file("api_response_wrapper_config.json")

    assert LambdaHandlerOfFunction(
        api_basic,
        PARSE_BODY=False,
        API_INPUT_VERIFICATION=False,
        API_RESPONSE_VERIFICATION=False).wrap_lambda(
            event, context)["statusCode"] == 200
    assert len(caplog.messages) == 0
def test_expected_exception_and_return_api_response(run_from_file_directory):
    environ._load_config_from_file("api_response_wrapper_config.json")
    from aws_serverless_wrapper._environ_variables import NoExceptDict

    environ["ERROR_LOG"] = NoExceptDict({"API_RESPONSE": True})

    from aws_serverless_wrapper.serverless_handler import LambdaHandlerOfClass

    event = load_single(
        f"../schema_validation/test_data/api/request_basic.json")

    response = LambdaHandlerOfClass(RaiseExpectedException,
                                    with_context=True).wrap_lambda(
                                        event, context)
    response["body"] = loads(response["body"])

    assert response == {
        "statusCode": 500,
        "body": {
            "basic": "internal server error",
            "error_log_item": {
                "body": "item in db not found",
                "lambda_name": "test_function",
                "service_name": "group",
                "function_version": "$LATEST",
                "headers": {
                    "Content-Type": "text/plain"
                },
                "aws_log_group": "test/log/group",
                "aws_request_id": "uuid",
                "statusCode": 404,
                "timestamp": 1577836800.0,
            },
        },
        "headers": {
            "Content-Type": "application/json"
        },
    }
def test_function_occurring_exception_with_error_log(run_from_file_directory):
    def api_basic():
        raise Exception("test")

    environ._load_config_from_file("api_response_wrapper_config.json")

    environ["ERROR_LOG"] = {"API_RESPONSE": True}

    from aws_serverless_wrapper.serverless_handler import (
        LambdaHandlerOfFunction, )

    event = load_single(
        f"../schema_validation/test_data/api/request_basic.json")

    response = LambdaHandlerOfFunction(api_basic).wrap_lambda(event, context)
    response["body"] = loads(response["body"])

    assert response["statusCode"] == 500
    assert response["headers"] == {"Content-Type": "application/json"}
    assert len(response["body"]) == 2
    assert len(response["body"]["error_log_item"]) == 12

    assert response["body"]["basic"] == "internal server error"
    assert set(response["body"]["error_log_item"].keys()) == {
        "aws_request_id",
        "aws_log_group",
        "lambda_name",
        "service_name",
        "function_version",
        "timestamp",
        "exception_type",
        "exception_text",
        "exception_file",
        "exception_line_no",
        "exception_function",
        "exception_stack",
    }
def response_validation_env():
    actual_cwd = getcwd()
    chdir(dirname(realpath(__file__)))
    environ._load_config_from_file("api_response_wrapper_config.json")
    yield
    chdir(actual_cwd)