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 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776 1777 1778 1779 1780 1781 1782 1783 1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 1802 1803 1804 1805 1806 1807 1808 1809 1810 1811 1812 1813 1814 1815 1816 1817 1818 1819 1820 1821 1822 1823 1824 1825 1826 1827 1828 1829 1830 1831 1832 1833 1834 1835 1836 1837 1838 1839 1840 1841 1842 1843 1844 1845 1846 1847 1848 1849 1850 1851 1852 1853 1854 1855 1856 1857 1858 1859 1860 1861 1862 1863 1864 1865 1866 1867 1868 1869 1870 1871 1872 1873 1874 1875 1876 1877 1878 1879 1880 1881 1882 1883 1884 1885 1886 1887 1888 1889 1890 1891 1892 1893 1894 1895 1896 1897 1898 1899 1900 1901 1902 1903 1904 1905 1906 1907 1908 1909 1910 1911 1912 1913 1914 1915 1916 1917 1918 1919 1920 1921 1922 1923 1924 1925 1926 1927 1928 1929 1930 1931 1932 1933 1934 1935 1936 1937 1938 1939 1940 1941 1942 1943 1944 1945 1946 1947 1948 1949 1950 1951 1952 1953 1954 1955 1956 1957 1958 1959 1960 1961 1962 1963 1964 1965 1966 1967 1968 1969 1970 1971 1972 1973 1974 1975 1976 1977 1978 1979 1980 1981 1982 1983 1984 1985 1986 1987 1988 1989 1990 1991 1992 1993 1994 1995 1996 1997 1998 1999 2000 2001 2002 2003 2004 2005 2006 2007 2008 2009 2010 2011 2012 2013 2014 2015 2016 2017 2018 2019 2020 2021 2022 2023 2024 2025 2026 2027 2028 2029 2030 2031 2032 2033 2034 2035 2036 2037 2038 2039 2040 2041 2042 2043 2044 2045 2046 2047 2048 2049 2050 2051 2052 2053 2054 2055 2056 2057 2058 2059 2060 2061 2062 2063 2064 2065 2066 2067 2068 2069 2070 2071 2072 2073 2074 2075 2076 2077 2078 2079 2080 2081 2082 2083 2084 2085 2086 2087 2088 2089 2090 2091 2092 2093 2094 2095 2096 2097 2098 2099 2100 2101 2102 2103 2104 2105 2106 2107 2108 2109 2110 2111 2112 2113 2114 2115 2116 2117 2118 2119 2120 2121 2122 2123 2124 2125 2126 2127 2128 2129 2130 2131 2132 2133 2134 2135 2136 2137 2138 2139 2140 2141 2142 2143 2144 2145 2146 2147 2148 2149 2150 2151 2152 2153 2154 2155 2156 2157 2158 2159 2160 2161 2162 2163 2164 2165 2166 2167 2168 2169 2170 2171 2172 2173 2174 2175 2176 2177 2178 2179 2180 2181 2182 2183 2184 2185 2186 2187 2188 2189 2190 2191 2192 2193 2194 2195 2196 2197 2198 2199 2200 2201 2202 2203 2204 2205 2206 2207 2208 2209 2210 2211 2212 2213 2214 2215 2216 2217 2218 2219 2220 2221 2222 2223 2224 2225 2226 2227 2228 2229 2230 2231 2232 2233 2234 2235 2236 2237 2238 2239 2240 2241 2242 2243 2244 2245 2246 2247 2248 2249 2250 2251 2252 2253 2254 2255 2256 2257 2258 2259 2260 2261 2262 2263 2264 2265 2266 2267 2268 2269 2270 2271 2272 2273 2274 2275 2276 2277 2278 2279 2280 2281 2282 2283 2284 2285 2286 2287 2288 2289 2290 2291 2292 2293 2294 2295 2296 2297 2298 2299 2300 2301 2302 2303 2304 2305 2306 2307 2308 2309 2310 2311 2312 2313 2314 2315 2316 2317 2318 2319 2320 2321 2322 2323 2324 2325 2326 2327 2328 2329 2330 2331 2332 2333 2334 2335 2336 2337 2338 2339 2340 2341 2342 2343 2344 2345 2346 2347 2348 2349 2350 2351 2352 2353 2354 2355 2356 2357 2358 2359 2360 2361 2362 2363 2364 2365 2366 2367 2368 2369 2370 2371 2372 2373 2374 2375 2376 2377 2378 2379 2380 2381 2382 2383 2384 2385 2386 2387 2388 2389 2390 2391 2392 2393 2394 2395 2396 2397 2398 2399 2400 2401 2402 2403 2404 2405 2406 2407 2408 2409 2410 2411 2412 2413 2414 2415 2416 2417 2418 2419 2420 2421 2422 2423 2424 2425 2426 2427 2428 2429 2430 2431 2432 2433 2434 2435 2436 2437 2438 2439
|
"""General integration tests for main code generation functionality."""
from __future__ import annotations
import warnings
from argparse import ArgumentTypeError, Namespace
from typing import TYPE_CHECKING
import black
import pytest
from inline_snapshot import snapshot
import datamodel_code_generator
from datamodel_code_generator import (
AllExportsScope,
DataModelType,
Error,
GeneratedModules,
InputFileType,
SchemaParseError,
chdir,
generate,
snooper_to_methods,
)
from datamodel_code_generator.__main__ import Config, Exit
from datamodel_code_generator.arguments import _dataclass_arguments
from datamodel_code_generator.config import GenerateConfig
from datamodel_code_generator.format import CodeFormatter, Formatter, PythonVersion
from datamodel_code_generator.model.pydantic_v2 import UnionMode
from datamodel_code_generator.parser.openapi import OpenAPIParser
from tests.conftest import assert_output, assert_runtime_import_package, create_assert_file_content, freeze_time
from tests.main.conftest import (
DATA_PATH,
DEFAULT_VALUES_DATA_PATH,
EXPECTED_MAIN_PATH,
JSON_SCHEMA_DATA_PATH,
OPEN_API_DATA_PATH,
PYTHON_DATA_PATH,
TIMESTAMP,
run_generate_file_and_assert,
run_main_and_assert,
run_main_with_args,
)
if TYPE_CHECKING:
from pathlib import Path
from pytest_mock import MockerFixture
assert_file_content = create_assert_file_content(EXPECTED_MAIN_PATH)
def test_debug(mocker: MockerFixture) -> None:
"""Test debug flag functionality."""
with pytest.raises(expected_exception=SystemExit):
run_main_with_args(["--debug", "--help"])
# Simulate pysnooper not being installed by making import fail
mocker.patch.dict("sys.modules", {"pysnooper": None})
with pytest.raises(expected_exception=SystemExit):
run_main_with_args(["--debug", "--help"])
def test_snooper_to_methods_without_pysnooper(mocker: MockerFixture) -> None:
"""Test snooper_to_methods function without pysnooper installed."""
# Simulate pysnooper not being installed by making import fail
mocker.patch.dict("sys.modules", {"pysnooper": None})
mock = mocker.Mock()
assert snooper_to_methods()(mock) == mock
@pytest.mark.parametrize(argnames="no_color", argvalues=[False, True])
def test_show_help(no_color: bool, capsys: pytest.CaptureFixture[str]) -> None:
"""Test help output with and without color."""
args = ["--no-color"] if no_color else []
args += ["--help"]
with pytest.raises(expected_exception=SystemExit) as context:
run_main_with_args(args)
assert context.value.code == Exit.OK
output = capsys.readouterr().out
assert ("\x1b" not in output) == no_color
def test_show_help_when_no_input(mocker: MockerFixture) -> None:
"""Test help display when no input is provided."""
print_help_mock = mocker.patch("datamodel_code_generator.__main__.arg_parser.print_help")
isatty_mock = mocker.patch("sys.stdin.isatty", return_value=True)
return_code: Exit = run_main_with_args([], expected_exit=Exit.ERROR)
assert return_code == Exit.ERROR
assert isatty_mock.called
assert print_help_mock.called
def test_no_args_has_default(monkeypatch: pytest.MonkeyPatch) -> None:
"""No argument should have a default value set because it would override pyproject.toml values.
Default values are set in __main__.Config class.
"""
namespace = Namespace()
monkeypatch.setattr("datamodel_code_generator.__main__.namespace", namespace)
run_main_with_args([], expected_exit=Exit.ERROR)
for field in Config.get_fields():
assert getattr(namespace, field, None) is None
def test_space_and_special_characters_dict(output_file: Path) -> None:
"""Test dict input with space and special characters."""
run_main_and_assert(
input_path=PYTHON_DATA_PATH / "space_and_special_characters_dict.py",
output_path=output_file,
input_file_type="dict",
assert_func=assert_file_content,
)
@freeze_time("2024-12-14")
def test_direct_input_dict(tmp_path: Path) -> None:
"""Test direct dict input code generation."""
output_file = tmp_path / "output.py"
generate(
{"foo": 1, "bar": {"baz": 2}},
input_file_type=InputFileType.Dict,
output=output_file,
output_model_type=DataModelType.PydanticV2BaseModel,
snake_case_field=True,
)
assert_file_content(output_file)
@freeze_time(TIMESTAMP)
@pytest.mark.parametrize(
("keyword_only", "target_python_version", "expected_file"),
[
(False, PythonVersion.PY_310, "frozen_dataclasses.py"),
(True, PythonVersion.PY_310, "frozen_dataclasses_keyword_only.py"),
],
)
def test_frozen_dataclasses(
output_file: Path,
keyword_only: bool,
target_python_version: PythonVersion,
expected_file: str,
) -> None:
"""Test --frozen-dataclasses flag functionality."""
run_generate_file_and_assert(
input_path=DATA_PATH / "jsonschema" / "simple_frozen_test.json",
output_path=output_file,
input_file_type=InputFileType.JsonSchema,
assert_func=assert_file_content,
expected_file=expected_file,
output_model_type=DataModelType.DataclassesDataclass,
frozen_dataclasses=True,
keyword_only=keyword_only,
target_python_version=target_python_version,
)
@pytest.mark.cli_doc(
options=["--frozen-dataclasses"],
option_description="""Generate frozen dataclasses with optional keyword-only fields.
The `--frozen-dataclasses` flag generates dataclass instances that are immutable
(frozen=True). Combined with `--keyword-only` (Python 3.10+), all fields become
keyword-only arguments.""",
input_schema="jsonschema/simple_frozen_test.json",
cli_args=["--output-model-type", "dataclasses.dataclass", "--frozen-dataclasses"],
golden_output="frozen_dataclasses.py",
related_options=["--keyword-only", "--output-model-type"],
)
@freeze_time(TIMESTAMP)
@pytest.mark.parametrize(
("extra_args", "expected_file"),
[
(["--output-model-type", "dataclasses.dataclass", "--frozen-dataclasses"], "frozen_dataclasses.py"),
(
[
"--output-model-type",
"dataclasses.dataclass",
"--frozen-dataclasses",
"--keyword-only",
"--target-python-version",
"3.10",
],
"frozen_dataclasses_keyword_only.py",
),
],
)
def test_frozen_dataclasses_command_line(output_file: Path, extra_args: list[str], expected_file: str) -> None:
"""Generate frozen dataclasses with optional keyword-only fields.
The `--frozen-dataclasses` flag generates dataclass instances that are immutable
(frozen=True). Combined with `--keyword-only` (Python 3.10+), all fields become
keyword-only arguments.
"""
run_main_and_assert(
input_path=DATA_PATH / "jsonschema" / "simple_frozen_test.json",
output_path=output_file,
input_file_type="jsonschema",
assert_func=assert_file_content,
expected_file=expected_file,
extra_args=extra_args,
)
@freeze_time(TIMESTAMP)
def test_class_decorators(output_file: Path) -> None:
"""Test --class-decorators flag functionality."""
run_generate_file_and_assert(
input_path=DATA_PATH / "jsonschema" / "simple_frozen_test.json",
output_path=output_file,
input_file_type=InputFileType.JsonSchema,
assert_func=assert_file_content,
expected_file="class_decorators_dataclass.py",
output_model_type=DataModelType.DataclassesDataclass,
class_decorators=["@dataclass_json"],
additional_imports=["dataclasses_json.dataclass_json"],
)
@pytest.mark.cli_doc(
options=["--class-decorators"],
option_description="""Add custom decorators to generated model classes.
The `--class-decorators` option adds custom decorators to all generated model classes.
This is useful for integrating with serialization libraries like `dataclasses_json`.
Use with `--additional-imports` to add the required imports for the decorators.
The `@` prefix is optional and will be added automatically if missing.""",
input_schema="jsonschema/simple_frozen_test.json",
cli_args=[
"--output-model-type",
"dataclasses.dataclass",
"--class-decorators",
"@dataclass_json",
"--additional-imports",
"dataclasses_json.dataclass_json",
],
golden_output="class_decorators_dataclass.py",
related_options=["--additional-imports", "--output-model-type"],
)
@freeze_time(TIMESTAMP)
def test_class_decorators_command_line(output_file: Path) -> None:
"""Add custom decorators to generated model classes.
The `--class-decorators` option adds custom decorators to all generated model classes.
This is useful for integrating with serialization libraries like `dataclasses_json`.
Use with `--additional-imports` to add the required imports for the decorators.
The `@` prefix is optional and will be added automatically if missing.
"""
run_main_and_assert(
input_path=DATA_PATH / "jsonschema" / "simple_frozen_test.json",
output_path=output_file,
input_file_type="jsonschema",
assert_func=assert_file_content,
expected_file="class_decorators_dataclass.py",
extra_args=[
"--output-model-type",
"dataclasses.dataclass",
"--class-decorators",
"@dataclass_json",
"--additional-imports",
"dataclasses_json.dataclass_json",
],
)
@freeze_time(TIMESTAMP)
def test_class_decorators_without_at_prefix(output_file: Path) -> None:
"""Test --class-decorators auto-adds @ prefix when missing."""
run_main_and_assert(
input_path=DATA_PATH / "jsonschema" / "simple_frozen_test.json",
output_path=output_file,
input_file_type="jsonschema",
assert_func=assert_file_content,
expected_file="class_decorators_dataclass.py",
extra_args=[
"--output-model-type",
"dataclasses.dataclass",
"--class-decorators",
"dataclass_json",
"--additional-imports",
"dataclasses_json.dataclass_json",
],
)
@freeze_time(TIMESTAMP)
def test_class_decorators_with_empty_entries(output_file: Path) -> None:
"""Test --class-decorators filters out empty entries from comma-separated list."""
run_main_and_assert(
input_path=DATA_PATH / "jsonschema" / "simple_frozen_test.json",
output_path=output_file,
input_file_type="jsonschema",
assert_func=assert_file_content,
expected_file="class_decorators_dataclass.py",
extra_args=[
"--output-model-type",
"dataclasses.dataclass",
"--class-decorators",
"@dataclass_json, ,",
"--additional-imports",
"dataclasses_json.dataclass_json",
],
)
@freeze_time(TIMESTAMP)
@pytest.mark.parametrize(
("output_model_type", "expected_file"),
[
("pydantic_v2.BaseModel", "class_decorators_pydantic_v2_BaseModel.py"),
("pydantic_v2.dataclass", "class_decorators_pydantic_v2_dataclass.py"),
("dataclasses.dataclass", "class_decorators_dataclasses_dataclass.py"),
("msgspec.Struct", "class_decorators_msgspec_Struct.py"),
# Note: TypedDict is excluded because its template doesn't support decorators
],
ids=[
"pydantic_v2",
"pydantic_v2_dataclass",
"dataclasses",
"msgspec",
],
)
def test_class_decorators_all_output_types(output_file: Path, output_model_type: str, expected_file: str) -> None:
"""Test --class-decorators works with all output model types that support decorators."""
run_main_and_assert(
input_path=DATA_PATH / "jsonschema" / "simple_frozen_test.json",
output_path=output_file,
input_file_type="jsonschema",
assert_func=assert_file_content,
expected_file=expected_file,
extra_args=[
"--output-model-type",
output_model_type,
"--class-decorators",
"@my_decorator",
"--additional-imports",
"my_module.my_decorator",
],
)
@freeze_time(TIMESTAMP)
def test_use_attribute_docstrings(tmp_path: Path) -> None:
"""Test --use-attribute-docstrings flag functionality."""
output_file = tmp_path / "output.py"
generate(
DATA_PATH / "jsonschema" / "use_attribute_docstrings_test.json",
input_file_type=InputFileType.JsonSchema,
output=output_file,
output_model_type=DataModelType.PydanticV2BaseModel,
use_field_description=True,
use_attribute_docstrings=True,
)
assert_file_content(output_file)
@freeze_time(TIMESTAMP)
@pytest.mark.cli_doc(
options=["--use-attribute-docstrings"],
option_description="""Generate field descriptions as attribute docstrings instead of Field descriptions.
The `--use-attribute-docstrings` flag places field descriptions in Python docstring
format (PEP 224 attribute docstrings) rather than in Field(..., description=...).
This provides better IDE support for hovering over attributes. Requires
`--use-field-description` to be enabled.""",
input_schema="jsonschema/use_attribute_docstrings_test.json",
cli_args=[
"--output-model-type",
"pydantic_v2.BaseModel",
"--use-field-description",
"--use-attribute-docstrings",
],
golden_output="use_attribute_docstrings.py",
related_options=["--use-field-description"],
)
def test_use_attribute_docstrings_command_line(output_file: Path) -> None:
"""Generate field descriptions as attribute docstrings instead of Field descriptions.
The `--use-attribute-docstrings` flag places field descriptions in Python docstring
format (PEP 224 attribute docstrings) rather than in Field(..., description=...).
This provides better IDE support for hovering over attributes. Requires
`--use-field-description` to be enabled.
"""
run_main_and_assert(
input_path=DATA_PATH / "jsonschema" / "use_attribute_docstrings_test.json",
output_path=output_file,
input_file_type="jsonschema",
assert_func=assert_file_content,
expected_file="use_attribute_docstrings.py",
extra_args=[
"--output-model-type",
"pydantic_v2.BaseModel",
"--use-field-description",
"--use-attribute-docstrings",
],
)
def test_filename_with_newline_injection(tmp_path: Path) -> None:
"""Test that filenames with newlines cannot inject code into generated files."""
schema_content = """{"type": "object", "properties": {"name": {"type": "string"}}}"""
malicious_filename = """schema.json
# INJECTED CODE:
import os
os.system('echo INJECTED')
# END INJECTION"""
output_path = tmp_path / "output.py"
generate(
input_=schema_content,
input_filename=malicious_filename,
input_file_type=InputFileType.JsonSchema,
output=output_path,
)
generated_content = output_path.read_text()
assert "# filename: schema.json # INJECTED CODE: import os" in generated_content, (
"Filename not properly sanitized"
)
assert not any(
line.strip().startswith("import os") and not line.strip().startswith("#")
for line in generated_content.split("\n")
)
assert not any("os.system" in line and not line.strip().startswith("#") for line in generated_content.split("\n"))
compile(generated_content, str(output_path), "exec")
def test_filename_with_various_control_characters(tmp_path: Path) -> None:
"""Test that various control characters in filenames are properly sanitized."""
schema_content = """{"type": "object", "properties": {"test": {"type": "string"}}}"""
test_cases = [
("newline", "schema.json\nimport os; os.system('echo INJECTED')"),
("carriage_return", "schema.json\rimport os; os.system('echo INJECTED')"),
("crlf", "schema.json\r\nimport os; os.system('echo INJECTED')"),
("tab_newline", "schema.json\t\nimport os; os.system('echo TAB')"),
("form_feed", "schema.json\f\nimport os; os.system('echo FF')"),
("vertical_tab", "schema.json\v\nimport os; os.system('echo VT')"),
("unicode_line_separator", "schema.json\u2028import os; os.system('echo U2028')"),
("unicode_paragraph_separator", "schema.json\u2029import os; os.system('echo U2029')"),
("multiple_newlines", "schema.json\n\n\nimport os; os.system('echo MULTI')"),
("mixed_characters", "schema.json\n\r\t\nimport os; os.system('echo MIXED')"),
]
for test_name, malicious_filename in test_cases:
output_path = tmp_path / "output.py"
generate(
input_=schema_content,
input_filename=malicious_filename,
input_file_type=InputFileType.JsonSchema,
output=output_path,
)
generated_content = output_path.read_text()
assert not any(
line.strip().startswith("import ") and not line.strip().startswith("#")
for line in generated_content.split("\n")
), f"Injection found for {test_name}"
assert not any(
"os.system" in line and not line.strip().startswith("#") for line in generated_content.split("\n")
), f"System call found for {test_name}"
compile(generated_content, str(output_path), "exec")
def test_generate_with_nonexistent_file(tmp_path: Path) -> None:
"""Test that generating from a nonexistent file raises an error."""
nonexistent_file = tmp_path / "nonexistent.json"
output_file = tmp_path / "output.py"
with pytest.raises(Error, match="File not found"):
generate(
input_=nonexistent_file,
output=output_file,
)
def test_generate_with_invalid_file_format(tmp_path: Path) -> None:
"""Test that generating from an invalid file format raises an error."""
invalid_file = tmp_path / "invalid.txt"
invalid_file.write_text("this is not valid json or yaml or anything")
output_file = tmp_path / "output.py"
with pytest.raises(Error, match="Invalid file format"):
generate(
input_=invalid_file,
output=output_file,
)
def test_schema_parse_error_includes_path(tmp_path: Path) -> None:
"""Test that schema parse errors include the schema path context."""
invalid_schema = tmp_path / "invalid_schema.json"
invalid_schema.write_text("""{
"type": "object",
"properties": {
"myField": {
"type": "integer",
"minimum": "not_a_number"
}
}
}""")
output_file = tmp_path / "output.py"
with pytest.raises(SchemaParseError, match="Error at schema path"):
generate(
input_=invalid_schema,
output=output_file,
)
def test_schema_parse_error_includes_nested_path(tmp_path: Path) -> None:
"""Test that schema parse errors include nested schema path context."""
invalid_schema = tmp_path / "invalid_nested_schema.json"
invalid_schema.write_text("""{
"$defs": {
"MyModel": {
"type": "object",
"properties": {
"nestedField": {
"type": "number",
"maximum": "invalid_value"
}
}
}
},
"type": "object",
"properties": {
"ref": {"$ref": "#/$defs/MyModel"}
}
}""")
output_file = tmp_path / "output.py"
with pytest.raises(SchemaParseError, match=r"\$defs/MyModel"):
generate(
input_=invalid_schema,
output=output_file,
)
def test_schema_parse_error_original_error(tmp_path: Path) -> None:
"""Test that SchemaParseError preserves the original error."""
invalid_schema = tmp_path / "invalid_schema.json"
invalid_schema.write_text("""{
"type": "integer",
"minimum": "not_a_number"
}""")
output_file = tmp_path / "output.py"
with pytest.raises(SchemaParseError) as exc_info:
generate(
input_=invalid_schema,
output=output_file,
)
assert exc_info.value.original_error is not None
assert exc_info.value.path is not None
def test_schema_parse_error_without_path() -> None:
"""Test SchemaParseError message formatting without path."""
error = SchemaParseError("Test error message")
assert error.message == "Test error message"
assert error.path == []
assert error.original_error is None
def test_generate_cli_command_with_no_use_specialized_enum(tmp_path: Path, capsys: pytest.CaptureFixture[str]) -> None:
"""Test --generate-cli-command with use-specialized-enum = false."""
pyproject_toml = """
[tool.datamodel-codegen]
input = "schema.yaml"
use-specialized-enum = false
"""
(tmp_path / "pyproject.toml").write_text(pyproject_toml)
with chdir(tmp_path):
run_main_with_args(
["--generate-cli-command"],
capsys=capsys,
expected_stdout_path=EXPECTED_MAIN_PATH / "generate_cli_command" / "no_use_specialized_enum.txt",
)
def test_generate_cli_command_with_false_boolean(tmp_path: Path, capsys: pytest.CaptureFixture[str]) -> None:
"""Test --generate-cli-command with regular boolean set to false (should be skipped)."""
pyproject_toml = """
[tool.datamodel-codegen]
input = "schema.yaml"
snake-case-field = false
"""
(tmp_path / "pyproject.toml").write_text(pyproject_toml)
with chdir(tmp_path):
run_main_with_args(
["--generate-cli-command"],
capsys=capsys,
expected_stdout_path=EXPECTED_MAIN_PATH / "generate_cli_command" / "false_boolean.txt",
)
def test_generate_cli_command_with_true_boolean(tmp_path: Path, capsys: pytest.CaptureFixture[str]) -> None:
"""Test --generate-cli-command with boolean set to true."""
pyproject_toml = """
[tool.datamodel-codegen]
input = "schema.yaml"
snake-case-field = true
"""
(tmp_path / "pyproject.toml").write_text(pyproject_toml)
with chdir(tmp_path):
run_main_with_args(
["--generate-cli-command"],
capsys=capsys,
expected_stdout_path=EXPECTED_MAIN_PATH / "generate_cli_command" / "true_boolean.txt",
)
def test_generate_cli_command_with_list_option(tmp_path: Path, capsys: pytest.CaptureFixture[str]) -> None:
"""Test --generate-cli-command with list option."""
pyproject_toml = """
[tool.datamodel-codegen]
input = "schema.yaml"
strict-types = ["str", "int"]
"""
(tmp_path / "pyproject.toml").write_text(pyproject_toml)
with chdir(tmp_path):
run_main_with_args(
["--generate-cli-command"],
capsys=capsys,
expected_stdout_path=EXPECTED_MAIN_PATH / "generate_cli_command" / "list_option.txt",
)
@pytest.mark.parametrize(
("json_str", "expected"),
[
('{"frozen": true, "slots": true}', {"frozen": True, "slots": True}),
("{}", {}),
],
)
def test_dataclass_arguments_valid(json_str: str, expected: dict) -> None:
"""Test that valid JSON is parsed correctly."""
assert _dataclass_arguments(json_str) == expected
@pytest.mark.parametrize(
("json_str", "match"),
[
("not-valid-json", "Invalid JSON:"),
("[1, 2, 3]", "Expected a JSON dictionary, got list"),
('"just a string"', "Expected a JSON dictionary, got str"),
("42", "Expected a JSON dictionary, got int"),
('{"invalid_key": true}', "Invalid keys:"),
('{"frozen": "not_bool"}', "Expected bool for 'frozen', got str"),
],
)
def test_dataclass_arguments_invalid(json_str: str, match: str) -> None:
"""Test that invalid input raises ArgumentTypeError."""
with pytest.raises(ArgumentTypeError, match=match):
_dataclass_arguments(json_str)
@pytest.mark.cli_doc(
options=["--type-overrides"],
option_description="""Replace schema model types with custom Python types via JSON mapping.
This option is useful for importing models from external libraries (like `geojson-pydantic`)
instead of generating them.
**Override Formats:**
| Format | Description |
|--------|-------------|
| `{"ModelName": "package.Type"}` | Model-level: Skip generating `ModelName` and import from `package` |
| `{"Model.field": "package.Type"}` | Scoped: Override only specific field in specific model |
!!! note "Model-level overrides skip generation"
When you specify a model-level override (without a dot in the key), the generator will
**skip generating that model entirely** and import it from the specified package instead.
**Common Use Cases:**
| Use Case | Example Override |
|----------|------------------|
| GeoJSON types | `{"Feature": "geojson_pydantic.Feature"}` |
| Custom datetime | `{"Timestamp": "pendulum.DateTime"}` |
| MongoDB ObjectId | `{"ObjectId": "bson.ObjectId"}` |
| Custom validators | `{"Email": "my_app.types.ValidatedEmail"}` |
""",
input_schema="jsonschema/type_overrides_test.json",
cli_args=["--type-overrides", '{"CustomType": "my_app.types.CustomType"}'],
golden_output="main/type_overrides_model_level.py",
primary=True,
)
@freeze_time(TIMESTAMP)
def test_type_overrides_model_level(output_file: Path) -> None:
"""Replace schema model types with custom Python types via JSON mapping."""
run_main_and_assert(
input_path=JSON_SCHEMA_DATA_PATH / "type_overrides_test.json",
output_path=output_file,
input_file_type="jsonschema",
assert_func=assert_file_content,
extra_args=[
"--type-overrides",
'{"CustomType": "my_app.types.CustomType"}',
],
)
@pytest.mark.cli_doc(
options=["--type-overrides"],
option_description="""Replace schema model types with custom Python types via JSON mapping.""",
input_schema="jsonschema/type_overrides_external_lib.json",
cli_args=[
"--type-overrides",
'{"Feature": "geojson_pydantic.Feature", "FeatureCollection": "geojson_pydantic.FeatureCollection"}',
],
golden_output="main/type_overrides_external_lib.py",
)
@freeze_time(TIMESTAMP)
def test_type_overrides_external_lib(output_file: Path) -> None:
"""Test --type-overrides with external library types like geojson-pydantic."""
run_main_and_assert(
input_path=JSON_SCHEMA_DATA_PATH / "type_overrides_external_lib.json",
output_path=output_file,
input_file_type="jsonschema",
assert_func=assert_file_content,
extra_args=[
"--type-overrides",
'{"Feature": "geojson_pydantic.Feature", "FeatureCollection": "geojson_pydantic.FeatureCollection"}',
],
)
@freeze_time(TIMESTAMP)
def test_type_overrides_scoped(output_file: Path) -> None:
"""Test --type-overrides with scoped override replaces specific field only."""
run_main_and_assert(
input_path=JSON_SCHEMA_DATA_PATH / "type_overrides_scoped.json",
output_path=output_file,
input_file_type="jsonschema",
assert_func=assert_file_content,
extra_args=[
"--type-overrides",
'{"User.address": "my_app.Address"}',
],
)
@freeze_time(TIMESTAMP)
def test_type_overrides_nested_types(output_file: Path) -> None:
"""Test --type-overrides with nested types like List[CustomType]."""
run_main_and_assert(
input_path=JSON_SCHEMA_DATA_PATH / "type_overrides_nested.json",
output_path=output_file,
input_file_type="jsonschema",
assert_func=assert_file_content,
extra_args=[
"--type-overrides",
'{"Tag": "my_app.Tag"}',
],
)
def test_skip_root_model(tmp_path: Path) -> None:
"""Test --skip-root-model flag functionality using generate()."""
output_file = tmp_path / "output.py"
generate(
DATA_PATH / "jsonschema" / "skip_root_model_test.json",
input_file_type=InputFileType.JsonSchema,
output=output_file,
output_model_type=DataModelType.PydanticV2BaseModel,
skip_root_model=True,
)
assert_file_content(output_file, "skip_root_model.py")
@pytest.mark.cli_doc(
options=["--skip-root-model"],
option_description="""Skip generation of root model when schema contains nested definitions.
The `--skip-root-model` flag prevents generating a model for the root schema object
when the schema primarily contains reusable definitions. This is useful when the root
object is just a container for $defs and not a meaningful model itself.""",
input_schema="jsonschema/skip_root_model_test.json",
cli_args=["--output-model-type", "pydantic_v2.BaseModel", "--skip-root-model"],
golden_output="skip_root_model.py",
)
def test_skip_root_model_command_line(output_file: Path) -> None:
"""Skip generation of root model when schema contains nested definitions.
The `--skip-root-model` flag prevents generating a model for the root schema object
when the schema primarily contains reusable definitions. This is useful when the root
object is just a container for $defs and not a meaningful model itself.
"""
run_main_and_assert(
input_path=DATA_PATH / "jsonschema" / "skip_root_model_test.json",
output_path=output_file,
input_file_type="jsonschema",
assert_func=assert_file_content,
expected_file="skip_root_model.py",
extra_args=["--output-model-type", "pydantic_v2.BaseModel", "--skip-root-model"],
)
@pytest.mark.cli_doc(
options=["--check"],
option_description="""Verify generated code matches existing output without modifying files.
The `--check` flag compares the generated output with existing files and exits with
a non-zero status if they differ. Useful for CI/CD validation to ensure schemas
and generated code stay in sync. Works with both single files and directory outputs.""",
input_schema="jsonschema/person.json",
cli_args=["--disable-timestamp", "--check"],
golden_output="person.py",
)
def test_check_file_matches(output_file: Path) -> None:
"""Verify generated code matches existing output without modifying files.
The `--check` flag compares the generated output with existing files and exits with
a non-zero status if they differ. Useful for CI/CD validation to ensure schemas
and generated code stay in sync. Works with both single files and directory outputs.
"""
input_path = DATA_PATH / "jsonschema" / "person.json"
run_main_and_assert(
input_path=input_path,
output_path=output_file,
input_file_type="jsonschema",
extra_args=["--disable-timestamp"],
)
run_main_and_assert(
input_path=input_path,
output_path=output_file,
input_file_type="jsonschema",
extra_args=["--disable-timestamp", "--check"],
expected_exit=Exit.OK,
)
def test_check_file_does_not_exist(tmp_path: Path) -> None:
"""Test --check returns DIFF when file does not exist."""
run_main_and_assert(
input_path=DATA_PATH / "jsonschema" / "person.json",
output_path=tmp_path / "nonexistent.py",
input_file_type="jsonschema",
extra_args=["--disable-timestamp", "--check"],
expected_exit=Exit.DIFF,
)
def test_check_file_differs(output_file: Path) -> None:
"""Test --check returns DIFF when file content differs."""
output_file.write_text("# Different content\n", encoding="utf-8")
run_main_and_assert(
input_path=DATA_PATH / "jsonschema" / "person.json",
output_path=output_file,
input_file_type="jsonschema",
extra_args=["--disable-timestamp", "--check"],
expected_exit=Exit.DIFF,
)
def test_check_with_stdout_output(capsys: pytest.CaptureFixture[str]) -> None:
"""Test --check with stdout output returns error."""
run_main_and_assert(
input_path=DATA_PATH / "jsonschema" / "person.json",
output_path=None,
input_file_type="jsonschema",
extra_args=["--check"],
expected_exit=Exit.ERROR,
capsys=capsys,
expected_stderr_contains="--check cannot be used with stdout",
)
def test_check_with_nonexistent_input(tmp_path: Path) -> None:
"""Test --check with nonexistent input file returns error."""
run_main_and_assert(
input_path=tmp_path / "nonexistent.json",
output_path=tmp_path / "output.py",
input_file_type="jsonschema",
extra_args=["--check"],
expected_exit=Exit.ERROR,
)
def test_check_normalizes_line_endings(output_file: Path) -> None:
"""Test --check normalizes line endings (CRLF vs LF)."""
input_path = DATA_PATH / "jsonschema" / "person.json"
run_main_and_assert(
input_path=input_path,
output_path=output_file,
input_file_type="jsonschema",
extra_args=["--disable-timestamp"],
)
content = output_file.read_text(encoding="utf-8")
output_file.write_bytes(content.replace("\n", "\r\n").encode("utf-8"))
run_main_and_assert(
input_path=input_path,
output_path=output_file,
input_file_type="jsonschema",
extra_args=["--disable-timestamp", "--check"],
expected_exit=Exit.OK,
)
def test_check_directory_matches(output_dir: Path) -> None:
"""Test --check returns OK when directory matches."""
input_path = OPEN_API_DATA_PATH / "modular.yaml"
run_main_and_assert(
input_path=input_path,
output_path=output_dir,
input_file_type="openapi",
extra_args=["--disable-timestamp"],
)
run_main_and_assert(
input_path=input_path,
output_path=output_dir,
input_file_type="openapi",
extra_args=["--disable-timestamp", "--check"],
expected_exit=Exit.OK,
)
def test_check_directory_file_differs(output_dir: Path) -> None:
"""Test --check returns DIFF when a file in directory differs."""
input_path = OPEN_API_DATA_PATH / "modular.yaml"
run_main_and_assert(
input_path=input_path,
output_path=output_dir,
input_file_type="openapi",
extra_args=["--disable-timestamp"],
)
py_files = list(output_dir.rglob("*.py"))
py_files[0].write_text("# Modified content\n", encoding="utf-8")
run_main_and_assert(
input_path=input_path,
output_path=output_dir,
input_file_type="openapi",
extra_args=["--disable-timestamp", "--check"],
expected_exit=Exit.DIFF,
)
def test_check_directory_missing_file(output_dir: Path) -> None:
"""Test --check returns DIFF when a generated file is missing."""
input_path = OPEN_API_DATA_PATH / "modular.yaml"
run_main_and_assert(
input_path=input_path,
output_path=output_dir,
input_file_type="openapi",
extra_args=["--disable-timestamp"],
)
py_files = list(output_dir.rglob("*.py"))
py_files[0].unlink()
run_main_and_assert(
input_path=input_path,
output_path=output_dir,
input_file_type="openapi",
extra_args=["--disable-timestamp", "--check"],
expected_exit=Exit.DIFF,
)
def test_check_directory_extra_file(output_dir: Path) -> None:
"""Test --check returns DIFF when an extra file exists."""
input_path = OPEN_API_DATA_PATH / "modular.yaml"
run_main_and_assert(
input_path=input_path,
output_path=output_dir,
input_file_type="openapi",
extra_args=["--disable-timestamp"],
)
(output_dir / "extra_model.py").write_text("# Extra file\n", encoding="utf-8")
run_main_and_assert(
input_path=input_path,
output_path=output_dir,
input_file_type="openapi",
extra_args=["--disable-timestamp", "--check"],
expected_exit=Exit.DIFF,
)
def test_check_directory_does_not_exist(tmp_path: Path) -> None:
"""Test --check returns DIFF when output directory does not exist."""
run_main_and_assert(
input_path=OPEN_API_DATA_PATH / "modular.yaml",
output_path=tmp_path / "nonexistent_model",
input_file_type="openapi",
extra_args=["--disable-timestamp", "--check"],
expected_exit=Exit.DIFF,
)
def test_check_directory_ignores_pycache(output_dir: Path) -> None:
"""Test --check ignores __pycache__ directories in actual output."""
input_path = OPEN_API_DATA_PATH / "modular.yaml"
run_main_and_assert(
input_path=input_path,
output_path=output_dir,
input_file_type="openapi",
extra_args=["--disable-timestamp"],
)
pycache_dir = output_dir / "__pycache__"
pycache_dir.mkdir()
(pycache_dir / "module.cpython-313.pyc").write_bytes(b"fake bytecode")
(pycache_dir / "extra.py").write_text("# should be ignored\n", encoding="utf-8")
run_main_and_assert(
input_path=input_path,
output_path=output_dir,
input_file_type="openapi",
extra_args=["--disable-timestamp", "--check"],
expected_exit=Exit.OK,
)
def test_check_with_invalid_class_name(tmp_path: Path) -> None:
"""Test --check cleans up temp directory when InvalidClassNameError occurs."""
invalid_schema = tmp_path / "invalid.json"
invalid_schema.write_text('{"title": "123InvalidName", "type": "object"}', encoding="utf-8")
output_path = tmp_path / "output.py"
run_main_and_assert(
input_path=invalid_schema,
output_path=output_path,
input_file_type="jsonschema",
extra_args=["--check"],
expected_exit=Exit.ERROR,
expected_stderr_contains="You have to set `--class-name` option",
)
def test_check_with_invalid_file_format(tmp_path: Path) -> None:
"""Test --check cleans up temp directory when Error occurs (invalid file format)."""
invalid_file = tmp_path / "invalid.txt"
invalid_file.write_text("This is not a valid schema format!!!", encoding="utf-8")
output_path = tmp_path / "output.py"
run_main_and_assert(
input_path=invalid_file,
output_path=output_path,
extra_args=["--check"],
expected_exit=Exit.ERROR,
expected_stderr_contains="Invalid file format",
)
@pytest.mark.cli_doc(
options=["--all-exports-scope"],
option_description="""Generate __all__ exports for child modules in __init__.py files.
The `--all-exports-scope=children` flag adds __all__ to each __init__.py containing
exports from direct child modules. This improves IDE autocomplete and explicit exports.
Use 'recursive' to include all descendant exports with collision handling.""",
input_schema="openapi/modular.yaml",
cli_args=["--all-exports-scope", "children"],
golden_output="openapi/modular_all_exports_children",
related_options=["--all-exports-collision-strategy"],
)
def test_all_exports_scope_children(output_dir: Path) -> None:
"""Generate __all__ exports for child modules in __init__.py files.
The `--all-exports-scope=children` flag adds __all__ to each __init__.py containing
exports from direct child modules. This improves IDE autocomplete and explicit exports.
Use 'recursive' to include all descendant exports with collision handling.
"""
run_main_and_assert(
input_path=OPEN_API_DATA_PATH / "modular.yaml",
output_path=output_dir,
input_file_type="openapi",
extra_args=["--disable-timestamp", "--all-exports-scope", "children"],
expected_directory=EXPECTED_MAIN_PATH / "openapi" / "modular_all_exports_children",
)
@pytest.mark.cli_doc(
options=["--all-exports-collision-strategy"],
option_description="""Handle name collisions when exporting recursive module hierarchies.
The `--all-exports-collision-strategy` flag determines how to resolve naming conflicts
when using `--all-exports-scope=recursive`. The 'minimal-prefix' strategy adds the
minimum module path prefix needed to disambiguate colliding names, while 'full-prefix'
uses the complete module path. Requires `--all-exports-scope=recursive`.""",
input_schema="openapi/modular.yaml",
cli_args=["--all-exports-scope", "recursive", "--all-exports-collision-strategy", "minimal-prefix"],
golden_output="openapi/modular_all_exports_recursive",
related_options=["--all-exports-scope"],
)
def test_all_exports_scope_recursive_with_collision(output_dir: Path) -> None:
"""Handle name collisions when exporting recursive module hierarchies.
The `--all-exports-collision-strategy` flag determines how to resolve naming conflicts
when using `--all-exports-scope=recursive`. The 'minimal-prefix' strategy adds the
minimum module path prefix needed to disambiguate colliding names, while 'full-prefix'
uses the complete module path. Requires `--all-exports-scope=recursive`.
"""
run_main_and_assert(
input_path=OPEN_API_DATA_PATH / "modular.yaml",
output_path=output_dir,
input_file_type="openapi",
extra_args=[
"--disable-timestamp",
"--all-exports-scope",
"recursive",
"--all-exports-collision-strategy",
"minimal-prefix",
],
expected_directory=EXPECTED_MAIN_PATH / "openapi" / "modular_all_exports_recursive",
)
def test_all_exports_scope_children_with_docstring_header(output_dir: Path) -> None:
"""Test --all-exports-scope=children with --custom-file-header containing docstring."""
run_main_and_assert(
input_path=OPEN_API_DATA_PATH / "modular.yaml",
output_path=output_dir,
input_file_type="openapi",
extra_args=[
"--all-exports-scope",
"children",
"--custom-file-header-path",
str(DATA_PATH / "custom_file_header_docstring.txt"),
],
expected_directory=EXPECTED_MAIN_PATH / "openapi" / "modular_all_exports_children_docstring",
)
def test_all_exports_scope_recursive_collision_avoided_by_renaming(output_dir: Path) -> None:
"""Test --all-exports-scope=recursive avoids collision through automatic class renaming.
With circular import resolution, conflicting class names (e.g., foo.Tea and nested.foo.Tea)
are automatically renamed (e.g., Tea and Tea_1) in _internal.py, so no collision error occurs.
"""
run_main_and_assert(
input_path=OPEN_API_DATA_PATH / "modular.yaml",
output_path=output_dir,
input_file_type="openapi",
extra_args=["--disable-timestamp", "--all-exports-scope", "recursive"],
)
# Verify both Tea and Tea_1 exist in _internal.py (collision avoided through renaming)
internal_content = (output_dir / "_internal.py").read_text()
assert "class Tea(BaseModel):" in internal_content, "Tea class should exist in _internal.py"
assert "class Tea_1(BaseModel):" in internal_content, "Tea_1 class should exist in _internal.py"
def test_all_exports_collision_strategy_requires_recursive(output_dir: Path) -> None:
"""Test --all-exports-collision-strategy requires --all-exports-scope=recursive."""
run_main_and_assert(
input_path=OPEN_API_DATA_PATH / "modular.yaml",
output_path=output_dir,
input_file_type="openapi",
extra_args=[
"--all-exports-scope",
"children",
"--all-exports-collision-strategy",
"minimal-prefix",
],
expected_exit=Exit.ERROR,
expected_stderr_contains="--all-exports-collision-strategy",
)
def test_all_exports_scope_recursive_with_full_prefix(output_dir: Path) -> None:
"""Test --all-exports-scope=recursive with --all-exports-collision-strategy=full-prefix."""
run_main_and_assert(
input_path=OPEN_API_DATA_PATH / "modular.yaml",
output_path=output_dir,
input_file_type="openapi",
extra_args=[
"--disable-timestamp",
"--all-exports-scope",
"recursive",
"--all-exports-collision-strategy",
"full-prefix",
],
expected_directory=EXPECTED_MAIN_PATH / "openapi" / "modular_all_exports_recursive_full_prefix",
)
def test_all_exports_collision_resolved_successfully(output_dir: Path) -> None:
"""Test collision resolution successfully adds prefix when no local model conflict."""
run_main_and_assert(
input_path=OPEN_API_DATA_PATH / "all_exports_collision_success.yaml",
output_path=output_dir,
input_file_type="openapi",
extra_args=[
"--disable-timestamp",
"--all-exports-scope",
"recursive",
"--all-exports-collision-strategy",
"minimal-prefix",
],
expected_directory=EXPECTED_MAIN_PATH / "openapi" / "all_exports_collision_success",
)
@pytest.mark.parametrize(
"strategy",
["minimal-prefix", "full-prefix"],
ids=["minimal_prefix", "full_prefix"],
)
def test_all_exports_recursive_prefix_collision_with_local_model(output_dir: Path, strategy: str) -> None:
"""Test that prefix resolution raises error when renamed export collides with local model."""
run_main_and_assert(
input_path=OPEN_API_DATA_PATH / "all_exports_prefix_collision.yaml",
output_path=output_dir,
input_file_type="openapi",
extra_args=[
"--all-exports-scope",
"recursive",
"--all-exports-collision-strategy",
strategy,
],
expected_exit=Exit.ERROR,
expected_stderr_contains="InputMessage",
)
def test_all_exports_scope_recursive_jsonschema_multi_file(output_dir: Path) -> None:
"""Test --all-exports-scope=recursive with JSONSchema multi-file input."""
run_main_and_assert(
input_path=JSON_SCHEMA_DATA_PATH / "all_exports_multi_file",
output_path=output_dir,
input_file_type="jsonschema",
extra_args=[
"--disable-timestamp",
"--all-exports-scope",
"recursive",
],
expected_directory=EXPECTED_MAIN_PATH / "jsonschema" / "all_exports_multi_file",
)
def test_all_exports_recursive_local_model_collision_error(output_dir: Path) -> None:
"""Test --all-exports-scope=recursive raises error when child export collides with local model."""
run_main_and_assert(
input_path=OPEN_API_DATA_PATH / "all_exports_local_collision.yaml",
output_path=output_dir,
input_file_type="openapi",
extra_args=[
"--all-exports-scope",
"recursive",
],
expected_exit=Exit.ERROR,
expected_stderr_contains="conflicts with a model in __init__.py",
)
def test_all_exports_scope_children_no_child_exports(output_dir: Path) -> None:
"""Test --all-exports-scope=children when __init__.py has models but no direct child exports."""
run_main_and_assert(
input_path=OPEN_API_DATA_PATH / "all_exports_no_child.yaml",
output_path=output_dir,
input_file_type="openapi",
extra_args=[
"--disable-timestamp",
"--all-exports-scope",
"children",
],
expected_directory=EXPECTED_MAIN_PATH / "openapi" / "all_exports_no_child",
)
def test_all_exports_scope_children_with_local_models(output_dir: Path) -> None:
"""Test --all-exports-scope=children when __init__.py has both local models and child exports."""
run_main_and_assert(
input_path=OPEN_API_DATA_PATH / "all_exports_with_local_models.yaml",
output_path=output_dir,
input_file_type="openapi",
extra_args=[
"--disable-timestamp",
"--all-exports-scope",
"children",
],
expected_directory=EXPECTED_MAIN_PATH / "openapi" / "all_exports_with_local_models",
)
def test_all_exports_scope_children_jsonschema_hyphenated_package(output_dir: Path) -> None:
"""Test --all-exports-scope=children with hyphenated JSON Schema directories."""
run_main_and_assert(
input_path=JSON_SCHEMA_DATA_PATH / "all_exports_hyphenated_directory",
output_path=output_dir,
input_file_type="jsonschema",
extra_args=[
"--disable-timestamp",
"--all-exports-scope",
"children",
],
expected_directory=EXPECTED_MAIN_PATH / "jsonschema" / "all_exports_hyphenated_directory",
)
def test_check_respects_pyproject_toml_settings(tmp_path: Path) -> None:
"""Test --check uses pyproject.toml formatter settings from output path.
This test verifies that both generation and --check mode use the same
pyproject.toml settings from the output directory. Without the fix,
generation would use cwd's settings while --check would use output path's
settings, causing a diff even with identical input.
"""
pyproject_toml = tmp_path / "pyproject.toml"
pyproject_toml.write_text("[tool.black]\nline-length = 60\n", encoding="utf-8")
input_json = tmp_path / "input.json"
input_json.write_text(
"""{
"$schema": "http://json-schema.org/draft-07/schema#",
"title": "Person",
"type": "object",
"properties": {
"firstName": {
"type": "string",
"minLength": 1,
"maxLength": 100,
"pattern": "^[A-Za-z]+$"
}
},
"required": ["firstName"]
}""",
encoding="utf-8",
)
output_file = tmp_path / "output.py"
expected_output = """\
# generated by datamodel-codegen:
# filename: input.json
from __future__ import annotations
from typing import Annotated
from pydantic import BaseModel, Field
class Person(BaseModel):
firstName: Annotated[
str,
Field(
max_length=100,
min_length=1,
pattern='^[A-Za-z]+$',
),
]
"""
run_main_and_assert(
input_path=input_json,
output_path=output_file,
input_file_type="jsonschema",
extra_args=["--disable-timestamp", "--use-annotated"],
expected_output=expected_output,
)
run_main_and_assert(
input_path=input_json,
output_path=output_file,
input_file_type="jsonschema",
extra_args=["--disable-timestamp", "--use-annotated", "--check"],
expected_exit=Exit.OK,
)
def test_use_specialized_enum_requires_python_311(
tmp_path: Path,
capsys: pytest.CaptureFixture[str],
) -> None:
"""Test --use-specialized-enum requires --target-python-version 3.11+."""
input_json = tmp_path / "input.json"
input_json.write_text(
'{"type": "string", "enum": ["A", "B"]}',
encoding="utf-8",
)
run_main_and_assert(
input_path=input_json,
output_path=tmp_path / "output.py",
input_file_type="jsonschema",
extra_args=["--use-specialized-enum"],
expected_exit=Exit.ERROR,
capsys=capsys,
expected_stderr_contains="--use-specialized-enum requires --target-python-version 3.11 or later",
)
@pytest.mark.skipif(
black.__version__.split(".")[0] == "22",
reason="Installed black doesn't support StrEnum formatting",
)
def test_use_specialized_enum_with_python_311_ok(output_file: Path) -> None:
"""Test --use-specialized-enum works with --target-python-version 3.11."""
run_main_and_assert(
input_path=JSON_SCHEMA_DATA_PATH / "string_enum.json",
output_path=output_file,
input_file_type="jsonschema",
extra_args=["--use-specialized-enum", "--target-python-version", "3.11"],
assert_func=assert_file_content,
expected_file="use_specialized_enum_py311.py",
)
def test_use_specialized_enum_pyproject_requires_python_311(
tmp_path: Path,
capsys: pytest.CaptureFixture[str],
) -> None:
"""Test use_specialized_enum in pyproject.toml requires target_python_version 3.11+."""
pyproject_toml = tmp_path / "pyproject.toml"
pyproject_toml.write_text(
"[tool.datamodel-codegen]\nuse_specialized_enum = true\n",
encoding="utf-8",
)
input_json = tmp_path / "input.json"
input_json.write_text(
'{"type": "string", "enum": ["A", "B"]}',
encoding="utf-8",
)
with chdir(tmp_path):
run_main_and_assert(
input_path=input_json,
output_path=tmp_path / "output.py",
input_file_type="jsonschema",
expected_exit=Exit.ERROR,
capsys=capsys,
expected_stderr_contains="--use-specialized-enum requires --target-python-version 3.11 or later",
)
def test_use_specialized_enum_pyproject_override_with_cli(output_file: Path, tmp_path: Path) -> None:
"""Test --no-use-specialized-enum CLI can override pyproject.toml use_specialized_enum=true."""
pyproject_toml = tmp_path / "pyproject.toml"
pyproject_toml.write_text(
"[tool.datamodel-codegen]\nuse_specialized_enum = true\n",
encoding="utf-8",
)
with chdir(tmp_path):
run_main_and_assert(
input_path=JSON_SCHEMA_DATA_PATH / "string_enum.json",
output_path=output_file,
input_file_type="jsonschema",
extra_args=["--no-use-specialized-enum"],
assert_func=assert_file_content,
expected_file="no_use_specialized_enum.py",
)
@pytest.mark.cli_doc(
options=["--module-split-mode"],
option_description="""Split generated models into separate files, one per model class.
The `--module-split-mode=single` flag generates each model class in its own file,
named after the class in snake_case. Use with `--all-exports-scope=recursive` to
create an __init__.py that re-exports all models for convenient imports.""",
input_schema="jsonschema/module_split_single/input.json",
cli_args=["--module-split-mode", "single", "--all-exports-scope", "recursive", "--use-exact-imports"],
golden_output="jsonschema/module_split_single",
related_options=["--all-exports-scope", "--use-exact-imports"],
)
def test_module_split_mode_single(output_dir: Path) -> None:
"""Split generated models into separate files, one per model class.
The `--module-split-mode=single` flag generates each model class in its own file,
named after the class in snake_case. Use with `--all-exports-scope=recursive` to
create an __init__.py that re-exports all models for convenient imports.
"""
run_main_and_assert(
input_path=JSON_SCHEMA_DATA_PATH / "module_split_single" / "input.json",
output_path=output_dir,
input_file_type="jsonschema",
extra_args=[
"--disable-timestamp",
"--module-split-mode",
"single",
"--all-exports-scope",
"recursive",
"--use-exact-imports",
],
expected_directory=EXPECTED_MAIN_PATH / "jsonschema" / "module_split_single",
)
@pytest.mark.cli_doc(
options=["--use-standard-primitive-types"],
option_description="""Use Python standard library types for string formats instead of str.
The `--use-standard-primitive-types` flag configures the code generation to use
Python standard library types (UUID, IPv4Address, IPv6Address, Path) for corresponding
string formats instead of plain str. This affects dataclass, msgspec, and TypedDict
output types. Pydantic already uses these types by default.""",
input_schema="jsonschema/use_standard_primitive_types.json",
cli_args=[
"--output-model-type",
"dataclasses.dataclass",
"--use-standard-primitive-types",
],
golden_output="use_standard_primitive_types.py",
related_options=["--output-model-type", "--output-datetime-class"],
)
@freeze_time(TIMESTAMP)
def test_use_standard_primitive_types(output_file: Path) -> None:
"""Use Python standard library types for string formats instead of str.
The `--use-standard-primitive-types` flag configures the code generation to use
Python standard library types (UUID, IPv4Address, IPv6Address, Path) for corresponding
string formats instead of plain str. This affects dataclass, msgspec, and TypedDict
output types. Pydantic already uses these types by default.
"""
run_main_and_assert(
input_path=JSON_SCHEMA_DATA_PATH / "use_standard_primitive_types.json",
output_path=output_file,
input_file_type="jsonschema",
extra_args=[
"--output-model-type",
"dataclasses.dataclass",
"--use-standard-primitive-types",
],
expected_file=EXPECTED_MAIN_PATH / "use_standard_primitive_types.py",
)
def test_format_code_fallback_on_error(tmp_path: Path, mocker: MockerFixture) -> None:
"""Test that code generation continues with unformatted output when formatting fails."""
schema = tmp_path / "schema.json"
schema.write_text('{"type": "object", "properties": {"name": {"type": "string"}}}', encoding="utf-8")
output = tmp_path / "output.py"
def mock_format_code(_self: CodeFormatter, _code: str) -> str:
msg = "mock error"
raise black.InvalidInput(msg)
mocker.patch.object(CodeFormatter, "format_code", mock_format_code)
with pytest.warns(UserWarning, match="Failed to format code.*Emitting unformatted output"):
generate(
input_=schema,
input_file_type=InputFileType.JsonSchema,
output=output,
)
content = output.read_text()
assert "class Model" in content
assert "name:" in content
def test_format_code_fallback_on_error_init_exports(tmp_path: Path, mocker: MockerFixture) -> None:
"""Test that __init__.py generation continues with unformatted output when formatting fails."""
output_dir = tmp_path / "output"
def mock_format_code(_self: CodeFormatter, _code: str) -> str:
msg = "mock error"
raise black.InvalidInput(msg)
mocker.patch.object(CodeFormatter, "format_code", mock_format_code)
with pytest.warns(UserWarning, match="Failed to format code.*Emitting unformatted output"):
generate(
input_=OPEN_API_DATA_PATH / "modular.yaml",
input_file_type=InputFileType.OpenAPI,
output=output_dir,
all_exports_scope=AllExportsScope.Children,
)
init_content = (output_dir / "__init__.py").read_text()
assert "__all__" in init_content or "from ." in init_content
def test_init_exports_without_formatting(tmp_path: Path) -> None:
"""Test that __init__.py exports work correctly when formatting is disabled."""
output_dir = tmp_path / "output"
output_dir.mkdir()
parser = OpenAPIParser(source=OPEN_API_DATA_PATH / "modular.yaml")
results = parser.parse(
format_=False,
all_exports_scope=AllExportsScope.Children,
)
assert isinstance(results, dict)
init_key = ("__init__.py",)
assert init_key in results
init_content = results[init_key].body
assert "__all__" in init_content or "from ." in init_content
def test_generate_parent_scoped_naming_backward_compat(tmp_path: Path) -> None:
"""Test generate() with parent_scoped_naming=True triggers ModelResolver backward compat."""
output_file = tmp_path / "output.py"
generate(
input_=JSON_SCHEMA_DATA_PATH / "naming_strategy" / "input.json",
input_file_type=InputFileType.JsonSchema,
output=output_file,
output_model_type=DataModelType.PydanticV2BaseModel,
parent_scoped_naming=True,
)
content = output_file.read_text()
assert "class ModelOrderItem" in content
assert "class ModelCartItem" in content
def test_ruff_check_and_format_combined(output_file: Path) -> None:
"""Test ruff check and format run together in a pipeline for single file."""
run_main_and_assert(
input_path=JSON_SCHEMA_DATA_PATH / "simple_string.json",
output_path=output_file,
extra_args=["--formatters", "ruff-check", "ruff-format", "--disable-timestamp"],
expected_output="""\
# generated by datamodel-codegen:
# filename: simple_string.json
from __future__ import annotations
from pydantic import BaseModel
class Model(BaseModel):
s: str
""",
)
def test_ruff_check_only(output_file: Path) -> None:
"""Test ruff check formatter alone for single file."""
run_main_and_assert(
input_path=JSON_SCHEMA_DATA_PATH / "simple_string.json",
output_path=output_file,
extra_args=["--formatters", "ruff-check", "--disable-timestamp"],
expected_output="""\
# generated by datamodel-codegen:
# filename: simple_string.json
from __future__ import annotations
from pydantic import BaseModel
class Model(BaseModel):
s: str
""",
)
def test_ruff_format_only(output_file: Path) -> None:
"""Test ruff format formatter alone for single file."""
run_main_and_assert(
input_path=JSON_SCHEMA_DATA_PATH / "simple_string.json",
output_path=output_file,
extra_args=["--formatters", "ruff-format", "--disable-timestamp"],
expected_output="""\
# generated by datamodel-codegen:
# filename: simple_string.json
from __future__ import annotations
from pydantic import BaseModel
class Model(BaseModel):
s: str
""",
)
def test_ruff_batch_formatting_directory(output_dir: Path) -> None:
"""Test ruff batch formatting for directory output (multiple files)."""
run_main_and_assert(
input_path=JSON_SCHEMA_DATA_PATH / "all_exports_multi_file",
output_path=output_dir,
extra_args=["--formatters", "ruff-check", "ruff-format", "--disable-timestamp"],
skip_code_validation=True,
)
order_file = output_dir / "order.py"
assert order_file.exists()
content = order_file.read_text()
assert "from __future__ import annotations" in content
assert "class Order" in content
def test_type_checking_imports_default_to_runtime_imports_for_modular_pydantic_ruff(output_dir: Path) -> None:
"""Test modular Pydantic output keeps runtime imports by default when Ruff formats a directory."""
run_main_and_assert(
input_path=OPEN_API_DATA_PATH / "modular.yaml",
output_path=output_dir,
input_file_type="openapi",
extra_args=[
"--output-model-type",
"pydantic_v2.BaseModel",
"--formatters",
"ruff-check",
"ruff-format",
"--disable-timestamp",
],
)
assert_runtime_import_package(output_dir, EXPECTED_MAIN_PATH / "openapi" / "no_use_type_checking_imports")
@pytest.mark.cli_doc(
options=["--no-use-type-checking-imports"],
option_description="""Keep generated model imports available at runtime when using Ruff fixes.
The `--no-use-type-checking-imports` flag prevents Ruff from moving generated model imports
into `TYPE_CHECKING` blocks. This is useful for modular Pydantic output where referenced
models need to be importable at runtime without calling `model_rebuild()` manually.
In the multi-module Pydantic + `ruff-check` case, runtime imports are preserved by default.
`--use-type-checking-imports` opts back into the old TYPE_CHECKING-only behavior, which can
require manual `model_rebuild()` calls for cross-module runtime references.""",
input_schema="openapi/modular.yaml",
cli_args=[
"--output-model-type",
"pydantic_v2.BaseModel",
"--formatters",
"ruff-check",
"ruff-format",
"--no-use-type-checking-imports",
"--disable-timestamp",
],
golden_output="openapi/no_use_type_checking_imports_internal.py",
related_options=["--use-type-checking-imports", "--formatters", "--use-exact-imports"],
)
def test_no_use_type_checking_imports(output_dir: Path) -> None:
"""Keep generated model imports available at runtime when using Ruff fixes.
The `--no-use-type-checking-imports` flag prevents Ruff from moving generated model imports
into `TYPE_CHECKING` blocks. This is useful for modular Pydantic output where referenced
models need to be importable at runtime without calling `model_rebuild()` manually.
In the multi-module Pydantic + `ruff-check` case, runtime imports are preserved by default.
`--use-type-checking-imports` opts back into the old TYPE_CHECKING-only behavior, which can
require manual `model_rebuild()` calls for cross-module runtime references.
"""
run_main_and_assert(
input_path=OPEN_API_DATA_PATH / "modular.yaml",
output_path=output_dir,
input_file_type="openapi",
extra_args=[
"--output-model-type",
"pydantic_v2.BaseModel",
"--formatters",
"ruff-check",
"ruff-format",
"--no-use-type-checking-imports",
"--disable-timestamp",
],
)
assert_runtime_import_package(output_dir, EXPECTED_MAIN_PATH / "openapi" / "no_use_type_checking_imports")
def test_generate_multi_module_pydantic_ruff_defaults_to_runtime_imports() -> None:
"""Test generate() keeps runtime imports for multi-module Pydantic Ruff output."""
result = generate(
OPEN_API_DATA_PATH / "modular.yaml",
input_file_type=InputFileType.OpenAPI,
output=None,
output_model_type=DataModelType.PydanticV2BaseModel,
formatters=[Formatter.RUFF_CHECK, Formatter.RUFF_FORMAT],
disable_timestamp=True,
)
assert isinstance(result, dict)
internal = result["_internal.py",]
assert "TYPE_CHECKING" not in internal
assert "from . import models" in internal
assert "Tea_1.model_rebuild()" in internal
@pytest.mark.cli_doc(
options=["--use-type-checking-imports"],
option_description="""Allow Ruff to move typing-only imports into TYPE_CHECKING blocks.
The `--use-type-checking-imports` flag explicitly re-enables Ruff's TYPE_CHECKING import moves
for multi-module Pydantic output where runtime imports might otherwise be preserved by default.""",
input_schema="openapi/modular.yaml",
cli_args=[
"--output-model-type",
"pydantic_v2.BaseModel",
"--formatters",
"ruff-check",
"ruff-format",
"--use-type-checking-imports",
"--disable-timestamp",
],
golden_output="openapi/use_type_checking_imports_internal.py",
related_options=["--no-use-type-checking-imports", "--formatters", "--use-exact-imports"],
)
def test_use_type_checking_imports_for_multi_module_pydantic_ruff() -> None:
"""Allow Ruff to move typing-only imports into TYPE_CHECKING blocks.
The `--use-type-checking-imports` flag explicitly re-enables Ruff's TYPE_CHECKING import moves
for multi-module Pydantic output where runtime imports might otherwise be preserved by default.
"""
result = generate(
OPEN_API_DATA_PATH / "modular.yaml",
input_file_type=InputFileType.OpenAPI,
output=None,
output_model_type=DataModelType.PydanticV2BaseModel,
formatters=[Formatter.RUFF_CHECK, Formatter.RUFF_FORMAT],
use_type_checking_imports=True,
disable_timestamp=True,
)
assert isinstance(result, dict)
internal = result["_internal.py",]
assert "TYPE_CHECKING" in internal
assert internal == (EXPECTED_MAIN_PATH / "openapi" / "use_type_checking_imports_internal.py").read_text().rstrip()
def test_generate_returns_string_when_output_none() -> None:
"""Test that generate() returns str when output=None for single file."""
json_schema = '{"type": "object", "properties": {"name": {"type": "string"}}}'
result = generate(
json_schema,
input_file_type=InputFileType.JsonSchema,
input_filename="test.json",
disable_timestamp=True,
)
assert result == snapshot(
"""\
# generated by datamodel-codegen:
# filename: test.json
from __future__ import annotations
from pydantic import BaseModel
class Model(BaseModel):
name: str | None = None\
"""
)
def test_generate_returns_string_with_pydantic_v2() -> None:
"""Test that generate() returns str for Pydantic v2 models."""
json_schema = '{"type": "object", "properties": {"value": {"type": "number"}}}'
result = generate(
json_schema,
input_file_type=InputFileType.JsonSchema,
input_filename="schema.json",
output_model_type=DataModelType.PydanticV2BaseModel,
disable_timestamp=True,
)
assert result == snapshot(
"""\
# generated by datamodel-codegen:
# filename: schema.json
from __future__ import annotations
from pydantic import BaseModel
class Model(BaseModel):
value: float | None = None"""
)
def test_generate_returns_string_with_dataclass() -> None:
"""Test that generate() returns str for dataclass models."""
json_schema = '{"type": "object", "properties": {"value": {"type": "string"}}}'
result = generate(
json_schema,
input_file_type=InputFileType.JsonSchema,
input_filename="data.json",
output_model_type=DataModelType.DataclassesDataclass,
disable_timestamp=True,
)
assert result == snapshot(
"""\
# generated by datamodel-codegen:
# filename: data.json
from __future__ import annotations
from dataclasses import dataclass
@dataclass
class Model:
value: str | None = None"""
)
def test_generate_returns_none_when_output_path_provided(tmp_path: Path) -> None:
"""Test that generate() returns None when output path is provided."""
json_schema = '{"type": "object", "properties": {"name": {"type": "string"}}}'
output = tmp_path / "model.py"
result = generate(
json_schema,
input_file_type=InputFileType.JsonSchema,
output=output,
disable_timestamp=True,
)
assert result is None
assert output.exists()
def test_generate_file_content_matches_return_value(tmp_path: Path) -> None:
"""Test that file content matches what would be returned with output=None."""
json_schema = '{"type": "object", "properties": {"id": {"type": "integer"}}}'
return_result = generate(
json_schema,
input_file_type=InputFileType.JsonSchema,
input_filename="test.json",
disable_timestamp=True,
)
output = tmp_path / "model.py"
generate(
json_schema,
input_file_type=InputFileType.JsonSchema,
input_filename="test.json",
output=output,
disable_timestamp=True,
)
file_content = output.read_text()
assert isinstance(return_result, str)
assert return_result.strip() == file_content.strip()
def test_generate_returns_dict_for_multiple_modules(tmp_path: Path) -> None:
"""Test that generate() returns GeneratedModules dict for multiple modules."""
main_schema = tmp_path / "main.json"
main_schema.write_text(
"""{
"$schema": "http://json-schema.org/draft-07/schema#",
"definitions": {
"User": {
"type": "object",
"properties": {
"id": {"type": "integer"},
"address": {"$ref": "address.json#/definitions/Address"}
}
}
}
}"""
)
address_schema = tmp_path / "address.json"
address_schema.write_text(
"""{
"$schema": "http://json-schema.org/draft-07/schema#",
"definitions": {
"Address": {
"type": "object",
"properties": {
"street": {"type": "string"},
"city": {"type": "string"}
}
}
}
}"""
)
result = generate(
tmp_path,
input_file_type=InputFileType.JsonSchema,
disable_timestamp=True,
)
assert result == snapshot({
("__init__.py",): """\
# generated by datamodel-codegen:
# filename: test_generate_returns_dict_for0\
""",
("address.py",): """\
# generated by datamodel-codegen:
# filename: address.json
from __future__ import annotations
from typing import Any
from pydantic import BaseModel, RootModel
class Model(RootModel[Any]):
root: Any
class Address(BaseModel):
street: str | None = None
city: str | None = None\
""",
("main.py",): """\
# generated by datamodel-codegen:
# filename: main.json
from __future__ import annotations
from typing import Any
from pydantic import BaseModel, RootModel
from . import address as address_1
class Model(RootModel[Any]):
root: Any
class User(BaseModel):
id: int | None = None
address: address_1.Address | None = None\
""",
})
def test_generated_modules_type_alias_is_exported() -> None:
"""Test that GeneratedModules is exported from the module."""
assert GeneratedModules is not None
def test_generate_returns_string_with_custom_file_header() -> None:
"""Test generate() with custom_file_header when output=None."""
json_schema = '{"type": "object", "properties": {"name": {"type": "string"}}}'
custom_header = "# Custom header\n# More comments"
result = generate(
json_schema,
input_file_type=InputFileType.JsonSchema,
custom_file_header=custom_header,
)
assert result == snapshot(
"""\
# Custom header
# More comments
from __future__ import annotations
from pydantic import BaseModel
class Model(BaseModel):
name: str | None = None"""
)
def test_generate_returns_string_with_custom_file_header_and_code() -> None:
"""Test generate() with custom_file_header containing code after docstring."""
json_schema = '{"type": "object", "properties": {"id": {"type": "integer"}}}'
custom_header = '"""Module docstring."""\n\nimport sys'
result = generate(
json_schema,
input_file_type=InputFileType.JsonSchema,
custom_file_header=custom_header,
)
assert result == snapshot(
'''\
"""Module docstring."""
from __future__ import annotations
import sys
from pydantic import BaseModel
class Model(BaseModel):
id: int | None = None\
'''
)
def test_generate_returns_string_with_custom_file_header_no_future() -> None:
"""Test generate() with custom_file_header when body has no future imports."""
json_schema = '{"type": "object", "properties": {"id": {"type": "integer"}}}'
custom_header = "# Custom header for legacy code"
result = generate(
json_schema,
input_file_type=InputFileType.JsonSchema,
custom_file_header=custom_header,
disable_future_imports=True,
)
assert result == snapshot("""\
# Custom header for legacy code
from pydantic import BaseModel
class Model(BaseModel):
id: int | None = None\
""")
def test_generate_with_dict_jsonschema() -> None:
"""Test generate() with dict input as JsonSchema."""
from tests.data.dict_input import jsonschema_dict
result = generate(
jsonschema_dict,
input_file_type=InputFileType.JsonSchema,
disable_timestamp=True,
)
assert_output(result, EXPECTED_MAIN_PATH / "dict_input" / "jsonschema.py")
def test_generate_with_dict_openapi() -> None:
"""Test generate() with dict input as OpenAPI."""
from tests.data.dict_input import openapi_dict
result = generate(
openapi_dict,
input_file_type=InputFileType.OpenAPI,
disable_timestamp=True,
)
assert_output(result, EXPECTED_MAIN_PATH / "dict_input" / "openapi.py")
def test_generate_with_dict_auto_raises_error() -> None:
"""Test generate() with dict input + Auto raises error."""
from tests.data.dict_input import auto_error_dict
with pytest.raises(Error, match="input_file_type=Auto is not supported for dict input"):
generate(auto_error_dict, input_file_type=InputFileType.Auto)
def test_generate_with_dict_graphql_raises_error() -> None:
"""Test generate() with dict input + GraphQL raises error."""
from tests.data.dict_input import graphql_error_dict
with pytest.raises(Error, match="Dict input is not supported for GraphQL"):
generate(graphql_error_dict, input_file_type=InputFileType.GraphQL)
def test_generate_with_dict_openapi_validation_warns() -> None:
"""Test generate() with dict input + validation skips validation with warning."""
import warnings
from tests.data.dict_input import openapi_dict
with warnings.catch_warnings(record=True) as w:
warnings.simplefilter("always")
result = generate(
openapi_dict,
input_file_type=InputFileType.OpenAPI,
validation=True,
disable_timestamp=True,
)
assert_output(result, EXPECTED_MAIN_PATH / "dict_input" / "openapi.py")
# Check that both deprecated warning and dict input warning were raised
warning_messages = [str(warning.message) for warning in w]
assert any("deprecated" in msg.lower() for msg in warning_messages)
assert any("dict input" in msg.lower() for msg in warning_messages)
@pytest.mark.parametrize(
"input_file_type",
[InputFileType.Json, InputFileType.Yaml, InputFileType.CSV],
ids=["json", "yaml", "csv"],
)
def test_generate_with_dict_raw_data_types_raises_error(input_file_type: InputFileType) -> None:
"""Test generate() with dict input + Json/Yaml/CSV raises error."""
from tests.data.dict_input import auto_error_dict
with pytest.raises(Error, match=f"Dict input is not supported for {input_file_type.value}"):
generate(auto_error_dict, input_file_type=input_file_type)
def test_generate_with_config_object(output_file: Path) -> None:
"""Test generate() with GenerateConfig object."""
from datamodel_code_generator.model.pydantic_v2 import UnionMode
from datamodel_code_generator.types import StrictTypes
GenerateConfig.model_rebuild(_types_namespace={"StrictTypes": StrictTypes, "UnionMode": UnionMode})
config = GenerateConfig(
input_filename="test.json",
output=output_file,
output_model_type=DataModelType.PydanticV2BaseModel,
use_schema_description=True,
snake_case_field=True,
field_constraints=True,
extra_template_data={"Model": {"custom_key": "custom_value"}},
)
generate(
input_='{"type": "object", "properties": {"userName": {"type": "string"}}}',
config=config,
)
content = output_file.read_text(encoding="utf-8")
assert "class Model" in content
assert "user_name" in content
def test_generate_config_with_union_mode() -> None:
"""Test GenerateConfig with union_mode field."""
config = GenerateConfig(
output_model_type=DataModelType.PydanticV2BaseModel,
union_mode=UnionMode.left_to_right,
disable_timestamp=True,
)
result = generate(
input_='{"type": "object", "properties": {"value": {"anyOf": [{"type": "string"}, {"type": "integer"}]}}}',
config=config,
)
assert_output(result, EXPECTED_MAIN_PATH / "generate_config_union_mode.py")
def test_generate_with_config_and_kwargs_raises_error(output_file: Path) -> None:
"""Test generate() raises error when both config and kwargs are provided."""
from datamodel_code_generator.model.pydantic_v2 import UnionMode
from datamodel_code_generator.types import StrictTypes
GenerateConfig.model_rebuild(_types_namespace={"StrictTypes": StrictTypes, "UnionMode": UnionMode})
config = GenerateConfig(
input_filename="test.json",
output_model_type=DataModelType.PydanticV2BaseModel,
)
# Passing both config and kwargs should raise ValueError
with pytest.raises(ValueError, match="Cannot specify both 'config' and keyword arguments"):
generate(
input_='{"type": "object", "properties": {"name": {"type": "string"}}}',
output=output_file,
config=config,
field_constraints=True,
)
def test_parser_with_config_and_options_raises_error() -> None:
"""Test Parser raises error when both config and options are provided."""
from datamodel_code_generator.config import ParserConfig
from datamodel_code_generator.model.base import DataModel, DataModelFieldBase
from datamodel_code_generator.parser.jsonschema import JsonSchemaParser
from datamodel_code_generator.types import DataTypeManager, StrictTypes
ParserConfig.model_rebuild(
_types_namespace={
"StrictTypes": StrictTypes,
"DataModel": DataModel,
"DataModelFieldBase": DataModelFieldBase,
"DataTypeManager": DataTypeManager,
}
)
config = ParserConfig()
with pytest.raises(ValueError, match="Cannot specify both 'config' and keyword arguments"):
JsonSchemaParser(source="{}", config=config, field_constraints=True)
def test_jsonschema_parser_with_explicit_target_datetime_class() -> None:
"""Test JsonSchemaParser with explicit target_datetime_class option."""
from datamodel_code_generator.format import DatetimeClassType
from datamodel_code_generator.parser.jsonschema import JsonSchemaParser
parser = JsonSchemaParser(source="{}", target_datetime_class=DatetimeClassType.Datetime)
assert parser.data_type_manager.target_datetime_class == DatetimeClassType.Datetime
def test_openapi_parser_with_explicit_wrap_string_literal() -> None:
"""Test OpenAPIParser with explicit wrap_string_literal option."""
from datamodel_code_generator.parser.openapi import OpenAPIParser
parser = OpenAPIParser(
source='{"openapi": "3.0.0", "info": {"title": "Test", "version": "1.0"}, "paths": {}}',
wrap_string_literal=True,
)
assert parser.wrap_string_literal is True
def test_graphql_parser_with_explicit_target_datetime_class() -> None:
"""Test GraphQLParser with explicit target_datetime_class option."""
from datamodel_code_generator.format import DatetimeClassType
from datamodel_code_generator.parser.graphql import GraphQLParser
parser = GraphQLParser(source="type Query { id: ID }", target_datetime_class=DatetimeClassType.Awaredatetime)
assert parser.data_type_manager.target_datetime_class == DatetimeClassType.Awaredatetime
def test_jsonschema_parser_with_config_object() -> None:
"""Test JsonSchemaParser with ParserConfig object to cover config is not None branch."""
from datamodel_code_generator.config import ParserConfig
from datamodel_code_generator.format import DatetimeClassType
from datamodel_code_generator.model.base import DataModel, DataModelFieldBase
from datamodel_code_generator.parser.jsonschema import JsonSchemaParser
from datamodel_code_generator.types import DataTypeManager, StrictTypes
ParserConfig.model_rebuild(
_types_namespace={
"StrictTypes": StrictTypes,
"DataModel": DataModel,
"DataModelFieldBase": DataModelFieldBase,
"DataTypeManager": DataTypeManager,
}
)
config = ParserConfig(target_datetime_class=DatetimeClassType.Datetime)
parser = JsonSchemaParser(source="{}", config=config)
assert parser.data_type_manager.target_datetime_class == DatetimeClassType.Datetime
def test_openapi_parser_with_config_object() -> None:
"""Test OpenAPIParser with OpenAPIParserConfig object to cover config is not None branch."""
from datamodel_code_generator.config import OpenAPIParserConfig
from datamodel_code_generator.model.base import DataModel, DataModelFieldBase
from datamodel_code_generator.parser.openapi import OpenAPIParser
from datamodel_code_generator.types import DataTypeManager, StrictTypes
OpenAPIParserConfig.model_rebuild(
_types_namespace={
"StrictTypes": StrictTypes,
"DataModel": DataModel,
"DataModelFieldBase": DataModelFieldBase,
"DataTypeManager": DataTypeManager,
}
)
config = OpenAPIParserConfig(wrap_string_literal=True)
parser = OpenAPIParser(
source='{"openapi": "3.0.0", "info": {"title": "Test", "version": "1.0"}, "paths": {}}',
config=config,
)
assert parser.wrap_string_literal is True
def test_graphql_parser_with_config_object() -> None:
"""Test GraphQLParser with GraphQLParserConfig object to cover config is not None branch."""
from datamodel_code_generator.config import GraphQLParserConfig
from datamodel_code_generator.format import DatetimeClassType
from datamodel_code_generator.model.base import DataModel, DataModelFieldBase
from datamodel_code_generator.parser.graphql import GraphQLParser
from datamodel_code_generator.types import DataTypeManager, StrictTypes
GraphQLParserConfig.model_rebuild(
_types_namespace={
"StrictTypes": StrictTypes,
"DataModel": DataModel,
"DataModelFieldBase": DataModelFieldBase,
"DataTypeManager": DataTypeManager,
}
)
config = GraphQLParserConfig(target_datetime_class=DatetimeClassType.Awaredatetime)
parser = GraphQLParser(source="type Query { id: ID }", config=config)
assert parser.data_type_manager.target_datetime_class == DatetimeClassType.Awaredatetime
def test_default_values_invalid_json(output_file: Path, capsys: pytest.CaptureFixture[str]) -> None:
"""Test --default-values with invalid JSON file returns error."""
run_main_and_assert(
input_path=JSON_SCHEMA_DATA_PATH / "person.json",
output_path=output_file,
input_file_type="jsonschema",
extra_args=["--default-values", str(DEFAULT_VALUES_DATA_PATH / "invalid_json.json")],
expected_exit=Exit.ERROR,
capsys=capsys,
expected_stderr_contains="Unable to load default values mapping",
)
def test_default_values_non_dict(output_file: Path, capsys: pytest.CaptureFixture[str]) -> None:
"""Test --default-values with non-dict JSON file returns error."""
run_main_and_assert(
input_path=JSON_SCHEMA_DATA_PATH / "person.json",
output_path=output_file,
input_file_type="jsonschema",
extra_args=["--default-values", str(DEFAULT_VALUES_DATA_PATH / "non_dict.json")],
expected_exit=Exit.ERROR,
capsys=capsys,
expected_stderr_contains="Unable to load default values mapping: must be a JSON object",
)
def test_custom_formatters_kwargs_invalid(output_file: Path, capsys: pytest.CaptureFixture[str]) -> None:
"""Test --custom-formatters-kwargs with non-string values returns error."""
run_main_and_assert(
input_path=JSON_SCHEMA_DATA_PATH / "person.json",
output_path=output_file,
input_file_type="jsonschema",
extra_args=[
"--custom-formatters-kwargs",
str(DEFAULT_VALUES_DATA_PATH / "invalid_formatters_kwargs.json"),
],
expected_exit=Exit.ERROR,
capsys=capsys,
expected_stderr_contains="Unable to load custom_formatters_kwargs mapping: must be a JSON string mapping",
)
def test_use_annotated_deprecation_warning_pydantic_v2(output_file: Path) -> None:
"""Test that deprecation warning is emitted for Pydantic v2 without --use-annotated."""
with pytest.warns(DeprecationWarning, match=r"--use-annotated will be enabled by default for Pydantic v2"):
run_main_and_assert(
input_path=JSON_SCHEMA_DATA_PATH / "simple_string.json",
output_path=output_file,
input_file_type="jsonschema",
extra_args=["--output-model-type", "pydantic_v2.BaseModel"],
)
def test_use_annotated_no_warning_with_flag(output_file: Path) -> None:
"""Test that no warning is emitted when --use-annotated is explicitly set."""
with warnings.catch_warnings(record=True) as w:
warnings.simplefilter("always")
run_main_and_assert(
input_path=JSON_SCHEMA_DATA_PATH / "simple_string.json",
output_path=output_file,
input_file_type="jsonschema",
extra_args=["--output-model-type", "pydantic_v2.BaseModel", "--use-annotated"],
)
assert not any("--use-annotated will be enabled" in str(warning.message) for warning in w)
def test_use_annotated_no_warning_with_no_flag(output_file: Path) -> None:
"""Test that no warning is emitted when --no-use-annotated is explicitly set."""
with warnings.catch_warnings(record=True) as w:
warnings.simplefilter("always")
run_main_and_assert(
input_path=JSON_SCHEMA_DATA_PATH / "simple_string.json",
output_path=output_file,
input_file_type="jsonschema",
extra_args=["--output-model-type", "pydantic_v2.BaseModel", "--no-use-annotated"],
)
assert not any("--use-annotated will be enabled" in str(warning.message) for warning in w)
def test_import_generate_config_from_top_level() -> None:
"""Test that GenerateConfig can be imported from top-level module."""
from datamodel_code_generator import GenerateConfig as TopLevelGenerateConfig
assert TopLevelGenerateConfig is not None
assert TopLevelGenerateConfig is GenerateConfig
def test_generate_with_imported_config_from_top_level() -> None:
"""Test generate() with GenerateConfig imported from top-level."""
config = datamodel_code_generator.GenerateConfig(class_name="TestModel")
result = generate('{"type": "object"}', config=config)
assert result is not None
assert "class TestModel" in result
def test_all_exports_includes_generate_config() -> None:
"""Test that __all__ includes GenerateConfig."""
assert "GenerateConfig" in datamodel_code_generator.__all__
|