From 457188e18d0ee1362d6f72e1c9c6f7e3184fd3db Mon Sep 17 00:00:00 2001 From: Thor Whalen Date: Fri, 4 Oct 2024 11:57:19 +0200 Subject: [PATCH] feat: pydantic_model_to_code test --- ju/pydantic_util.py | 6 ++-- ju/tests/pydantic_util_test.py | 55 ++++++++++++++++++++++++++++++++++ 2 files changed, 58 insertions(+), 3 deletions(-) create mode 100644 ju/tests/pydantic_util_test.py diff --git a/ju/pydantic_util.py b/ju/pydantic_util.py index f92f726..1aa4930 100644 --- a/ju/pydantic_util.py +++ b/ju/pydantic_util.py @@ -314,7 +314,7 @@ def pydantic_model_to_code( ... } ... } ... }''' - >>> print(pydantic_model_to_code(json_schema)) + >>> print(pydantic_model_to_code(json_schema)) # doctest: +SKIP from __future__ import annotations from enum import Enum @@ -338,8 +338,8 @@ class Model(BaseModel): This means you can get some model code from an example data dict, using pydantic_model_to_code - >>> M = data_to_pydantic_model({"name": "John", "age": 30}, "Simple") - >>> print(pydantic_model_to_code(M)) + >>> M = data_to_pydantic_model({"name": "John", "age": 30}, "Simple") # doctest: +SKIP + >>> print(pydantic_model_to_code(M)) # doctest: +SKIP from __future__ import annotations from pydantic import BaseModel, Field diff --git a/ju/tests/pydantic_util_test.py b/ju/tests/pydantic_util_test.py new file mode 100644 index 0000000..976d525 --- /dev/null +++ b/ju/tests/pydantic_util_test.py @@ -0,0 +1,55 @@ + +import json +from ju.pydantic_util import ModelSource, pydantic_model_to_code, data_to_pydantic_model + + + +def test_pydantic_model_to_code() -> str: + """ + >>> json_schema: str = '''{ + ... "type": "object", + ... "properties": { + ... "number": {"type": "number"}, + ... "street_name": {"type": "string"}, + ... "street_type": {"type": "string", + ... "enum": ["Street", "Avenue", "Boulevard"] + ... } + ... } + ... }''' + >>> print(pydantic_model_to_code(json_schema)) + from __future__ import annotations + + from enum import Enum + from typing import Optional + + from pydantic import BaseModel + + + class StreetType(Enum): + Street = 'Street' + Avenue = 'Avenue' + Boulevard = 'Boulevard' + + + class Model(BaseModel): + number: Optional[float] = None + street_name: Optional[str] = None + street_type: Optional[StreetType] = None + + + This means you can get some model code from an example data dict, + using pydantic_model_to_code + + >>> M = data_to_pydantic_model({"name": "John", "age": 30}, "Simple") + >>> print(pydantic_model_to_code(M)) + from __future__ import annotations + + from pydantic import BaseModel, Field + + + class Simple(BaseModel): + name: str = Field(..., title='Name') + age: int = Field(..., title='Age') + + + """ \ No newline at end of file