Skip to content

chore(ci): add the Event Handler feature to nox tests #4581

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
Merged
Show file tree
Hide file tree
Changes from 2 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
18 changes: 18 additions & 0 deletions noxfile.py
Original file line number Diff line number Diff line change
Expand Up @@ -54,13 +54,15 @@ def test_with_only_required_packages(session: nox.Session):
# Metrics - Base provider
# Middleware factory without tracer
# Typing
# Event Handler without OpenAPI
build_and_run_test(
session,
folders=[
f"{PREFIX_TESTS_FUNCTIONAL}/logger/required_dependencies/",
f"{PREFIX_TESTS_FUNCTIONAL}/metrics/required_dependencies/",
f"{PREFIX_TESTS_FUNCTIONAL}/middleware_factory/required_dependencies/",
f"{PREFIX_TESTS_FUNCTIONAL}/typing/required_dependencies/",
f"{PREFIX_TESTS_FUNCTIONAL}/event_handler/required_dependencies/",
],
)

Expand Down Expand Up @@ -133,3 +135,19 @@ def test_with_aws_encryption_sdk_as_required_package(session: nox.Session):
],
extras="datamasking",
)


@nox.session()
@nox.parametrize("pydantic", ["1.10", "2.0"])
def test_with_pydantic_required_package(session: nox.Session, pydantic: str):
"""Tests that only depends for required libraries"""
# Event Handler OpenAPI

session.install(f"pydantic>={pydantic}")

build_and_run_test(
session,
folders=[
f"{PREFIX_TESTS_FUNCTIONAL}/event_handler/_pydantic/",
],
)
Empty file added tests/__init__.py
Empty file.
Empty file.
80 changes: 80 additions & 0 deletions tests/functional/event_handler/_pydantic/test_api_gateway.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,80 @@
from pydantic import BaseModel

from aws_lambda_powertools.event_handler import content_types
from aws_lambda_powertools.event_handler.api_gateway import (
ApiGatewayResolver,
Response,
)
from aws_lambda_powertools.event_handler.openapi.exceptions import RequestValidationError
from tests.functional.utils import load_event

LOAD_GW_EVENT = load_event("apiGatewayProxyEvent.json")


def test_exception_handler_with_data_validation():
# GIVEN a resolver with an exception handler defined for RequestValidationError
app = ApiGatewayResolver(enable_validation=True)

@app.exception_handler(RequestValidationError)
def handle_validation_error(ex: RequestValidationError):
return Response(
status_code=422,
content_type=content_types.TEXT_PLAIN,
body=f"Invalid data. Number of errors: {len(ex.errors())}",
)

@app.get("/my/path")
def get_lambda(param: int): ...

# WHEN calling the event handler
# AND a RequestValidationError is raised
result = app(LOAD_GW_EVENT, {})

# THEN call the exception_handler
assert result["statusCode"] == 422
assert result["multiValueHeaders"]["Content-Type"] == [content_types.TEXT_PLAIN]
assert result["body"] == "Invalid data. Number of errors: 1"


def test_exception_handler_with_data_validation_pydantic_response():
# GIVEN a resolver with an exception handler defined for RequestValidationError
app = ApiGatewayResolver(enable_validation=True)

class Err(BaseModel):
msg: str

@app.exception_handler(RequestValidationError)
def handle_validation_error(ex: RequestValidationError):
return Response(
status_code=422,
content_type=content_types.APPLICATION_JSON,
body=Err(msg=f"Invalid data. Number of errors: {len(ex.errors())}"),
)

@app.get("/my/path")
def get_lambda(param: int): ...

# WHEN calling the event handler
# AND a RequestValidationError is raised
result = app(LOAD_GW_EVENT, {})

# THEN exception handler's pydantic response should be serialized correctly
assert result["statusCode"] == 422
assert result["body"] == '{"msg":"Invalid data. Number of errors: 1"}'


def test_data_validation_error():
# GIVEN a resolver without an exception handler
app = ApiGatewayResolver(enable_validation=True)

@app.get("/my/path")
def get_lambda(param: int): ...

# WHEN calling the event handler
# AND a RequestValidationError is raised
result = app(LOAD_GW_EVENT, {})

