Skip to content

feat(validation): returns output from validate function #4839

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 6 commits into from
Aug 6, 2024
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
16 changes: 14 additions & 2 deletions aws_lambda_powertools/utilities/validation/base.py
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@ def validate_data_against_schema(
formats: Optional[Dict] = None,
handlers: Optional[Dict] = None,
provider_options: Optional[Dict] = None,
):
) -> Union[Dict, str]:
"""Validate dict data against given JSON Schema

Parameters
Expand All @@ -31,6 +31,12 @@ def validate_data_against_schema(
Arguments that will be passed directly to the underlying validation call, in this case fastjsonchema.validate.
For all supported arguments see: https://horejsek.github.io/python-fastjsonschema/#fastjsonschema.validate

Returns
-------
Dict
The validated event. If the schema includes a `default` for fields that are not provided, they will be included
in the response.

Raises
------
SchemaValidationError
Expand All @@ -42,7 +48,13 @@ def validate_data_against_schema(
formats = formats or {}
handlers = handlers or {}
provider_options = provider_options or {}
fastjsonschema.validate(definition=schema, data=data, formats=formats, handlers=handlers, **provider_options)
return fastjsonschema.validate(
definition=schema,
data=data,
formats=formats,
handlers=handlers,
**provider_options,
)
except (TypeError, AttributeError, fastjsonschema.JsonSchemaDefinitionException) as e:
raise InvalidSchemaFormatError(f"Schema received: {schema}, Formats: {formats}. Error: {e}")
except fastjsonschema.JsonSchemaValueException as e:
Expand Down
10 changes: 8 additions & 2 deletions aws_lambda_powertools/utilities/validation/validator.py
Original file line number Diff line number Diff line change
Expand Up @@ -172,7 +172,7 @@ def validate(
provider_options: Optional[Dict] = None,
envelope: Optional[str] = None,
jmespath_options: Optional[Dict] = None,
):
) -> Any:
"""Standalone function to validate event data using a JSON Schema

Typically used when you need more control over the validation process.
Expand Down Expand Up @@ -245,6 +245,12 @@ def handler(event, context):
validate(event=event, schema=json_schema_dict, envelope="awslogs.powertools_base64_gzip(data) | powertools_json(@).logEvents[*]")
return event

Returns
-------
Dict
The validated event. If the schema includes a `default` for fields that are not provided, they will be included
in the response.

Raises
------
SchemaValidationError
Expand All @@ -261,7 +267,7 @@ def handler(event, context):
jmespath_options=jmespath_options,
)

validate_data_against_schema(
return validate_data_against_schema(
data=event,
schema=schema,
formats=formats,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,12 @@ def test_validate_raw_event(schema, raw_event):
validate(event=raw_event, schema=schema)


def test_validate_raw_event_default(schema_default, raw_event_default):
resp = validate(event=raw_event_default, schema=schema_default)
assert resp["username"] == "blah blah"
assert resp["message"] == "The default message"


def test_validate_wrapped_event_raw_envelope(schema, wrapped_event):
validate(event=wrapped_event, schema=schema, envelope="data.payload")

Expand Down
33 changes: 33 additions & 0 deletions tests/functional/validator/conftest.py
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,34 @@ def schema():
}


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


@pytest.fixture
def schema_array():
return {
Expand Down Expand Up @@ -137,6 +165,11 @@ def raw_event():
return {"message": "hello hello", "username": "blah blah"}


@pytest.fixture
def raw_event_default():
return {"username": "blah blah"}


@pytest.fixture
def wrapped_event():
return {"data": {"payload": {"message": "hello hello", "username": "blah blah"}}}
Expand Down