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 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415
|
import re
from typing import Annotated, Generic, TypeVar
import pytest
from pydantic import (
BaseModel,
ConfigDict,
Field,
PrivateAttr,
PydanticDeprecatedSince20,
PydanticUserError,
ValidationError,
create_model,
field_validator,
validator,
)
def test_create_model() -> None:
FooModel = create_model(
'FooModel',
foo=(str, ...),
bar=(int, 123),
baz=int,
qux=Annotated[int, Field(title='QUX')],
)
assert issubclass(FooModel, BaseModel)
assert FooModel.model_config == BaseModel.model_config
assert FooModel.__name__ == 'FooModel'
assert FooModel.__qualname__ == 'FooModel'
assert FooModel.model_fields.keys() == {'foo', 'bar', 'baz', 'qux'}
assert FooModel.model_fields['foo'].is_required()
assert not FooModel.model_fields['bar'].is_required()
assert FooModel.model_fields['baz'].is_required()
assert FooModel.model_fields['qux'].title == 'QUX'
assert not FooModel.__pydantic_decorators__.validators
assert not FooModel.__pydantic_decorators__.root_validators
assert not FooModel.__pydantic_decorators__.field_validators
assert not FooModel.__pydantic_decorators__.field_serializers
assert FooModel.__module__ == 'tests.test_create_model'
def test_create_model_invalid_tuple():
with pytest.raises(PydanticUserError) as exc_info:
create_model('FooModel', foo=(tuple[int, int], (1, 2), 'more'))
assert exc_info.value.code == 'create-model-field-definitions'
def test_create_model_usage():
FooModel = create_model('FooModel', foo=(str, ...), bar=(int, 123))
m = FooModel(foo='hello')
assert m.foo == 'hello'
assert m.bar == 123
with pytest.raises(ValidationError):
FooModel()
with pytest.raises(ValidationError):
FooModel(foo='hello', bar='xxx')
def test_create_model_private_attr() -> None:
FooModel = create_model('FooModel', _priv1=int, _priv2=(int, PrivateAttr(default=2)))
assert set(FooModel.__private_attributes__) == {'_priv1', '_priv2'}
m = FooModel()
m._priv1 = 1
assert m._priv1 == 1
assert m._priv2 == 2
def test_create_model_pickle(create_module):
"""
Pickle will work for dynamically created model only if it was defined globally with its class name
and module where it's defined was specified
"""
@create_module
def module():
import pickle
from pydantic import create_model
FooModel = create_model('FooModel', foo=(str, ...), bar=(int, 123), __module__=__name__)
m = FooModel(foo='hello')
d = pickle.dumps(m)
m2 = pickle.loads(d)
assert m2.foo == m.foo == 'hello'
assert m2.bar == m.bar == 123
assert m2 == m
assert m2 is not m
def test_create_model_multi_inheritance():
class Mixin:
pass
Generic_T = Generic[TypeVar('T')]
FooModel = create_model('FooModel', value=(int, ...), __base__=(BaseModel, Generic_T))
assert FooModel.__orig_bases__ == (BaseModel, Generic_T)
def test_create_model_must_not_reset_parent_namespace():
# It's important to use the annotation `'namespace'` as this is a particular string that is present
# in the parent namespace if you reset the parent namespace in the call to `create_model`.
AbcModel = create_model('AbcModel', abc=('namespace', None))
with pytest.raises(
PydanticUserError,
match=re.escape(
'`AbcModel` is not fully defined; you should define `namespace`, then call `AbcModel.model_rebuild()`.'
),
):
AbcModel(abc=1)
# Rebuild the model now that `namespace` is defined
namespace = int # noqa F841
AbcModel.model_rebuild()
assert AbcModel(abc=1).abc == 1
with pytest.raises(ValidationError) as exc_info:
AbcModel(abc='a')
# insert_assert(exc_info.value.errors(include_url=False))
assert exc_info.value.errors(include_url=False) == [
{
'type': 'int_parsing',
'loc': ('abc',),
'msg': 'Input should be a valid integer, unable to parse string as an integer',
'input': 'a',
}
]
def test_config_and_base():
class Base(BaseModel):
a: str
model_config = {'str_to_lower': True}
Model = create_model('Model', __base__=Base, __config__={'str_max_length': 3})
assert Model(a='AAA').a == 'aaa'
with pytest.raises(ValidationError):
Model(a='AAAA')
def test_inheritance():
class BarModel(BaseModel):
x: int = 1
y: int = 2
model = create_model('FooModel', foo=(str, ...), bar=(int, 123), __base__=BarModel)
assert model.model_fields.keys() == {'foo', 'bar', 'x', 'y'}
m = model(foo='a', x=4)
assert m.model_dump() == {'bar': 123, 'foo': 'a', 'x': 4, 'y': 2}
# bases as a tuple
model = create_model('FooModel', foo=(str, ...), bar=(int, 123), __base__=(BarModel,))
assert model.model_fields.keys() == {'foo', 'bar', 'x', 'y'}
m = model(foo='a', x=4)
assert m.model_dump() == {'bar': 123, 'foo': 'a', 'x': 4, 'y': 2}
def test_custom_config():
config = ConfigDict(frozen=True)
expected_config = BaseModel.model_config.copy()
expected_config['frozen'] = True
model = create_model('FooModel', foo=(int, ...), __config__=config)
m = model(**{'foo': '987'})
assert m.foo == 987
assert model.model_config == expected_config
with pytest.raises(ValidationError):
m.foo = 654
def test_custom_config_inherits():
class Config(ConfigDict):
custom_config: bool
config = Config(custom_config=True, validate_assignment=True)
expected_config = Config(BaseModel.model_config)
expected_config.update(config)
model = create_model('FooModel', foo=(int, ...), __config__=config)
m = model(**{'foo': '987'})
assert m.foo == 987
assert model.model_config == expected_config
with pytest.raises(ValidationError):
m.foo = ['123']
def test_custom_config_extras():
config = ConfigDict(extra='forbid')
model = create_model('FooModel', foo=(int, ...), __config__=config)
assert model(foo=654)
with pytest.raises(ValidationError):
model(bar=654)
def test_inheritance_validators():
class BarModel(BaseModel):
@field_validator('a', check_fields=False)
@classmethod
def check_a(cls, v):
if 'foobar' not in v:
raise ValueError('"foobar" not found in a')
return v
model = create_model('FooModel', a=(str, 'cake'), __base__=BarModel)
assert model().a == 'cake'
assert model(a='this is foobar good').a == 'this is foobar good'
with pytest.raises(ValidationError):
model(a='something else')
def test_inheritance_validators_always():
class BarModel(BaseModel):
@field_validator('a', check_fields=False)
@classmethod
def check_a(cls, v):
if 'foobar' not in v:
raise ValueError('"foobar" not found in a')
return v
model = create_model('FooModel', a=(str, Field('cake', validate_default=True)), __base__=BarModel)
with pytest.raises(ValidationError):
model()
assert model(a='this is foobar good').a == 'this is foobar good'
with pytest.raises(ValidationError):
model(a='something else')
def test_inheritance_validators_all():
with pytest.warns(PydanticDeprecatedSince20, match='Pydantic V1 style `@validator` validators are deprecated'):
class BarModel(BaseModel):
@validator('*')
@classmethod
def check_all(cls, v):
return v * 2
model = create_model('FooModel', a=(int, ...), b=(int, ...), __base__=BarModel)
assert model(a=2, b=6).model_dump() == {'a': 4, 'b': 12}
def test_field_invalid_identifier() -> None:
model = create_model('FooModel', **{'invalid-identifier': (int, ...)})
m = model(**{'invalid-identifier': '123'})
assert m.model_dump() == {'invalid-identifier': 123}
with pytest.raises(ValidationError) as exc_info:
model()
assert exc_info.value.errors(include_url=False) == [
{'input': {}, 'loc': ('invalid-identifier',), 'msg': 'Field required', 'type': 'missing'}
]
def test_repeat_base_usage():
class Model(BaseModel):
a: str
assert Model.model_fields.keys() == {'a'}
model = create_model('FooModel', b=(int, 1), __base__=Model)
assert Model.model_fields.keys() == {'a'}
assert model.model_fields.keys() == {'a', 'b'}
model2 = create_model('Foo2Model', c=(int, 1), __base__=Model)
assert Model.model_fields.keys() == {'a'}
assert model.model_fields.keys() == {'a', 'b'}
assert model2.model_fields.keys() == {'a', 'c'}
model3 = create_model('Foo2Model', d=(int, 1), __base__=model)
assert Model.model_fields.keys() == {'a'}
assert model.model_fields.keys() == {'a', 'b'}
assert model2.model_fields.keys() == {'a', 'c'}
assert model3.model_fields.keys() == {'a', 'b', 'd'}
def test_dynamic_and_static():
class A(BaseModel):
x: int
y: float
z: str
DynamicA = create_model('A', x=(int, ...), y=(float, ...), z=(str, ...))
for field_name in ('x', 'y', 'z'):
assert A.model_fields[field_name].default == DynamicA.model_fields[field_name].default
def test_create_model_field_and_model_title():
m = create_model('M', __config__=ConfigDict(title='abc'), a=(str, Field(title='field-title')))
assert m.model_json_schema() == {
'properties': {'a': {'title': 'field-title', 'type': 'string'}},
'required': ['a'],
'title': 'abc',
'type': 'object',
}
def test_create_model_field_description():
m = create_model('M', a=(str, Field(description='descr')), __doc__='Some doc')
assert m.model_json_schema() == {
'properties': {'a': {'description': 'descr', 'title': 'A', 'type': 'string'}},
'required': ['a'],
'title': 'M',
'type': 'object',
'description': 'Some doc',
}
def test_create_model_with_doc():
model = create_model('FooModel', foo=(str, ...), bar=(int, 123), __doc__='The Foo model')
assert model.__name__ == 'FooModel'
assert model.__doc__ == 'The Foo model'
def test_create_model_protected_namespace_default():
with pytest.warns(
UserWarning, match="Field 'model_dump_something' in 'Model' conflicts with protected namespace 'model_dump'"
):
create_model('Model', model_dump_something=(str, ...))
def test_create_model_custom_protected_namespace():
with pytest.warns(UserWarning, match="Field 'test_field' in 'Model' conflicts with protected namespace 'test_'"):
create_model(
'Model',
__config__=ConfigDict(protected_namespaces=('test_',)),
model_prefixed_field=(str, ...),
test_field=(str, ...),
)
def test_create_model_multiple_protected_namespace():
with pytest.warns(
UserWarning, match="Field 'also_protect_field' in 'Model' conflicts with protected namespace 'also_protect_'"
):
create_model(
'Model',
__config__=ConfigDict(protected_namespaces=('protect_me_', 'also_protect_')),
also_protect_field=(str, ...),
)
def test_json_schema_with_inner_models_with_duplicate_names():
model_a = create_model(
'a',
inner=(str, ...),
)
model_b = create_model(
'a',
outer=(model_a, ...),
)
assert model_b.model_json_schema() == {
'$defs': {
'a': {
'properties': {'inner': {'title': 'Inner', 'type': 'string'}},
'required': ['inner'],
'title': 'a',
'type': 'object',
}
},
'properties': {'outer': {'$ref': '#/$defs/a'}},
'required': ['outer'],
'title': 'a',
'type': 'object',
}
def test_resolving_forward_refs_across_modules(create_module):
module = create_module(
# language=Python
"""\
from __future__ import annotations
from dataclasses import dataclass
from pydantic import BaseModel
class X(BaseModel):
pass
@dataclass
class Y:
x: X
"""
)
Z = create_model('Z', y=(module.Y, ...))
assert Z(y={'x': {}}).y is not None
def test_type_field_in_the_same_module():
class A:
pass
B = create_model('B', a_cls=(type, A))
b = B()
assert b.a_cls == A
def test_create_model_qualname() -> None:
FooModel = create_model('FooModel', __qualname__='test_create_model_qualname.FooModel')
assert FooModel.__name__ == 'FooModel'
assert FooModel.__qualname__ == 'test_create_model_qualname.FooModel'
|