-
Notifications
You must be signed in to change notification settings - Fork 42
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Extract schema transformation in module
- Loading branch information
Showing
4 changed files
with
463 additions
and
93 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,203 @@ | ||
import base64 | ||
import datetime | ||
import io | ||
import typing as t | ||
|
||
from pulp_glue.common.i18n import get_translation | ||
|
||
translation = get_translation(__package__) | ||
_ = translation.gettext | ||
|
||
ISO_DATE_FORMAT = "%Y-%m-%d" | ||
ISO_DATETIME_FORMAT = "%Y-%m-%dT%H:%M:%S.%fZ" | ||
|
||
|
||
class SchemaError(ValueError): | ||
pass | ||
|
||
|
||
class ValidationError(ValueError): | ||
pass | ||
|
||
|
||
def _assert_type( | ||
name: str, | ||
value: t.Any, | ||
types: t.Union[t.Type[object], t.Tuple[t.Type[object], ...]], | ||
type_name: str, | ||
) -> None: | ||
if not isinstance(value, types): | ||
raise ValidationError( | ||
_("'{name}' is expected to be a {type_name}.").format(name=name, type_name=type_name) | ||
) | ||
|
||
|
||
def _assert_min_max(schema: t.Any, name: str, value: t.Any): | ||
if (minimum := schema.get("minimum")) is not None: | ||
if schema.get("exclusiveMinimum", False): | ||
if minimum >= value: | ||
raise ValidationError( | ||
_("'{name}' is expected to be larger than {minimum}").format( | ||
name=name, minimum=minimum | ||
) | ||
) | ||
else: | ||
if minimum > value: | ||
raise ValidationError( | ||
_("'{name}' is expected to not be smaller than {minimum}").format( | ||
name=name, minimum=minimum | ||
) | ||
) | ||
if (maximum := schema.get("maximum")) is not None: | ||
if schema.get("exclusiveMaximum", False): | ||
if maximum <= value: | ||
raise ValidationError( | ||
_("'{name}' is expected to be smaller than {maximum}").format( | ||
name=name, maximum=maximum | ||
) | ||
) | ||
else: | ||
if maximum < value: | ||
raise ValidationError( | ||
_("'{name}' is expected to not be larger than {maximum}").format( | ||
name=name, maximum=maximum | ||
) | ||
) | ||
|
||
|
||
def transform(schema: t.Any, name: str, value: t.Any, components: t.Dict[str, t.Any]) -> t.Any: | ||
if (schema_ref := schema.get("$ref")) is not None: | ||
# From json-schema: | ||
# "All other properties in a "$ref" object MUST be ignored." | ||
return transform_ref(schema_ref, name, value, components) | ||
schema_type: t.Optional[str] = schema.get("type") | ||
if schema_type is None: | ||
return value | ||
|
||
if value is None: | ||
if schema.get("nullable", False): | ||
return None | ||
else: | ||
raise ValidationError(_("'{name}' cannot be 'null'.").format(name=name)) | ||
|
||
if (typed_transform := _TYPED_TRANSFORMS.get(schema_type)) is not None: | ||
return typed_transform(schema, name, value, components) | ||
else: | ||
raise NotImplementedError( | ||
_("Type `{schema_type}` is not implemented yet.").format(schema_type=schema_type) | ||
) | ||
|
||
|
||
def transform_ref( | ||
schema_ref: str, name: str, value: t.Any, components: t.Dict[str, t.Any] | ||
) -> t.Any: | ||
if not schema_ref.startswith("#/components/schemas/"): | ||
raise SchemaError(_("'{name}' contains an invalid reference.").format(name=name)) | ||
schema_name = schema_ref[21:] | ||
return transform(components[schema_name], name, value, components) | ||
|
||
|
||
def transform_array( | ||
schema: t.Any, name: str, value: t.Any, components: t.Dict[str, t.Any] | ||
) -> t.Any: | ||
_assert_type(name, value, list, "array") | ||
if (min_items := schema.get("minItems")) is not None: | ||
if len(value) < min_items: | ||
raise ValidationError( | ||
_("'{name}' is expected to have at least {min_items} items.").format( | ||
name=name, min_items=min_items | ||
) | ||
) | ||
if (max_items := schema.get("maxItems")) is not None: | ||
if len(value) > max_items: | ||
raise ValidationError( | ||
_("'{name}' is expected to have at most {max_items} items.").format( | ||
name=name, max_items=max_items | ||
) | ||
) | ||
if schema.get("uniqueItems", False): | ||
if len(set(value)) != len(value): | ||
raise ValidationError(_("'{name}' is expected to have unique items.").format(name=name)) | ||
|
||
value = [ | ||
transform(schema["items"], f"{name}[{i}]", item, components) for i, item in enumerate(value) | ||
] | ||
return value | ||
|
||
|
||
def transform_boolean( | ||
schema: t.Any, name: str, value: t.Any, components: t.Dict[str, t.Any] | ||
) -> t.Any: | ||
_assert_type(name, value, bool, "boolean") | ||
return value | ||
|
||
|
||
def transform_integer( | ||
schema: t.Any, name: str, value: t.Any, components: t.Dict[str, t.Any] | ||
) -> t.Any: | ||
_assert_type(name, value, int, "integer") | ||
_assert_min_max(schema, name, value) | ||
|
||
if (multiple_of := schema.get("multipleOf")) is not None: | ||
if value % multiple_of != 0: | ||
raise ValidationError( | ||
_("'{name}' is expected to be a multiple of {multiple_of}").format( | ||
name=name, multiple_of=multiple_of | ||
) | ||
) | ||
|
||
return value | ||
|
||
|
||
def transform_number( | ||
schema: t.Any, name: str, value: t.Any, components: t.Dict[str, t.Any] | ||
) -> t.Any: | ||
_assert_type(name, value, float, "number") | ||
_assert_min_max(schema, name, value) | ||
return value | ||
|
||
|
||
def transform_object( | ||
schema: t.Any, name: str, value: t.Any, components: t.Dict[str, t.Any] | ||
) -> t.Any: | ||
_assert_type(name, value, dict, "object") | ||
return value | ||
|
||
|
||
def transform_string( | ||
schema: t.Any, name: str, value: t.Any, components: t.Dict[str, t.Any] | ||
) -> t.Any: | ||
schema_format = schema.get("format") | ||
if schema_format == "byte": | ||
_assert_type(name, value, bytes, "bytes") | ||
value = base64.b64encode(value).decode() | ||
elif schema_format == "binary": | ||
# This is not really useful for json serialization. | ||
# It is there for file transfer, e.g. in multipart. | ||
_assert_type(name, value, (bytes, io.BufferedReader, io.BytesIO), "binary") | ||
elif schema_format == "date": | ||
_assert_type(name, value, datetime.date, "date") | ||
value = value.strftime(ISO_DATE_FORMAT) | ||
elif schema_format == "date-time": | ||
_assert_type(name, value, datetime.datetime, "date-time") | ||
value = value.strftime(ISO_DATETIME_FORMAT) | ||
else: | ||
_assert_type(name, value, str, "string") | ||
if (enum := schema.get("enum")) is not None: | ||
if value not in enum: | ||
raise ValidationError( | ||
_("'{name}' is expected to be on of [{enums}].").format( | ||
name=name, enums=", ".join(enum) | ||
) | ||
) | ||
return value | ||
|
||
|
||
_TYPED_TRANSFORMS = { | ||
"array": transform_array, | ||
"boolean": transform_boolean, | ||
"integer": transform_integer, | ||
"number": transform_number, | ||
"object": transform_object, | ||
"string": transform_string, | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.