11import ast
22from textwrap import dedent
33
4+ import pydantic
5+ import pytest
46from open_data_contract_standard .model import Description , OpenDataContractStandard , SchemaObject , SchemaProperty
57
68import datacontract .export .pydantic_exporter as conv
@@ -16,7 +18,7 @@ def test_simple_model_export():
1618 == dedent (
1719 """
1820 class Test(pydantic.BaseModel):
19- f: typing.Optional[str]
21+ f: typing.Optional[str] = None
2022 """
2123 ).strip ()
2224 )
@@ -39,7 +41,7 @@ def test_array_model_export():
3941 == dedent (
4042 """
4143 class Test(pydantic.BaseModel):
42- f: typing.Optional[list[str]]
44+ f: typing.Optional[list[str]] = None
4345 """
4446 ).strip ()
4547 )
@@ -65,7 +67,7 @@ class Test(pydantic.BaseModel):
6567
6668 class F(pydantic.BaseModel):
6769 f1: str
68- f: typing.Optional[F]
70+ f: typing.Optional[F] = None
6971 """
7072 ).strip ()
7173 )
@@ -86,7 +88,7 @@ class Test(pydantic.BaseModel):
8688
8789 class F(pydantic.BaseModel):
8890 pass
89- f: typing.Optional[F]
91+ f: typing.Optional[F] = None
9092 """
9193 ).strip ()
9294 )
@@ -117,7 +119,7 @@ class Test(pydantic.BaseModel):
117119 class F(pydantic.BaseModel):
118120 \" \" \" A test field\" \" \"
119121 f1: str
120- f: typing.Optional[F]
122+ f: typing.Optional[F] = None
121123 """
122124 ).strip ()
123125 )
@@ -144,7 +146,7 @@ class Test(pydantic.BaseModel):
144146 class F(pydantic.BaseModel):
145147 f1: str
146148 'A test field'
147- f: typing.Optional[F]
149+ f: typing.Optional[F] = None
148150 """
149151 ).strip ()
150152 )
@@ -166,7 +168,7 @@ def test_model_description_export():
166168 'Contract description'
167169
168170 class Test_model(pydantic.BaseModel):
169- f: typing.Optional[str]
171+ f: typing.Optional[str] = None
170172 """
171173 ).strip ()
172174 )
@@ -182,7 +184,178 @@ def test_decimal_model_export():
182184 == dedent (
183185 """
184186 class Test(pydantic.BaseModel):
185- f: typing.Optional[decimal.Decimal]
187+ f: typing.Optional[decimal.Decimal] = None
186188 """
187189 ).strip ()
188190 )
191+
192+
193+ def test_string_constraints_export ():
194+ schema = SchemaObject (
195+ name = "Test" ,
196+ properties = [
197+ SchemaProperty (
198+ name = "f" ,
199+ logicalType = "string" ,
200+ required = True ,
201+ logicalTypeOptions = {"pattern" : "^[^,]+(,\\ s*[^,]+)*$" , "minLength" : 1 , "maxLength" : 64 },
202+ )
203+ ],
204+ )
205+ ast_class = conv .generate_model_class ("Test" , schema )
206+ assert (
207+ ast .unparse (ast_class )
208+ == dedent (
209+ r"""
210+ class Test(pydantic.BaseModel):
211+ f: str = pydantic.Field(pattern='^[^,]+(,\\s*[^,]+)*$', min_length=1, max_length=64)
212+ """
213+ ).strip ()
214+ )
215+
216+
217+ def test_optional_constrained_field_defaults_to_none ():
218+ schema = SchemaObject (
219+ name = "Test" ,
220+ properties = [
221+ SchemaProperty (
222+ name = "f" ,
223+ logicalType = "string" ,
224+ description = "A labelled field" ,
225+ logicalTypeOptions = {"pattern" : "^a$" },
226+ )
227+ ],
228+ )
229+ ast_class = conv .generate_model_class ("Test" , schema )
230+ assert (
231+ ast .unparse (ast_class )
232+ == dedent (
233+ """
234+ class Test(pydantic.BaseModel):
235+ f: typing.Optional[str] = pydantic.Field(default=None, pattern='^a$')
236+ 'A labelled field'
237+ """
238+ ).strip ()
239+ )
240+
241+
242+ def test_numeric_bounds_export ():
243+ schema = SchemaObject (
244+ name = "Test" ,
245+ properties = [
246+ SchemaProperty (
247+ name = "f" ,
248+ logicalType = "integer" ,
249+ required = True ,
250+ logicalTypeOptions = {"minimum" : 0 , "maximum" : 100 , "exclusiveMinimum" : - 1 , "exclusiveMaximum" : 101.5 },
251+ )
252+ ],
253+ )
254+ ast_class = conv .generate_model_class ("Test" , schema )
255+ assert (
256+ ast .unparse (ast_class )
257+ == dedent (
258+ """
259+ class Test(pydantic.BaseModel):
260+ f: int = pydantic.Field(ge=0, le=100, gt=-1, lt=101.5)
261+ """
262+ ).strip ()
263+ )
264+
265+
266+ def test_date_bounds_export_as_strings ():
267+ schema = SchemaObject (
268+ name = "Test" ,
269+ properties = [
270+ SchemaProperty (name = "f" , logicalType = "date" , required = True , logicalTypeOptions = {"minimum" : "2020-01-01" })
271+ ],
272+ )
273+ ast_class = conv .generate_model_class ("Test" , schema )
274+ assert (
275+ ast .unparse (ast_class )
276+ == dedent (
277+ """
278+ class Test(pydantic.BaseModel):
279+ f: datetime.date = pydantic.Field(ge='2020-01-01')
280+ """
281+ ).strip ()
282+ )
283+
284+
285+ def test_options_outside_the_logical_type_are_ignored ():
286+ """`maxLength` on an integer, a boolean bound, and an empty pattern have no Pydantic counterpart."""
287+ schema = SchemaObject (
288+ name = "Test" ,
289+ properties = [
290+ SchemaProperty (name = "f" , logicalType = "integer" , required = True , logicalTypeOptions = {"maxLength" : 10 }),
291+ SchemaProperty (
292+ name = "g" , logicalType = "string" , required = True , logicalTypeOptions = {"pattern" : "" , "maxLength" : True }
293+ ),
294+ ],
295+ )
296+ ast_class = conv .generate_model_class ("Test" , schema )
297+ assert (
298+ ast .unparse (ast_class )
299+ == dedent (
300+ """
301+ class Test(pydantic.BaseModel):
302+ f: int
303+ g: str
304+ """
305+ ).strip ()
306+ )
307+
308+
309+ def test_enum_field_keeps_its_constraints ():
310+ schema = SchemaObject (
311+ name = "Test" ,
312+ properties = [
313+ SchemaProperty (
314+ name = "f" ,
315+ logicalType = "string" ,
316+ required = True ,
317+ logicalTypeOptions = {"enum" : ["ab" , "cd" ], "maxLength" : 2 },
318+ )
319+ ],
320+ )
321+ ast_class = conv .generate_model_class ("Test" , schema )
322+ assert (
323+ ast .unparse (ast_class )
324+ == dedent (
325+ """
326+ class Test(pydantic.BaseModel):
327+ f: typing.Literal['ab', 'cd'] = pydantic.Field(max_length=2)
328+ """
329+ ).strip ()
330+ )
331+
332+
333+ def test_generated_model_enforces_the_constraints ():
334+ """What the contract constrains, the model rejects: the string tests cannot prove Pydantic accepts the output."""
335+ contract = OpenDataContractStandard (
336+ apiVersion = "v3.1.0" ,
337+ kind = "DataContract" ,
338+ schema = [
339+ SchemaObject (
340+ name = "orders" ,
341+ properties = [
342+ SchemaProperty (
343+ name = "label" , logicalType = "string" , logicalTypeOptions = {"pattern" : "^[^,]+(,\\ s*[^,]+)*$" }
344+ ),
345+ SchemaProperty (
346+ name = "total" , logicalType = "integer" , required = True , logicalTypeOptions = {"minimum" : 0 }
347+ ),
348+ ],
349+ )
350+ ],
351+ )
352+ namespace = {}
353+ exec (conv .to_pydantic_model_str (contract ), namespace )
354+ orders = namespace ["Orders" ]
355+
356+ assert orders (total = 1 , label = "a, b" ).label == "a, b"
357+ assert orders (total = 0 ).label is None
358+ with pytest .raises (pydantic .ValidationError ):
359+ orders (total = 1 , label = "a,,b" )
360+ with pytest .raises (pydantic .ValidationError ):
361+ orders (total = - 1 )
0 commit comments