/
test_annotated_types.py
239 lines (194 loc) · 6.42 KB
/
test_annotated_types.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
"""
Tests for annotated types that _pydantic_ can validate like
- NamedTuple
- TypedDict
"""
import sys
from collections import namedtuple
from typing import List, NamedTuple
if sys.version_info < (3, 9):
try:
from typing import TypedDict as LegacyTypedDict
except ImportError:
LegacyTypedDict = None
try:
from typing_extensions import TypedDict
except ImportError:
TypedDict = None
else:
from typing import TypedDict
LegacyTypedDict = None
import pytest
from pydantic import BaseModel, ValidationError
def test_namedtuple():
Position = namedtuple('Pos', 'x y')
class Event(NamedTuple):
a: int
b: int
c: int
d: str
class Model(BaseModel):
pos: Position
events: List[Event]
model = Model(pos=('1', 2), events=[[b'1', '2', 3, 'qwe']])
assert isinstance(model.pos, Position)
assert isinstance(model.events[0], Event)
assert model.pos.x == '1'
assert model.pos == Position('1', 2)
assert model.events[0] == Event(1, 2, 3, 'qwe')
assert repr(model) == "Model(pos=Pos(x='1', y=2), events=[Event(a=1, b=2, c=3, d='qwe')])"
assert model.json() == '{"pos": ["1", 2], "events": [[1, 2, 3, "qwe"]]}'
with pytest.raises(ValidationError) as exc_info:
Model(pos=('1', 2), events=[['qwe', '2', 3, 'qwe']])
assert exc_info.value.errors() == [
{
'loc': ('events', 0, 'a'),
'msg': 'value is not a valid integer',
'type': 'type_error.integer',
}
]
assert Model.schema() == {
'title': 'Model',
'type': 'object',
'properties': {
'pos': {'$ref': '#/definitions/Pos'},
'events': {'type': 'array', 'title': 'Events', 'items': {'$ref': '#/definitions/Event'}},
},
'required': ['pos', 'events'],
'definitions': {
'Pos': {
'type': 'object',
'title': 'Pos',
'properties': {'x': {'title': 'X'}, 'y': {'title': 'Y'}},
'required': ['x', 'y'],
},
'Event': {
'type': 'object',
'title': 'Event',
'properties': {
'a': {'title': 'A', 'type': 'integer'},
'b': {'title': 'B', 'type': 'integer'},
'c': {'title': 'C', 'type': 'integer'},
'd': {'title': 'D', 'type': 'string'},
},
'required': ['a', 'b', 'c', 'd'],
},
},
}
@pytest.mark.skipif(not TypedDict, reason='typing_extensions not installed')
def test_typeddict():
class TD(TypedDict):
a: int
b: int
c: int
d: str
class Model(BaseModel):
td: TD
m = Model(td={'a': '3', 'b': b'1', 'c': 4, 'd': 'qwe'})
assert m.td == {'a': 3, 'b': 1, 'c': 4, 'd': 'qwe'}
with pytest.raises(ValidationError) as exc_info:
Model(td={'a': [1], 'b': 2, 'c': 3, 'd': 'qwe'})
assert exc_info.value.errors() == [
{
'loc': ('td', 'a'),
'msg': 'value is not a valid integer',
'type': 'type_error.integer',
}
]
@pytest.mark.skipif(not TypedDict, reason='typing_extensions not installed')
def test_typeddict_non_total():
class FullMovie(TypedDict, total=True):
name: str
year: int
class Model(BaseModel):
movie: FullMovie
with pytest.raises(ValidationError) as exc_info:
Model(movie={'year': '2002'})
assert exc_info.value.errors() == [
{
'loc': ('movie', 'name'),
'msg': 'field required',
'type': 'value_error.missing',
}
]
class PartialMovie(TypedDict, total=False):
name: str
year: int
class Model(BaseModel):
movie: PartialMovie
m = Model(movie={'year': '2002'})
assert m.movie == {'year': 2002}
@pytest.mark.skipif(not TypedDict, reason='typing_extensions not installed')
def test_partial_new_typeddict():
class OptionalUser(TypedDict, total=False):
name: str
class User(OptionalUser):
id: int
class Model(BaseModel):
user: User
m = Model(user={'id': 1})
assert m.user == {'id': 1}
@pytest.mark.skipif(not LegacyTypedDict, reason='python 3.9+ is used or typing_extensions is installed')
def test_partial_legacy_typeddict():
class OptionalUser(LegacyTypedDict, total=False):
name: str
class User(OptionalUser):
id: int
with pytest.warns(
UserWarning,
match='You should use `typing_extensions.TypedDict` instead of `typing.TypedDict` for better support!',
):
class Model(BaseModel):
user: User
with pytest.raises(ValidationError) as exc_info:
Model(user={'id': 1})
assert exc_info.value.errors() == [
{
'loc': ('user', 'name'),
'msg': 'field required',
'type': 'value_error.missing',
}
]
@pytest.mark.skipif(not TypedDict, reason='typing_extensions not installed')
def test_typeddict_extra():
class User(TypedDict):
name: str
age: int
class Model(BaseModel):
u: User
class Config:
extra = 'forbid'
with pytest.raises(ValidationError) as exc_info:
Model(u={'name': 'pika', 'age': 7, 'rank': 1})
assert exc_info.value.errors() == [
{'loc': ('u', 'rank'), 'msg': 'extra fields not permitted', 'type': 'value_error.extra'},
]
@pytest.mark.skipif(not TypedDict, reason='typing_extensions not installed')
def test_typeddict_schema():
class Data(BaseModel):
a: int
class DataTD(TypedDict):
a: int
class Model(BaseModel):
data: Data
data_td: DataTD
assert Model.schema() == {
'title': 'Model',
'type': 'object',
'properties': {'data': {'$ref': '#/definitions/Data'}, 'data_td': {'$ref': '#/definitions/DataTD'}},
'required': ['data', 'data_td'],
'definitions': {
'Data': {
'type': 'object',
'title': 'Data',
'properties': {'a': {'title': 'A', 'type': 'integer'}},
'required': ['a'],
},
'DataTD': {
'type': 'object',
'title': 'DataTD',
'properties': {'a': {'title': 'A', 'type': 'integer'}},
'required': ['a'],
},
},
}