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 all 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 specifies a `default` value for fields that are omitted,
those default values 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 specifies a `default` value for fields that are omitted,
those default values 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
4 changes: 4 additions & 0 deletions docs/utilities/validation.md
Original file line number Diff line number Diff line change
Expand Up @@ -67,6 +67,10 @@ It will fail fast with `SchemaValidationError` exception if event or response do

**Validate** standalone function is typically used within the Lambda handler, or any other methods that perform data validation.

???+ info
This function returns the validated event as a JSON object. If the schema specifies `default` values for omitted fields,
those default values will be included in the response.

You can also gracefully handle schema validation errors by catching `SchemaValidationError` exception.

=== "getting_started_validator_standalone_function.py"
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
53 changes: 43 additions & 10 deletions tests/functional/validator/conftest.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,8 +6,8 @@
@pytest.fixture
def schema():
return {
"$schema": "http://json-schema.org/draft-07/schema",
"$id": "http://example.com/example.json",
"$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.",
Expand All @@ -30,11 +30,39 @@ def schema():
}


@pytest.fixture
def schema_default():
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"}, {"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 {
"$schema": "http://json-schema.org/draft-07/schema",
"$id": "http://example.com/example.json",
"$schema": "https://json-schema.org/draft-07/schema",
"$id": "https://example.com/example.json",
"type": "array",
"title": "Sample schema",
"description": "Sample JSON Schema for dummy data in an array",
Expand Down Expand Up @@ -71,8 +99,8 @@ def schema_array():
@pytest.fixture
def schema_response():
return {
"$schema": "http://json-schema.org/draft-07/schema",
"$id": "http://example.com/example.json",
"$schema": "https://json-schema.org/draft-07/schema",
"$id": "https://example.com/example.json",
"type": "object",
"title": "Sample outgoing schema",
"description": "The root schema comprises the entire JSON document.",
Expand All @@ -89,7 +117,7 @@ def schema_response():
def schema_refs():
return {
"ParentSchema": {
"$schema": "http://json-schema.org/draft-07/schema",
"$schema": "https://json-schema.org/draft-07/schema",
"$id": "testschema://ParentSchema",
"type": "object",
"title": "Sample schema",
Expand All @@ -104,7 +132,7 @@ def schema_refs():
},
},
"ChildSchema": {
"$schema": "http://json-schema.org/draft-07/schema",
"$schema": "https://json-schema.org/draft-07/schema",
"$id": "testschema://ChildSchema",
"type": "object",
"title": "Sample schema",
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 Expand Up @@ -407,7 +440,7 @@ def cloudwatch_logs_event():
@pytest.fixture
def cloudwatch_logs_schema():
return {
"$schema": "http://json-schema.org/draft-07/schema",
"$schema": "https://json-schema.org/draft-07/schema",
"$id": "http://example.com/example.json",
"type": "array",
"title": "Sample schema",
Expand Down Expand Up @@ -622,7 +655,7 @@ def eventbridge_schema_registry_cloudtrail_v2_s3():
@pytest.fixture
def schema_datetime_format():
return {
"$schema": "http://json-schema.org/draft-07/schema",
"$schema": "https://json-schema.org/draft-07/schema",
"$id": "http://example.com/example.json",
"type": "object",
"title": "Sample schema with string date-time format",
Expand Down