From 681e8a76a5fbb13fced5c781f55a4ec7237baafc Mon Sep 17 00:00:00 2001 From: Artur Chakhvadze Date: Fri, 28 Jun 2024 19:35:27 +0400 Subject: [PATCH] Make schema field ordering consistent. --- tests/test_schema.py | 2 +- wanga/schema/schema.py | 25 +++++++++++++------------ 2 files changed, 14 insertions(+), 13 deletions(-) diff --git a/tests/test_schema.py b/tests/test_schema.py index 5fa7e07..6a4f78a 100644 --- a/tests/test_schema.py +++ b/tests/test_schema.py @@ -420,7 +420,7 @@ def foo( "enum": ["x", "y"], }, "f": { - "type": ["integer", "string"], + "type": ["string", "integer"], }, }, "required": ["a", "b", "c"], diff --git a/wanga/schema/schema.py b/wanga/schema/schema.py index fa005bf..c553e47 100644 --- a/wanga/schema/schema.py +++ b/wanga/schema/schema.py @@ -27,22 +27,24 @@ "ObjectNode", "PrimitiveNode", "SchemaNode", + "SchemaValidationError", "SequenceNode", "TupleNode", "UndefinedNode", "UnionNode", + "UnsupportedSchemaError", ] JSON: TypeAlias = int | float | str | bool | None | dict[str, "JSON"] | list["JSON"] -type_to_jsonname: dict[type | None, LeafTypeName] = { - int: "integer", +_type_to_jsonname: dict[type | None, LeafTypeName] = { + None: "null", + bool: "boolean", float: "number", + int: "integer", str: "string", - bool: "boolean", - None: "null", } @@ -105,7 +107,7 @@ class PrimitiveNode(SchemaNode): def json_schema(self, parent_hint: str | None = None) -> LeafJsonSchema: result = LeafJsonSchema( - type=type_to_jsonname[self.primitive_type], + type=_type_to_jsonname[self.primitive_type], ) if parent_hint: result["description"] = parent_hint @@ -160,7 +162,7 @@ class TupleNode(SchemaNode): item_schemas: list[SchemaNode] def json_schema(self, parent_hint: str | None = None) -> JsonSchema: - raise UndefinedSchemaError( + raise UnsupportedSchemaError( "JSON schema cannot be generated for heterogeneous tuple types." ) @@ -223,14 +225,13 @@ def json_schema(self, parent_hint: str | None = None) -> JsonSchema: raise UnsupportedSchemaError( "JSON schema cannot be generated for non-trivial Union types." ) - type_names = { - type_to_jsonname[option.primitive_type] # type: ignore + type_names = [ + _type_to_jsonname[option.primitive_type] # type: ignore for option in self.options if option is not None - } + ] if "number" in type_names and "integer" in type_names: type_names.remove("integer") - type_names = list(type_names) if len(type_names) == 1: type_names = type_names[0] result = LeafJsonSchema( @@ -314,8 +315,8 @@ class ObjectNode(SchemaNode): Attributes: constructor_fn: Callable that can be used to construct an object. - constructor_signature: Signature of the constructor. Used to properly dispatch - positional and keyword-only args during evaluation. + constructor_signature: Used to properly dispatch positional and + keyword-only args during evaluation. name: Name of the object. fields: The fields of the object. hint: Hint extracted from the docstring.