# THEN call the exception_handler
assert result["statusCode"] == 422
assert result["multiValueHeaders"]["Content-Type"] == [content_types.APPLICATION_JSON]
assert "missing" in result["body"]
Empty file.
Original file line number Diff line number Diff line change
@@ -0,0 +1,73 @@
import json

import pytest

from tests.functional.utils import load_event


@pytest.fixture
def json_dump():
# our serializers reduce length to save on costs; fixture to replicate separators
return lambda obj: json.dumps(obj, separators=(",", ":"))


@pytest.fixture
def validation_schema():
return {
"$schema": "https://json-schema.org/draft-07/schema",
"$id": "https://example.com/example.json",
"type": "object",
"title": "Sample schema",
"description": "The root schema comprises the entire JSON document.",
"examples": [{"message": "hello world", "username": "lessa"}],
"required": ["message", "username"],
"properties": {
"message": {
"$id": "#/properties/message",
"type": "string",
"title": "The message",
"examples": ["hello world"],
},
"username": {
"$id": "#/properties/username",
"type": "string",
"title": "The username",
"examples": ["lessa"],
},
},
}


@pytest.fixture
def raw_event():
return {"message": "hello hello", "username": "blah blah"}


@pytest.fixture
def gw_event():
return load_event("apiGatewayProxyEvent.json")


@pytest.fixture
def gw_event_http():
return load_event("apiGatewayProxyV2Event.json")


@pytest.fixture
def gw_event_alb():
return load_event("albMultiValueQueryStringEvent.json")


@pytest.fixture
def gw_event_lambda_url():
return load_event("lambdaFunctionUrlEventWithHeaders.json")


@pytest.fixture
def gw_event_vpc_lattice():
return load_event("vpcLatticeV2EventWithHeaders.json")


@pytest.fixture
def gw_event_vpc_lattice_v1():
return load_event("vpcLatticeEvent.json")
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,6 @@
from typing import Dict

import pytest
from pydantic import BaseModel

from aws_lambda_powertools.event_handler import content_types
from aws_lambda_powertools.event_handler.api_gateway import (
Expand All @@ -31,7 +30,6 @@
ServiceError,
UnauthorizedError,
)
from aws_lambda_powertools.event_handler.openapi.exceptions import RequestValidationError
from aws_lambda_powertools.shared import constants
from aws_lambda_powertools.shared.cookies import Cookie
from aws_lambda_powertools.shared.json_encoder import Encoder
Expand All @@ -45,7 +43,7 @@


def read_media(file_name: str) -> bytes:
path = Path(str(Path(__file__).parent.parent.parent.parent) + "/docs/media/" + file_name)
path = Path(str(Path(__file__).parent.parent.parent.parent) + "/../docs/media/" + file_name)
return path.read_bytes()


Expand Down Expand Up @@ -1458,58 +1456,6 @@ def get_lambda() -> Response:
assert result["body"] == "Foo!"


def test_exception_handler_with_data_validation():
# GIVEN a resolver with an exception handler defined for RequestValidationError
app = ApiGatewayResolver(enable_validation=True)

@app.exception_handler(RequestValidationError)
def handle_validation_error(ex: RequestValidationError):
return Response(
status_code=422,
content_type=content_types.TEXT_PLAIN,
body=f"Invalid data. Number of errors: {len(ex.errors())}",
)

@app.get("/my/path")
def get_lambda(param: int): ...

# WHEN calling the event handler
# AND a RequestValidationError is raised
result = app(LOAD_GW_EVENT, {})

# THEN call the exception_handler
assert result["statusCode"] == 422
assert result["multiValueHeaders"]["Content-Type"] == [content_types.TEXT_PLAIN]
assert result["body"] == "Invalid data. Number of errors: 1"


def test_exception_handler_with_data_validation_pydantic_response():
# GIVEN a resolver with an exception handler defined for RequestValidationError
app = ApiGatewayResolver(enable_validation=True)

class Err(BaseModel):
msg: str

@app.exception_handler(RequestValidationError)
def handle_validation_error(ex: RequestValidationError):
return Response(
status_code=422,
content_type=content_types.APPLICATION_JSON,
body=Err(msg=f"Invalid data. Number of errors: {len(ex.errors())}"),
)

@app.get("/my/path")
def get_lambda(param: int): ...

