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
|
"""Tests for schema version detection and features."""
from __future__ import annotations
from pathlib import Path
import pytest
from inline_snapshot import snapshot
import datamodel_code_generator
from datamodel_code_generator.enums import JsonSchemaVersion, OpenAPIVersion, VersionMode
from datamodel_code_generator.parser.schema_version import (
JsonSchemaFeatures,
OpenAPISchemaFeatures,
detect_jsonschema_version,
detect_openapi_version,
)
# Path to test data
JSON_SCHEMA_DATA_PATH = Path(__file__).parent.parent / "data" / "jsonschema"
def test_detect_jsonschema_version_draft4() -> None:
"""Test detection of Draft 4 from $schema field."""
assert detect_jsonschema_version({"$schema": "http://json-schema.org/draft-04/schema#"}) == snapshot(
JsonSchemaVersion.Draft4
)
def test_detect_jsonschema_version_draft6() -> None:
"""Test detection of Draft 6 from $schema field."""
assert detect_jsonschema_version({"$schema": "http://json-schema.org/draft-06/schema#"}) == snapshot(
JsonSchemaVersion.Draft6
)
def test_detect_jsonschema_version_draft7() -> None:
"""Test detection of Draft 7 from $schema field."""
assert detect_jsonschema_version({"$schema": "http://json-schema.org/draft-07/schema#"}) == snapshot(
JsonSchemaVersion.Draft7
)
def test_detect_jsonschema_version_2019_09() -> None:
"""Test detection of Draft 2019-09 from $schema field."""
assert detect_jsonschema_version({"$schema": "https://json-schema.org/draft/2019-09/schema"}) == snapshot(
JsonSchemaVersion.Draft201909
)
def test_detect_jsonschema_version_2020_12() -> None:
"""Test detection of Draft 2020-12 from $schema field."""
assert detect_jsonschema_version({"$schema": "https://json-schema.org/draft/2020-12/schema"}) == snapshot(
JsonSchemaVersion.Draft202012
)
def test_detect_jsonschema_version_defs_heuristic() -> None:
"""Test detection using $defs heuristic.
$defs was introduced in Draft 2019-09, but Draft 2020-12 also uses it.
Since 2020-12 is a superset, default to 2020-12 to avoid false warnings.
"""
assert detect_jsonschema_version({"$defs": {"Foo": {"type": "string"}}}) == snapshot(JsonSchemaVersion.Draft202012)
def test_detect_jsonschema_version_definitions_heuristic() -> None:
"""Test detection using definitions heuristic."""
assert detect_jsonschema_version({"definitions": {"Foo": {"type": "string"}}}) == snapshot(JsonSchemaVersion.Draft7)
def test_detect_jsonschema_version_fallback() -> None:
"""Test fallback to Draft 7 when no indicators present."""
assert detect_jsonschema_version({"type": "object"}) == snapshot(JsonSchemaVersion.Draft7)
def test_detect_jsonschema_version_non_string_schema() -> None:
"""Test handling of non-string $schema value."""
assert detect_jsonschema_version({"$schema": 123}) == snapshot(JsonSchemaVersion.Draft7)
def test_detect_openapi_version_30() -> None:
"""Test detection of OpenAPI 3.0."""
assert detect_openapi_version({"openapi": "3.0.0"}) == snapshot(OpenAPIVersion.V30)
def test_detect_openapi_version_30_patch() -> None:
"""Test detection of OpenAPI 3.0.x."""
assert detect_openapi_version({"openapi": "3.0.3"}) == snapshot(OpenAPIVersion.V30)
def test_detect_openapi_version_31() -> None:
"""Test detection of OpenAPI 3.1."""
assert detect_openapi_version({"openapi": "3.1.0"}) == snapshot(OpenAPIVersion.V31)
def test_detect_openapi_version_fallback() -> None:
"""Test fallback to OpenAPI 3.1 when no version present."""
assert detect_openapi_version({"info": {"title": "Test"}}) == snapshot(OpenAPIVersion.V31)
def test_detect_openapi_version_non_string() -> None:
"""Test handling of non-string openapi value."""
assert detect_openapi_version({"openapi": 3.0}) == snapshot(OpenAPIVersion.V31)
def test_jsonschema_features_draft4() -> None:
"""Test Draft 4 features."""
assert JsonSchemaFeatures.from_version(JsonSchemaVersion.Draft4) == snapshot(
JsonSchemaFeatures(
null_in_type_array=False,
defs_not_definitions=False,
const_support=False,
property_names=False,
prefix_items=False,
boolean_schemas=False,
id_field="id",
definitions_key="definitions",
exclusive_as_number=False,
read_only_write_only=False,
recursive_ref=False,
dynamic_ref=False,
)
)
def test_jsonschema_features_draft6() -> None:
"""Test Draft 6 features."""
assert JsonSchemaFeatures.from_version(JsonSchemaVersion.Draft6) == snapshot(
JsonSchemaFeatures(
null_in_type_array=False,
defs_not_definitions=False,
prefix_items=False,
boolean_schemas=True,
id_field="$id",
definitions_key="definitions",
exclusive_as_number=True,
read_only_write_only=False,
recursive_ref=False,
dynamic_ref=False,
)
)
def test_jsonschema_features_draft7() -> None:
"""Test Draft 7 features."""
assert JsonSchemaFeatures.from_version(JsonSchemaVersion.Draft7) == snapshot(
JsonSchemaFeatures(
null_in_type_array=False,
defs_not_definitions=False,
prefix_items=False,
boolean_schemas=True,
id_field="$id",
definitions_key="definitions",
exclusive_as_number=True,
read_only_write_only=True,
recursive_ref=False,
dynamic_ref=False,
)
)
def test_jsonschema_features_2019_09() -> None:
"""Test Draft 2019-09 features."""
assert JsonSchemaFeatures.from_version(JsonSchemaVersion.Draft201909) == snapshot(
JsonSchemaFeatures(
null_in_type_array=False,
defs_not_definitions=True,
prefix_items=False,
boolean_schemas=True,
id_field="$id",
definitions_key="$defs",
exclusive_as_number=True,
read_only_write_only=True,
recursive_ref=True,
dynamic_ref=False,
)
)
def test_jsonschema_features_2020_12() -> None:
"""Test Draft 2020-12 features."""
assert JsonSchemaFeatures.from_version(JsonSchemaVersion.Draft202012) == snapshot(
JsonSchemaFeatures(
null_in_type_array=True,
defs_not_definitions=True,
prefix_items=True,
boolean_schemas=True,
id_field="$id",
definitions_key="$defs",
exclusive_as_number=True,
read_only_write_only=True,
recursive_ref=True,
dynamic_ref=True,
)
)
def test_jsonschema_features_auto() -> None:
"""Test Auto version defaults to latest features."""
assert JsonSchemaFeatures.from_version(JsonSchemaVersion.Auto) == snapshot(
JsonSchemaFeatures(
null_in_type_array=True,
defs_not_definitions=True,
prefix_items=True,
boolean_schemas=True,
id_field="$id",
definitions_key="$defs",
exclusive_as_number=True,
read_only_write_only=True,
recursive_ref=True,
dynamic_ref=True,
)
)
def test_jsonschema_features_frozen() -> None:
"""Test that features are immutable."""
features = JsonSchemaFeatures.from_version(JsonSchemaVersion.Draft7)
with pytest.raises(AttributeError):
features.null_in_type_array = True # type: ignore[misc]
def test_openapi_features_v30() -> None:
"""Test OpenAPI 3.0 features."""
assert OpenAPISchemaFeatures.from_openapi_version(OpenAPIVersion.V30) == snapshot(
OpenAPISchemaFeatures(
null_in_type_array=False,
defs_not_definitions=False,
prefix_items=False,
boolean_schemas=False,
id_field="$id",
definitions_key="definitions",
exclusive_as_number=False,
read_only_write_only=True,
recursive_ref=False,
dynamic_ref=False,
nullable_keyword=True,
discriminator_support=True,
)
)
def test_openapi_features_v31() -> None:
"""Test OpenAPI 3.1 features."""
assert OpenAPISchemaFeatures.from_openapi_version(OpenAPIVersion.V31) == snapshot(
OpenAPISchemaFeatures(
null_in_type_array=True,
defs_not_definitions=True,
prefix_items=True,
boolean_schemas=True,
id_field="$id",
definitions_key="$defs",
webhooks=True,
ref_sibling_keywords=True,
exclusive_as_number=True,
read_only_write_only=True,
recursive_ref=True,
dynamic_ref=True,
nullable_keyword=False,
discriminator_support=True,
)
)
def test_openapi_features_auto() -> None:
"""Test Auto version defaults to latest features."""
assert OpenAPISchemaFeatures.from_openapi_version(OpenAPIVersion.Auto) == snapshot(
OpenAPISchemaFeatures(
null_in_type_array=True,
defs_not_definitions=True,
prefix_items=True,
boolean_schemas=True,
id_field="$id",
definitions_key="$defs",
webhooks=True,
ref_sibling_keywords=True,
exclusive_as_number=True,
read_only_write_only=True,
recursive_ref=True,
dynamic_ref=True,
nullable_keyword=False,
discriminator_support=True,
)
)
def test_openapi_features_inherits_jsonschema() -> None:
"""Test that OpenAPISchemaFeatures inherits from JsonSchemaFeatures."""
features = OpenAPISchemaFeatures.from_openapi_version(OpenAPIVersion.V31)
assert isinstance(features, JsonSchemaFeatures)
assert features.prefix_items == snapshot(True)
def test_openapi_features_frozen() -> None:
"""Test that features are immutable."""
features = OpenAPISchemaFeatures.from_openapi_version(OpenAPIVersion.V30)
with pytest.raises(AttributeError):
features.nullable_keyword = False # type: ignore[misc]
def test_lazy_import_detect_jsonschema_version() -> None:
"""Test that detect_jsonschema_version can be imported from main module."""
detect_func = datamodel_code_generator.detect_jsonschema_version
assert detect_func({"$schema": "http://json-schema.org/draft-07/schema#"}) == snapshot(JsonSchemaVersion.Draft7)
def test_lazy_import_detect_openapi_version() -> None:
"""Test that detect_openapi_version can be imported from main module."""
detect_func = datamodel_code_generator.detect_openapi_version
assert detect_func({"openapi": "3.1.0"}) == snapshot(OpenAPIVersion.V31)
def test_lazy_import_jsonschema_version_enum() -> None:
"""Test that JsonSchemaVersion is exported from main module."""
assert datamodel_code_generator.JsonSchemaVersion is JsonSchemaVersion
def test_lazy_import_openapi_version_enum() -> None:
"""Test that OpenAPIVersion is exported from main module."""
assert datamodel_code_generator.OpenAPIVersion is OpenAPIVersion
def test_lazy_import_version_mode_enum() -> None:
"""Test that VersionMode is exported from main module."""
assert datamodel_code_generator.VersionMode is VersionMode
def test_get_data_formats_jsonschema() -> None:
"""Test that JsonSchema formats exclude OpenAPI-specific formats."""
from datamodel_code_generator.parser.schema_version import get_data_formats
from datamodel_code_generator.types import Types
assert get_data_formats(is_openapi=False) == snapshot({
"integer": {
"int32": Types.int32,
"int64": Types.int64,
"default": Types.integer,
"date-time": Types.date_time,
"unix-time": Types.int64,
"unixtime": Types.int64,
},
"number": {
"float": Types.float,
"double": Types.double,
"decimal": Types.decimal,
"date-time": Types.date_time,
"time": Types.time,
"time-delta": Types.timedelta,
"default": Types.number,
"unixtime": Types.int64,
},
"string": {
"default": Types.string,
"byte": Types.byte,
"date": Types.date,
"date-time": Types.date_time,
"timestamp with time zone": Types.date_time,
"date-time-local": Types.date_time_local,
"duration": Types.timedelta,
"time": Types.time,
"time-local": Types.time_local,
"path": Types.path,
"email": Types.email,
"idn-email": Types.email,
"uuid": Types.uuid,
"uuid1": Types.uuid1,
"uuid2": Types.uuid2,
"uuid3": Types.uuid3,
"uuid4": Types.uuid4,
"uuid5": Types.uuid5,
"uri": Types.uri,
"uri-reference": Types.string,
"hostname": Types.hostname,
"ipv4": Types.ipv4,
"ipv4-network": Types.ipv4_network,
"ipv6": Types.ipv6,
"ipv6-network": Types.ipv6_network,
"decimal": Types.decimal,
"integer": Types.integer,
"unixtime": Types.int64,
"ulid": Types.ulid,
},
"boolean": {"default": Types.boolean},
"object": {"default": Types.object},
"null": {"default": Types.null},
"array": {"default": Types.array},
})
def test_get_data_formats_openapi() -> None:
"""Test that OpenAPI formats include OpenAPI-specific formats."""
from datamodel_code_generator.parser.schema_version import get_data_formats
from datamodel_code_generator.types import Types
assert get_data_formats(is_openapi=True) == snapshot({
"integer": {
"int32": Types.int32,
"int64": Types.int64,
"default": Types.integer,
"date-time": Types.date_time,
"unix-time": Types.int64,
"unixtime": Types.int64,
},
"number": {
"float": Types.float,
"double": Types.double,
"decimal": Types.decimal,
"date-time": Types.date_time,
"time": Types.time,
"time-delta": Types.timedelta,
"default": Types.number,
"unixtime": Types.int64,
},
"string": {
"default": Types.string,
"byte": Types.byte,
"date": Types.date,
"date-time": Types.date_time,
"timestamp with time zone": Types.date_time,
"date-time-local": Types.date_time_local,
"duration": Types.timedelta,
"time": Types.time,
"time-local": Types.time_local,
"path": Types.path,
"email": Types.email,
"idn-email": Types.email,
"uuid": Types.uuid,
"uuid1": Types.uuid1,
"uuid2": Types.uuid2,
"uuid3": Types.uuid3,
"uuid4": Types.uuid4,
"uuid5": Types.uuid5,
"uri": Types.uri,
"uri-reference": Types.string,
"hostname": Types.hostname,
"ipv4": Types.ipv4,
"ipv4-network": Types.ipv4_network,
"ipv6": Types.ipv6,
"ipv6-network": Types.ipv6_network,
"decimal": Types.decimal,
"integer": Types.integer,
"unixtime": Types.int64,
"ulid": Types.ulid,
"binary": Types.binary,
"password": Types.password,
},
"boolean": {"default": Types.boolean},
"object": {"default": Types.object},
"null": {"default": Types.null},
"array": {"default": Types.array},
})
def test_jsonschema_parser_schema_features_detection() -> None:
"""Test that JsonSchemaParser detects schema version from $schema."""
from datamodel_code_generator.parser.jsonschema import JsonSchemaParser
parser = JsonSchemaParser("")
parser.raw_obj = {"$schema": "http://json-schema.org/draft-07/schema#"}
features = parser.schema_features
assert features.boolean_schemas == snapshot(True)
assert features.definitions_key == snapshot("definitions")
def test_openapi_parser_schema_features_detection() -> None:
"""Test that OpenAPIParser detects OpenAPI version from openapi field."""
from datamodel_code_generator.parser.openapi import OpenAPIParser
parser = OpenAPIParser("")
parser.raw_obj = {"openapi": "3.1.0"}
features = parser.schema_features
assert features.nullable_keyword == snapshot(False)
assert features.null_in_type_array == snapshot(True)
def test_jsonschema_parser_config_version_override() -> None:
"""Test that JsonSchemaParser uses config version over auto-detection."""
from datamodel_code_generator.parser.jsonschema import JsonSchemaParser
parser = JsonSchemaParser("", jsonschema_version=JsonSchemaVersion.Draft4)
parser.raw_obj = {"$schema": "http://json-schema.org/draft-07/schema#"}
features = parser.schema_features
assert features.id_field == snapshot("id")
assert features.boolean_schemas == snapshot(False)
def test_openapi_parser_config_version_override() -> None:
"""Test that OpenAPIParser uses config version over auto-detection."""
from datamodel_code_generator.parser.openapi import OpenAPIParser
parser = OpenAPIParser("", openapi_version=OpenAPIVersion.V30)
parser.raw_obj = {"openapi": "3.1.0"}
features = parser.schema_features
assert features.nullable_keyword == snapshot(True)
assert features.null_in_type_array == snapshot(False)
@pytest.mark.cli_doc(
options=["--schema-version"],
option_description="""Schema version to use for parsing.
The `--schema-version` option specifies the schema version to use instead of auto-detection.
Valid values depend on input type: JsonSchema (draft-04, draft-06, draft-07, 2019-09, 2020-12)
or OpenAPI (3.0, 3.1). Default is 'auto' (detected from $schema or openapi field).""",
input_schema="jsonschema/simple_string.json",
cli_args=["--schema-version", "draft-07"],
golden_output="jsonschema/simple_string.py",
)
def test_cli_schema_version_jsonschema() -> None:
"""Test --schema-version option with JSON Schema input."""
from datamodel_code_generator import generate
result = generate(
JSON_SCHEMA_DATA_PATH / "simple_string.json",
input_file_type=datamodel_code_generator.InputFileType.JsonSchema,
schema_version="draft-07",
)
assert result is not None
assert "class Model" in result or "Model" in result
@pytest.mark.cli_doc(
options=["--schema-version-mode"],
option_description="""Schema version validation mode.
The `--schema-version-mode` option controls how schema version validation is performed.
'lenient' (default): accept all features regardless of version.
'strict': warn on features outside the declared/detected version.""",
input_schema="jsonschema/simple_string.json",
cli_args=["--schema-version-mode", "lenient"],
golden_output="jsonschema/simple_string.py",
)
def test_cli_schema_version_mode() -> None:
"""Test --schema-version-mode option."""
from datamodel_code_generator import generate
result = generate(
JSON_SCHEMA_DATA_PATH / "simple_string.json",
input_file_type=datamodel_code_generator.InputFileType.JsonSchema,
schema_version_mode=VersionMode.Lenient,
)
assert result is not None
def test_schema_paths_lenient_mode_draft7() -> None:
"""Test schema_paths returns both paths in Lenient mode for Draft 7."""
from datamodel_code_generator.parser.jsonschema import JsonSchemaParser
parser = JsonSchemaParser("", jsonschema_version=JsonSchemaVersion.Draft7)
paths = parser.schema_paths
assert paths == snapshot([
("#/definitions", ["definitions"]),
("#/$defs", ["$defs"]),
])
def test_schema_paths_lenient_mode_2020_12() -> None:
"""Test schema_paths returns $defs first in Lenient mode for 2020-12."""
from datamodel_code_generator.parser.jsonschema import JsonSchemaParser
parser = JsonSchemaParser("", jsonschema_version=JsonSchemaVersion.Draft202012)
paths = parser.schema_paths
assert paths == snapshot([
("#/$defs", ["$defs"]),
("#/definitions", ["definitions"]),
])
def test_schema_paths_strict_mode_draft7() -> None:
"""Test schema_paths returns only definitions in Strict mode for Draft 7."""
from datamodel_code_generator.parser.jsonschema import JsonSchemaParser
parser = JsonSchemaParser(
"",
jsonschema_version=JsonSchemaVersion.Draft7,
schema_version_mode=VersionMode.Strict,
)
paths = parser.schema_paths
assert paths == snapshot([("#/definitions", ["definitions"])])
def test_schema_paths_strict_mode_2020_12() -> None:
"""Test schema_paths returns only $defs in Strict mode for 2020-12."""
from datamodel_code_generator.parser.jsonschema import JsonSchemaParser
parser = JsonSchemaParser(
"",
jsonschema_version=JsonSchemaVersion.Draft202012,
schema_version_mode=VersionMode.Strict,
)
paths = parser.schema_paths
assert paths == snapshot([("#/$defs", ["$defs"])])
def test_openapi_schema_paths_unchanged() -> None:
"""Test that OpenAPI schema_paths uses SCHEMA_PATHS regardless of version mode."""
from datamodel_code_generator.parser.openapi import OpenAPIParser
parser = OpenAPIParser(
"",
openapi_version=OpenAPIVersion.V31,
schema_version_mode=VersionMode.Strict,
)
paths = parser.schema_paths
assert paths == snapshot([("#/components/schemas", ["components", "schemas"])])
def test_nullable_keyword_openapi_31_strict_warning() -> None:
"""Test that nullable keyword emits warning in OpenAPI 3.1 Strict mode."""
import warnings
from datamodel_code_generator.parser.jsonschema import JsonSchemaObject
from datamodel_code_generator.parser.openapi import OpenAPIParser
parser = OpenAPIParser(
"",
openapi_version=OpenAPIVersion.V31,
schema_version_mode=VersionMode.Strict,
strict_nullable=True,
)
obj = JsonSchemaObject(type="string", nullable=True)
with warnings.catch_warnings(record=True) as w:
warnings.simplefilter("always")
parser.get_data_type(obj)
assert len(w) == 1
assert issubclass(w[0].category, DeprecationWarning)
assert "nullable keyword is deprecated" in str(w[0].message)
def test_nullable_keyword_openapi_30_no_warning() -> None:
"""Test that nullable keyword does NOT emit warning in OpenAPI 3.0."""
import warnings
from datamodel_code_generator.parser.jsonschema import JsonSchemaObject
from datamodel_code_generator.parser.openapi import OpenAPIParser
parser = OpenAPIParser(
"",
openapi_version=OpenAPIVersion.V30,
schema_version_mode=VersionMode.Strict,
strict_nullable=True,
)
obj = JsonSchemaObject(type="string", nullable=True)
with warnings.catch_warnings(record=True) as w:
warnings.simplefilter("always")
parser.get_data_type(obj)
deprecation_warnings = [x for x in w if issubclass(x.category, DeprecationWarning)]
assert len(deprecation_warnings) == 0
def test_nullable_keyword_openapi_31_lenient_no_warning() -> None:
"""Test that nullable keyword does NOT emit warning in OpenAPI 3.1 Lenient mode."""
import warnings
from datamodel_code_generator.parser.jsonschema import JsonSchemaObject
from datamodel_code_generator.parser.openapi import OpenAPIParser
parser = OpenAPIParser(
"",
openapi_version=OpenAPIVersion.V31,
schema_version_mode=VersionMode.Lenient,
strict_nullable=True,
)
obj = JsonSchemaObject(type="string", nullable=True)
with warnings.catch_warnings(record=True) as w:
warnings.simplefilter("always")
parser.get_data_type(obj)
deprecation_warnings = [x for x in w if issubclass(x.category, DeprecationWarning)]
assert len(deprecation_warnings) == 0
def test_null_in_type_array_strict_warning_draft7() -> None:
"""Test that null in type array emits warning in Draft 7 Strict mode."""
import warnings
from datamodel_code_generator.parser.jsonschema import JsonSchemaParser
parser = JsonSchemaParser(
"",
jsonschema_version=JsonSchemaVersion.Draft7,
schema_version_mode=VersionMode.Strict,
)
raw_schema = {"type": ["string", "null"]}
with warnings.catch_warnings(record=True) as w:
warnings.simplefilter("always")
parser._check_version_specific_features(raw_schema, ["test"])
user_warnings = [x for x in w if issubclass(x.category, UserWarning)]
assert len(user_warnings) == 1
assert "null in type array" in str(user_warnings[0].message)
def test_null_in_type_array_no_warning_2020_12() -> None:
"""Test that null in type array does NOT emit warning in Draft 2020-12."""
import warnings
from datamodel_code_generator.parser.jsonschema import JsonSchemaParser
parser = JsonSchemaParser(
"",
jsonschema_version=JsonSchemaVersion.Draft202012,
schema_version_mode=VersionMode.Strict,
)
raw_schema = {"type": ["string", "null"]}
with warnings.catch_warnings(record=True) as w:
warnings.simplefilter("always")
parser._check_version_specific_features(raw_schema, ["test"])
user_warnings = [x for x in w if issubclass(x.category, UserWarning)]
assert len(user_warnings) == 0
def test_exclusive_as_number_strict_warning_draft4() -> None:
"""Test that numeric exclusiveMinimum emits warning in Draft 4 Strict mode."""
import warnings
from datamodel_code_generator.parser.jsonschema import JsonSchemaParser
parser = JsonSchemaParser(
"",
jsonschema_version=JsonSchemaVersion.Draft4,
schema_version_mode=VersionMode.Strict,
)
raw_schema = {"type": "number", "exclusiveMinimum": 5}
with warnings.catch_warnings(record=True) as w:
warnings.simplefilter("always")
parser._check_version_specific_features(raw_schema, ["test"])
user_warnings = [x for x in w if issubclass(x.category, UserWarning)]
assert len(user_warnings) == 1
assert "exclusiveMinimum as number" in str(user_warnings[0].message)
def test_exclusive_as_bool_strict_warning_draft7() -> None:
"""Test that boolean exclusiveMinimum emits warning in Draft 7 Strict mode."""
import warnings
from datamodel_code_generator.parser.jsonschema import JsonSchemaParser
parser = JsonSchemaParser(
"",
jsonschema_version=JsonSchemaVersion.Draft7,
schema_version_mode=VersionMode.Strict,
)
raw_schema = {"type": "number", "minimum": 5, "exclusiveMinimum": True}
with warnings.catch_warnings(record=True) as w:
warnings.simplefilter("always")
parser._check_version_specific_features(raw_schema, ["test"])
user_warnings = [x for x in w if issubclass(x.category, UserWarning)]
assert len(user_warnings) == 1
assert "exclusiveMinimum as boolean" in str(user_warnings[0].message)
def test_prefix_items_strict_warning_draft7() -> None:
"""Test that prefixItems emits warning in Draft 7 Strict mode."""
import warnings
from datamodel_code_generator.parser.jsonschema import JsonSchemaObject, JsonSchemaParser
parser = JsonSchemaParser(
"",
jsonschema_version=JsonSchemaVersion.Draft7,
schema_version_mode=VersionMode.Strict,
)
obj = JsonSchemaObject(
type="array",
prefixItems=[JsonSchemaObject(type="string"), JsonSchemaObject(type="number")],
)
with warnings.catch_warnings(record=True) as w:
warnings.simplefilter("always")
parser._check_array_version_features(obj, ["test"])
user_warnings = [x for x in w if issubclass(x.category, UserWarning)]
assert len(user_warnings) == 1
assert "prefixItems is not supported" in str(user_warnings[0].message)
def test_items_array_strict_warning_2020_12() -> None:
"""Test that items as array emits warning in Draft 2020-12 Strict mode."""
import warnings
from datamodel_code_generator.parser.jsonschema import JsonSchemaObject, JsonSchemaParser
parser = JsonSchemaParser(
"",
jsonschema_version=JsonSchemaVersion.Draft202012,
schema_version_mode=VersionMode.Strict,
)
obj = JsonSchemaObject(
type="array",
items=[JsonSchemaObject(type="string"), JsonSchemaObject(type="number")],
)
with warnings.catch_warnings(record=True) as w:
warnings.simplefilter("always")
parser._check_array_version_features(obj, ["test"])
user_warnings = [x for x in w if issubclass(x.category, UserWarning)]
assert len(user_warnings) == 1
assert "items as array" in str(user_warnings[0].message)
def test_boolean_schema_strict_warning_draft4() -> None:
"""Test that boolean schema emits warning in Draft 4 Strict mode."""
import warnings
from datamodel_code_generator.parser.jsonschema import JsonSchemaParser
parser = JsonSchemaParser(
"",
jsonschema_version=JsonSchemaVersion.Draft4,
schema_version_mode=VersionMode.Strict,
)
with warnings.catch_warnings(record=True) as w:
warnings.simplefilter("always")
parser._check_version_specific_features(True, ["test"])
user_warnings = [x for x in w if issubclass(x.category, UserWarning)]
assert len(user_warnings) == 1
assert "Boolean schemas" in str(user_warnings[0].message)
def test_boolean_schema_no_warning_draft7() -> None:
"""Test that boolean schema does NOT emit warning in Draft 7."""
import warnings
from datamodel_code_generator.parser.jsonschema import JsonSchemaParser
parser = JsonSchemaParser(
"",
jsonschema_version=JsonSchemaVersion.Draft7,
schema_version_mode=VersionMode.Strict,
)
with warnings.catch_warnings(record=True) as w:
warnings.simplefilter("always")
parser._check_version_specific_features(True, ["test"])
user_warnings = [x for x in w if issubclass(x.category, UserWarning)]
assert len(user_warnings) == 0
def test_read_only_strict_warning_draft6() -> None:
"""Test that readOnly emits warning in Draft 6 Strict mode."""
import warnings
from datamodel_code_generator.parser.jsonschema import JsonSchemaParser
parser = JsonSchemaParser(
"",
jsonschema_version=JsonSchemaVersion.Draft6,
schema_version_mode=VersionMode.Strict,
)
raw_schema = {"type": "string", "readOnly": True}
with warnings.catch_warnings(record=True) as w:
warnings.simplefilter("always")
parser._check_version_specific_features(raw_schema, ["test"])
user_warnings = [x for x in w if issubclass(x.category, UserWarning)]
assert len(user_warnings) == 1
assert "readOnly is not supported" in str(user_warnings[0].message)
def test_write_only_strict_warning_draft4() -> None:
"""Test that writeOnly emits warning in Draft 4 Strict mode."""
import warnings
from datamodel_code_generator.parser.jsonschema import JsonSchemaParser
parser = JsonSchemaParser(
"",
jsonschema_version=JsonSchemaVersion.Draft4,
schema_version_mode=VersionMode.Strict,
)
raw_schema = {"type": "string", "writeOnly": True}
with warnings.catch_warnings(record=True) as w:
warnings.simplefilter("always")
parser._check_version_specific_features(raw_schema, ["test"])
user_warnings = [x for x in w if issubclass(x.category, UserWarning)]
assert len(user_warnings) == 1
assert "writeOnly is not supported" in str(user_warnings[0].message)
def test_read_only_no_warning_draft7() -> None:
"""Test that readOnly does NOT emit warning in Draft 7."""
import warnings
from datamodel_code_generator.parser.jsonschema import JsonSchemaParser
parser = JsonSchemaParser(
"",
jsonschema_version=JsonSchemaVersion.Draft7,
schema_version_mode=VersionMode.Strict,
)
raw_schema = {"type": "string", "readOnly": True}
with warnings.catch_warnings(record=True) as w:
warnings.simplefilter("always")
parser._check_version_specific_features(raw_schema, ["test"])
user_warnings = [x for x in w if issubclass(x.category, UserWarning)]
assert len(user_warnings) == 0
def test_write_only_no_warning_openapi_30() -> None:
"""Test that writeOnly does NOT emit warning in OpenAPI 3.0."""
import warnings
from datamodel_code_generator.parser.openapi import OpenAPIParser
parser = OpenAPIParser(
"",
openapi_version=OpenAPIVersion.V30,
schema_version_mode=VersionMode.Strict,
)
raw_schema = {"type": "string", "writeOnly": True}
with warnings.catch_warnings(record=True) as w:
warnings.simplefilter("always")
parser._check_version_specific_features(raw_schema, ["test"])
user_warnings = [x for x in w if issubclass(x.category, UserWarning)]
assert len(user_warnings) == 0
def test_version_checks_lenient_no_warnings() -> None:
"""Test that version checks do NOT emit warnings in Lenient mode."""
import warnings
from datamodel_code_generator.parser.jsonschema import JsonSchemaParser
parser = JsonSchemaParser(
"",
jsonschema_version=JsonSchemaVersion.Draft4,
schema_version_mode=VersionMode.Lenient,
)
raw_schema = {"type": ["string", "null"], "exclusiveMinimum": 5}
with warnings.catch_warnings(record=True) as w:
warnings.simplefilter("always")
parser._check_version_specific_features(raw_schema, ["test"])
parser._check_version_specific_features(True, ["test"])
user_warnings = [x for x in w if issubclass(x.category, UserWarning)]
assert len(user_warnings) == 0
# =============================================================================
# Parameterized E2E tests for --schema-version and --schema-version-mode
# =============================================================================
OPENAPI_DATA_PATH = Path(__file__).parent.parent / "data" / "openapi"
@pytest.mark.parametrize(
"schema_version",
["draft-04", "draft-06", "draft-07", "2019-09", "2020-12"],
ids=["draft-04", "draft-06", "draft-07", "2019-09", "2020-12"],
)
@pytest.mark.cli_doc(
options=["--schema-version"],
option_description="""Schema version to use for parsing JSON Schema.
The `--schema-version` option specifies the JSON Schema version to use instead of auto-detection.
Valid values: draft-04, draft-06, draft-07, 2019-09, 2020-12.
Default is 'auto' (detected from $schema field).""",
input_schema="jsonschema/simple_string.json",
cli_args=["--schema-version", "draft-07"],
golden_output="jsonschema/simple_string.py",
)
def test_cli_schema_version_jsonschema_parametrized(schema_version: str) -> None:
"""Test --schema-version option with different JSON Schema versions."""
from datamodel_code_generator import generate
result = generate(
JSON_SCHEMA_DATA_PATH / "simple_string.json",
input_file_type=datamodel_code_generator.InputFileType.JsonSchema,
schema_version=schema_version,
disable_timestamp=True,
)
assert result is not None
assert "class Model" in result
assert result == snapshot(
"""\
# generated by datamodel-codegen:
# filename: simple_string.json
from __future__ import annotations
from pydantic import BaseModel
class Model(BaseModel):
s: str"""
)
@pytest.mark.parametrize(
"openapi_version",
["3.0", "3.1"],
ids=["openapi-3.0", "openapi-3.1"],
)
@pytest.mark.cli_doc(
options=["--schema-version"],
option_description="""Schema version to use for parsing OpenAPI.
The `--schema-version` option specifies the OpenAPI version to use instead of auto-detection.
Valid values: 3.0, 3.1.
Default is 'auto' (detected from openapi field).""",
input_schema="openapi/api.yaml",
cli_args=["--schema-version", "3.0"],
golden_output="openapi/api.py",
)
def test_cli_schema_version_openapi_parametrized(openapi_version: str) -> None:
"""Test --schema-version option with different OpenAPI versions."""
from datamodel_code_generator import generate
result = generate(
OPENAPI_DATA_PATH / "api.yaml",
input_file_type=datamodel_code_generator.InputFileType.OpenAPI,
schema_version=openapi_version,
disable_timestamp=True,
)
assert result is not None
assert "Pet" in result or "Pets" in result
@pytest.mark.parametrize(
"version_mode",
[VersionMode.Lenient, VersionMode.Strict],
ids=["lenient", "strict"],
)
@pytest.mark.cli_doc(
options=["--schema-version-mode"],
option_description="""Schema version validation mode.
The `--schema-version-mode` option controls how schema version validation is performed.
'lenient' (default): accept all features regardless of version.
'strict': warn on features outside the declared/detected version.""",
input_schema="jsonschema/simple_string.json",
cli_args=["--schema-version-mode", "lenient"],
golden_output="jsonschema/simple_string.py",
)
def test_cli_schema_version_mode_parametrized(version_mode: VersionMode) -> None:
"""Test --schema-version-mode option with different modes."""
from datamodel_code_generator import generate
result = generate(
JSON_SCHEMA_DATA_PATH / "simple_string.json",
input_file_type=datamodel_code_generator.InputFileType.JsonSchema,
schema_version_mode=version_mode,
disable_timestamp=True,
)
assert result is not None
assert "class Model" in result
assert result == snapshot(
"""\
# generated by datamodel-codegen:
# filename: simple_string.json
from __future__ import annotations
from pydantic import BaseModel
class Model(BaseModel):
s: str"""
)
# =============================================================================
# Error handling tests for invalid schema versions
# =============================================================================
def test_invalid_jsonschema_version_error() -> None:
"""Test that invalid JSON Schema version raises Error."""
from datamodel_code_generator import Error, generate
with pytest.raises(Error) as exc_info:
generate(
JSON_SCHEMA_DATA_PATH / "simple_string.json",
input_file_type=datamodel_code_generator.InputFileType.JsonSchema,
schema_version="invalid-version",
)
assert "Invalid JSON Schema version" in str(exc_info.value)
assert "invalid-version" in str(exc_info.value)
def test_invalid_openapi_version_error() -> None:
"""Test that invalid OpenAPI version raises Error."""
from datamodel_code_generator import Error, generate
with pytest.raises(Error) as exc_info:
generate(
OPENAPI_DATA_PATH / "api.yaml",
input_file_type=datamodel_code_generator.InputFileType.OpenAPI,
schema_version="invalid-version",
)
assert "Invalid OpenAPI version" in str(exc_info.value)
assert "invalid-version" in str(exc_info.value)
def test_graphql_schema_version_not_supported() -> None:
"""Test that --schema-version is not supported for GraphQL."""
from datamodel_code_generator import Error, generate
graphql_data_path = Path(__file__).parent.parent / "data" / "graphql"
with pytest.raises(Error) as exc_info:
generate(
graphql_data_path / "schema.graphql",
input_file_type=datamodel_code_generator.InputFileType.GraphQL,
schema_version="draft-07",
)
assert "--schema-version is not supported" in str(exc_info.value)
assert "graphql" in str(exc_info.value).lower()
# =============================================================================
# E2E tests for strict mode warnings
# =============================================================================
def test_e2e_exclusive_maximum_as_bool_strict_warning_draft7() -> None:
"""Test that boolean exclusiveMaximum emits warning in Draft 7 Strict mode via generate()."""
import json
import tempfile
import warnings
from datamodel_code_generator import generate
# Draft 4 style schema with boolean exclusiveMaximum in definitions
schema = {
"type": "object",
"definitions": {
"MyValue": {
"type": "number",
"maximum": 10,
"exclusiveMaximum": True,
}
},
"properties": {"value": {"$ref": "#/definitions/MyValue"}},
}
with tempfile.NamedTemporaryFile(encoding="utf-8", mode="w", suffix=".json", delete=False) as f:
json.dump(schema, f)
f.flush()
with warnings.catch_warnings(record=True) as w:
warnings.simplefilter("always")
result = generate(
Path(f.name),
input_file_type=datamodel_code_generator.InputFileType.JsonSchema,
schema_version="draft-07",
schema_version_mode=VersionMode.Strict,
)
user_warnings = [x for x in w if issubclass(x.category, UserWarning)]
assert any("exclusiveMaximum as boolean" in str(uw.message) for uw in user_warnings)
assert result is not None
def test_e2e_exclusive_maximum_as_number_strict_warning_draft4() -> None:
"""Test that numeric exclusiveMaximum emits warning in Draft 4 Strict mode via generate()."""
import json
import tempfile
import warnings
from datamodel_code_generator import generate
# Draft 6+ style schema with numeric exclusiveMaximum in definitions
schema = {
"type": "object",
"definitions": {
"MyValue": {
"type": "number",
"exclusiveMaximum": 10,
}
},
"properties": {"value": {"$ref": "#/definitions/MyValue"}},
}
with tempfile.NamedTemporaryFile(encoding="utf-8", mode="w", suffix=".json", delete=False) as f:
json.dump(schema, f)
f.flush()
with warnings.catch_warnings(record=True) as w:
warnings.simplefilter("always")
result = generate(
Path(f.name),
input_file_type=datamodel_code_generator.InputFileType.JsonSchema,
schema_version="draft-04",
schema_version_mode=VersionMode.Strict,
)
user_warnings = [x for x in w if issubclass(x.category, UserWarning)]
assert any("exclusiveMaximum as number" in str(uw.message) for uw in user_warnings)
assert result is not None
|