forked from pydantic/pydantic
-
Notifications
You must be signed in to change notification settings - Fork 0
/
test_docs_extraction.py
337 lines (239 loc) · 8.14 KB
/
test_docs_extraction.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
import textwrap
from typing import Generic, TypeVar
from typing_extensions import Annotated, TypedDict
from pydantic import BaseModel, ConfigDict, Field, TypeAdapter, create_model
from pydantic.dataclasses import dataclass as pydantic_dataclass
T = TypeVar('T')
def dec_noop(obj):
return obj
def test_model_no_docs_extraction():
class MyModel(BaseModel):
a: int = 1
"""A docs"""
b: str = '1'
"""B docs"""
assert MyModel.model_fields['a'].description is None
assert MyModel.model_fields['b'].description is None
def test_model_docs_extraction():
# Using a couple dummy decorators to make sure the frame is pointing at
# the `class` line:
@dec_noop
@dec_noop
class MyModel(BaseModel):
a: int
"""A docs"""
b: int = 1
"""B docs"""
c: int = 1
# This isn't used as a description.
d: int
def dummy_method(self) -> None:
"""Docs for dummy that won't be used for d"""
e: Annotated[int, Field(description='Real description')]
"""Won't be used"""
f: int
"""F docs"""
"""Useless docs"""
g: int
"""G docs"""
model_config = ConfigDict(
use_attribute_docstrings=True,
)
assert MyModel.model_fields['a'].description == 'A docs'
assert MyModel.model_fields['b'].description == 'B docs'
assert MyModel.model_fields['c'].description is None
assert MyModel.model_fields['d'].description is None
assert MyModel.model_fields['e'].description == 'Real description'
assert MyModel.model_fields['g'].description == 'G docs'
def test_model_docs_duplicate_class():
"""Ensure source parsing is working correctly when using frames."""
@dec_noop
class MyModel(BaseModel):
a: int
"""A docs"""
model_config = ConfigDict(
use_attribute_docstrings=True,
)
@dec_noop
class MyModel(BaseModel):
b: int
"""B docs"""
model_config = ConfigDict(
use_attribute_docstrings=True,
)
assert MyModel.model_fields['b'].description == 'B docs'
# With https://github.com/python/cpython/pull/106815/ introduced,
# inspect will fallback to the last found class in the source file.
# The following is to ensure using frames will still get the correct one
if True:
class MyModel(BaseModel):
a: int
"""A docs"""
model_config = ConfigDict(
use_attribute_docstrings=True,
)
else:
class MyModel(BaseModel):
b: int
"""B docs"""
model_config = ConfigDict(
use_attribute_docstrings=True,
)
assert MyModel.model_fields['a'].description == 'A docs'
def test_model_docs_dedented_string():
# fmt: off
class MyModel(BaseModel):
def bar(self):
"""
An inconveniently dedented string
"""
a: int
"""A docs"""
model_config = ConfigDict(
use_attribute_docstrings=True,
)
# fmt: on
assert MyModel.model_fields['a'].description == 'A docs'
def test_model_docs_inheritance():
class MyModel(BaseModel):
a: int
"""A docs"""
b: int
"""B docs"""
model_config = ConfigDict(
use_attribute_docstrings=True,
)
FirstModel = MyModel
class MyModel(FirstModel):
a: int
"""A overridden docs"""
assert FirstModel.model_fields['a'].description == 'A docs'
assert MyModel.model_fields['a'].description == 'A overridden docs'
assert MyModel.model_fields['b'].description == 'B docs'
def test_model_different_name():
# As we extract docstrings from cls in `ModelMetaclass.__new__`,
# we are not affected by `__name__` being altered in any way.
class MyModel(BaseModel):
a: int
"""A docs"""
model_config = ConfigDict(
use_attribute_docstrings=True,
)
MyModel.__name__ = 'OtherModel'
print(MyModel.__name__)
assert MyModel.model_fields['a'].description == 'A docs'
def test_model_generic():
class MyModel(BaseModel, Generic[T]):
a: T
"""A docs"""
model_config = ConfigDict(
use_attribute_docstrings=True,
)
assert MyModel.model_fields['a'].description == 'A docs'
class MyParameterizedModel(MyModel[int]):
a: int
"""A parameterized docs"""
assert MyParameterizedModel.model_fields['a'].description == 'A parameterized docs'
assert MyModel[int].model_fields['a'].description == 'A docs'
def test_dataclass_no_docs_extraction():
@pydantic_dataclass
class MyModel:
a: int = 1
"""A docs"""
b: str = '1'
"""B docs"""
assert MyModel.__pydantic_fields__['a'].description is None
assert MyModel.__pydantic_fields__['b'].description is None
def test_dataclass_docs_extraction():
@pydantic_dataclass(
config=ConfigDict(use_attribute_docstrings=True),
)
@dec_noop
class MyModel:
a: int
"""A docs"""
b: int = 1
"""B docs"""
c: int = 1
# This isn't used as a description.
d: int = 1
def dummy_method(self) -> None:
"""Docs for dummy_method that won't be used for d"""
e: int = Field(1, description='Real description')
"""Won't be used"""
f: int = 1
"""F docs"""
"""Useless docs"""
g: int = 1
"""G docs"""
h = 1
"""H docs"""
i: Annotated[int, Field(description='Real description')] = 1
"""Won't be used"""
assert MyModel.__pydantic_fields__['a'].description == 'A docs'
assert MyModel.__pydantic_fields__['b'].description == 'B docs'
assert MyModel.__pydantic_fields__['c'].description is None
assert MyModel.__pydantic_fields__['d'].description is None
assert MyModel.__pydantic_fields__['e'].description == 'Real description'
assert MyModel.__pydantic_fields__['g'].description == 'G docs'
assert MyModel.__pydantic_fields__['i'].description == 'Real description'
def test_typeddict():
class MyModel(TypedDict):
a: int
"""A docs"""
ta = TypeAdapter(MyModel)
assert ta.json_schema() == {
'properties': {'a': {'title': 'A', 'type': 'integer'}},
'required': ['a'],
'title': 'MyModel',
'type': 'object',
}
class MyModel(TypedDict):
a: int
"""A docs"""
__pydantic_config__ = ConfigDict(use_attribute_docstrings=True)
ta = TypeAdapter(MyModel)
assert ta.json_schema() == {
'properties': {'a': {'title': 'A', 'type': 'integer', 'description': 'A docs'}},
'required': ['a'],
'title': 'MyModel',
'type': 'object',
}
def test_typeddict_as_field():
class ModelTDAsField(TypedDict):
a: int
"""A docs"""
__pydantic_config__ = ConfigDict(use_attribute_docstrings=True)
class MyModel(BaseModel):
td: ModelTDAsField
a_property = MyModel.model_json_schema()['$defs']['ModelTDAsField']['properties']['a']
assert a_property['description'] == 'A docs'
def test_create_model_test():
# Duplicate class creation to ensure create_model
# doesn't fallback to using inspect, which could
# in turn use the wrong class:
class MyModel(BaseModel):
foo: str = '123'
"""Shouldn't be used"""
model_config = ConfigDict(
use_attribute_docstrings=True,
)
assert MyModel.model_fields['foo'].description == "Shouldn't be used"
MyModel = create_model(
'MyModel',
foo=(int, 123),
__config__=ConfigDict(use_attribute_docstrings=True),
)
assert MyModel.model_fields['foo'].description is None
def test_exec_cant_be_parsed():
source = textwrap.dedent(
'''
class MyModel(BaseModel):
a: int
"""A docs"""
model_config = ConfigDict(use_attribute_docstrings=True)
'''
)
locals_dict = {}
exec(source, globals(), locals_dict)
assert locals_dict['MyModel'].model_fields['a'].description is None