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
|
"""Tests for main CLI functionality with Korean locale settings."""
from __future__ import annotations
from argparse import Namespace
from pathlib import Path
from typing import TYPE_CHECKING
from unittest.mock import Mock, patch
import black
import pydantic
import pytest
from packaging import version
from datamodel_code_generator import MIN_VERSION, chdir, inferred_message
from datamodel_code_generator.__main__ import Exit, main
from datamodel_code_generator.arguments import arg_parser
from tests.conftest import assert_error_message, create_assert_file_content, freeze_time
from tests.main.conftest import run_main_and_assert, run_main_with_args
if TYPE_CHECKING:
from pytest_mock import MockerFixture
DATA_PATH: Path = Path(__file__).parent / "data"
OPEN_API_DATA_PATH: Path = DATA_PATH / "openapi"
JSON_SCHEMA_DATA_PATH: Path = DATA_PATH / "jsonschema"
EXPECTED_MAIN_KR_PATH = DATA_PATH / "expected" / "main_kr"
assert_file_content = create_assert_file_content(EXPECTED_MAIN_KR_PATH)
TIMESTAMP = "1985-10-26T01:21:00-07:00"
@pytest.fixture(autouse=True)
def reset_namespace(monkeypatch: pytest.MonkeyPatch) -> None:
"""Reset argument namespace before each test."""
namespace_ = Namespace(no_color=False)
monkeypatch.setattr("datamodel_code_generator.__main__.namespace", namespace_)
monkeypatch.setattr("datamodel_code_generator.arguments.namespace", namespace_)
@pytest.fixture
def output_file(tmp_path: Path) -> Path:
"""Return standard output file path."""
return tmp_path / "output.py"
@pytest.fixture
def output_dir(tmp_path: Path) -> Path:
"""Return standard output directory path."""
return tmp_path / "model"
@freeze_time("2019-07-26")
def test_main(output_file: Path) -> None:
"""Test basic main function with OpenAPI input."""
run_main_and_assert(
input_path=OPEN_API_DATA_PATH / "api.yaml",
output_path=output_file,
input_file_type=None,
assert_func=assert_file_content,
expected_file="main/output.py",
)
@freeze_time("2019-07-26")
def test_main_base_class(output_file: Path, tmp_path: Path) -> None:
"""Test main function with custom base class."""
run_main_and_assert(
input_path=OPEN_API_DATA_PATH / "api.yaml",
output_path=output_file,
input_file_type=None,
assert_func=assert_file_content,
expected_file=EXPECTED_MAIN_KR_PATH / "main_base_class" / "output.py",
extra_args=["--base-class", "custom_module.Base"],
copy_files=[(DATA_PATH / "pyproject.toml", tmp_path / "pyproject.toml")],
)
@freeze_time("2019-07-26")
def test_target_python_version(output_file: Path) -> None:
"""Test main function with target Python version."""
run_main_and_assert(
input_path=OPEN_API_DATA_PATH / "api.yaml",
output_path=output_file,
input_file_type=None,
assert_func=assert_file_content,
expected_file=EXPECTED_MAIN_KR_PATH / "target_python_version" / "output.py",
extra_args=["--target-python-version", f"3.{MIN_VERSION}"],
)
def test_main_modular(output_dir: Path) -> None:
"""Test main function on modular file."""
with freeze_time(TIMESTAMP):
run_main_and_assert(
input_path=OPEN_API_DATA_PATH / "modular.yaml",
output_path=output_dir,
expected_directory=EXPECTED_MAIN_KR_PATH / "main_modular",
)
def test_main_modular_no_file(capsys: pytest.CaptureFixture[str]) -> None:
"""Test main function on modular file with no output name outputs to stdout."""
run_main_with_args(["--input", str(OPEN_API_DATA_PATH / "modular.yaml")], expected_exit=Exit.OK)
captured = capsys.readouterr()
assert "class Chocolate" in captured.out
assert "class Source" in captured.out
def test_main_modular_filename(output_file: Path) -> None:
"""Test main function on modular file with filename."""
run_main_and_assert(
input_path=OPEN_API_DATA_PATH / "modular.yaml",
output_path=output_file,
expected_exit=Exit.ERROR,
)
def test_main_no_file(capsys: pytest.CaptureFixture[str], tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None:
"""Test main function on non-modular file with no output name."""
monkeypatch.chdir(tmp_path)
with freeze_time(TIMESTAMP):
run_main_and_assert(
input_path=OPEN_API_DATA_PATH / "api.yaml",
output_path=None,
expected_stdout_path=EXPECTED_MAIN_KR_PATH / "main_no_file" / "output.py",
capsys=capsys,
expected_stderr=inferred_message.format("openapi") + "\n",
)
def test_main_custom_template_dir(
capsys: pytest.CaptureFixture[str], tmp_path: Path, monkeypatch: pytest.MonkeyPatch
) -> None:
"""Test main function with custom template directory."""
monkeypatch.chdir(tmp_path)
custom_template_dir = DATA_PATH / "templates"
extra_template_data = OPEN_API_DATA_PATH / "extra_data.json"
with freeze_time(TIMESTAMP):
run_main_and_assert(
input_path=OPEN_API_DATA_PATH / "api.yaml",
output_path=None,
expected_stdout_path=EXPECTED_MAIN_KR_PATH / "main_custom_template_dir" / "output.py",
capsys=capsys,
extra_args=[
"--custom-template-dir",
str(custom_template_dir),
"--extra-template-data",
str(extra_template_data),
],
expected_stderr=inferred_message.format("openapi") + "\n",
)
@pytest.mark.skipif(
black.__version__.split(".")[0] >= "24",
reason="Installed black doesn't support the old style",
)
@freeze_time("2019-07-26")
def test_pyproject(output_file: Path, tmp_path: Path) -> None:
"""Test main function with pyproject.toml configuration."""
run_main_and_assert(
input_path=OPEN_API_DATA_PATH / "api.yaml",
output_path=output_file,
input_file_type=None,
assert_func=assert_file_content,
expected_file="pyproject/output.py",
copy_files=[(DATA_PATH / "project" / "pyproject.toml", tmp_path / "pyproject.toml")],
)
@pytest.mark.parametrize("language", ["UK", "US"])
def test_pyproject_respects_both_spellings_of_capitalize_enum_members_flag(language: str, tmp_path: Path) -> None:
"""Test that both UK and US spellings of capitalise are accepted."""
pyproject_toml_data = f"""
[tool.datamodel-codegen]
capitali{"s" if language == "UK" else "z"}e-enum-members = true
enable-version-header = false
input-file-type = "jsonschema"
"""
with (tmp_path / "pyproject.toml").open("w") as f:
f.write(pyproject_toml_data)
input_data = """
{
"$schema": "http://json-schema.org/draft-07/schema#",
"definitions": {
"MyEnum": {
"enum": [
"MEMBER_1",
"member_2"
]
}
}
}
"""
input_file = tmp_path / "schema.json"
with input_file.open("w") as f:
f.write(input_data)
expected_output = """# generated by datamodel-codegen:
# filename: schema.json
from __future__ import annotations
from enum import Enum
from typing import Any
from pydantic import RootModel
class Model(RootModel[Any]):
root: Any
class MyEnum(Enum):
MEMBER_1 = 'MEMBER_1'
member_2 = 'member_2'
"""
output_file: Path = tmp_path / "output.py"
run_main_and_assert(
input_path=input_file,
output_path=output_file,
expected_output=expected_output,
extra_args=["--disable-timestamp"],
)
@pytest.mark.skipif(
black.__version__.split(".")[0] == "19",
reason="Installed black doesn't support the old style",
)
@freeze_time("2019-07-26")
def test_pyproject_with_tool_section(output_file: Path, tmp_path: Path) -> None:
"""Test that a pyproject.toml with [tool.datamodel-codegen] section is found and applied."""
pyproject_toml = """
[tool.datamodel-codegen]
target-python-version = "3.10"
strict-types = ["str"]
"""
(tmp_path / "pyproject.toml").write_text(pyproject_toml)
with chdir(tmp_path):
run_main_and_assert(
input_path=(OPEN_API_DATA_PATH / "api.yaml").resolve(),
output_path=output_file.resolve(),
input_file_type=None,
assert_func=assert_file_content,
expected_file=EXPECTED_MAIN_KR_PATH / "pyproject" / "output.strictstr.py",
)
@pytest.mark.cli_doc(
options=["--use-schema-description"],
option_description="""Use schema description as class docstring.
The `--use-schema-description` flag extracts the `description` property from
schema definitions and adds it as a docstring to the generated class. This is
useful for preserving documentation from your schema in the generated code.""",
input_schema="openapi/api_multiline_docstrings.yaml",
cli_args=["--use-schema-description"],
golden_output="main_kr/main_use_schema_description/output.py",
related_options=["--use-field-description", "--use-inline-field-description"],
)
@freeze_time("2019-07-26")
def test_main_use_schema_description(output_file: Path) -> None:
"""Use schema description as class docstring.
The `--use-schema-description` flag extracts the `description` property from
schema definitions and adds it as a docstring to the generated class. This is
useful for preserving documentation from your schema in the generated code.
"""
run_main_and_assert(
input_path=OPEN_API_DATA_PATH / "api_multiline_docstrings.yaml",
output_path=output_file,
input_file_type=None,
assert_func=assert_file_content,
expected_file=EXPECTED_MAIN_KR_PATH / "main_use_schema_description" / "output.py",
extra_args=["--use-schema-description"],
)
@freeze_time("2019-07-26")
def test_main_docstring_special_chars(output_file: Path) -> None:
"""Escape special characters in docstrings.
Backslashes and triple quotes in schema descriptions must be escaped
to prevent Python syntax errors and type checker warnings. See GitHub
issue #1808.
"""
run_main_and_assert(
input_path=OPEN_API_DATA_PATH / "docstring_special_chars.yaml",
output_path=output_file,
input_file_type=None,
assert_func=assert_file_content,
expected_file=EXPECTED_MAIN_KR_PATH / "main_docstring_special_chars" / "output.py",
extra_args=["--use-schema-description", "--use-field-description"],
)
@pytest.mark.cli_doc(
options=["--use-field-description"],
option_description="""Add field descriptions using Pydantic Field().
The `--use-field-description` flag adds the `description` property from
schema fields as the `description` parameter in Pydantic Field(). This
provides documentation that is accessible via model schema and OpenAPI docs.""",
input_schema="openapi/api_multiline_docstrings.yaml",
cli_args=["--use-field-description"],
golden_output="main_kr/main_use_field_description/output.py",
related_options=["--use-schema-description", "--use-inline-field-description"],
)
@freeze_time("2022-11-11")
def test_main_use_field_description(output_file: Path) -> None:
"""Add field descriptions using Pydantic Field().
The `--use-field-description` flag adds the `description` property from
schema fields as the `description` parameter in Pydantic Field(). This
provides documentation that is accessible via model schema and OpenAPI docs.
"""
run_main_and_assert(
input_path=OPEN_API_DATA_PATH / "api_multiline_docstrings.yaml",
output_path=output_file,
input_file_type=None,
assert_func=assert_file_content,
expected_file=EXPECTED_MAIN_KR_PATH / "main_use_field_description" / "output.py",
extra_args=["--use-field-description"],
)
@pytest.mark.cli_doc(
options=["--use-inline-field-description"],
option_description="""Add field descriptions as inline comments.
The `--use-inline-field-description` flag adds the `description` property from
schema fields as inline comments after each field definition. This provides
documentation without using Field() wrappers.""",
input_schema="openapi/api_multiline_docstrings.yaml",
cli_args=["--use-inline-field-description"],
golden_output="main_kr/main_use_inline_field_description/output.py",
related_options=["--use-field-description", "--use-schema-description"],
)
@freeze_time("2022-11-11")
def test_main_use_inline_field_description(output_file: Path) -> None:
"""Add field descriptions as inline comments.
The `--use-inline-field-description` flag adds the `description` property from
schema fields as inline comments after each field definition. This provides
documentation without using Field() wrappers.
"""
run_main_and_assert(
input_path=OPEN_API_DATA_PATH / "api_multiline_docstrings.yaml",
output_path=output_file,
input_file_type=None,
assert_func=assert_file_content,
expected_file=EXPECTED_MAIN_KR_PATH / "main_use_inline_field_description" / "output.py",
extra_args=["--use-inline-field-description"],
)
@pytest.mark.cli_doc(
options=["--use-field-description-example"],
option_description="""Add field examples to docstrings.
The `--use-field-description-example` flag adds the `example` or `examples`
property from schema fields as docstrings. This provides documentation that
is visible in IDE intellisense.""",
input_schema="jsonschema/extras.json",
cli_args=["--use-field-description-example"],
golden_output="main_kr/main_use_field_description_example/output.py",
related_options=["--use-field-description", "--use-inline-field-description"],
)
@freeze_time("2022-11-11")
def test_main_use_field_description_example(output_file: Path) -> None:
"""Add field examples to docstrings.
The `--use-field-description-example` flag adds the `example` or `examples`
property from schema fields as docstrings. This provides documentation that
is visible in IDE intellisense.
"""
run_main_and_assert(
input_path=JSON_SCHEMA_DATA_PATH / "extras.json",
output_path=output_file,
input_file_type=None,
assert_func=assert_file_content,
expected_file=EXPECTED_MAIN_KR_PATH / "main_use_field_description_example" / "output.py",
extra_args=["--use-field-description-example"],
)
@freeze_time("2022-11-11")
def test_main_use_field_description_example_dataclass(output_file: Path) -> None:
"""Test single example docstrings with dataclass output."""
run_main_and_assert(
input_path=JSON_SCHEMA_DATA_PATH / "single_line_description_with_example.json",
output_path=output_file,
input_file_type=None,
assert_func=assert_file_content,
expected_file=EXPECTED_MAIN_KR_PATH / "main_use_field_description_example_dataclass" / "output.py",
extra_args=["--use-field-description-example", "--output-model-type", "dataclasses.dataclass"],
)
@pytest.mark.cli_doc(
options=["--use-field-description", "--use-field-description-example"],
option_description="""Add field descriptions and examples to docstrings.
When both `--use-field-description` and `--use-field-description-example` are used,
the docstring includes both the description and example(s).""",
input_schema="jsonschema/extras.json",
cli_args=["--use-field-description", "--use-field-description-example"],
golden_output="main_kr/main_use_field_description_with_example/output.py",
related_options=["--use-inline-field-description"],
)
@freeze_time("2022-11-11")
def test_main_use_field_description_with_example(output_file: Path) -> None:
"""Add field descriptions and examples to docstrings.
When both `--use-field-description` and `--use-field-description-example` are used,
the docstring includes both the description and example(s).
"""
run_main_and_assert(
input_path=JSON_SCHEMA_DATA_PATH / "extras.json",
output_path=output_file,
input_file_type=None,
assert_func=assert_file_content,
expected_file=EXPECTED_MAIN_KR_PATH / "main_use_field_description_with_example" / "output.py",
extra_args=["--use-field-description", "--use-field-description-example"],
)
@pytest.mark.cli_doc(
options=["--use-inline-field-description", "--use-field-description-example"],
option_description="""Add field descriptions and examples to docstrings with inline description.
When both `--use-inline-field-description` and `--use-field-description-example` are used,
multi-line descriptions and examples are included in the docstring.""",
input_schema="jsonschema/multiline_description_with_example.json",
cli_args=["--use-inline-field-description", "--use-field-description-example"],
golden_output="main_kr/main_use_inline_field_description_with_example/output.py",
related_options=["--use-field-description"],
)
@freeze_time("2022-11-11")
def test_main_use_inline_field_description_with_example(output_file: Path) -> None:
"""Add field descriptions and examples to docstrings with inline description.
When both `--use-inline-field-description` and `--use-field-description-example` are used,
multi-line descriptions and examples are included in the docstring.
"""
run_main_and_assert(
input_path=JSON_SCHEMA_DATA_PATH / "multiline_description_with_example.json",
output_path=output_file,
input_file_type=None,
assert_func=assert_file_content,
expected_file=EXPECTED_MAIN_KR_PATH / "main_use_inline_field_description_with_example" / "output.py",
extra_args=["--use-inline-field-description", "--use-field-description-example"],
)
@freeze_time("2022-11-11")
def test_main_use_inline_field_description_example_only(output_file: Path) -> None:
"""Test single-line description with use_inline_field_description and use_field_description_example.
When both flags are used with a single-line description, only the example
appears in the docstring (the single-line description stays in Field()).
"""
run_main_and_assert(
input_path=JSON_SCHEMA_DATA_PATH / "single_line_description_with_example.json",
output_path=output_file,
input_file_type=None,
assert_func=assert_file_content,
expected_file=EXPECTED_MAIN_KR_PATH / "main_use_inline_field_description_example_only" / "output.py",
extra_args=["--use-inline-field-description", "--use-field-description-example"],
)
@freeze_time("2022-11-11")
def test_main_use_field_description_example_multiple(output_file: Path) -> None:
"""Test multiple examples in docstring.
When a field has multiple examples, they are formatted as a bulleted list.
"""
run_main_and_assert(
input_path=JSON_SCHEMA_DATA_PATH / "multiple_examples.json",
output_path=output_file,
input_file_type=None,
assert_func=assert_file_content,
expected_file=EXPECTED_MAIN_KR_PATH / "main_use_field_description_example_multiple" / "output.py",
extra_args=["--use-field-description-example"],
)
def test_capitalise_enum_members(tmp_path: Path) -> None:
"""Test capitalise-enum-members option (issue #2370)."""
input_data = """
openapi: 3.0.3
info:
version: X.Y.Z
title: example schema
servers:
- url: "https://acme.org"
paths: {}
components:
schemas:
EnumSystems:
type: enum
enum:
- linux
- osx
- windows
"""
input_file = tmp_path / "myschema.yaml"
input_file.write_text(input_data, encoding="utf_8")
expected_output = """# generated by datamodel-codegen:
# filename: myschema.yaml
from __future__ import annotations
from enum import Enum
class EnumSystems(Enum):
LINUX = 'linux'
OSX = 'osx'
WINDOWS = 'windows'
"""
output_file: Path = tmp_path / "output.py"
run_main_and_assert(
input_path=input_file,
output_path=output_file,
expected_output=expected_output,
extra_args=[
"--output-model-type",
"pydantic_v2.BaseModel",
"--disable-timestamp",
"--capitalise-enum-members",
"--snake-case-field",
],
)
def test_capitalise_enum_members_and_use_subclass_enum(tmp_path: Path) -> None:
"""Test combination of capitalise-enum-members and use-subclass-enum (issue #2395)."""
input_data = """
openapi: 3.0.3
info:
version: X.Y.Z
title: example schema
servers:
- url: "https://acme.org"
paths: {}
components:
schemas:
EnumSystems:
type: string
enum:
- linux
- osx
- windows
"""
input_file = tmp_path / "myschema.yaml"
input_file.write_text(input_data, encoding="utf_8")
expected_output = """# generated by datamodel-codegen:
# filename: myschema.yaml
from __future__ import annotations
from enum import Enum
class EnumSystems(str, Enum):
LINUX = 'linux'
OSX = 'osx'
WINDOWS = 'windows'
"""
output_file: Path = tmp_path / "output.py"
run_main_and_assert(
input_path=input_file,
output_path=output_file,
expected_output=expected_output,
extra_args=[
"--output-model-type",
"pydantic_v2.BaseModel",
"--disable-timestamp",
"--capitalise-enum-members",
"--snake-case-field",
"--use-subclass-enum",
],
)
def test_capitalise_enum_members_builtin_conflict(output_file: Path) -> None:
"""Test capitalise-enum-members does not add underscore to builtin names (#2970)."""
run_main_and_assert(
input_path=JSON_SCHEMA_DATA_PATH / "enum_builtin_conflict.json",
output_path=output_file,
assert_func=assert_file_content,
input_file_type="jsonschema",
extra_args=[
"--output-model-type",
"pydantic_v2.BaseModel",
"--disable-timestamp",
"--capitalise-enum-members",
],
)
def test_capitalise_enum_members_and_use_subclass_enum_builtin_conflict(output_file: Path) -> None:
"""Test capitalise-enum-members + use-subclass-enum with builtin names (#2970)."""
run_main_and_assert(
input_path=JSON_SCHEMA_DATA_PATH / "enum_builtin_conflict_two.json",
output_path=output_file,
assert_func=assert_file_content,
input_file_type="jsonschema",
extra_args=[
"--output-model-type",
"pydantic_v2.BaseModel",
"--disable-timestamp",
"--capitalise-enum-members",
"--use-subclass-enum",
],
)
def test_use_subclass_enum_builtin_conflict_no_capitalise(output_file: Path) -> None:
"""Test use-subclass-enum without capitalise adds underscore for builtin conflicts."""
run_main_and_assert(
input_path=JSON_SCHEMA_DATA_PATH / "enum_builtin_conflict_two.json",
output_path=output_file,
assert_func=assert_file_content,
input_file_type="jsonschema",
extra_args=[
"--output-model-type",
"pydantic_v2.BaseModel",
"--disable-timestamp",
"--use-subclass-enum",
],
)
def test_no_subclass_enum_no_capitalise_builtin_names(output_file: Path) -> None:
"""Test default behavior with builtin names has no underscore suffix."""
run_main_and_assert(
input_path=JSON_SCHEMA_DATA_PATH / "enum_builtin_conflict_two.json",
output_path=output_file,
assert_func=assert_file_content,
input_file_type="jsonschema",
extra_args=[
"--output-model-type",
"pydantic_v2.BaseModel",
"--disable-timestamp",
],
)
EXPECTED_GENERATE_PYPROJECT_CONFIG_PATH = EXPECTED_MAIN_KR_PATH / "generate_pyproject_config"
@pytest.mark.cli_doc(
options=["--generate-pyproject-config"],
option_description="""Generate pyproject.toml configuration from CLI arguments.
The `--generate-pyproject-config` flag outputs a pyproject.toml configuration
snippet based on the provided CLI arguments. This is useful for converting
a working CLI command into a reusable configuration file.""",
cli_args=["--generate-pyproject-config", "--input", "schema.yaml", "--output", "model.py"],
expected_stdout="main_kr/generate_pyproject_config/basic.txt",
)
def test_generate_pyproject_config_basic(capsys: pytest.CaptureFixture[str]) -> None:
"""Generate pyproject.toml configuration from CLI arguments.
The `--generate-pyproject-config` flag outputs a pyproject.toml configuration
snippet based on the provided CLI arguments. This is useful for converting
a working CLI command into a reusable configuration file.
"""
run_main_with_args(
[
"--generate-pyproject-config",
"--input",
"schema.yaml",
"--output",
"model.py",
],
capsys=capsys,
expected_stdout_path=EXPECTED_GENERATE_PYPROJECT_CONFIG_PATH / "basic.txt",
)
def test_generate_pyproject_config_with_boolean_options(capsys: pytest.CaptureFixture[str]) -> None:
"""Test --generate-pyproject-config with boolean options."""
run_main_with_args(
[
"--generate-pyproject-config",
"--snake-case-field",
"--use-annotated",
"--collapse-root-models",
],
capsys=capsys,
expected_stdout_path=EXPECTED_GENERATE_PYPROJECT_CONFIG_PATH / "boolean_options.txt",
)
def test_generate_pyproject_config_with_list_options(capsys: pytest.CaptureFixture[str]) -> None:
"""Test --generate-pyproject-config with list options."""
run_main_with_args(
[
"--generate-pyproject-config",
"--strict-types",
"str",
"int",
],
capsys=capsys,
expected_stdout_path=EXPECTED_GENERATE_PYPROJECT_CONFIG_PATH / "list_options.txt",
)
def test_generate_pyproject_config_with_multiple_options(capsys: pytest.CaptureFixture[str]) -> None:
"""Test --generate-pyproject-config with various option types."""
run_main_with_args(
[
"--generate-pyproject-config",
"--input",
"schema.yaml",
"--output",
"model.py",
"--output-model-type",
"pydantic_v2.BaseModel",
"--target-python-version",
"3.11",
"--snake-case-field",
"--strict-types",
"str",
"bytes",
],
capsys=capsys,
expected_stdout_path=EXPECTED_GENERATE_PYPROJECT_CONFIG_PATH / "multiple_options.txt",
)
def test_generate_pyproject_config_excludes_meta_options(capsys: pytest.CaptureFixture[str]) -> None:
"""Test that meta options are excluded from generated config."""
run_main_with_args(
[
"--generate-pyproject-config",
"--input",
"schema.yaml",
],
capsys=capsys,
expected_stdout_path=EXPECTED_GENERATE_PYPROJECT_CONFIG_PATH / "excludes_meta_options.txt",
)
def test_generate_pyproject_config_with_enum_option(capsys: pytest.CaptureFixture[str]) -> None:
"""Test --generate-pyproject-config with Enum option."""
run_main_with_args(
[
"--generate-pyproject-config",
"--input",
"schema.yaml",
"--read-only-write-only-model-type",
"all",
],
capsys=capsys,
expected_stdout_path=EXPECTED_GENERATE_PYPROJECT_CONFIG_PATH / "enum_option.txt",
)
EXPECTED_GENERATE_CLI_COMMAND_PATH = EXPECTED_MAIN_KR_PATH / "generate_cli_command"
@pytest.mark.cli_doc(
options=["--generate-cli-command"],
option_description="""Generate CLI command from pyproject.toml configuration.
The `--generate-cli-command` flag reads your pyproject.toml configuration
and outputs the equivalent CLI command. This is useful for debugging
configuration issues or sharing commands with others.""",
cli_args=["--generate-cli-command"],
config_content="""[tool.datamodel-codegen]
input = "schema.yaml"
output = "model.py"
""",
expected_stdout="main_kr/generate_cli_command/basic.txt",
)
def test_generate_cli_command_basic(tmp_path: Path, capsys: pytest.CaptureFixture[str]) -> None:
"""Generate CLI command from pyproject.toml configuration.
The `--generate-cli-command` flag reads your pyproject.toml configuration
and outputs the equivalent CLI command. This is useful for debugging
configuration issues or sharing commands with others.
"""
pyproject_toml = """
[tool.datamodel-codegen]
input = "schema.yaml"
output = "model.py"
"""
(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_GENERATE_CLI_COMMAND_PATH / "basic.txt",
)
def test_generate_cli_command_with_boolean_options(tmp_path: Path, capsys: pytest.CaptureFixture[str]) -> None:
"""Test --generate-cli-command with boolean options."""
pyproject_toml = """
[tool.datamodel-codegen]
snake-case-field = true
use-annotated = true
collapse-root-models = 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_GENERATE_CLI_COMMAND_PATH / "boolean_options.txt",
)
def test_generate_cli_command_with_list_options(tmp_path: Path, capsys: pytest.CaptureFixture[str]) -> None:
"""Test --generate-cli-command with list options."""
pyproject_toml = """
[tool.datamodel-codegen]
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_GENERATE_CLI_COMMAND_PATH / "list_options.txt",
)
def test_generate_cli_command_with_multiple_options(tmp_path: Path, capsys: pytest.CaptureFixture[str]) -> None:
"""Test --generate-cli-command with various option types."""
pyproject_toml = """
[tool.datamodel-codegen]
input = "schema.yaml"
output = "model.py"
output-model-type = "pydantic_v2.BaseModel"
target-python-version = "3.11"
snake-case-field = true
strict-types = ["str", "bytes"]
"""
(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_GENERATE_CLI_COMMAND_PATH / "multiple_options.txt",
)
def test_generate_cli_command_no_config(tmp_path: Path) -> None:
"""Test --generate-cli-command when no config found."""
with chdir(tmp_path):
run_main_with_args(
["--generate-cli-command"],
expected_exit=Exit.ERROR,
)
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_GENERATE_CLI_COMMAND_PATH / "no_use_specialized_enum.txt",
)
def test_generate_cli_command_with_spaces_in_values(tmp_path: Path, capsys: pytest.CaptureFixture[str]) -> None:
"""Test --generate-cli-command with spaces in values."""
pyproject_toml = """
[tool.datamodel-codegen]
input = "my schema.yaml"
output = "my model.py"
http-headers = ["Authorization: Bearer token", "X-Custom: value"]
"""
(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_GENERATE_CLI_COMMAND_PATH / "spaces_in_values.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_GENERATE_CLI_COMMAND_PATH / "false_boolean.txt",
)
def test_generate_cli_command_excludes_excluded_options(tmp_path: Path, capsys: pytest.CaptureFixture[str]) -> None:
"""Test --generate-cli-command excludes options like debug, version, etc."""
pyproject_toml = """
[tool.datamodel-codegen]
input = "schema.yaml"
debug = true
version = true
no-color = true
disable-warnings = 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_GENERATE_CLI_COMMAND_PATH / "excluded_options.txt",
)
EXPECTED_PYPROJECT_PROFILE_PATH = EXPECTED_MAIN_KR_PATH / "pyproject_profile"
@pytest.mark.skipif(
version.parse(black.__version__) < version.parse("23.0.0"),
reason="black 22.x doesn't support Python 3.11 target version",
)
@freeze_time("2019-07-26")
def test_pyproject_with_profile(output_file: Path, tmp_path: Path) -> None:
"""Test loading a named profile from pyproject.toml."""
pyproject_toml = """
[tool.datamodel-codegen]
target-python-version = "3.10"
enable-version-header = false
[tool.datamodel-codegen.profiles.api]
target-python-version = "3.11"
snake-case-field = true
"""
(tmp_path / "pyproject.toml").write_text(pyproject_toml)
input_data = """
{
"$schema": "http://json-schema.org/draft-07/schema#",
"type": "object",
"properties": {
"firstName": {"type": "string"},
"lastName": {"type": "string"}
}
}
"""
input_file = tmp_path / "schema.json"
input_file.write_text(input_data)
with chdir(tmp_path):
run_main_and_assert(
input_path=input_file,
output_path=output_file.resolve(),
assert_func=assert_file_content,
expected_file=EXPECTED_PYPROJECT_PROFILE_PATH / "with_profile.py",
extra_args=["--profile", "api", "--disable-timestamp"],
)
def test_pyproject_profile_not_found(tmp_path: Path, capsys: pytest.CaptureFixture[str]) -> None:
"""Test error when profile is not found."""
pyproject_toml = """
[tool.datamodel-codegen]
target-python-version = "3.10"
"""
(tmp_path / "pyproject.toml").write_text(pyproject_toml)
input_file = tmp_path / "schema.json"
input_file.write_text('{"type": "object"}')
output_file = tmp_path / "output.py"
with chdir(tmp_path):
return_code = run_main_with_args(
["--input", str(input_file), "--output", str(output_file), "--profile", "nonexistent"],
expected_exit=Exit.ERROR,
capsys=capsys,
)
assert return_code == Exit.ERROR
captured = capsys.readouterr()
assert "Profile 'nonexistent' not found in pyproject.toml" in captured.err
@freeze_time("2019-07-26")
def test_ignore_pyproject_option(output_file: Path, tmp_path: Path) -> None:
"""Test --ignore-pyproject ignores pyproject.toml configuration."""
pyproject_toml = """
[tool.datamodel-codegen]
snake-case-field = true
enable-version-header = true
"""
(tmp_path / "pyproject.toml").write_text(pyproject_toml)
input_data = """
{
"$schema": "http://json-schema.org/draft-07/schema#",
"type": "object",
"properties": {
"firstName": {"type": "string"},
"lastName": {"type": "string"}
}
}
"""
input_file = tmp_path / "schema.json"
input_file.write_text(input_data)
with chdir(tmp_path):
run_main_and_assert(
input_path=input_file,
output_path=output_file.resolve(),
assert_func=assert_file_content,
expected_file=EXPECTED_PYPROJECT_PROFILE_PATH / "ignore_pyproject.py",
extra_args=["--ignore-pyproject", "--disable-timestamp"],
)
@freeze_time("2019-07-26")
def test_profile_overrides_base_config_shallow_merge(output_file: Path, tmp_path: Path) -> None:
"""Test that profile settings shallow-merge (replace) base settings for lists."""
pyproject_toml = """
[tool.datamodel-codegen]
strict-types = ["str", "int"]
target-python-version = "3.10"
enable-version-header = false
[tool.datamodel-codegen.profiles.api]
strict-types = ["bytes"]
"""
(tmp_path / "pyproject.toml").write_text(pyproject_toml)
input_data = """
{
"$schema": "http://json-schema.org/draft-07/schema#",
"type": "object",
"properties": {
"data": {"type": "string", "format": "binary"}
}
}
"""
input_file = tmp_path / "schema.json"
input_file.write_text(input_data)
with chdir(tmp_path):
run_main_and_assert(
input_path=input_file,
output_path=output_file.resolve(),
assert_func=assert_file_content,
expected_file=EXPECTED_PYPROJECT_PROFILE_PATH / "shallow_merge.py",
extra_args=["--profile", "api", "--disable-timestamp"],
)
def test_generate_cli_command_with_profile(tmp_path: Path, capsys: pytest.CaptureFixture[str]) -> None:
"""Test --generate-cli-command reflects merged profile settings."""
pyproject_toml = """
[tool.datamodel-codegen]
target-python-version = "3.10"
snake-case-field = true
[tool.datamodel-codegen.profiles.api]
input = "api.yaml"
target-python-version = "3.11"
"""
(tmp_path / "pyproject.toml").write_text(pyproject_toml)
with chdir(tmp_path):
run_main_with_args(
["--profile", "api", "--generate-cli-command"],
capsys=capsys,
)
captured = capsys.readouterr()
# Profile value should override base
assert "--target-python-version 3.11" in captured.out
# Base value should be inherited
assert "--snake-case-field" in captured.out
# Profile-specific value (no quotes when no spaces in value)
assert "--input api.yaml" in captured.out
def test_help_shows_new_options() -> None:
"""Test that --profile and --ignore-pyproject appear in help."""
help_text = arg_parser.format_help()
assert "--profile" in help_text
assert "--ignore-pyproject" in help_text
assert "pyproject.toml" in help_text
@pytest.mark.skipif(
version.parse(black.__version__) < version.parse("23.0.0"),
reason="black 22.x doesn't support Python 3.11 target version",
)
def test_pyproject_profile_inherits_base_settings(output_file: Path, tmp_path: Path) -> None:
"""Test that profile inherits settings from base config."""
pyproject_toml = """
[tool.datamodel-codegen]
snake-case-field = true
enable-version-header = false
[tool.datamodel-codegen.profiles.api]
target-python-version = "3.11"
"""
(tmp_path / "pyproject.toml").write_text(pyproject_toml)
input_data = """
{
"$schema": "http://json-schema.org/draft-07/schema#",
"type": "object",
"properties": {
"firstName": {"type": "string"}
}
}
"""
input_file = tmp_path / "schema.json"
input_file.write_text(input_data)
with chdir(tmp_path):
run_main_and_assert(
input_path=input_file,
output_path=output_file.resolve(),
assert_func=assert_file_content,
expected_file=EXPECTED_PYPROJECT_PROFILE_PATH / "inherits_base.py",
extra_args=["--profile", "api", "--disable-timestamp"],
)
@pytest.mark.skipif(
version.parse(black.__version__) < version.parse("23.0.0"),
reason="black 22.x doesn't support Python 3.11 target version",
)
@freeze_time("2019-07-26")
def test_cli_args_override_profile_and_base(output_file: Path, tmp_path: Path) -> None:
"""Test that CLI arguments take precedence over profile and base settings."""
pyproject_toml = """
[tool.datamodel-codegen]
target-python-version = "3.10"
enable-version-header = false
[tool.datamodel-codegen.profiles.api]
target-python-version = "3.11"
"""
(tmp_path / "pyproject.toml").write_text(pyproject_toml)
input_data = """
{
"$schema": "http://json-schema.org/draft-07/schema#",
"type": "object",
"properties": {
"firstName": {"type": "string"}
}
}
"""
input_file = tmp_path / "schema.json"
input_file.write_text(input_data)
with chdir(tmp_path):
run_main_and_assert(
input_path=input_file,
output_path=output_file.resolve(),
assert_func=assert_file_content,
expected_file=EXPECTED_PYPROJECT_PROFILE_PATH / "cli_override.py",
extra_args=[
"--profile",
"api",
"--disable-timestamp",
"--target-python-version",
"3.11",
"--use-union-operator",
],
)
def test_ignore_pyproject_with_profile(tmp_path: Path) -> None:
"""Test that --ignore-pyproject ignores --profile as well."""
pyproject_toml = """
[tool.datamodel-codegen]
snake-case-field = true
[tool.datamodel-codegen.profiles.api]
target-python-version = "3.11"
"""
(tmp_path / "pyproject.toml").write_text(pyproject_toml)
input_data = """
{
"$schema": "http://json-schema.org/draft-07/schema#",
"type": "object",
"properties": {
"firstName": {"type": "string"}
}
}
"""
input_file = tmp_path / "schema.json"
input_file.write_text(input_data)
output_file = tmp_path / "output.py"
with chdir(tmp_path):
run_main_with_args(
[
"--input",
str(input_file),
"--output",
str(output_file),
"--ignore-pyproject",
"--profile",
"api",
"--disable-timestamp",
],
)
output_content = output_file.read_text()
assert "firstName" in output_content
assert "first_name" not in output_content
def test_profile_without_pyproject_errors(tmp_path: Path, capsys: pytest.CaptureFixture[str]) -> None:
"""Test that --profile without pyproject.toml raises an error."""
input_file = tmp_path / "schema.json"
input_file.write_text('{"type": "object"}')
output_file = tmp_path / "output.py"
with chdir(tmp_path):
return_code = run_main_with_args(
["--input", str(input_file), "--output", str(output_file), "--profile", "api"],
expected_exit=Exit.ERROR,
capsys=capsys,
)
assert return_code == Exit.ERROR
captured = capsys.readouterr()
assert "no [tool.datamodel-codegen] section found" in captured.err.lower()
@freeze_time("2019-07-26")
def test_allof_with_description_generates_class_not_alias(output_file: Path) -> None:
"""Test that allOf with description generates class definition, not alias."""
run_main_and_assert(
input_path=OPEN_API_DATA_PATH / "allof_with_description_only.yaml",
output_path=output_file,
input_file_type=None,
assert_func=assert_file_content,
expected_file=EXPECTED_MAIN_KR_PATH / "main_allof_with_description_only" / "output.py",
extra_args=[
"--output-model-type",
"pydantic_v2.BaseModel",
"--use-schema-description",
],
)
@pytest.mark.cli_doc(
options=["--use-decimal-for-multiple-of"],
option_description="""Generate Decimal types for fields with multipleOf constraint.
The `--use-decimal-for-multiple-of` flag generates `condecimal` or `Decimal`
types for numeric fields that have a `multipleOf` constraint. This ensures
precise decimal arithmetic when validating values against the constraint.""",
input_schema="jsonschema/use_decimal_for_multiple_of.json",
cli_args=["--use-decimal-for-multiple-of"],
golden_output="main_kr/use_decimal_for_multiple_of/output.py",
)
@freeze_time("2019-07-26")
def test_use_decimal_for_multiple_of(output_file: Path) -> None:
"""Generate Decimal types for fields with multipleOf constraint.
The `--use-decimal-for-multiple-of` flag generates `condecimal` or `Decimal`
types for numeric fields that have a `multipleOf` constraint. This ensures
precise decimal arithmetic when validating values against the constraint.
"""
run_main_and_assert(
input_path=JSON_SCHEMA_DATA_PATH / "use_decimal_for_multiple_of.json",
output_path=output_file,
input_file_type="jsonschema",
assert_func=assert_file_content,
expected_file=EXPECTED_MAIN_KR_PATH / "use_decimal_for_multiple_of" / "output.py",
extra_args=["--use-decimal-for-multiple-of"],
)
@pytest.mark.cli_doc(
options=["--use-pendulum"],
option_description="""Use pendulum types for date, time, and duration fields.
The `--use-pendulum` flag maps schema `date`, `time`, and `duration` values to
Pendulum types such as `pendulum.Date`, `pendulum.Time`, and `pendulum.Duration`.
`date-time` fields continue to use `pydantic.AwareDatetime`.
If you need a different datetime class for `date-time` fields, use
[`--output-datetime-class`](#output-datetime-class).""",
input_schema="jsonschema/use_pendulum.json",
cli_args=["--use-pendulum"],
golden_output="main_kr/use_pendulum/output.py",
)
@freeze_time("2019-07-26")
def test_use_pendulum(output_file: Path) -> None:
"""Use pendulum types for date, time, and duration fields.
The `--use-pendulum` flag maps schema `date`, `time`, and `duration` values
to Pendulum types such as `pendulum.Date`, `pendulum.Time`, and
`pendulum.Duration`. `date-time` fields continue to use
`pydantic.AwareDatetime`.
If you need a different datetime class for `date-time` fields, use
`--output-datetime-class`.
"""
run_main_and_assert(
input_path=JSON_SCHEMA_DATA_PATH / "use_pendulum.json",
output_path=output_file,
input_file_type="jsonschema",
assert_func=assert_file_content,
expected_file=EXPECTED_MAIN_KR_PATH / "use_pendulum" / "output.py",
extra_args=["--use-pendulum"],
)
@pytest.mark.cli_doc(
options=["--use-non-positive-negative-number-constrained-types"],
option_description="""Use NonPositive/NonNegative types for number constraints.
The `--use-non-positive-negative-number-constrained-types` flag generates
Pydantic's NonPositiveInt, NonNegativeInt, NonPositiveFloat, and NonNegativeFloat
types for fields with minimum: 0 or maximum: 0 constraints, instead of using
conint/confloat with ge/le parameters.""",
input_schema="jsonschema/use_non_positive_negative.json",
cli_args=["--use-non-positive-negative-number-constrained-types"],
golden_output="main_kr/use_non_positive_negative/output.py",
)
@pytest.mark.skipif(pydantic.VERSION < "2.0.0", reason="Require Pydantic version 2.0.0 or later")
@freeze_time("2019-07-26")
def test_use_non_positive_negative_number_constrained_types(output_file: Path) -> None:
"""Use NonPositive/NonNegative types for number constraints."""
run_main_and_assert(
input_path=JSON_SCHEMA_DATA_PATH / "use_non_positive_negative.json",
output_path=output_file,
input_file_type="jsonschema",
assert_func=assert_file_content,
expected_file=EXPECTED_MAIN_KR_PATH / "use_non_positive_negative" / "output.py",
extra_args=["--use-non-positive-negative-number-constrained-types"],
)
@pytest.mark.skipif(pydantic.VERSION < "2.0.0", reason="Require Pydantic version 2.0.0 or later")
@freeze_time("2019-07-26")
def test_use_non_positive_negative_number_constrained_types_with_use_annotated(output_file: Path) -> None:
"""Use NonPositive/NonNegative types combined with --use-annotated."""
run_main_and_assert(
input_path=JSON_SCHEMA_DATA_PATH / "use_non_positive_negative.json",
output_path=output_file,
input_file_type="jsonschema",
assert_func=assert_file_content,
expected_file=EXPECTED_MAIN_KR_PATH / "use_non_positive_negative_with_use_annotated" / "output.py",
extra_args=["--use-non-positive-negative-number-constrained-types", "--use-annotated"],
)
@pytest.mark.cli_doc(
options=["--include-path-parameters"],
option_description="""Include OpenAPI path parameters in generated parameter models.
The `--include-path-parameters` flag adds path parameters (like /users/{userId})
to the generated request parameter models. By default, only query parameters
are included. Use this with `--openapi-scopes parameters` to generate parameter
models that include both path and query parameters.""",
input_schema="openapi/include_path_parameters.yaml",
cli_args=["--include-path-parameters", "--openapi-scopes", "schemas", "paths", "parameters"],
golden_output="main_kr/include_path_parameters/output.py",
)
@freeze_time("2019-07-26")
def test_include_path_parameters(output_file: Path) -> None:
"""Include OpenAPI path parameters in generated parameter models.
The `--include-path-parameters` flag adds path parameters (like /users/{userId})
to the generated request parameter models. By default, only query parameters
are included. Use this with `--openapi-scopes parameters` to generate parameter
models that include both path and query parameters.
"""
run_main_and_assert(
input_path=OPEN_API_DATA_PATH / "include_path_parameters.yaml",
output_path=output_file,
input_file_type="openapi",
assert_func=assert_file_content,
expected_file=EXPECTED_MAIN_KR_PATH / "include_path_parameters" / "output.py",
extra_args=["--include-path-parameters", "--openapi-scopes", "schemas", "paths", "parameters"],
)
@pytest.mark.cli_doc(
options=["--no-alias"],
option_description="""Disable Field alias generation for non-Python-safe property names.
The `--no-alias` flag disables automatic alias generation when JSON property
names contain characters invalid in Python (like hyphens). Without this flag,
fields are renamed to Python-safe names with `Field(alias='original-name')`.
With this flag, only Python-safe names are used without aliases.""",
input_schema="jsonschema/no_alias.json",
cli_args=["--no-alias"],
golden_output="main_kr/no_alias/with_option.py",
comparison_output="main_kr/no_alias/without_option.py",
)
@freeze_time("2019-07-26")
def test_no_alias(output_file: Path) -> None:
"""Disable Field alias generation for non-Python-safe property names.
The `--no-alias` flag disables automatic alias generation when JSON property
names contain characters invalid in Python (like hyphens). Without this flag,
fields are renamed to Python-safe names with `Field(alias='original-name')`.
With this flag, only Python-safe names are used without aliases.
"""
run_main_and_assert(
input_path=JSON_SCHEMA_DATA_PATH / "no_alias.json",
output_path=output_file,
input_file_type="jsonschema",
assert_func=assert_file_content,
expected_file=EXPECTED_MAIN_KR_PATH / "no_alias" / "with_option.py",
extra_args=["--no-alias"],
)
@pytest.mark.cli_doc(
options=["--use-serialization-alias"],
option_description="""Use serialization_alias instead of alias for field aliasing (Pydantic v2 only).
The `--use-serialization-alias` flag changes field aliasing to use `serialization_alias`
instead of `alias`. This allows setting values using the Pythonic field name while
serializing to the original JSON property name.""",
input_schema="jsonschema/no_alias.json",
cli_args=["--use-serialization-alias", "--output-model-type", "pydantic_v2.BaseModel"],
golden_output="main_kr/use_serialization_alias/output.py",
comparison_output="main_kr/no_alias/without_option.py",
)
@freeze_time("2019-07-26")
def test_use_serialization_alias(output_file: Path) -> None:
"""Use serialization_alias instead of alias for field aliasing (Pydantic v2 only).
The `--use-serialization-alias` flag changes field aliasing to use `serialization_alias`
instead of `alias`. This allows setting values using the Pythonic field name while
serializing to the original JSON property name.
"""
run_main_and_assert(
input_path=JSON_SCHEMA_DATA_PATH / "no_alias.json",
output_path=output_file,
input_file_type="jsonschema",
assert_func=assert_file_content,
expected_file=EXPECTED_MAIN_KR_PATH / "use_serialization_alias" / "output.py",
extra_args=["--use-serialization-alias", "--output-model-type", "pydantic_v2.BaseModel"],
)
@pytest.mark.cli_doc(
options=["--custom-file-header"],
option_description="""Add custom header text to the generated file.
The `--custom-file-header` flag replaces the default "generated by datamodel-codegen"
header with custom text. This is useful for adding copyright notices, license
headers, or other metadata to generated files.""",
input_schema="jsonschema/no_alias.json",
cli_args=["--custom-file-header", "# Copyright 2024 MyCompany"],
golden_output="main_kr/custom_file_header/with_option.py",
comparison_output="main_kr/custom_file_header/without_option.py",
)
@freeze_time("2019-07-26")
def test_custom_file_header(output_file: Path) -> None:
"""Add custom header text to the generated file.
The `--custom-file-header` flag replaces the default "generated by datamodel-codegen"
header with custom text. This is useful for adding copyright notices, license
headers, or other metadata to generated files.
"""
run_main_and_assert(
input_path=JSON_SCHEMA_DATA_PATH / "no_alias.json",
output_path=output_file,
input_file_type="jsonschema",
assert_func=assert_file_content,
expected_file=EXPECTED_MAIN_KR_PATH / "custom_file_header" / "with_option.py",
extra_args=["--custom-file-header", "# Copyright 2024 MyCompany"],
)
@pytest.mark.cli_doc(
options=["--url", "--http-headers"],
option_description="""Fetch schema from URL with custom HTTP headers.
The `--url` flag specifies a remote URL to fetch the schema from instead of
a local file. The `--http-headers` flag adds custom HTTP headers to the request,
useful for authentication (e.g., Bearer tokens) or custom API requirements.
Format: `HeaderName:HeaderValue`.""",
input_schema="jsonschema/pet_simple.json",
cli_args=["--url", "https://api.example.com/schema.json", "--http-headers", "Authorization:Bearer token"],
golden_output="main_kr/url_with_headers/output.py",
)
@freeze_time("2019-07-26")
def test_url_with_http_headers(mocker: MockerFixture, output_file: Path) -> None:
"""Fetch schema from URL with custom HTTP headers.
The `--url` flag specifies a remote URL to fetch the schema from instead of
a local file. The `--http-headers` flag adds custom HTTP headers to the request,
useful for authentication (e.g., Bearer tokens) or custom API requirements.
Format: `HeaderName:HeaderValue`.
"""
mock_response = Mock()
mock_response.text = JSON_SCHEMA_DATA_PATH.joinpath("pet_simple.json").read_text()
mocker.patch("httpx.get", return_value=mock_response)
return_code = main([
"--url",
"https://api.example.com/schema.json",
"--output",
str(output_file),
"--input-file-type",
"jsonschema",
"--http-headers",
"Authorization:Bearer token",
])
assert return_code == 0
assert_file_content(output_file, EXPECTED_MAIN_KR_PATH / "url_with_headers" / "output.py")
@pytest.mark.cli_doc(
options=["--input"],
option_description="""Specify the input schema file path.
The `--input` flag specifies the path to the schema file (JSON Schema,
OpenAPI, GraphQL, etc.). Multiple input files can be specified to merge
schemas. Required unless using `--url` to fetch schema from a URL.""",
input_schema="jsonschema/pet_simple.json",
cli_args=["--input", "pet_simple.json", "--output", "output.py"],
golden_output="main_kr/input_output/output.py",
)
@freeze_time("2019-07-26")
def test_input_option(output_file: Path) -> None:
"""Specify the input schema file path.
The `--input` flag specifies the path to the schema file (JSON Schema,
OpenAPI, GraphQL, etc.). Multiple input files can be specified to merge
schemas. Required unless using `--url` to fetch schema from a URL.
"""
run_main_and_assert(
input_path=JSON_SCHEMA_DATA_PATH / "pet_simple.json",
output_path=output_file,
input_file_type="jsonschema",
assert_func=assert_file_content,
expected_file=EXPECTED_MAIN_KR_PATH / "input_output" / "output.py",
)
@pytest.mark.cli_doc(
options=["--output"],
option_description="""Specify the destination path for generated Python code.
The `--output` flag specifies where to write the generated Python code.
It can be either a file path (single-file output) or a directory path
(multi-file output for modular schemas). If omitted, the generated code
is written to stdout.""",
input_schema="jsonschema/pet_simple.json",
cli_args=["--input", "pet_simple.json", "--output", "output.py"],
golden_output="main_kr/input_output/output.py",
)
@freeze_time("2019-07-26")
def test_output_option(output_file: Path) -> None:
"""Specify the destination path for generated Python code.
The `--output` flag specifies where to write the generated Python code.
It can be either a file path (single-file output) or a directory path
(multi-file output for modular schemas). If omitted, the generated code
is written to stdout.
"""
run_main_and_assert(
input_path=JSON_SCHEMA_DATA_PATH / "pet_simple.json",
output_path=output_file,
input_file_type="jsonschema",
assert_func=assert_file_content,
expected_file=EXPECTED_MAIN_KR_PATH / "input_output" / "output.py",
)
@pytest.mark.cli_doc(
options=["--encoding"],
option_description="""Specify character encoding for input and output files.
The `--encoding` flag sets the character encoding used when reading
the schema file and writing the generated Python code. This is useful
for schemas containing non-ASCII characters (e.g., Japanese, Chinese).
Default is UTF-8, which is the standard encoding for JSON and most modern text files.""",
input_schema="jsonschema/encoding_test.json",
cli_args=["--encoding", "utf-8"],
golden_output="main_kr/encoding/output.py",
)
@freeze_time("2019-07-26")
def test_encoding_option(output_file: Path) -> None:
"""Specify character encoding for input and output files.
The `--encoding` flag sets the character encoding used when reading
the schema file and writing the generated Python code. This is useful
for schemas containing non-ASCII characters (e.g., Japanese, Chinese).
Default is UTF-8, which is the standard encoding for JSON and most modern text files.
"""
run_main_and_assert(
input_path=JSON_SCHEMA_DATA_PATH / "encoding_test.json",
output_path=output_file,
input_file_type="jsonschema",
assert_func=assert_file_content,
expected_file=EXPECTED_MAIN_KR_PATH / "encoding" / "output.py",
extra_args=["--encoding", "utf-8"],
)
@pytest.mark.cli_doc(
options=["--formatters"],
option_description="""Specify code formatters to apply to generated output.
The `--formatters` flag specifies which code formatters to apply to
the generated Python code. Available formatters are: black, isort,
ruff, yapf, autopep8, autoflake. Default is [black, isort].
Use this to customize formatting or disable formatters entirely.""",
input_schema="jsonschema/pet_simple.json",
cli_args=["--formatters", "isort"],
golden_output="main_kr/formatters/output.py",
)
@freeze_time("2019-07-26")
def test_formatters_option(output_file: Path) -> None:
"""Specify code formatters to apply to generated output.
The `--formatters` flag specifies which code formatters to apply to
the generated Python code. Available formatters are: black, isort,
ruff, yapf, autopep8, autoflake. Default is [black, isort].
Use this to customize formatting or disable formatters entirely.
"""
run_main_and_assert(
input_path=JSON_SCHEMA_DATA_PATH / "pet_simple.json",
output_path=output_file,
input_file_type="jsonschema",
assert_func=assert_file_content,
expected_file=EXPECTED_MAIN_KR_PATH / "formatters" / "output.py",
extra_args=["--formatters", "isort"],
)
@pytest.mark.cli_doc(
options=["--custom-formatters-kwargs"],
option_description="""Pass custom arguments to custom formatters via JSON file.
The `--custom-formatters-kwargs` flag accepts a path to a JSON file containing
custom configuration for custom formatters (used with --custom-formatters).
The file should contain a JSON object mapping formatter names to their kwargs.
Note: This option is primarily used with --custom-formatters to pass
configuration to user-defined formatter modules.""",
input_schema="jsonschema/pet_simple.json",
cli_args=["--custom-formatters-kwargs", "formatter_kwargs.json"],
golden_output="main_kr/input_output/output.py",
)
@freeze_time("2019-07-26")
def test_custom_formatters_kwargs_option(output_file: Path) -> None:
"""Pass custom arguments to custom formatters via JSON file.
The `--custom-formatters-kwargs` flag accepts a path to a JSON file containing
custom configuration for custom formatters (used with --custom-formatters).
The file should contain a JSON object mapping formatter names to their kwargs.
Note: This option is primarily used with --custom-formatters to pass
configuration to user-defined formatter modules.
"""
# Simple test - the option is accepted. Full usage requires custom formatter module.
run_main_and_assert(
input_path=JSON_SCHEMA_DATA_PATH / "pet_simple.json",
output_path=output_file,
input_file_type="jsonschema",
assert_func=assert_file_content,
expected_file=EXPECTED_MAIN_KR_PATH / "input_output" / "output.py",
extra_args=["--custom-formatters-kwargs", str(DATA_PATH / "config" / "formatter_kwargs.json")],
)
@pytest.mark.cli_doc(
options=["--http-ignore-tls"],
option_description="""Disable TLS certificate verification for HTTPS requests.
The `--http-ignore-tls` flag disables SSL/TLS certificate verification
when fetching schemas from HTTPS URLs. This is useful for development
environments with self-signed certificates. Not recommended for production.""",
input_schema="jsonschema/pet_simple.json",
cli_args=["--url", "https://api.example.com/schema.json", "--http-ignore-tls"],
golden_output="main_kr/url_with_headers/output.py",
)
@freeze_time("2019-07-26")
def test_http_ignore_tls(output_file: Path) -> None:
"""Disable TLS certificate verification for HTTPS requests.
The `--http-ignore-tls` flag disables SSL/TLS certificate verification
when fetching schemas from HTTPS URLs. This is useful for development
environments with self-signed certificates. Not recommended for production.
"""
mock_response = Mock()
mock_response.text = JSON_SCHEMA_DATA_PATH.joinpath("pet_simple.json").read_text()
with patch("httpx.get", return_value=mock_response) as mock_get:
return_code = main([
"--url",
"https://api.example.com/schema.json",
"--output",
str(output_file),
"--input-file-type",
"jsonschema",
"--http-ignore-tls",
])
assert return_code == 0
# Verify that verify=False was passed to httpx.get
mock_get.assert_called_once()
call_kwargs = mock_get.call_args[1]
assert call_kwargs.get("verify") is False
@pytest.mark.cli_doc(
options=["--http-query-parameters"],
option_description="""Add query parameters to HTTP requests for remote schemas.
The `--http-query-parameters` flag adds query parameters to HTTP requests
when fetching schemas from URLs. Useful for APIs that require version
or format parameters. Format: `key=value`. Multiple parameters can be
specified: `--http-query-parameters version=v2 format=json`.""",
input_schema="jsonschema/pet_simple.json",
cli_args=["--url", "https://api.example.com/schema.json", "--http-query-parameters", "version=v2", "format=json"],
golden_output="main_kr/url_with_headers/output.py",
)
@freeze_time("2019-07-26")
def test_http_query_parameters(output_file: Path) -> None:
"""Add query parameters to HTTP requests for remote schemas.
The `--http-query-parameters` flag adds query parameters to HTTP requests
when fetching schemas from URLs. Useful for APIs that require version
or format parameters. Format: `key=value`. Multiple parameters can be
specified: `--http-query-parameters version=v2 format=json`.
"""
mock_response = Mock()
mock_response.text = JSON_SCHEMA_DATA_PATH.joinpath("pet_simple.json").read_text()
with patch("httpx.get", return_value=mock_response) as mock_get:
return_code = main([
"--url",
"https://api.example.com/schema.json",
"--output",
str(output_file),
"--input-file-type",
"jsonschema",
"--http-query-parameters",
"version=v2",
"format=json",
])
assert return_code == 0
# Verify query parameters were passed as list of tuples
mock_get.assert_called_once()
call_kwargs = mock_get.call_args[1]
assert "params" in call_kwargs
# params is a list of tuples: [("version", "v2"), ("format", "json")]
params = call_kwargs["params"]
assert ("version", "v2") in params
assert ("format", "json") in params
@pytest.mark.cli_doc(
options=["--http-timeout"],
option_description="""Set timeout for HTTP requests to remote hosts.
The `--http-timeout` flag sets the timeout in seconds for HTTP requests
when fetching schemas from URLs. Useful for slow servers or large schemas.
Default is 30 seconds.""",
input_schema="jsonschema/pet_simple.json",
cli_args=["--url", "https://api.example.com/schema.json", "--http-timeout", "60"],
golden_output="main_kr/url_with_headers/output.py",
)
@freeze_time("2019-07-26")
def test_http_timeout(output_file: Path) -> None:
"""Set timeout for HTTP requests to remote hosts.
The `--http-timeout` flag sets the timeout in seconds for HTTP requests
when fetching schemas from URLs. Useful for slow servers or large schemas.
Default is 30 seconds.
"""
mock_response = Mock()
mock_response.text = JSON_SCHEMA_DATA_PATH.joinpath("pet_simple.json").read_text()
with patch("httpx.get", return_value=mock_response) as mock_get:
return_code = main([
"--url",
"https://api.example.com/schema.json",
"--output",
str(output_file),
"--input-file-type",
"jsonschema",
"--http-timeout",
"60",
])
assert return_code == 0
# Verify that timeout=60 was passed to httpx.get
mock_get.assert_called_once()
call_kwargs = mock_get.call_args[1]
assert call_kwargs.get("timeout") == 60.0
@pytest.mark.cli_doc(
options=["--ignore-pyproject"],
option_description="""Ignore pyproject.toml configuration file.
The `--ignore-pyproject` flag tells datamodel-codegen to ignore any
[tool.datamodel-codegen] configuration in pyproject.toml. This is useful
when you want to override project defaults with CLI arguments, or when
testing without project configuration.""",
input_schema="jsonschema/ignore_pyproject_example.json",
cli_args=["--ignore-pyproject"],
golden_output="main_kr/ignore_pyproject/output.py",
comparison_output="main_kr/ignore_pyproject/without_option.py",
)
@freeze_time("2019-07-26")
def test_ignore_pyproject_cli_doc(output_file: Path, tmp_path: Path) -> None:
"""Ignore pyproject.toml configuration file.
The `--ignore-pyproject` flag tells datamodel-codegen to ignore any
[tool.datamodel-codegen] configuration in pyproject.toml. This is useful
when you want to override project defaults with CLI arguments, or when
testing without project configuration.
"""
# Create a pyproject.toml with snake-case-field to demonstrate ignoring
pyproject_toml = """
[tool.datamodel-codegen]
snake-case-field = true
"""
(tmp_path / "pyproject.toml").write_text(pyproject_toml)
input_data = """
{
"$schema": "http://json-schema.org/draft-07/schema#",
"type": "object",
"properties": {
"firstName": {"type": "string"},
"lastName": {"type": "string"}
}
}
"""
input_file = tmp_path / "schema.json"
input_file.write_text(input_data)
with chdir(tmp_path):
run_main_and_assert(
input_path=input_file,
output_path=output_file.resolve(),
assert_func=assert_file_content,
expected_file=EXPECTED_MAIN_KR_PATH / "ignore_pyproject" / "output.py",
extra_args=["--ignore-pyproject", "--disable-timestamp"],
)
@pytest.mark.cli_doc(
options=["--shared-module-name"],
option_description="""Customize the name of the shared module for deduplicated models.
The `--shared-module-name` flag sets the name of the shared module created
when using `--reuse-model` with `--reuse-scope=tree`. This module contains
deduplicated models that are referenced from multiple files. Default is
`shared`. Use this if your schema already has a file named `shared`.
Note: This option only affects modular output with tree-level model reuse.""",
input_schema="jsonschema/pet_simple.json",
cli_args=["--shared-module-name", "my_shared"],
golden_output="main_kr/input_output/output.py",
)
@freeze_time("2019-07-26")
def test_shared_module_name(output_file: Path) -> None:
"""Customize the name of the shared module for deduplicated models.
The `--shared-module-name` flag sets the name of the shared module created
when using `--reuse-model` with `--reuse-scope=tree`. This module contains
deduplicated models that are referenced from multiple files. Default is
`shared`. Use this if your schema already has a file named `shared`.
Note: This option only affects modular output with tree-level model reuse.
"""
# Simple test - the option is accepted but only affects modular output with reuse
run_main_and_assert(
input_path=JSON_SCHEMA_DATA_PATH / "pet_simple.json",
output_path=output_file,
input_file_type="jsonschema",
assert_func=assert_file_content,
expected_file=EXPECTED_MAIN_KR_PATH / "input_output" / "output.py",
extra_args=["--shared-module-name", "my_shared"],
)
@pytest.mark.cli_doc(
options=["--use-exact-imports"],
option_description="""Import exact types instead of modules.
The `--use-exact-imports` flag changes import style from module imports
to exact type imports. For example, instead of `from . import foo` then
`foo.Bar`, it generates `from .foo import Bar`. This can make the generated
code more explicit and easier to read.
Note: This option primarily affects modular output where imports between
modules are generated. For single-file output, the difference is minimal.""",
input_schema="jsonschema/pet_simple.json",
cli_args=["--use-exact-imports"],
golden_output="main_kr/input_output/output.py",
)
@freeze_time("2019-07-26")
def test_use_exact_imports(output_file: Path) -> None:
"""Import exact types instead of modules.
The `--use-exact-imports` flag changes import style from module imports
to exact type imports. For example, instead of `from . import foo` then
`foo.Bar`, it generates `from .foo import Bar`. This can make the generated
code more explicit and easier to read.
Note: This option primarily affects modular output where imports between
modules are generated. For single-file output, the difference is minimal.
"""
# Simple test - the option is accepted and works for single file output
run_main_and_assert(
input_path=JSON_SCHEMA_DATA_PATH / "pet_simple.json",
output_path=output_file,
input_file_type="jsonschema",
assert_func=assert_file_content,
expected_file=EXPECTED_MAIN_KR_PATH / "input_output" / "output.py",
extra_args=["--use-exact-imports"],
)
@pytest.mark.cli_doc(
options=["--target-python-version"],
option_description="""Target Python version for generated code syntax and imports.
The `--target-python-version` flag controls Python version-specific syntax:
- **Python 3.10-3.11**: Uses `X | None` union operator, `TypeAlias` annotation
- **Python 3.12+**: Uses `type` statement for type aliases
This affects import statements and type annotation syntax in generated code.""",
input_schema="jsonschema/person.json",
cli_args=["--target-python-version", "3.10", "--use-standard-collections"],
version_outputs={
"3.10": "main_kr/target_python_version/py310.py",
},
primary=True,
)
@freeze_time("2019-07-26")
def test_target_python_version_outputs(output_file: Path) -> None:
"""Target Python version for generated code syntax and imports.
The `--target-python-version` flag controls Python version-specific syntax:
- **Python 3.10-3.11**: Uses `X | None` union operator, `TypeAlias` annotation
- **Python 3.12+**: Uses `type` statement for type aliases
This affects import statements and type annotation syntax in generated code.
"""
# Test with Python 3.10 style
run_main_and_assert(
input_path=JSON_SCHEMA_DATA_PATH / "person.json",
output_path=output_file,
assert_func=assert_file_content,
expected_file=EXPECTED_MAIN_KR_PATH / "target_python_version" / "py310.py",
extra_args=["--target-python-version", "3.10", "--use-standard-collections"],
)
@pytest.mark.cli_doc(
options=["--target-pydantic-version"],
option_description="""Target Pydantic version for generated code compatibility.
The `--target-pydantic-version` flag controls Pydantic version-specific config:
- **2**: Uses `populate_by_name=True` (compatible with Pydantic 2.0-2.10)
- **2.11**: Uses `validate_by_name=True` (for Pydantic 2.11+)
This prevents breaking changes when generated code is used on older Pydantic versions.""",
input_schema="jsonschema/person.json",
cli_args=[
"--target-pydantic-version",
"2.11",
"--allow-population-by-field-name",
"--output-model-type",
"pydantic_v2.BaseModel",
],
golden_output="main_kr/target_pydantic_version/v2_11.py",
primary=True,
)
@freeze_time("2019-07-26")
def test_target_pydantic_version(output_file: Path) -> None:
"""Target Pydantic version for generated code compatibility.
The `--target-pydantic-version` flag controls Pydantic version-specific config:
- **2**: Uses `populate_by_name=True` (compatible with Pydantic 2.0-2.10)
- **2.11**: Uses `validate_by_name=True` (for Pydantic 2.11+)
This prevents breaking changes when generated code is used on older Pydantic versions.
"""
run_main_and_assert(
input_path=JSON_SCHEMA_DATA_PATH / "person.json",
output_path=output_file,
assert_func=assert_file_content,
expected_file=EXPECTED_MAIN_KR_PATH / "target_pydantic_version" / "v2_11.py",
extra_args=[
"--target-pydantic-version",
"2.11",
"--allow-population-by-field-name",
"--output-model-type",
"pydantic_v2.BaseModel",
],
)
def test_generate_prompt_basic(capsys: pytest.CaptureFixture[str]) -> None:
"""Generate a prompt for consulting LLMs about CLI options.
The `--generate-prompt` flag outputs a formatted prompt containing:
- Current CLI options
- Options organized by category with descriptions
- Full help text
This prompt can be copied to ChatGPT, Claude, or other LLMs to get
recommendations for appropriate CLI options.
"""
return_code = main(["--generate-prompt"])
assert return_code == Exit.OK
captured = capsys.readouterr()
# Verify structure
assert "# datamodel-code-generator CLI Options Consultation" in captured.out
assert "## Current CLI Options" in captured.out
assert "## Options by Category" in captured.out
assert "## All Available Options (Full Help)" in captured.out
assert "## Instructions" in captured.out
assert "(No options specified)" in captured.out
def test_generate_prompt_with_question(capsys: pytest.CaptureFixture[str]) -> None:
"""Test --generate-prompt with a question argument."""
question = "How do I convert enums to Literal types?"
return_code = main(["--generate-prompt", question])
assert return_code == Exit.OK
captured = capsys.readouterr()
assert "## Your Question" in captured.out
assert question in captured.out
def test_generate_prompt_with_options(capsys: pytest.CaptureFixture[str]) -> None:
"""Test --generate-prompt with other CLI options set."""
return_code = main([
"--input",
"schema.json",
"--output-model-type",
"pydantic_v2.BaseModel",
"--snake-case-field",
"--generate-prompt",
"What other options should I use?",
])
assert return_code == Exit.OK
captured = capsys.readouterr()
# Verify options are shown
assert "--input schema.json" in captured.out
assert "--output-model-type pydantic_v2.BaseModel" in captured.out
assert "--snake-case-field" in captured.out
assert "What other options should I use?" in captured.out
def test_generate_prompt_with_list_options(capsys: pytest.CaptureFixture[str]) -> None:
"""Test --generate-prompt with list options (e.g., --strict-types)."""
return_code = main([
"--strict-types",
"str",
"int",
"--generate-prompt",
])
assert return_code == Exit.OK
captured = capsys.readouterr()
# Verify list options are formatted correctly
assert "--strict-types str int" in captured.out
@freeze_time("2019-07-26")
def test_profile_extends_single_parent(output_file: Path, tmp_path: Path) -> None:
"""Test profile inheritance with single extends."""
pyproject_toml = """
[tool.datamodel-codegen]
target-python-version = "3.10"
enable-version-header = false
[tool.datamodel-codegen.profiles._base]
snake-case-field = true
[tool.datamodel-codegen.profiles.api]
extends = "_base"
"""
(tmp_path / "pyproject.toml").write_text(pyproject_toml)
input_data = '{"type": "object", "properties": {"firstName": {"type": "string"}}}'
input_file = tmp_path / "schema.json"
input_file.write_text(input_data)
with chdir(tmp_path):
run_main_and_assert(
input_path=input_file,
output_path=output_file.resolve(),
assert_func=assert_file_content,
expected_file=EXPECTED_PYPROJECT_PROFILE_PATH / "extends_single.py",
extra_args=["--profile", "api", "--disable-timestamp"],
)
@freeze_time("2019-07-26")
def test_profile_extends_multiple_parents(output_file: Path, tmp_path: Path) -> None:
"""Test profile inheritance with multiple extends (list)."""
pyproject_toml = """
[tool.datamodel-codegen]
target-python-version = "3.10"
enable-version-header = false
[tool.datamodel-codegen.profiles._snake]
snake-case-field = true
[tool.datamodel-codegen.profiles._constraints]
field-constraints = true
[tool.datamodel-codegen.profiles.api]
extends = ["_snake", "_constraints"]
"""
(tmp_path / "pyproject.toml").write_text(pyproject_toml)
input_data = '{"type": "object", "properties": {"firstName": {"type": "string", "minLength": 1}}}'
input_file = tmp_path / "schema.json"
input_file.write_text(input_data)
with chdir(tmp_path):
run_main_and_assert(
input_path=input_file,
output_path=output_file.resolve(),
assert_func=assert_file_content,
expected_file=EXPECTED_PYPROJECT_PROFILE_PATH / "extends_multiple.py",
extra_args=["--profile", "api", "--disable-timestamp"],
)
@freeze_time("2019-07-26")
def test_profile_extends_chain(output_file: Path, tmp_path: Path) -> None:
"""Test profile inheritance chain (a extends b extends c)."""
pyproject_toml = """
[tool.datamodel-codegen]
target-python-version = "3.10"
enable-version-header = false
[tool.datamodel-codegen.profiles._base]
snake-case-field = true
[tool.datamodel-codegen.profiles._middle]
extends = "_base"
field-constraints = true
[tool.datamodel-codegen.profiles.api]
extends = "_middle"
"""
(tmp_path / "pyproject.toml").write_text(pyproject_toml)
input_data = '{"type": "object", "properties": {"firstName": {"type": "string", "minLength": 1}}}'
input_file = tmp_path / "schema.json"
input_file.write_text(input_data)
with chdir(tmp_path):
run_main_and_assert(
input_path=input_file,
output_path=output_file.resolve(),
assert_func=assert_file_content,
expected_file=EXPECTED_PYPROJECT_PROFILE_PATH / "extends_chain.py",
extra_args=["--profile", "api", "--disable-timestamp"],
)
def test_profile_extends_circular_error(tmp_path: Path, capsys: pytest.CaptureFixture[str]) -> None:
"""Test error when circular extends is detected."""
pyproject_toml = """
[tool.datamodel-codegen]
[tool.datamodel-codegen.profiles.a]
extends = "b"
[tool.datamodel-codegen.profiles.b]
extends = "a"
"""
(tmp_path / "pyproject.toml").write_text(pyproject_toml)
input_file = tmp_path / "schema.json"
input_file.write_text('{"type": "object"}')
output_file = tmp_path / "output.py"
with chdir(tmp_path):
run_main_with_args(
["--input", str(input_file), "--output", str(output_file), "--profile", "a"],
expected_exit=Exit.ERROR,
)
assert_error_message(capsys, "Circular extends detected")
def test_profile_extends_not_found_error(tmp_path: Path, capsys: pytest.CaptureFixture[str]) -> None:
"""Test error when extended profile is not found."""
pyproject_toml = """
[tool.datamodel-codegen]
[tool.datamodel-codegen.profiles.api]
extends = "nonexistent"
"""
(tmp_path / "pyproject.toml").write_text(pyproject_toml)
input_file = tmp_path / "schema.json"
input_file.write_text('{"type": "object"}')
output_file = tmp_path / "output.py"
with chdir(tmp_path):
run_main_with_args(
["--input", str(input_file), "--output", str(output_file), "--profile", "api"],
expected_exit=Exit.ERROR,
)
assert_error_message(capsys, "Extended profile 'nonexistent' not found")
def test_profile_extends_self_error(tmp_path: Path, capsys: pytest.CaptureFixture[str]) -> None:
"""Test error when profile extends itself."""
pyproject_toml = """
[tool.datamodel-codegen]
[tool.datamodel-codegen.profiles.api]
extends = "api"
"""
(tmp_path / "pyproject.toml").write_text(pyproject_toml)
input_file = tmp_path / "schema.json"
input_file.write_text('{"type": "object"}')
output_file = tmp_path / "output.py"
with chdir(tmp_path):
run_main_with_args(
["--input", str(input_file), "--output", str(output_file), "--profile", "api"],
expected_exit=Exit.ERROR,
)
assert_error_message(capsys, "cannot extend itself")
@freeze_time("2019-07-26")
def test_profile_extends_child_overrides_parent(output_file: Path, tmp_path: Path) -> None:
"""Test that child profile settings override parent settings."""
pyproject_toml = """
[tool.datamodel-codegen]
target-python-version = "3.10"
enable-version-header = false
[tool.datamodel-codegen.profiles._base]
snake-case-field = true
[tool.datamodel-codegen.profiles.api]
extends = "_base"
snake-case-field = false
"""
(tmp_path / "pyproject.toml").write_text(pyproject_toml)
input_data = '{"type": "object", "properties": {"firstName": {"type": "string"}}}'
input_file = tmp_path / "schema.json"
input_file.write_text(input_data)
with chdir(tmp_path):
run_main_and_assert(
input_path=input_file,
output_path=output_file.resolve(),
assert_func=assert_file_content,
expected_file=EXPECTED_PYPROJECT_PROFILE_PATH / "extends_override.py",
extra_args=["--profile", "api", "--disable-timestamp"],
)
|