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 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477
|
import re
import sys
import textwrap
from collections import Counter, deque
from dataclasses import dataclass
from datetime import date, datetime, time, timedelta
from decimal import Decimal
from ipaddress import IPv4Address, IPv4Interface, IPv4Network, IPv6Address, IPv6Interface, IPv6Network
from pathlib import Path
from types import ModuleType
from typing import Any, Callable, Dict, FrozenSet, List, Literal, Optional, Sequence, Set, Tuple, Type, Union
from uuid import UUID
import pytest
from annotated_types import Ge, Gt, Le, LowerCase, MinLen, UpperCase
from typing_extensions import Annotated, TypeAlias
import pydantic
from pydantic import (
UUID1,
UUID3,
UUID4,
UUID5,
AmqpDsn,
AnyHttpUrl,
AnyUrl,
BaseModel,
ByteSize,
ConfigDict,
DirectoryPath,
EmailStr,
Field,
FilePath,
FutureDate,
HttpUrl,
IPvAnyAddress,
IPvAnyInterface,
IPvAnyNetwork,
Json,
KafkaDsn,
NameEmail,
NegativeFloat,
NegativeInt,
NonNegativeInt,
NonPositiveFloat,
PastDate,
PositiveFloat,
PositiveInt,
PostgresDsn,
RedisDsn,
SecretBytes,
SecretStr,
StrictBool,
StrictBytes,
StrictFloat,
StrictInt,
StrictStr,
ValidationError,
conbytes,
condecimal,
confloat,
confrozenset,
conint,
conlist,
conset,
constr,
validator,
)
from polyfactory.exceptions import ParameterException
from polyfactory.factories import DataclassFactory
from polyfactory.factories.pydantic_factory import _IS_PYDANTIC_V1, ModelFactory
from polyfactory.field_meta import FieldMeta
from tests.models import Person, PetFactory
IS_PYDANTIC_V1 = _IS_PYDANTIC_V1
IS_PYDANTIC_V2 = not _IS_PYDANTIC_V1
REGEX_PATTERN = r"(a|b|c)zz"
@pytest.mark.skipif(IS_PYDANTIC_V2, reason="pydantic v1 only functionality")
def test_const() -> None:
class A(BaseModel):
v: int = Field(1, const=True) # type: ignore[call-overload]
class AFactory(ModelFactory[A]):
__model__ = A
for _ in range(5):
assert AFactory.build()
def test_optional_with_constraints() -> None:
class A(BaseModel):
a: Optional[float] = Field(None, ge=0, le=1)
class AFactory(ModelFactory[A]):
__model__ = A
# Setting random seed so that we get a non-optional value
random_seed = 1
__random_seed__ = random_seed
# verify no pydantic.ValidationError is thrown
assert isinstance(AFactory.build().a, float)
@pytest.mark.skipif(sys.version_info < (3, 10), reason="requires python3.9 or higher")
def test_list_unions() -> None:
# issue: https://github.com/litestar-org/polyfactory/issues/300, no error reproduced
class A(BaseModel):
a: str
class B(BaseModel):
b: str
class C(BaseModel):
c: list[A] | list[B]
class CFactory(ModelFactory[C]):
__forward_ref_resolution_type_mapping__ = {"A": A, "B": B, "C": C}
__model__ = C
assert isinstance(CFactory.build().c, list)
assert len(CFactory.build().c) > 0
assert isinstance(CFactory.build().c[0], (A, B))
@pytest.mark.skipif(IS_PYDANTIC_V1, reason="only for Pydantic v2")
def test_json_type() -> None:
class A(BaseModel):
a: Json[int]
class AFactory(ModelFactory[A]):
__model__ = A
assert isinstance(AFactory.build(), A)
@pytest.mark.skipif(IS_PYDANTIC_V1, reason="only for Pydantic v2")
def test_nested_json_type() -> None:
class A(BaseModel):
a: int
class B(BaseModel):
b: Json[A]
class BFactory(ModelFactory[B]):
__model__ = B
assert isinstance(BFactory.build(), B)
def test_sequence_with_annotated_item_types() -> None:
ConstrainedInt = Annotated[int, Field(ge=100, le=200)]
class Foo(BaseModel):
list_field: List[ConstrainedInt]
tuple_field: Tuple[ConstrainedInt]
variable_tuple_field: Tuple[ConstrainedInt, ...]
set_field: Set[ConstrainedInt]
class FooFactory(ModelFactory[Foo]):
__model__ = Foo
assert FooFactory.build()
def test_mapping_with_annotated_item_types() -> None:
ConstrainedInt = Annotated[int, Field(ge=100, le=200)]
ConstrainedStr = Annotated[str, Field(min_length=1, max_length=3)]
class Foo(BaseModel):
dict_field: Dict[ConstrainedStr, ConstrainedInt]
class FooFactory(ModelFactory[Foo]):
__model__ = Foo
assert FooFactory.build()
def test_use_default_with_callable_default() -> None:
class Foo(BaseModel):
default_field: int = Field(default_factory=lambda: 10)
class FooFactory(ModelFactory[Foo]):
__model__ = Foo
__use_defaults__ = True
foo = FooFactory.build()
assert foo.default_field == 10
@pytest.mark.skipif(IS_PYDANTIC_V1, reason="only for Pydantic v2")
def test_use_default_with_callable_default_with_arg() -> None:
class Foo(BaseModel):
other: int
default_field: int = Field(default_factory=lambda data: data["other"])
class FooFactory(ModelFactory[Foo]):
__model__ = Foo
__use_defaults__ = True
foo = FooFactory.build(other=10)
assert foo.default_field == 10
def test_use_default_with_non_callable_default() -> None:
class Foo(BaseModel):
default_field: int = Field(default=10)
class FooFactory(ModelFactory[Foo]):
__model__ = Foo
__use_defaults__ = True
foo = FooFactory.build()
assert foo.default_field == 10
def test_factory_nested_model_collection_coverage() -> None:
class Nested(BaseModel):
foo: int
class CollectionModel(BaseModel):
collection: List[Nested]
class CollectionModelFactory(ModelFactory[CollectionModel]):
__model__ = CollectionModel
instances = list(CollectionModelFactory.coverage())
assert len(instances) == 1
instance = instances[0]
assert len(instance.collection) == 1
assert isinstance(instance.collection[0], Nested)
def test_factory_nested_model_collection_construct_coverage() -> None:
class Nested(BaseModel):
foo: int
@validator("foo")
@classmethod
def always_invalid(cls, v: int) -> None:
raise ValueError("invalid by validator")
class CollectionModel(BaseModel):
collection: List[Nested]
class CollectionModelFactory(ModelFactory[CollectionModel]):
__model__ = CollectionModel
instances = list(CollectionModelFactory.coverage(factory_use_construct=True))
assert len(instances) == 1
instance = instances[0]
assert len(instance.collection) == 1
assert isinstance(instance.collection[0], Nested)
def test_factory_use_construct() -> None:
# factory should pass values without validation
invalid_age = "non_valid_age"
non_validated_pet = PetFactory.build(factory_use_construct=True, age=invalid_age)
assert non_validated_pet.age == invalid_age # type: ignore[comparison-overlap]
with pytest.raises(ValidationError):
PetFactory.build(age=invalid_age)
def test_factory_use_construct_coverage() -> None:
class Foo(BaseModel):
invalid: int
@validator("invalid")
@classmethod
def always_invalid(cls, v: int) -> None:
raise ValueError("invalid by validator")
class FooFactory(ModelFactory[Foo]):
__model__ = Foo
non_validated = list(FooFactory.coverage(factory_use_construct=True))
assert len(non_validated) == 1
with pytest.raises(ValidationError):
FooFactory.build()
def test_factory_use_construct_nested() -> None:
class Child(BaseModel):
a: int = Field(ge=0)
class Parent(BaseModel):
child: Child
class ParentFactory(ModelFactory[Parent]):
__model__ = Parent
non_validated_parent = ParentFactory.build(factory_use_construct=True, child={"a": -1})
assert non_validated_parent.child.a == -1
with pytest.raises(ValidationError):
ParentFactory.build(child={"a": -1})
def test_factory_use_construct_validator() -> None:
class Foo(BaseModel):
invalid: int
@validator("invalid")
@classmethod
def always_invalid(cls, v: int) -> None:
raise ValueError("invalid by validator")
class FooFactory(ModelFactory[Foo]):
__model__ = Foo
non_validated = FooFactory.build(factory_use_construct=True)
assert isinstance(non_validated.invalid, int)
with pytest.raises(ValidationError):
FooFactory.build()
@pytest.mark.parametrize("sequence_type", (Tuple, List))
def test_factory_use_construct_nested_sequence(sequence_type: Type[Sequence]) -> None:
class Child(BaseModel):
a: int = Field(ge=0)
class Parent(BaseModel):
child: sequence_type[Child] # type: ignore[valid-type]
class ParentFactory(ModelFactory[Parent]):
__model__ = Parent
non_validated_parent = ParentFactory.build(factory_use_construct=True, child=[{"a": -1}])
assert len(non_validated_parent.child) == 1
with pytest.raises(ValidationError):
ParentFactory.build(child=[{"a": -1}])
@pytest.mark.parametrize("set_type", (FrozenSet, Set))
def test_factory_use_construct_nested_set(set_type: Union[Type[FrozenSet], Type[Set]]) -> None:
class Child(BaseModel):
invalid: int = Field()
@validator("invalid", allow_reuse=True)
@classmethod
def always_invalid(cls, v: int) -> None:
raise ValueError("invalid by validator")
def __hash__(self) -> int:
return hash(self.invalid)
class Parent(BaseModel):
child: set_type[Child] # type: ignore[valid-type]
class ParentFactory(ModelFactory[Parent]):
__model__ = Parent
non_validated_parent = ParentFactory.build(factory_use_construct=True)
assert len(non_validated_parent.child) == 1
assert isinstance(non_validated_parent.child, set_type)
with pytest.raises(ValidationError):
ParentFactory.build()
def test_mapping_with_annotated_nested_model() -> None:
class ChildValue(BaseModel):
a: int = Field(ge=0)
class Parent(BaseModel):
dict_field: Dict[str, ChildValue]
class ParentFactory(ModelFactory[Parent]):
__model__ = Parent
non_validated_parent = ParentFactory.build(factory_use_construct=True, dict_field={"arb": {"a": -1}})
assert set(non_validated_parent.dict_field) == {"arb"}
# not converted
assert non_validated_parent.dict_field["arb"] == {"a": -1} # type: ignore[comparison-overlap]
with pytest.raises(ValidationError):
assert ParentFactory.build(dict_field={"arb": {"a": -1}})
@pytest.mark.skipif(
True,
reason=(
"pydantic 1 only test, "
"get_args function not returning the origin type as expected for pydantic v1 constrained values, "
"ex. ConstrainedListValue. "
),
)
def test_factory_use_construct_nested_constraint_list_v1() -> None:
class Child(BaseModel):
a: int = Field(ge=0)
class Parent(BaseModel):
child: conlist(Child, min_items=1, max_items=4) # type: ignore[valid-type]
child_annotated: Annotated[List[Child], Field(min_items=1, max_items=4)]
class ParentFactory(ModelFactory[Parent]):
__model__ = Parent
non_validated_parent = ParentFactory.build(
factory_use_construct=True, child=[{"a": -1}], child_annotated=[{"a": -2}]
)
assert non_validated_parent.child[0].a == -1
assert non_validated_parent.child_annotated[0].a == -2
with pytest.raises(ValidationError):
ParentFactory.build(child=[{"a": -1}])
with pytest.raises(ValidationError):
ParentFactory.build(child_annotated=[{"a": -1}])
@pytest.mark.skipif(IS_PYDANTIC_V1, reason="pydantic 2 only test")
def test_factory_use_construct_nested_constraint_list_v2() -> None:
class Child(BaseModel):
a: int = Field(ge=0)
class Parent(BaseModel):
child: conlist(Child, min_length=1, max_length=4) # type: ignore[valid-type]
child_annotated: Annotated[List[Child], Field(min_length=1, max_length=4)]
class ParentFactory(ModelFactory[Parent]):
__model__ = Parent
non_validated_parent = ParentFactory.build(
factory_use_construct=True, child=[{"a": -1}], child_annotated=[{"a": -2}]
)
assert non_validated_parent.child[0].a == -1
assert non_validated_parent.child_annotated[0].a == -2
with pytest.raises(ValidationError):
ParentFactory.build(child=[{"a": -1}])
with pytest.raises(ValidationError):
ParentFactory.build(child_annotated=[{"a": -1}])
@pytest.mark.skipif(IS_PYDANTIC_V2, reason="pydantic 1 only test")
def test_build_instance_by_field_alias_with_allow_population_by_field_name_flag_pydantic_v1() -> None:
class MyModel(BaseModel):
aliased_field: str = Field(..., alias="special_field")
class Config:
allow_population_by_field_name = True
class MyFactory(ModelFactory):
__model__ = MyModel
instance = MyFactory.build(aliased_field="some")
assert instance.aliased_field == "some"
@pytest.mark.skipif(IS_PYDANTIC_V1, reason="pydantic 2 only test")
def test_build_instance_by_field_alias_with_populate_by_name_flag_pydantic_v2() -> None:
class MyModel(BaseModel):
model_config = {"populate_by_name": True}
aliased_field: str = Field(..., alias="special_field")
class MyFactory(ModelFactory):
__model__ = MyModel
instance = MyFactory.build(aliased_field="some")
assert instance.aliased_field == "some"
def test_build_instance_by_field_name_with_allow_population_by_field_name_flag() -> None:
class MyModel(BaseModel):
aliased_field: str = Field(..., alias="special_field")
class Config:
allow_population_by_field_name = True
class MyFactory(ModelFactory):
__model__ = MyModel
instance = MyFactory.build(special_field="some")
assert instance.aliased_field == "some"
def test_alias_parsing() -> None:
class MyModel(BaseModel):
aliased_field: str = Field(alias="special_field")
class MyFactory(ModelFactory):
__model__ = MyModel
assert isinstance(MyFactory.build().aliased_field, str)
def test_type_property_parsing() -> None:
class Base(BaseModel):
if IS_PYDANTIC_V2:
MongoDsn_pydantic_type: pydantic.networks.MongoDsn
MariaDBDsn_pydantic_type: pydantic.networks.MariaDBDsn
CockroachDsn_pydantic_type: pydantic.networks.CockroachDsn
MySQLDsn_pydantic_type: pydantic.networks.MySQLDsn
PastDatetime_pydantic_type: pydantic.PastDatetime
FutureDatetime_pydantic_type: pydantic.FutureDatetime
AwareDatetime_pydantic_type: pydantic.AwareDatetime
NaiveDatetime_pydantic_type: pydantic.NaiveDatetime
else:
PyObject_pydantic_type: pydantic.types.PyObject
Color_pydantic_type: pydantic.color.Color
class MyModel(Base):
object_field: object
float_field: float
int_field: int
bool_field: bool
str_field: str
bytes_field: bytes
# built-in objects
dict_field: dict
tuple_field: tuple
list_field: list
set_field: set
frozenset_field: frozenset
deque_field: deque
# standard library objects
Path_field: Path
Decimal_field: Decimal
UUID_field: UUID
# datetime
datetime_field: datetime
date_field: date
time_field: time
timedelta_field: timedelta
# ip addresses
IPv4Address_field: IPv4Address
IPv4Interface_field: IPv4Interface
IPv4Network_field: IPv4Network
IPv6Address_field: IPv6Address
IPv6Interface_field: IPv6Interface
IPv6Network_field: IPv6Network
# types
Callable_field: Callable
# pydantic specific
ByteSize_pydantic_type: ByteSize
PositiveInt_pydantic_type: PositiveInt
FilePath_pydantic_type: FilePath
NegativeFloat_pydantic_type: NegativeFloat
NegativeInt_pydantic_type: NegativeInt
PositiveFloat_pydantic_type: PositiveFloat
NonPositiveFloat_pydantic_type: NonPositiveFloat
NonNegativeInt_pydantic_type: NonNegativeInt
StrictInt_pydantic_type: StrictInt
StrictBool_pydantic_type: StrictBool
StrictBytes_pydantic_type: StrictBytes
StrictFloat_pydantic_type: StrictFloat
StrictStr_pydantic_type: StrictStr
DirectoryPath_pydantic_type: DirectoryPath
EmailStr_pydantic_type: EmailStr
NameEmail_pydantic_type: NameEmail
Json_pydantic_type: Json
AnyUrl_pydantic_type: AnyUrl
AnyHttpUrl_pydantic_type: AnyHttpUrl
HttpUrl_pydantic_type: HttpUrl
PostgresDsn_pydantic_type: PostgresDsn
RedisDsn_pydantic_type: RedisDsn
UUID1_pydantic_type: UUID1
UUID3_pydantic_type: UUID3
UUID4_pydantic_type: UUID4
UUID5_pydantic_type: UUID5
SecretBytes_pydantic_type: SecretBytes
SecretStr_pydantic_type: SecretStr
IPvAnyAddress_pydantic_type: IPvAnyAddress
IPvAnyInterface_pydantic_type: IPvAnyInterface
IPvAnyNetwork_pydantic_type: IPvAnyNetwork
AmqpDsn_pydantic_type: AmqpDsn
KafkaDsn_pydantic_type: KafkaDsn
PastDate_pydantic_type: PastDate
FutureDate_pydantic_type: FutureDate
Counter_pydantic_type: Counter
class MyFactory(ModelFactory):
__model__ = MyModel
result = MyFactory.build()
for key in MyFactory.get_provider_map():
key_name = key.__name__ if hasattr(key, "__name__") else key._name
if hasattr(result, f"{key_name}_field"):
assert isinstance(getattr(result, f"{key_name}_field"), key)
elif hasattr(result, f"{key_name}_pydantic_type"):
assert getattr(result, f"{key_name}_pydantic_type") is not None
@pytest.mark.parametrize(
"type_",
[AnyUrl, HttpUrl, KafkaDsn, PostgresDsn, RedisDsn, AmqpDsn, AnyHttpUrl],
)
def test_optional_url_field_parsed_correctly(type_: TypeAlias) -> None:
class MyModel(BaseModel):
url: Optional[type_]
class MyFactory(ModelFactory[MyModel]):
__model__ = MyModel
while not (url := MyFactory.build().url):
assert not url
assert MyModel(url=url) # no validation error raised
@pytest.mark.skipif(IS_PYDANTIC_V2, reason="pydantic 1 only test")
def test_handles_complex_typing_with_custom_root_type() -> None:
class MyModel(BaseModel):
__root__: List[int]
class MyFactory(ModelFactory[MyModel]):
__model__ = MyModel
result = MyFactory.build()
assert result.__root__
assert isinstance(result.__root__, list)
def test_union_types() -> None:
class A(BaseModel):
a: Union[List[str], List[int]]
b: Union[str, List[int]]
c: List[Union[Tuple[int, int], Tuple[str, int]]]
AFactory = ModelFactory.create_factory(A)
assert AFactory.build()
@pytest.mark.skipif(sys.version_info < (3, 10), reason="requires modern union types")
@pytest.mark.skipif(IS_PYDANTIC_V1, reason="pydantic 2 only test")
def test_optional_custom_type() -> None:
from pydantic_core import core_schema
class CustomType:
def __init__(self, _: Any) -> None:
pass
def __get_pydantic_core_schema__(self, _: Any) -> core_schema.StringSchema:
# for pydantic to stop complaining
return core_schema.str_schema()
class OptionalFormOne(BaseModel):
optional_custom_type: Optional[CustomType]
@classmethod
def should_set_none_value(cls, field_meta: FieldMeta) -> bool:
return False
class OptionalFormOneFactory(ModelFactory[OptionalFormOne]):
@classmethod
def should_set_none_value(cls, field_meta: FieldMeta) -> bool:
return False
class OptionalFormTwo(BaseModel):
# this is represented differently than `Optional[None]` internally
optional_custom_type_second_form: CustomType | None
class OptionalFormTwoFactory(ModelFactory[OptionalFormTwo]):
@classmethod
def should_set_none_value(cls, field_meta: FieldMeta) -> bool:
return False
# ensure the custom type field name and variant is in the error message
with pytest.raises(ParameterException, match=r"optional_custom_type"):
OptionalFormOneFactory.build()
with pytest.raises(ParameterException, match=r"optional_custom_type_second_form"):
OptionalFormTwoFactory.build()
def test_collection_unions_with_models() -> None:
class A(BaseModel):
a: int
class B(BaseModel):
a: str
class C(BaseModel):
a: Union[List[A], List[B]]
b: List[Union[A, B]]
CFactory = ModelFactory.create_factory(C)
assert CFactory.build()
def test_constrained_union_types() -> None:
class A(BaseModel):
a: Union[Annotated[List[str], MinLen(100)], Annotated[int, Ge(1000)]]
b: Union[List[Annotated[str, MinLen(100)]], int]
c: Union[Annotated[List[int], MinLen(100)], None]
d: Union[Annotated[List[int], MinLen(100)], Annotated[List[str], MinLen(100)]]
e: Optional[Union[Annotated[List[int], MinLen(10)], Annotated[List[str], MinLen(10)]]]
f: Optional[Union[Annotated[List[int], MinLen(10)], List[str]]]
AFactory = ModelFactory.create_factory(A, __allow_none_optionals__=False)
assert AFactory.build()
@pytest.mark.parametrize("allow_none", (True, False))
def test_optional_type(allow_none: bool) -> None:
class A(BaseModel):
a: Union[str, None]
b: Optional[str]
c: Optional[Union[str, int, List[int]]]
class AFactory(ModelFactory[A]):
__model__ = A
__allow_none_optionals__ = allow_none
assert AFactory.build()
def test_discriminated_unions() -> None:
class BasePet(BaseModel):
name: str
class BlackCat(BasePet):
pet_type: Literal["cat"]
color: Literal["black"]
class WhiteCat(BasePet):
pet_type: Literal["cat"]
color: Literal["white"]
class Dog(BasePet):
pet_type: Literal["dog"]
class Owner(BaseModel):
pet: Annotated[
Union[Annotated[Union[BlackCat, WhiteCat], Field(discriminator="color")], Dog],
Field(discriminator="pet_type"),
]
name: str
class OwnerFactory(ModelFactory):
__model__ = Owner
assert OwnerFactory.build()
def test_predicated_fields() -> None:
@dataclass
class PredicatedMusician:
name: Annotated[str, UpperCase]
band: Annotated[str, LowerCase]
class PredicatedMusicianFactory(DataclassFactory):
__model__ = PredicatedMusician
assert PredicatedMusicianFactory.build()
def test_tuple_with_annotated_constraints() -> None:
class Location(BaseModel):
long_lat: Tuple[Annotated[float, Ge(-180), Le(180)], Annotated[float, Ge(-90), Le(90)]]
class LocationFactory(ModelFactory[Location]):
__model__ = Location
assert LocationFactory.build()
def test_optional_tuple_with_annotated_constraints() -> None:
class Location(BaseModel):
long_lat: Union[Tuple[Annotated[float, Ge(-180), Le(180)], Annotated[float, Ge(-90), Le(90)]], None]
class LocationFactory(ModelFactory[Location]):
__model__ = Location
assert LocationFactory.build()
def test_legacy_tuple_with_annotated_constraints() -> None:
class Location(BaseModel):
long_lat: Tuple[Annotated[float, Ge(-180), Le(180)], Annotated[float, Ge(-90), Le(90)]]
class LocationFactory(ModelFactory[Location]):
__model__ = Location
assert LocationFactory.build()
def test_legacy_optional_tuple_with_annotated_constraints() -> None:
class Location(BaseModel):
long_lat: Union[Tuple[Annotated[float, Ge(-180), Le(180)], Annotated[float, Ge(-90), Le(90)]], None]
class LocationFactory(ModelFactory[Location]):
__model__ = Location
assert LocationFactory.build()
@pytest.mark.skipif(IS_PYDANTIC_V2, reason="pydantic 1 only test")
def test_constrained_attribute_parsing_pydantic_v1() -> None:
class ConstrainedModel(BaseModel):
conbytes_field: conbytes() # type: ignore[valid-type]
condecimal_field: condecimal() # type: ignore[valid-type]
confloat_field: confloat() # type: ignore[valid-type]
conint_field: conint() # type: ignore[valid-type]
conlist_field: conlist(str, min_items=5, max_items=10) # type: ignore[valid-type]
conset_field: conset(str, min_items=5, max_items=10) # type: ignore[valid-type]
confrozenset_field: confrozenset(str, min_items=5, max_items=10) # type: ignore[valid-type]
constr_field: constr(to_lower=True) # type: ignore[valid-type]
str_field1: str = Field(min_length=11)
str_field2: str = Field(max_length=11)
str_field3: str = Field(min_length=8, max_length=11, regex=REGEX_PATTERN) # type: ignore[call-overload]
int_field: int = Field(gt=1, multiple_of=5)
float_field: float = Field(gt=100, lt=1000)
decimal_field: Decimal = Field(ge=100, le=1000)
list_field: List[str] = Field(min_items=1, max_items=10) # type: ignore[call-overload]
constant_field: int = Field(const=True, default=100) # type: ignore[call-overload]
optional_field: Optional[constr(min_length=1)] # type: ignore[valid-type]
class MyFactory(ModelFactory):
__model__ = ConstrainedModel
result = MyFactory.build()
assert isinstance(result.conbytes_field, bytes)
assert isinstance(result.conint_field, int)
assert isinstance(result.confloat_field, float)
assert isinstance(result.condecimal_field, Decimal)
assert isinstance(result.conlist_field, list)
assert isinstance(result.conset_field, set)
assert isinstance(result.confrozenset_field, frozenset)
assert isinstance(result.str_field1, str)
assert isinstance(result.constr_field, str)
assert len(result.conlist_field) >= 5
assert len(result.conlist_field) <= 10
assert len(result.conset_field) >= 5
assert len(result.conset_field) <= 10
assert len(result.confrozenset_field) >= 5
assert len(result.confrozenset_field) <= 10
assert result.constr_field.lower() == result.constr_field
assert len(result.str_field1) >= 11
assert len(result.str_field2) <= 11
assert len(result.str_field3) >= 8
assert len(result.str_field3) <= 11
match = re.search(REGEX_PATTERN, result.str_field3)
assert match
assert match[0]
assert result.int_field >= 1
assert result.int_field % 5 == 0
assert result.float_field > 100
assert result.float_field < 1000
assert result.decimal_field > 100
assert result.decimal_field < 1000
assert len(result.list_field) >= 1
assert len(result.list_field) <= 10
assert all(isinstance(r, str) for r in result.list_field)
assert result.constant_field == 100
assert result.optional_field is None or len(result.optional_field) >= 1
@pytest.mark.skipif(IS_PYDANTIC_V2, reason="pydantic 1 only test")
def test_complex_constrained_attribute_parsing_pydantic_v1() -> None:
class MyModel(BaseModel):
conlist_with_model_field: conlist(Person, min_items=3) # type: ignore[valid-type]
conlist_with_complex_type: conlist( # type: ignore[valid-type]
Dict[str, Tuple[Person, Person, Person]],
min_items=1,
)
class MyFactory(ModelFactory):
__model__ = MyModel
result = MyFactory.build()
assert len(result.conlist_with_model_field) >= 3
assert all(isinstance(v, Person) for v in result.conlist_with_model_field)
assert result.conlist_with_complex_type
assert isinstance(result.conlist_with_complex_type[0], dict)
assert isinstance(next(iter(result.conlist_with_complex_type[0].values())), tuple)
assert len(next(iter(result.conlist_with_complex_type[0].values()))) == 3
assert all(isinstance(v, Person) for v in next(iter(result.conlist_with_complex_type[0].values())))
@pytest.mark.skipif(IS_PYDANTIC_V2, reason="pydantic 1 only test")
def test_nested_constrained_attribute_handling_pydantic_1() -> None:
# subclassing the constrained fields is not documented by pydantic,
# but is supported apparently
from pydantic import ConstrainedBytes, ConstrainedDecimal, ConstrainedFloat, ConstrainedInt, ConstrainedStr
class MyConstrainedString(ConstrainedStr): # type: ignore[misc,valid-type]
regex = re.compile("^vpc-.*$")
class MyConstrainedBytes(ConstrainedBytes): # type: ignore[misc,valid-type]
min_length = 11
class MyConstrainedInt(ConstrainedInt): # type: ignore[misc,valid-type]
ge = 11
class MyConstrainedFloat(ConstrainedFloat): # type: ignore[misc,valid-type]
ge = 11.0
class MyConstrainedDecimal(ConstrainedDecimal): # type: ignore[misc,valid-type]
ge = Decimal("11.0")
class MyModel(BaseModel):
conbytes_list_field: List[conbytes()] # type: ignore[valid-type]
condecimal_list_field: List[condecimal()] # type: ignore[valid-type]
confloat_list_field: List[confloat()] # type: ignore[valid-type]
conint_list_field: List[conint()] # type: ignore[valid-type]
conlist_list_field: List[conlist(str)] # type: ignore[valid-type]
conset_list_field: List[conset(str)] # type: ignore[valid-type]
constr_list_field: List[constr(to_lower=True)] # type: ignore[valid-type]
my_bytes_list_field: List[MyConstrainedBytes]
my_decimal_list_field: List[MyConstrainedDecimal]
my_float_list_field: List[MyConstrainedFloat]
my_int_list_field: List[MyConstrainedInt]
my_str_list_field: List[MyConstrainedString]
my_bytes_dict_field: Dict[str, MyConstrainedBytes]
my_decimal_dict_field: Dict[str, MyConstrainedDecimal]
my_float_dict_field: Dict[str, MyConstrainedFloat]
my_int_dict_field: Dict[str, MyConstrainedInt]
my_str_dict_field: Dict[str, MyConstrainedString]
class MyFactory(ModelFactory):
__model__ = MyModel
result = MyFactory.build()
assert result.conbytes_list_field
assert result.condecimal_list_field
assert result.confloat_list_field
assert result.conint_list_field
assert result.conlist_list_field
assert result.conset_list_field
assert result.constr_list_field
assert result.my_bytes_list_field
assert result.my_decimal_list_field
assert result.my_float_list_field
assert result.my_int_list_field
assert result.my_str_list_field
assert result.my_bytes_dict_field
assert result.my_decimal_dict_field
assert result.my_float_dict_field
assert result.my_int_dict_field
assert result.my_str_dict_field
@pytest.mark.skipif(
IS_PYDANTIC_V1 or sys.version_info < (3, 9),
reason="pydantic 2 only test, does not work correctly in py 3.8",
)
def test_nested_constrained_attribute_handling_pydantic_2() -> None:
# subclassing the constrained fields is not documented by pydantic,
# but is supported apparently
class MyModel(BaseModel):
conbytes_list_field: List[conbytes()] # type: ignore[valid-type]
condecimal_list_field: List[condecimal()] # type: ignore[valid-type]
confloat_list_field: List[confloat()] # type: ignore[valid-type]
conint_list_field: List[conint()] # type: ignore[valid-type]
conlist_list_field: List[conlist(str)] # type: ignore[valid-type]
conset_list_field: List[conset(str)] # type: ignore[valid-type]
constr_list_field: List[constr(to_lower=True)] # type: ignore[valid-type]
class MyFactory(ModelFactory):
__model__ = MyModel
result = MyFactory.build()
assert result.conbytes_list_field
assert result.condecimal_list_field
assert result.confloat_list_field
assert result.conint_list_field
assert result.conlist_list_field
assert result.conset_list_field
assert result.constr_list_field
@pytest.mark.skipif(
IS_PYDANTIC_V1 or sys.version_info < (3, 9),
reason="pydantic 2 only test, does not work correctly in py 3.8",
)
def test_constrained_attribute_parsing_pydantic_v2() -> None:
class ConstrainedModel(BaseModel):
conbytes_field: conbytes() # type: ignore[valid-type]
condecimal_field: condecimal() # type: ignore[valid-type]
confloat_field: confloat() # type: ignore[valid-type]
conint_field: conint() # type: ignore[valid-type]
conlist_field: conlist(str, min_length=5, max_length=10) # type: ignore[valid-type]
conset_field: conset(str, min_length=5, max_length=10) # type: ignore[valid-type]
confrozenset_field: confrozenset(str, min_length=5, max_length=10) # type: ignore[valid-type]
constr_field: constr(to_lower=True) # type: ignore[valid-type]
str_field1: str = Field(min_length=11)
str_field2: str = Field(max_length=11)
str_field3: str = Field(min_length=8, max_length=11, pattern=REGEX_PATTERN)
int_field: int = Field(gt=1, multiple_of=5)
float_field: float = Field(gt=100, lt=1000)
decimal_field: Decimal = Field(ge=100, le=1000)
list_field: List[str] = Field(min_length=1, max_length=10)
optional_field: Optional[constr(min_length=1)] # type: ignore[valid-type]
class MyFactory(ModelFactory):
__model__ = ConstrainedModel
result = MyFactory.build()
assert isinstance(result.conbytes_field, bytes)
assert isinstance(result.conint_field, int)
assert isinstance(result.confloat_field, float)
assert isinstance(result.condecimal_field, Decimal)
assert isinstance(result.conlist_field, list)
assert isinstance(result.conset_field, set)
assert isinstance(result.confrozenset_field, frozenset)
assert isinstance(result.str_field1, str)
assert isinstance(result.constr_field, str)
assert len(result.conlist_field) >= 5
assert len(result.conlist_field) <= 10
assert len(result.conset_field) >= 5
assert len(result.conset_field) <= 10
assert len(result.confrozenset_field) >= 5
assert len(result.confrozenset_field) <= 10
assert result.constr_field.lower() == result.constr_field
assert len(result.str_field1) >= 11
assert len(result.str_field2) <= 11
assert len(result.str_field3) >= 8
assert len(result.str_field3) <= 11
match = re.search(REGEX_PATTERN, result.str_field3)
assert match
assert match[0]
assert result.int_field >= 1
assert result.int_field % 5 == 0
assert result.float_field > 100
assert result.float_field < 1000
assert result.decimal_field > 100
assert result.decimal_field < 1000
assert len(result.list_field) >= 1
assert len(result.list_field) <= 10
assert all(isinstance(r, str) for r in result.list_field)
assert result.optional_field is None or len(result.optional_field) >= 1
@pytest.mark.skipif(IS_PYDANTIC_V1, reason="pydantic 2 only test")
def test_complex_constrained_attribute_parsing_pydantic_v2() -> None:
class MyModel(BaseModel):
conlist_with_model_field: conlist(Person, min_length=3) # type: ignore[valid-type]
conlist_with_complex_type: conlist( # type: ignore[valid-type]
Dict[str, Tuple[Person, Person, Person]],
min_length=1,
)
class MyFactory(ModelFactory):
__model__ = MyModel
result = MyFactory.build()
assert len(result.conlist_with_model_field) >= 3
assert all(isinstance(v, Person) for v in result.conlist_with_model_field)
assert result.conlist_with_complex_type
assert isinstance(result.conlist_with_complex_type[0], dict)
assert isinstance(next(iter(result.conlist_with_complex_type[0].values())), tuple)
assert len(next(iter(result.conlist_with_complex_type[0].values()))) == 3
assert all(isinstance(v, Person) for v in next(iter(result.conlist_with_complex_type[0].values())))
def test_annotated_children() -> None:
class A(BaseModel):
a: Dict[int, Annotated[str, MinLen(min_length=20)]]
b: List[Annotated[int, Gt(gt=1000)]]
c: Annotated[List[Annotated[int, Gt(gt=1000)]], MinLen(min_length=50)]
d: Dict[int, Annotated[List[Annotated[str, MinLen(1)]], MinLen(1)]]
AFactory = ModelFactory.create_factory(A)
assert AFactory.build()
@pytest.mark.skipif(IS_PYDANTIC_V1, reason="pydantic 2 only test")
def test_skip_validation() -> None:
class A(BaseModel):
a: Annotated[int, pydantic.SkipValidation]
AFactory = ModelFactory.create_factory(A)
assert AFactory.build()
@pytest.mark.skipif(_IS_PYDANTIC_V1, reason="Pydantic 1 doesn't support examples")
def test_use_examples_not_defined() -> None:
class Payment(BaseModel):
amount: int = Field(0)
currency: str = Field(examples=["USD", "EUR", "INR"])
class PaymentFactory(ModelFactory[Payment]): ...
instance = PaymentFactory.build()
# it cannot fit the listed items, because faker uses longer strings
assert instance.currency not in ["USD", "EUR", "INR"]
@pytest.mark.skipif(_IS_PYDANTIC_V1, reason="Pydantic 1 doesn't support examples")
def test_use_examples_true() -> None:
class Payment(BaseModel):
amount: int = Field(0)
currency: str = Field(examples=["USD", "EUR", "INR"])
class PaymentFactory(ModelFactory[Payment]):
__use_examples__ = True
instance = PaymentFactory.build()
assert instance.currency in ["USD", "EUR", "INR"]
@pytest.mark.skipif(_IS_PYDANTIC_V1, reason="Pydantic 1 doesn't support examples")
def test_use_examples_false() -> None:
class Payment(BaseModel):
amount: int = Field(0)
currency: str = Field(examples=["USD", "EUR", "INR"])
class PaymentFactory(ModelFactory[Payment]):
__use_examples__ = False
instance = PaymentFactory.build()
assert instance.currency not in ["USD", "EUR", "INR"]
@pytest.mark.skipif(_IS_PYDANTIC_V1, reason="Pydantic 1 doesn't support examples")
def test_use_examples_value_override() -> None:
class Payment(BaseModel):
amount: int = Field(0)
currency: str = Field(examples=["USD", "EUR", "INR"])
class PaymentFactory(ModelFactory[Payment]):
__use_examples__ = True
instance = PaymentFactory.build(currency="DKK")
assert instance.currency == "DKK"
class Base(BaseModel):
nested: "Nested"
class Nested(BaseModel):
value: int
def test_rebuild() -> None:
class BaseFactory(ModelFactory[Base]):
pass
assert isinstance(BaseFactory.build(), Base)
@pytest.mark.skipif(sys.version_info < (3, 12), reason="PEP 695 requires Python 3.12+")
@pytest.mark.skipif(IS_PYDANTIC_V1, reason="only for Pydantic v2")
def test_pep695_basic_type_alias(create_module: Callable[[str], ModuleType]) -> None:
"""Test basic type alias without generics."""
module = create_module(
textwrap.dedent("""
from pydantic import BaseModel
type UserId = int
type Username = str
class Foo(BaseModel):
id: UserId
name: Username
""")
)
ModelFactory.create_factory(module.Foo).build()
@pytest.mark.skipif(sys.version_info < (3, 12), reason="PEP 695 requires Python 3.12+")
@pytest.mark.skipif(IS_PYDANTIC_V1, reason="only for Pydantic v2")
def test_pep695_generic_type_alias(create_module: Callable[[str], ModuleType]) -> None:
"""Test generic type alias with single type parameter."""
module = create_module(
textwrap.dedent("""
from pydantic import BaseModel
type Container[T] = list[T] | tuple[T]
class Foo(BaseModel):
strings: Container[str]
numbers: Container[int]
""")
)
ModelFactory.create_factory(module.Foo).build()
@pytest.mark.skipif(sys.version_info < (3, 12), reason="PEP 695 requires Python 3.12+")
@pytest.mark.skipif(IS_PYDANTIC_V1, reason="only for Pydantic v2")
def test_pep695_nested_generic_type_alias(create_module: Callable[[str], ModuleType]) -> None:
"""Test nested generic type aliases."""
module = create_module(
textwrap.dedent("""
from pydantic import BaseModel
type Inner[T] = list[T]
type Outer[T] = Inner[Inner[T]]
class Foo(BaseModel):
nested: Outer[int]
""")
)
ModelFactory.create_factory(module.Foo).build()
@pytest.mark.skipif(sys.version_info < (3, 12), reason="PEP 695 requires Python 3.12+")
@pytest.mark.skipif(IS_PYDANTIC_V1, reason="only for Pydantic v2")
def test_pep695_annotated_type_alias(create_module: Callable[[str], ModuleType]) -> None:
"""Test type alias with Annotated types."""
module = create_module(
textwrap.dedent("""
from typing import Annotated
from annotated_types import Gt, MaxLen
from pydantic import BaseModel
type PositiveInt = Annotated[int, Gt(0)]
type ShortStr = Annotated[str, MaxLen(5)]
class Foo(BaseModel):
age: PositiveInt
code: ShortStr
""")
)
ModelFactory.create_factory(module.Foo).build()
@pytest.mark.skipif(sys.version_info < (3, 12), reason="PEP 695 requires Python 3.12+")
@pytest.mark.skipif(IS_PYDANTIC_V1, reason="only for Pydantic v2")
def test_pep695_union_of_annotated_types(create_module: Callable[[str], ModuleType]) -> None:
"""Test type alias that is a union of annotated types."""
module = create_module(
textwrap.dedent("""
from typing import Annotated
from annotated_types import Le, Ge
from pydantic import BaseModel
type SmallInt = Annotated[int, Le(10)]
type LargeInt = Annotated[int, Ge(100)]
type ExtremeInt = SmallInt | LargeInt
class Foo(BaseModel):
value: ExtremeInt
""")
)
ModelFactory.create_factory(module.Foo).build()
@pytest.mark.skipif(sys.version_info < (3, 12), reason="PEP 695 requires Python 3.12+")
@pytest.mark.skipif(IS_PYDANTIC_V1, reason="only for Pydantic v2")
def test_pep695_recursive_annotation_field(create_module: Callable[[str], ModuleType]) -> None:
"""Test the original recursive annotation case."""
module = create_module(
textwrap.dedent("""
from typing import Annotated
from annotated_types import Lt
from pydantic import BaseModel
type NegativeInt = Annotated[int, Lt(0)]
type NonEmptyIterable[T] = list[T] | tuple[T]
class Foo(BaseModel):
field: NonEmptyIterable[NonEmptyIterable[NegativeInt]]
""")
)
ModelFactory.create_factory(module.Foo).build()
@pytest.mark.skipif(sys.version_info < (3, 12), reason="PEP 695 requires Python 3.12+")
@pytest.mark.skipif(IS_PYDANTIC_V1, reason="only for Pydantic v2")
def test_pep695_complex_nested_unions(create_module: Callable[[str], ModuleType]) -> None:
"""Test complex nested unions with constraints."""
module = create_module(
textwrap.dedent("""
from typing import Annotated
from annotated_types import MinLen
from pydantic import BaseModel
type NumStr = int | str
type Container[T] = Annotated[list[T], MinLen(1)] | dict[str, T]
class Foo(BaseModel):
data: Container[Container[NumStr]]
""")
)
ModelFactory.create_factory(module.Foo).build()
@pytest.mark.skipif(sys.version_info < (3, 12), reason="PEP 695 requires Python 3.12+")
@pytest.mark.skipif(IS_PYDANTIC_V1, reason="only for Pydantic v2")
def test_pep695_multiple_type_parameters(create_module: Callable[[str], ModuleType]) -> None:
"""Test type alias with multiple type parameters."""
module = create_module(
textwrap.dedent("""
from pydantic import BaseModel
type Pair[T, U] = tuple[T, U] | list[T | U]
class Foo(BaseModel):
int_str_pair: Pair[int, str]
float_bool_pair: Pair[float, bool]
""")
)
ModelFactory.create_factory(module.Foo).build()
@pytest.mark.skipif(sys.version_info < (3, 12), reason="PEP 695 requires Python 3.12+")
@pytest.mark.skipif(IS_PYDANTIC_V1, reason="only for Pydantic v2")
def test_pep695_with_pydantic_field(create_module: Callable[[str], ModuleType]) -> None:
"""Test type alias with Pydantic Field constraints."""
module = create_module(
textwrap.dedent("""
from typing import Annotated
from annotated_types import Ge, Le
from pydantic import BaseModel, Field
type Score = Annotated[int, Ge(0), Le(100)]
class Foo(BaseModel):
test_score: Score = Field(description="Test score between 0 and 100")
final_score: Score = Field(default=75)
""")
)
ModelFactory.create_factory(module.Foo).build()
@pytest.mark.skipif(sys.version_info < (3, 12), reason="PEP 695 requires Python 3.12+")
@pytest.mark.skipif(IS_PYDANTIC_V1, reason="only for Pydantic v2")
def test_pep695_optional_types(create_module: Callable[[str], ModuleType]) -> None:
"""Test type alias with optional types."""
module = create_module(
textwrap.dedent("""
from pydantic import BaseModel
type MaybeInt = int | None
type OptionalContainer[T] = list[T] | None
class Foo(BaseModel):
maybe_number: MaybeInt
maybe_strings: OptionalContainer[str]
""")
)
ModelFactory.create_factory(module.Foo).build()
@pytest.mark.skipif(sys.version_info < (3, 12), reason="PEP 695 requires Python 3.12+")
@pytest.mark.skipif(IS_PYDANTIC_V1, reason="only for Pydantic v2")
def test_pep695_annotated_union_distribution(create_module: Callable[[str], ModuleType]) -> None:
"""Test that Annotated[Union[...], constraint] distributes constraints correctly."""
module = create_module(
textwrap.dedent("""
from typing import Annotated
from annotated_types import MinLen
from pydantic import BaseModel
type ConstrainedUnion = Annotated[list[int] | dict[str, int], MinLen(2)]
class Foo(BaseModel):
data: ConstrainedUnion
""")
)
ModelFactory.create_factory(module.Foo).build()
@pytest.mark.skipif(sys.version_info < (3, 12), reason="PEP 695 requires Python 3.12+")
@pytest.mark.skipif(IS_PYDANTIC_V1, reason="only for Pydantic v2")
def test_pep695_deeply_nested_structure(create_module: Callable[[str], ModuleType]) -> None:
"""Test deeply nested type aliases."""
module = create_module(
textwrap.dedent("""
from pydantic import BaseModel
type Level1[T] = list[T]
type Level2[T] = Level1[Level1[T]]
type Level3[T] = dict[str, Level2[T]] | Level2[T]
class Foo(BaseModel):
deep_data: Level3[int]
""")
)
ModelFactory.create_factory(module.Foo).build()
@pytest.mark.skipif(sys.version_info < (3, 12), reason="PEP 695 requires Python 3.12+")
@pytest.mark.skipif(IS_PYDANTIC_V1, reason="only for Pydantic v2")
def test_pep695_with_decimal_constraints(create_module: Callable[[str], ModuleType]) -> None:
"""Test type alias with decimal constraints."""
module = create_module(
textwrap.dedent("""
from typing import Annotated
from decimal import Decimal
from annotated_types import Ge, MultipleOf
from pydantic import BaseModel
type Price = Annotated[Decimal, Ge(0), MultipleOf(Decimal("0.01"))]
class Foo(BaseModel):
amount: Price
""")
)
ModelFactory.create_factory(module.Foo).build()
@pytest.mark.skipif(sys.version_info < (3, 12), reason="PEP 695 requires Python 3.12+")
@pytest.mark.skipif(IS_PYDANTIC_V1, reason="only for Pydantic v2")
def test_pep695_with_nested_constraints(create_module: Callable[[str], ModuleType]) -> None:
"""Test nested type aliases with various constraint combinations."""
module = create_module(
textwrap.dedent("""
from typing import Annotated
from annotated_types import Gt, MaxLen
from pydantic import BaseModel
type PositiveInt = Annotated[int, Gt(0)]
type SmallList[T] = Annotated[list[T], MaxLen(5)]
type Container[T] = SmallList[T] | tuple[T, ...]
class Foo(BaseModel):
numbers: Container[PositiveInt]
nested: SmallList[Container[int]]
""")
)
ModelFactory.create_factory(module.Foo).build()
@pytest.mark.skipif(sys.version_info < (3, 12), reason="PEP 695 requires Python 3.12+")
@pytest.mark.skipif(IS_PYDANTIC_V1, reason="only for Pydantic v2")
def test_pep695_dict_union_types(create_module: Callable[[str], ModuleType]) -> None:
"""Test type aliases with dict unions."""
module = create_module(
textwrap.dedent("""
from pydantic import BaseModel
type IntDict = dict[str, int]
type StrDict = dict[str, str]
type MixedDict = IntDict | StrDict
class Foo(BaseModel):
data: MixedDict
nested: dict[str, MixedDict]
""")
)
ModelFactory.create_factory(module.Foo).build()
@pytest.mark.skipif(IS_PYDANTIC_V1, reason="pydantic 2 only test")
def test_alias_overrides() -> None:
"""Test that type aliases can be overridden."""
class Foo(BaseModel):
model_config = ConfigDict(alias_generator=lambda x: x.upper())
name: str # type: ignore[pydantic-alias]
class FooFactory(ModelFactory[Foo]):
__check_model__ = True
NAME = "John"
instance = FooFactory.build()
assert instance.name == "John" # Should use the overridden alias
|