Skip to content

Commit

Permalink
feat: pydantic_model_to_code test
Browse files Browse the repository at this point in the history
  • Loading branch information
thorwhalen committed Oct 4, 2024
1 parent bc91939 commit 457188e
Show file tree
Hide file tree
Showing 2 changed files with 58 additions and 3 deletions.
6 changes: 3 additions & 3 deletions ju/pydantic_util.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
<BLANKLINE>
from enum import Enum
Expand All @@ -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
<BLANKLINE>
from pydantic import BaseModel, Field
Expand Down
55 changes: 55 additions & 0 deletions ju/tests/pydantic_util_test.py
Original file line number Diff line number Diff line change
@@ -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
<BLANKLINE>
from enum import Enum
from typing import Optional
<BLANKLINE>
from pydantic import BaseModel
<BLANKLINE>
<BLANKLINE>
class StreetType(Enum):
Street = 'Street'
Avenue = 'Avenue'
Boulevard = 'Boulevard'
<BLANKLINE>
<BLANKLINE>
class Model(BaseModel):
number: Optional[float] = None
street_name: Optional[str] = None
street_type: Optional[StreetType] = None
<BLANKLINE>
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
<BLANKLINE>
from pydantic import BaseModel, Field
<BLANKLINE>
<BLANKLINE>
class Simple(BaseModel):
name: str = Field(..., title='Name')
age: int = Field(..., title='Age')
<BLANKLINE>
"""

0 comments on commit 457188e

Please sign in to comment.