|
30 | 30 | ServiceError,
|
31 | 31 | UnauthorizedError,
|
32 | 32 | )
|
| 33 | +from aws_lambda_powertools.event_handler.openapi.exceptions import RequestValidationError |
33 | 34 | from aws_lambda_powertools.shared import constants
|
34 | 35 | from aws_lambda_powertools.shared.cookies import Cookie
|
35 | 36 | from aws_lambda_powertools.shared.json_encoder import Encoder
|
@@ -1458,6 +1459,51 @@ def get_lambda() -> Response:
|
1458 | 1459 | assert result["body"] == "Foo!"
|
1459 | 1460 |
|
1460 | 1461 |
|
| 1462 | +def test_exception_handler_with_data_validation(): |
| 1463 | + # GIVEN a resolver with an exception handler defined for RequestValidationError |
| 1464 | + app = ApiGatewayResolver(enable_validation=True) |
| 1465 | + |
| 1466 | + @app.exception_handler(RequestValidationError) |
| 1467 | + def handle_validation_error(ex: RequestValidationError): |
| 1468 | + print(f"request path is '{app.current_event.path}'") |
| 1469 | + return Response( |
| 1470 | + status_code=422, |
| 1471 | + content_type=content_types.TEXT_PLAIN, |
| 1472 | + body=f"Invalid data. Number of errors: {len(ex.errors())}", |
| 1473 | + ) |
| 1474 | + |
| 1475 | + @app.get("/my/path") |
| 1476 | + def get_lambda(param: int): |
| 1477 | + ... |
| 1478 | + |
| 1479 | + # WHEN calling the event handler |
| 1480 | + # AND a RequestValidationError is raised |
| 1481 | + result = app(LOAD_GW_EVENT, {}) |
| 1482 | + |
| 1483 | + # THEN call the exception_handler |
| 1484 | + assert result["statusCode"] == 422 |
| 1485 | + assert result["multiValueHeaders"]["Content-Type"] == [content_types.TEXT_PLAIN] |
| 1486 | + assert result["body"] == "Invalid data. Number of errors: 1" |
| 1487 | + |
| 1488 | + |
| 1489 | +def test_data_validation_error(): |
| 1490 | + # GIVEN a resolver without an exception handler |
| 1491 | + app = ApiGatewayResolver(enable_validation=True) |
| 1492 | + |
| 1493 | + @app.get("/my/path") |
| 1494 | + def get_lambda(param: int): |
| 1495 | + ... |
| 1496 | + |
| 1497 | + # WHEN calling the event handler |
| 1498 | + # AND a RequestValidationError is raised |
| 1499 | + result = app(LOAD_GW_EVENT, {}) |
| 1500 | + |
| 1501 | + # THEN call the exception_handler |
| 1502 | + assert result["statusCode"] == 422 |
| 1503 | + assert result["multiValueHeaders"]["Content-Type"] == [content_types.APPLICATION_JSON] |
| 1504 | + assert "missing" in result["body"] |
| 1505 | + |
| 1506 | + |
1461 | 1507 | def test_exception_handler_service_error():
|
1462 | 1508 | # GIVEN
|
1463 | 1509 | app = ApiGatewayResolver()
|
|
0 commit comments