Initial Fields Validators #1

Merged
HideyoshiNakazone merged 8 commits from initial-fields-validators into main 2025-04-10 02:22:48 +00:00
5 changed files with 50 additions and 16 deletions
Showing only changes of commit 936c5b350a - Show all commits

View File

@@ -9,17 +9,23 @@ from typing import Type
class SchemaConverter: class SchemaConverter:
@staticmethod """
def build(schema): Converts JSON Schema to Pydantic models.
try:
Validator.check_schema(schema)
except SchemaError as e:
raise ValueError(f"Invalid JSON Schema: {e}")
if schema["type"] != "object": This class is responsible for converting JSON Schema definitions into Pydantic models.
raise TypeError( It validates the schema and generates the corresponding Pydantic model with appropriate
f"Invalid JSON Schema: {schema['type']}. Only 'object' can be converted to Pydantic models." fields and types. The generated model can be used for data validation and serialization.
) """
@staticmethod
def build(schema: dict) -> Type:
"""
Converts a JSON Schema to a Pydantic model.
:param schema: The JSON Schema to convert.
:return: A Pydantic model class.
"""
if "title" not in schema:
raise ValueError("JSON Schema must have a title.")
return SchemaConverter.build_object(schema["title"], schema) return SchemaConverter.build_object(schema["title"], schema)
@@ -27,7 +33,19 @@ class SchemaConverter:
def build_object( def build_object(
name: str, name: str,
schema: dict, schema: dict,
): ) -> Type:
"""
Converts a JSON Schema object to a Pydantic model given a name.
:param name:
:param schema:
:return:
"""
try:
Validator.check_schema(schema)
except SchemaError as e:
raise ValueError(f"Invalid JSON Schema: {e}")
if schema["type"] != "object": if schema["type"] != "object":
raise TypeError( raise TypeError(
f"Invalid JSON Schema: {schema['type']}. Only 'object' can be converted to Pydantic models." f"Invalid JSON Schema: {schema['type']}. Only 'object' can be converted to Pydantic models."

View File

@@ -1,6 +1,8 @@
from abc import ABC, abstractmethod from abc import ABC, abstractmethod
from typing import Generic, Self, TypeVar from typing import Generic, Self, TypeVar
from pydantic import Field
T = TypeVar("T") T = TypeVar("T")
@@ -17,7 +19,7 @@ class GenericTypeParser(ABC, Generic[T]):
@abstractmethod @abstractmethod
def from_properties( def from_properties(
name: str, properties: dict[str, any] name: str, properties: dict[str, any]
) -> tuple[type[T], dict[str, any]]: ... ) -> tuple[type[T], Field]: ...
@classmethod @classmethod
def get_impl(cls, type_name: str) -> Self: def get_impl(cls, type_name: str) -> Self:

View File

@@ -1,3 +1,5 @@
from dataclasses import Field
from jambo.types._type_parser import GenericTypeParser from jambo.types._type_parser import GenericTypeParser
@@ -8,4 +10,15 @@ class IntTypeParser(GenericTypeParser):
@staticmethod @staticmethod
def from_properties(name, properties): def from_properties(name, properties):
return int, {} _field_properties = dict()
if "minimum" in properties:
_field_properties["ge"] = properties["minimum"]
if "maximum" in properties:
_field_properties["le"] = properties["maximum"]
if "multipleOf" in properties:
_field_properties["multiple_of"] = properties["multipleOf"]
return int, Field(**_field_properties)

View File

@@ -21,7 +21,7 @@ dev = [
# POE Tasks # POE Tasks
[tool.poe.tasks] [tool.poe.tasks]
create-hooks = "bash .githooks/set-hooks.sh" create-hooks = "bash .githooks/set-hooks.sh"
tests = "python -m unittest discover -s tests -v"
# Build System # Build System
[tool.hatch.version] [tool.hatch.version]

View File

@@ -21,9 +21,10 @@ class TestTypeParser(unittest.TestCase):
def test_int_parser(self): def test_int_parser(self):
parser = IntTypeParser() parser = IntTypeParser()
expected_definition = (int, {})
self.assertEqual(parser.from_properties("placeholder", {}), expected_definition) type_parsing, type_validator = parser.from_properties("placeholder", {})
self.assertEqual(type_parsing, int)
def test_float_parser(self): def test_float_parser(self):
parser = FloatTypeParser() parser = FloatTypeParser()