# WHEN calling the event handler
# AND a RequestValidationError is raised
result = app(LOAD_GW_EVENT, {})

# THEN exception handler's pydantic response should be serialized correctly
assert result["statusCode"] == 422
assert result["body"] == '{"msg":"Invalid data. Number of errors: 1"}'


def test_exception_handler_with_route():
app = ApiGatewayResolver()
# GIVEN a Router object with an exception handler defined for ValueError
Expand Down Expand Up @@ -1540,23 +1486,6 @@ def get_lambda() -> Response:
assert result["body"] == "Foo!"


def test_data_validation_error():
# GIVEN a resolver without an exception handler
app = ApiGatewayResolver(enable_validation=True)

@app.get("/my/path")
def get_lambda(param: int): ...

# WHEN calling the event handler
# AND a RequestValidationError is raised
result = app(LOAD_GW_EVENT, {})

# THEN call the exception_handler
assert result["statusCode"] == 422
assert result["multiValueHeaders"]["Content-Type"] == [content_types.APPLICATION_JSON]
assert "missing" in result["body"]


def test_exception_handler_service_error():
# GIVEN
app = ApiGatewayResolver()
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@


def test_base_path_api_gateway_rest():
app = APIGatewayRestResolver(enable_validation=True)
app = APIGatewayRestResolver()

@app.get("/")
def handle():
Expand All @@ -25,7 +25,7 @@ def handle():


def test_base_path_api_gateway_http():
app = APIGatewayHttpResolver(enable_validation=True)
app = APIGatewayHttpResolver()

@app.get("/")
def handle():
Expand All @@ -42,7 +42,7 @@ def handle():


def test_base_path_alb():
app = ALBResolver(enable_validation=True)
app = ALBResolver()

@app.get("/")
def handle():
Expand All @@ -57,7 +57,7 @@ def handle():


def test_base_path_lambda_function_url():
app = LambdaFunctionUrlResolver(enable_validation=True)
app = LambdaFunctionUrlResolver()

@app.get("/")
def handle():
Expand All @@ -74,7 +74,7 @@ def handle():


def test_vpc_lattice():
app = VPCLatticeResolver(enable_validation=True)
app = VPCLatticeResolver()

@app.get("/")
def handle():
Expand All @@ -89,7 +89,7 @@ def handle():


def test_vpc_latticev2():
app = VPCLatticeV2Resolver(enable_validation=True)
app = VPCLatticeV2Resolver()

@app.get("/")
def handle():
Expand Down
2 changes: 1 addition & 1 deletion tests/functional/idempotency/test_idempotency.py
Original file line number Diff line number Diff line change
Expand Up @@ -61,7 +61,7 @@
from tests.functional.utils import json_serialize, load_event

TABLE_NAME = "TEST_TABLE"
TESTS_MODULE_PREFIX = "test-func.functional.idempotency.test_idempotency"
TESTS_MODULE_PREFIX = "test-func.tests.functional.idempotency.test_idempotency"


def get_dataclasses_lib():
Expand Down
4 changes: 2 additions & 2 deletions tests/functional/idempotency/utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@ def build_idempotency_put_item_stub(
data: Dict,
function_name: str = "test-func",
function_qualified_name: str = "test_idempotent_lambda_first_execution_event_mutation.<locals>",
module_name: str = "functional.idempotency.test_idempotency",
module_name: str = "tests.functional.idempotency.test_idempotency",
handler_name: str = "lambda_handler",
) -> Dict:
idempotency_key_hash = (
Expand Down Expand Up @@ -57,7 +57,7 @@ def build_idempotency_update_item_stub(
handler_response: Dict,
function_name: str = "test-func",
function_qualified_name: str = "test_idempotent_lambda_first_execution_event_mutation.<locals>",
module_name: str = "functional.idempotency.test_idempotency",
module_name: str = "tests.functional.idempotency.test_idempotency",
handler_name: str = "lambda_handler",
) -> Dict:
idempotency_key_hash = (
Expand Down
2 changes: 1 addition & 1 deletion tests/unit/test_tracing.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@

# Maintenance: This should move to Functional tests and use Fake over mocks.

MODULE_PREFIX = "unit.test_tracing"
MODULE_PREFIX = "tests.unit.test_tracing"


@pytest.fixture
Expand Down