-
-
Notifications
You must be signed in to change notification settings - Fork 435
Expand file tree
/
Copy pathtest_main_jsonschema.py
More file actions
9516 lines (8289 loc) · 354 KB
/
test_main_jsonschema.py
File metadata and controls
9516 lines (8289 loc) · 354 KB
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
"""Tests for JSON Schema input file code generation."""
from __future__ import annotations
import itertools
import json
import os
import tempfile
from collections import defaultdict
from pathlib import Path
from typing import TYPE_CHECKING
from unittest.mock import call
import black
import pytest
from packaging import version
from datamodel_code_generator import (
MIN_VERSION,
DataModelType,
Error,
InputFileType,
PythonVersion,
PythonVersionMin,
TargetPydanticVersion,
chdir,
generate,
)
from datamodel_code_generator.__main__ import Exit, main
from datamodel_code_generator.format import is_supported_in_black
from datamodel_code_generator.model import base as model_base
from tests.conftest import assert_directory_content, freeze_time, validate_generated_code
from tests.main.conftest import (
ALIASES_DATA_PATH,
BLACK_PY313_SKIP,
DATA_PATH,
DEFAULT_VALUES_DATA_PATH,
EXPECTED_MAIN_PATH,
JSON_SCHEMA_DATA_PATH,
LEGACY_BLACK_SKIP,
MSGSPEC_LEGACY_BLACK_SKIP,
TIMESTAMP,
run_generate_file_and_assert,
run_main_and_assert,
run_main_url_and_assert,
run_main_with_args,
)
from tests.main.jsonschema.conftest import EXPECTED_JSON_SCHEMA_PATH, assert_file_content
if TYPE_CHECKING:
from pytest_mock import MockerFixture
FixtureRequest = pytest.FixtureRequest
def assert_run_main_with_args_error(args: list[str], capsys: pytest.CaptureFixture[str], expected_error: str) -> None:
"""Assert that running the CLI exits with code 2 and emits the expected error."""
with pytest.raises(SystemExit) as exc_info:
run_main_with_args(args)
assert exc_info.value.code == 2
captured = capsys.readouterr()
assert expected_error in captured.err
def _install_test_my_app(base_dir: Path, monkeypatch: pytest.MonkeyPatch) -> None:
package_dir = base_dir / "my_app"
package_dir.mkdir()
(package_dir / "__init__.py").write_text(
"""from typing import Literal
from pydantic import BaseModel
class AliasA(BaseModel):
type: Literal["a"] = "a"
class B(BaseModel):
type: Literal["b"] = "b"
""",
encoding="utf-8",
)
monkeypatch.syspath_prepend(str(base_dir))
@pytest.mark.benchmark
def test_main_inheritance_forward_ref(output_file: Path, tmp_path: Path) -> None:
"""Test inheritance with forward references."""
run_main_and_assert(
input_path=JSON_SCHEMA_DATA_PATH / "inheritance_forward_ref.json",
output_path=output_file,
input_file_type=None,
assert_func=assert_file_content,
copy_files=[(DATA_PATH / "pyproject.toml", tmp_path / "pyproject.toml")],
)
@pytest.mark.benchmark
@pytest.mark.cli_doc(
options=["--keep-model-order"],
option_description="""Keep model definition order as specified in schema.
The `--keep-model-order` flag preserves the original definition order from the schema
instead of reordering models based on dependencies. This is useful when the order
of model definitions matters for documentation or readability.""",
input_schema="jsonschema/inheritance_forward_ref.json",
cli_args=["--keep-model-order"],
golden_output="jsonschema/inheritance_forward_ref_keep_model_order.py",
related_options=["--collapse-root-models"],
)
def test_main_inheritance_forward_ref_keep_model_order(output_file: Path, tmp_path: Path) -> None:
"""Keep model definition order as specified in schema.
The `--keep-model-order` flag preserves the original definition order from the schema
instead of reordering models based on dependencies. This is useful when the order
of model definitions matters for documentation or readability.
"""
run_main_and_assert(
input_path=JSON_SCHEMA_DATA_PATH / "inheritance_forward_ref.json",
output_path=output_file,
input_file_type=None,
assert_func=assert_file_content,
extra_args=["--keep-model-order"],
copy_files=[(DATA_PATH / "pyproject.toml", tmp_path / "pyproject.toml")],
)
@pytest.mark.benchmark
def test_main_type_alias_forward_ref_keep_model_order(output_file: Path) -> None:
"""Test TypeAliasType with forward references keeping model order."""
run_main_and_assert(
input_path=JSON_SCHEMA_DATA_PATH / "type_alias_forward_ref.json",
output_path=output_file,
input_file_type=None,
assert_func=assert_file_content,
extra_args=[
"--keep-model-order",
"--output-model-type",
"typing.TypedDict",
"--use-standard-collections",
"--use-union-operator",
"--use-type-alias",
"--target-python-version",
"3.10",
],
)
@pytest.mark.benchmark
def test_main_type_alias_cycle_keep_model_order(output_file: Path) -> None:
"""Test TypeAlias cycle ordering with keep_model_order."""
run_main_and_assert(
input_path=JSON_SCHEMA_DATA_PATH / "type_alias_cycle.json",
output_path=output_file,
input_file_type=None,
assert_func=assert_file_content,
extra_args=[
"--keep-model-order",
"--output-model-type",
"typing.TypedDict",
"--use-standard-collections",
"--use-union-operator",
"--use-type-alias",
"--target-python-version",
"3.10",
],
)
@pytest.mark.cli_doc(
options=["--disable-future-imports"],
option_description="""Prevent automatic addition of __future__ imports in generated code.
The --disable-future-imports option stops the generator from adding
'from __future__ import annotations' to the output. This is useful when
you need compatibility with tools or environments that don't support
postponed evaluation of annotations (PEP 563).""",
input_schema="jsonschema/keep_model_order_field_references.json",
cli_args=["--disable-future-imports", "--target-python-version", "3.10"],
golden_output="main/jsonschema/keep_model_order_field_references.py",
)
@pytest.mark.benchmark
def test_main_keep_model_order_field_references(output_file: Path) -> None:
"""Prevent automatic addition of __future__ imports in generated code.
The --disable-future-imports option stops the generator from adding
'from __future__ import annotations' to the output. This is useful when
you need compatibility with tools or environments that don't support
postponed evaluation of annotations (PEP 563).
"""
run_main_and_assert(
input_path=JSON_SCHEMA_DATA_PATH / "keep_model_order_field_references.json",
output_path=output_file,
input_file_type=None,
assert_func=assert_file_content,
extra_args=[
"--keep-model-order",
"--disable-future-imports",
"--target-python-version",
"3.10",
],
)
@pytest.mark.parametrize(
("target_python_version", "keep_model_order", "disable_future_imports"),
[
("3.10", False, False),
("3.10", False, True),
("3.10", True, False),
("3.10", True, True),
("3.11", True, False),
("3.11", True, True),
("3.12", True, False),
("3.12", True, True),
("3.13", True, False),
("3.13", True, True),
("3.14", True, False),
("3.14", True, True),
],
)
def test_main_keep_model_order_matrix_keep_model_order_field_references(
output_file: Path,
target_python_version: str,
keep_model_order: bool,
disable_future_imports: bool,
) -> None:
"""E2E matrix for keep_model_order vs deferred annotations.
When deferred annotations are enabled (default), field references should not
force reordering (to avoid meaningless churn). When disabled, ordering must
satisfy runtime dependency requirements.
"""
target_version = PythonVersion(target_python_version)
if not is_supported_in_black(target_version):
pytest.skip(f"Installed black ({black.__version__}) doesn't support Python {target_python_version}")
args = [
"--input",
str(JSON_SCHEMA_DATA_PATH / "keep_model_order_field_references.json"),
"--output",
str(output_file),
"--input-file-type",
"jsonschema",
"--target-python-version",
target_python_version,
"--formatters",
"isort",
]
if keep_model_order:
args.append("--keep-model-order")
if disable_future_imports:
args.append("--disable-future-imports")
run_main_with_args(args)
code = output_file.read_text(encoding="utf-8")
compile(code, str(output_file), "exec")
if not keep_model_order:
return
metadata_index = code.index("class Metadata")
description_type_index = code.index("class DescriptionType")
use_deferred_annotations_for_target = target_version.has_native_deferred_annotations or not disable_future_imports
if use_deferred_annotations_for_target:
assert description_type_index < metadata_index
else:
assert metadata_index < description_type_index
# For targets without native deferred annotations, validate runtime safety
# under the current interpreter by executing the generated module.
if not target_version.has_native_deferred_annotations:
exec(compile(code, str(output_file), "exec"), {})
@pytest.mark.cli_doc(
options=["--target-python-version"],
option_description="""Target Python version for generated code syntax and imports.
The `--target-python-version` flag configures the code generation behavior.""",
input_schema="jsonschema/pydantic_v2_model_rebuild_inheritance.json",
cli_args=["--output-model-type", "pydantic_v2.BaseModel", "--keep-model-order", "--target-python-version", "3.10"],
golden_output="jsonschema/pydantic_v2_model_rebuild_inheritance.py",
)
@pytest.mark.benchmark
def test_main_pydantic_v2_model_rebuild_inheritance(output_file: Path) -> None:
"""Target Python version for generated code syntax and imports.
The `--target-python-version` flag configures the code generation behavior.
"""
run_main_and_assert(
input_path=JSON_SCHEMA_DATA_PATH / "pydantic_v2_model_rebuild_inheritance.json",
output_path=output_file,
input_file_type=None,
assert_func=assert_file_content,
extra_args=[
"--output-model-type",
"pydantic_v2.BaseModel",
"--keep-model-order",
"--target-python-version",
"3.10",
],
)
@pytest.mark.benchmark
def test_main_autodetect(output_file: Path) -> None:
"""Test automatic input file type detection."""
run_main_and_assert(
input_path=JSON_SCHEMA_DATA_PATH / "person.json",
output_path=output_file,
input_file_type="auto",
assert_func=assert_file_content,
)
def test_main_autodetect_failed(tmp_path: Path) -> None:
"""Test autodetect failure with invalid input."""
input_file: Path = tmp_path / "input.yaml"
output_file: Path = tmp_path / "output.py"
input_file.write_text(":", encoding="utf-8")
run_main_and_assert(
input_path=input_file,
output_path=output_file,
input_file_type="auto",
expected_exit=Exit.ERROR,
)
def test_main_jsonschema(output_file: Path) -> None:
"""Test JSON Schema file code generation."""
run_main_and_assert(
input_path=JSON_SCHEMA_DATA_PATH / "person.json",
output_path=output_file,
input_file_type="jsonschema",
assert_func=assert_file_content,
expected_file="general.py",
)
@pytest.mark.cli_doc(
options=["--keyword-only"],
option_description="""Generate dataclass fields as keyword-only arguments.
The `--keyword-only` flag generates all dataclass fields as keyword-only,
requiring explicit parameter names when instantiating models. Combined with
`--frozen-dataclasses`, creates immutable models with keyword-only constructors.""",
input_schema="jsonschema/person.json",
cli_args=["--output-model-type", "dataclasses.dataclass", "--frozen-dataclasses", "--keyword-only"],
golden_output="main/jsonschema/general_dataclass_frozen_kw_only.py",
related_options=["--frozen-dataclasses", "--output-model-type"],
)
def test_main_jsonschema_dataclass_frozen_keyword_only(output_file: Path) -> None:
"""Generate dataclass fields as keyword-only arguments.
The `--keyword-only` flag generates all dataclass fields as keyword-only,
requiring explicit parameter names when instantiating models. Combined with
`--frozen-dataclasses`, creates immutable models with keyword-only constructors.
"""
run_main_and_assert(
input_path=JSON_SCHEMA_DATA_PATH / "person.json",
output_path=output_file,
input_file_type="jsonschema",
assert_func=assert_file_content,
expected_file="general_dataclass_frozen_kw_only.py",
extra_args=[
"--output-model-type",
"dataclasses.dataclass",
"--frozen-dataclasses",
"--keyword-only",
"--target-python-version",
"3.10",
],
)
@pytest.mark.benchmark
def test_main_jsonschema_nested_deep(tmp_path: Path) -> None:
"""Test deeply nested JSON Schema generation."""
run_main_and_assert(
input_path=JSON_SCHEMA_DATA_PATH / "nested_person.json",
output_path=tmp_path,
output_to_expected=[
("__init__.py", EXPECTED_JSON_SCHEMA_PATH / "nested_deep" / "__init__.py"),
("nested/deep.py", EXPECTED_JSON_SCHEMA_PATH / "nested_deep" / "nested" / "deep.py"),
(
"empty_parent/nested/deep.py",
EXPECTED_JSON_SCHEMA_PATH / "nested_deep" / "empty_parent" / "nested" / "deep.py",
),
],
assert_func=assert_file_content,
input_file_type="jsonschema",
)
def test_main_jsonschema_nested_skip(output_dir: Path) -> None:
"""Test nested JSON Schema with skipped items."""
run_main_and_assert(
input_path=JSON_SCHEMA_DATA_PATH / "nested_skip.json",
output_path=output_dir,
expected_directory=EXPECTED_JSON_SCHEMA_PATH / "nested_skip",
input_file_type="jsonschema",
)
@pytest.mark.benchmark
def test_main_jsonschema_external_files(output_file: Path) -> None:
"""Test JSON Schema with external file references."""
run_main_and_assert(
input_path=JSON_SCHEMA_DATA_PATH / "external_parent_root.json",
output_path=output_file,
input_file_type="jsonschema",
assert_func=assert_file_content,
expected_file="external_files.py",
)
@pytest.mark.benchmark
def test_main_jsonschema_collapsed_external_references(tmp_path: Path) -> None:
"""Test collapsed external references in JSON Schema."""
run_main_and_assert(
input_path=JSON_SCHEMA_DATA_PATH / "external_reference",
output_path=tmp_path,
output_to_expected=[
("ref0.py", "external_ref0.py"),
("other/ref2.py", EXPECTED_JSON_SCHEMA_PATH / "external_other_ref2.py"),
],
assert_func=assert_file_content,
input_file_type="jsonschema",
extra_args=["--collapse-root-models"],
)
@pytest.mark.benchmark
def test_main_jsonschema_multiple_files(output_dir: Path) -> None:
"""Test JSON Schema generation from multiple files."""
run_main_and_assert(
input_path=JSON_SCHEMA_DATA_PATH / "multiple_files",
output_path=output_dir,
expected_directory=EXPECTED_JSON_SCHEMA_PATH / "multiple_files",
input_file_type="jsonschema",
)
@pytest.mark.benchmark
def test_main_jsonschema_no_empty_collapsed_external_model(tmp_path: Path) -> None:
"""Test no empty files with collapsed external models."""
run_main_and_assert(
input_path=JSON_SCHEMA_DATA_PATH / "external_collapse",
output_path=tmp_path,
file_should_not_exist=tmp_path / "child.py",
input_file_type="jsonschema",
extra_args=["--collapse-root-models"],
)
assert (tmp_path / "__init__.py").exists()
@pytest.mark.cli_doc(
options=["--output-model-type"],
option_description="""Select the output model type (Pydantic v2, Pydantic v2 dataclass,
dataclasses, TypedDict, msgspec).
The `--output-model-type` flag specifies which Python data model framework to use
for the generated code. Supported values include `pydantic_v2.BaseModel`,
`pydantic_v2.dataclass`, `dataclasses.dataclass`, `typing.TypedDict`, and `msgspec.Struct`.""",
input_schema="jsonschema/null_and_array.json",
cli_args=["--output-model-type", "pydantic_v2.BaseModel"],
model_outputs={
"pydantic_v2": "main/jsonschema/null_and_array_v2.py",
},
primary=True,
)
def test_main_null_and_array(output_file: Path) -> None:
"""Select the output model type.
The `--output-model-type` flag specifies which Python data model framework to use
for the generated code. Supported values include `pydantic_v2.BaseModel`,
`pydantic_v2.dataclass`, `dataclasses.dataclass`, `typing.TypedDict`, and `msgspec.Struct`.
"""
run_main_and_assert(
input_path=JSON_SCHEMA_DATA_PATH / "null_and_array.json",
output_path=output_file,
input_file_type="jsonschema",
assert_func=assert_file_content,
expected_file="null_and_array_v2.py",
extra_args=["--output-model-type", "pydantic_v2.BaseModel"],
)
@pytest.mark.cli_doc(
options=["--use-default"],
option_description="""Use default values from schema in generated models.
The `--use-default` flag allows required fields with default values to be generated
with their defaults, making them optional to provide when instantiating the model.
!!! warning "Fields with defaults become nullable"
When using `--use-default`, fields with default values are generated as nullable
types (e.g., `str | None` instead of `str`), even if the schema does not allow
null values.
If you want fields to strictly follow the schema's type definition (non-nullable),
use `--strict-nullable` together with `--use-default`.
!!! note "Future behavior change"
In a future major version, the default behavior of `--use-default` may change to
generate non-nullable types that match the schema definition (equivalent to using
`--strict-nullable`). If you rely on the current nullable behavior, consider
explicitly handling this in your code.""",
input_schema="jsonschema/use_default_with_const.json",
cli_args=["--output-model-type", "pydantic_v2.BaseModel", "--use-default"],
golden_output="jsonschema/use_default_with_const.py",
related_options=["--strict-nullable"],
)
def test_use_default_pydantic_v2_with_json_schema_const(output_file: Path) -> None:
"""Use default values from schema in generated models.
The `--use-default` flag allows required fields with default values to be generated
with their defaults, making them optional to provide when instantiating the model.
!!! warning "Fields with defaults become nullable"
When using `--use-default`, fields with default values are generated as nullable
types (e.g., `str | None` instead of `str`), even if the schema does not allow
null values.
If you want fields to strictly follow the schema's type definition (non-nullable),
use `--strict-nullable` together with `--use-default`.
!!! note "Future behavior change"
In a future major version, the default behavior of `--use-default` may change to
generate non-nullable types that match the schema definition (equivalent to using
`--strict-nullable`). If you rely on the current nullable behavior, consider
explicitly handling this in your code.
"""
run_main_and_assert(
input_path=JSON_SCHEMA_DATA_PATH / "use_default_with_const.json",
output_path=output_file,
input_file_type=None,
assert_func=assert_file_content,
expected_file="use_default_with_const.py",
extra_args=["--output-model-type", "pydantic_v2.BaseModel", "--use-default"],
)
@pytest.mark.parametrize(
("output_model", "expected_output", "option"),
[
(
"dataclasses.dataclass",
"complicated_enum_default_member_dataclass.py",
"--set-default-enum-member",
),
(
"dataclasses.dataclass",
"complicated_enum_default_member_dataclass.py",
None,
),
],
)
def test_main_complicated_enum_default_member(
output_model: str, expected_output: str, option: str | None, output_file: Path
) -> None:
"""Test complicated enum with default member."""
extra_args = [a for a in [option, "--output-model-type", output_model] if a]
run_main_and_assert(
input_path=JSON_SCHEMA_DATA_PATH / "complicated_enum.json",
output_path=output_file,
input_file_type=None,
assert_func=assert_file_content,
expected_file=expected_output,
extra_args=extra_args,
)
@pytest.mark.cli_doc(
options=["--set-default-enum-member"],
option_description="""Set the first enum member as the default value for enum fields.
The `--set-default-enum-member` flag configures the code generation behavior.""",
input_schema="jsonschema/duplicate_enum.json",
cli_args=["--reuse-model", "--set-default-enum-member"],
golden_output="jsonschema/json_reuse_enum_default_member.py",
)
@pytest.mark.benchmark
def test_main_json_reuse_enum_default_member(output_file: Path) -> None:
"""Set the first enum member as the default value for enum fields.
The `--set-default-enum-member` flag configures the code generation behavior.
"""
run_main_and_assert(
input_path=JSON_SCHEMA_DATA_PATH / "duplicate_enum.json",
output_path=output_file,
input_file_type="jsonschema",
assert_func=assert_file_content,
extra_args=["--reuse-model", "--set-default-enum-member"],
)
def test_main_invalid_model_name_failed(capsys: pytest.CaptureFixture[str], output_file: Path) -> None:
"""Test invalid model name error handling."""
run_main_and_assert(
input_path=JSON_SCHEMA_DATA_PATH / "invalid_model_name.json",
output_path=output_file,
input_file_type="jsonschema",
extra_args=["--class-name", "with"],
expected_exit=Exit.ERROR,
capsys=capsys,
expected_stderr_contains="title='with' is invalid class name. You have to set `--class-name` option",
)
def test_main_invalid_model_name_converted(capsys: pytest.CaptureFixture[str], output_file: Path) -> None:
"""Test invalid model name conversion error."""
run_main_and_assert(
input_path=JSON_SCHEMA_DATA_PATH / "invalid_model_name.json",
output_path=output_file,
input_file_type="jsonschema",
expected_exit=Exit.ERROR,
capsys=capsys,
expected_stderr_contains="title='1Xyz' is invalid class name. You have to set `--class-name` option",
)
@pytest.mark.cli_doc(
options=["--class-name"],
option_description="""Override the auto-generated class name with a custom name.
The --class-name option allows you to specify a custom class name for the
generated model. This is useful when the schema title is invalid as a Python
class name (e.g., starts with a number) or when you want to use a different
naming convention than what's in the schema.""",
input_schema="jsonschema/invalid_model_name.json",
cli_args=["--class-name", "ValidModelName"],
golden_output="main/jsonschema/invalid_model_name.py",
)
def test_main_invalid_model_name(output_file: Path) -> None:
"""Override the auto-generated class name with a custom name.
The --class-name option allows you to specify a custom class name for the
generated model. This is useful when the schema title is invalid as a Python
class name (e.g., starts with a number) or when you want to use a different
naming convention than what's in the schema.
"""
run_main_and_assert(
input_path=JSON_SCHEMA_DATA_PATH / "invalid_model_name.json",
output_path=output_file,
input_file_type="jsonschema",
assert_func=assert_file_content,
extra_args=["--class-name", "ValidModelName"],
)
@pytest.mark.cli_doc(
options=["--class-name-prefix"],
option_description="""Add a prefix to all generated class names.
The --class-name-prefix option allows you to add a prefix to all generated class
names, including both models and enums. This is useful for namespacing generated
code or avoiding conflicts with existing classes.""",
input_schema="jsonschema/class_name_affix.json",
cli_args=["--class-name-prefix", "Api"],
golden_output="main/jsonschema/class_name_prefix/output.py",
related_options=["--class-name-suffix", "--class-name-affix-scope"],
)
@freeze_time("2019-07-26")
def test_main_class_name_prefix(output_file: Path) -> None:
"""Add a prefix to all generated class names.
The --class-name-prefix option allows you to add a prefix to all generated class
names, including both models and enums. This is useful for namespacing generated
code or avoiding conflicts with existing classes.
"""
run_main_and_assert(
input_path=JSON_SCHEMA_DATA_PATH / "class_name_affix.json",
output_path=output_file,
input_file_type="jsonschema",
assert_func=assert_file_content,
expected_file="class_name_prefix/output.py",
extra_args=["--class-name-prefix", "Api"],
)
@pytest.mark.cli_doc(
options=["--class-name-suffix"],
option_description="""Add a suffix to all generated class names.
The --class-name-suffix option allows you to add a suffix to all generated class
names, including both models and enums. This is useful for distinguishing generated
classes (e.g., adding 'Schema' or 'Model' suffix).""",
input_schema="jsonschema/class_name_affix.json",
cli_args=["--class-name-suffix", "Schema"],
golden_output="main/jsonschema/class_name_suffix/output.py",
related_options=["--class-name-prefix", "--class-name-affix-scope"],
)
@freeze_time("2019-07-26")
def test_main_class_name_suffix(output_file: Path) -> None:
"""Add a suffix to all generated class names.
The --class-name-suffix option allows you to add a suffix to all generated class
names, including both models and enums. This is useful for distinguishing generated
classes (e.g., adding 'Schema' or 'Model' suffix).
"""
run_main_and_assert(
input_path=JSON_SCHEMA_DATA_PATH / "class_name_affix.json",
output_path=output_file,
input_file_type="jsonschema",
assert_func=assert_file_content,
expected_file="class_name_suffix/output.py",
extra_args=["--class-name-suffix", "Schema"],
)
@pytest.mark.cli_doc(
options=["--class-name-affix-scope"],
option_description="""Control which classes receive the prefix/suffix.
The --class-name-affix-scope option controls which types of classes receive the
prefix or suffix specified by --class-name-prefix or --class-name-suffix:
- 'all': Apply to all classes (models and enums) - this is the default
- 'models': Apply only to model classes (BaseModel, dataclass, TypedDict, etc.)
- 'enums': Apply only to enum classes""",
input_schema="jsonschema/class_name_affix.json",
cli_args=["--class-name-suffix", "Schema", "--class-name-affix-scope", "models"],
golden_output="main/jsonschema/class_name_affix_scope_models/output.py",
related_options=["--class-name-prefix", "--class-name-suffix"],
)
@freeze_time("2019-07-26")
def test_main_class_name_affix_scope_models(output_file: Path) -> None:
"""Control which classes receive the prefix/suffix.
The --class-name-affix-scope option controls which types of classes receive the
prefix or suffix specified by --class-name-prefix or --class-name-suffix:
- 'all': Apply to all classes (models and enums) - this is the default
- 'models': Apply only to model classes (BaseModel, dataclass, TypedDict, etc.)
- 'enums': Apply only to enum classes
"""
run_main_and_assert(
input_path=JSON_SCHEMA_DATA_PATH / "class_name_affix.json",
output_path=output_file,
input_file_type="jsonschema",
assert_func=assert_file_content,
expected_file="class_name_affix_scope_models/output.py",
extra_args=["--class-name-suffix", "Schema", "--class-name-affix-scope", "models"],
)
@freeze_time("2019-07-26")
def test_main_class_name_suffix_with_class_name(output_file: Path) -> None:
"""Test that --class-name-suffix does not apply to root when --class-name is specified.
When --class-name is explicitly set, the suffix should not be applied to the root model
because the user has explicitly chosen the root model name.
"""
run_main_and_assert(
input_path=JSON_SCHEMA_DATA_PATH / "class_name_affix.json",
output_path=output_file,
input_file_type="jsonschema",
assert_func=assert_file_content,
expected_file="class_name_suffix_with_class_name/output.py",
extra_args=["--class-name-suffix", "Schema", "--class-name", "MyRootModel"],
)
def test_main_class_name_prefix_invalid(output_file: Path) -> None:
"""Test that invalid --class-name-prefix is rejected."""
return_code: Exit = main([
"--input",
str(JSON_SCHEMA_DATA_PATH / "class_name_affix.json"),
"--output",
str(output_file),
"--class-name-prefix",
"123Invalid",
])
assert return_code == Exit.ERROR
def test_main_class_name_suffix_invalid(output_file: Path) -> None:
"""Test that invalid --class-name-suffix is rejected."""
return_code: Exit = main([
"--input",
str(JSON_SCHEMA_DATA_PATH / "class_name_affix.json"),
"--output",
str(output_file),
"--class-name-suffix",
"Schema!",
])
assert return_code == Exit.ERROR
def test_main_jsonschema_reserved_field_names(output_file: Path) -> None:
"""Test reserved names are safely suffixed and aliased."""
run_main_and_assert(
input_path=JSON_SCHEMA_DATA_PATH / "reserved_property.json",
output_path=output_file,
input_file_type="jsonschema",
assert_func=assert_file_content,
expected_file="reserved_property.py",
)
def test_main_jsonschema_with_local_anchor(output_file: Path) -> None:
"""Test $id anchor lookup resolves without error and reuses definitions."""
run_main_and_assert(
input_path=JSON_SCHEMA_DATA_PATH / "with_anchor.json",
output_path=output_file,
input_file_type="jsonschema",
assert_func=assert_file_content,
expected_file="with_anchor.py",
)
def test_main_jsonschema_missing_anchor_reports_error(capsys: pytest.CaptureFixture[str], output_file: Path) -> None:
"""Test missing $id anchor produces a clear error instead of KeyError trace."""
run_main_and_assert(
input_path=JSON_SCHEMA_DATA_PATH / "missing_anchor.json",
output_path=output_file,
input_file_type="jsonschema",
expected_exit=Exit.ERROR,
capsys=capsys,
expected_stderr_contains="Unresolved $id reference '#address'",
)
def test_main_root_id_jsonschema_with_local_file(mocker: MockerFixture, output_file: Path) -> None:
"""Test root ID JSON Schema with local file reference."""
root_id_response = mocker.Mock()
root_id_response.status_code = 200
root_id_response.headers = {}
root_id_response.text = "dummy"
person_response = mocker.Mock()
person_response.status_code = 200
person_response.headers = {}
person_response.text = (JSON_SCHEMA_DATA_PATH / "person.json").read_text()
httpx_get_mock = mocker.patch("httpx.get", side_effect=[person_response])
run_main_and_assert(
input_path=JSON_SCHEMA_DATA_PATH / "root_id.json",
output_path=output_file,
input_file_type="jsonschema",
assert_func=assert_file_content,
expected_file="root_id.py",
)
httpx_get_mock.assert_not_called()
@pytest.mark.cli_doc(
options=["--allow-remote-refs"],
option_description="""Enable fetching of `$ref` targets over HTTP/HTTPS.
When enabled, the generator will resolve `$ref` references that point to remote URLs,
including relative refs resolved against a schema's `$id` base URL. This is required
for schemas that reference definitions hosted on external servers.
Automatically enabled when using `--url` input.""",
input_schema="jsonschema/root_id.json",
cli_args=["--allow-remote-refs"],
golden_output="main/jsonschema/root_id.py",
)
def test_main_root_id_jsonschema_with_remote_file(mocker: MockerFixture, tmp_path: Path) -> None:
"""Enable fetching of `$ref` targets over HTTP/HTTPS.
When enabled, the generator will resolve `$ref` references that point to remote URLs,
including relative refs resolved against a schema's `$id` base URL. This is required
for schemas that reference definitions hosted on external servers.
Automatically enabled when using `--url` input.
"""
root_id_response = mocker.Mock()
root_id_response.status_code = 200
root_id_response.headers = {}
root_id_response.text = "dummy"
person_response = mocker.Mock()
person_response.status_code = 200
person_response.headers = {}
person_response.text = (JSON_SCHEMA_DATA_PATH / "person.json").read_text()
httpx_get_mock = mocker.patch("httpx.get", side_effect=[person_response])
input_file = tmp_path / "root_id.json"
output_file: Path = tmp_path / "output.py"
run_main_and_assert(
input_path=input_file,
output_path=output_file,
input_file_type="jsonschema",
extra_args=["--allow-remote-refs"],
assert_func=assert_file_content,
expected_file="root_id.py",
copy_files=[(JSON_SCHEMA_DATA_PATH / "root_id.json", input_file)],
)
httpx_get_mock.assert_has_calls([
call(
"https://example.com/person.json",
headers=None,
verify=True,
follow_redirects=True,
params=None,
timeout=30.0,
),
])
@pytest.mark.benchmark
def test_main_root_id_jsonschema_self_refs_with_local_file(mocker: MockerFixture, output_file: Path) -> None:
"""Test root ID JSON Schema self-references with local file."""
person_response = mocker.Mock()
person_response.status_code = 200
person_response.headers = {}
person_response.text = (JSON_SCHEMA_DATA_PATH / "person.json").read_text()
httpx_get_mock = mocker.patch("httpx.get", side_effect=[person_response])
run_main_and_assert(
input_path=JSON_SCHEMA_DATA_PATH / "root_id_self_ref.json",
output_path=output_file,
input_file_type="jsonschema",
assert_func=assert_file_content,
expected_file="root_id.py",
transform=lambda s: s.replace("filename: root_id_self_ref.json", "filename: root_id.json"),
)
httpx_get_mock.assert_not_called()
@pytest.mark.benchmark
def test_main_root_id_jsonschema_self_refs_with_remote_file(mocker: MockerFixture, tmp_path: Path) -> None:
"""Test root ID JSON Schema self-references with remote file."""
person_response = mocker.Mock()
person_response.status_code = 200
person_response.headers = {}
person_response.text = (JSON_SCHEMA_DATA_PATH / "person.json").read_text()
httpx_get_mock = mocker.patch("httpx.get", side_effect=[person_response])
input_file = tmp_path / "root_id_self_ref.json"
output_file: Path = tmp_path / "output.py"
run_main_and_assert(
input_path=input_file,
output_path=output_file,
input_file_type="jsonschema",
extra_args=["--allow-remote-refs"],
assert_func=assert_file_content,
expected_file="root_id.py",
transform=lambda s: s.replace("filename: root_id_self_ref.json", "filename: root_id.json"),
copy_files=[(JSON_SCHEMA_DATA_PATH / "root_id_self_ref.json", input_file)],
)
httpx_get_mock.assert_has_calls([
call(
"https://example.com/person.json",
headers=None,
verify=True,
follow_redirects=True,
params=None,
timeout=30.0,
),
])
def test_main_root_id_jsonschema_with_absolute_remote_file(mocker: MockerFixture, tmp_path: Path) -> None:
"""Test root ID JSON Schema with absolute remote file URL."""
root_id_response = mocker.Mock()
root_id_response.status_code = 200
root_id_response.headers = {}
root_id_response.text = "dummy"
person_response = mocker.Mock()
person_response.status_code = 200
person_response.headers = {}
person_response.text = (JSON_SCHEMA_DATA_PATH / "person.json").read_text()
httpx_get_mock = mocker.patch("httpx.get", side_effect=[person_response])
input_file = tmp_path / "root_id_absolute_url.json"
output_file: Path = tmp_path / "output.py"
run_main_and_assert(
input_path=input_file,
output_path=output_file,
input_file_type="jsonschema",
extra_args=["--allow-remote-refs"],
assert_func=assert_file_content,
expected_file="root_id_absolute_url.py",
copy_files=[(JSON_SCHEMA_DATA_PATH / "root_id_absolute_url.json", input_file)],
)
httpx_get_mock.assert_has_calls([
call(
"https://example.com/person.json",
headers=None,
verify=True,
follow_redirects=True,
params=None,
timeout=30.0,
),
])
def test_main_root_id_jsonschema_with_absolute_local_file(output_file: Path) -> None:
"""Test root ID JSON Schema with absolute local file path."""
run_main_and_assert(
input_path=JSON_SCHEMA_DATA_PATH / "root_id_absolute_url.json",
output_path=output_file,
input_file_type="jsonschema",
assert_func=assert_file_content,
expected_file="root_id_absolute_url.py",
)
def test_main_remote_ref_emits_deprecation_warning(mocker: MockerFixture, tmp_path: Path) -> None:
"""Test that implicit remote $ref fetching emits a FutureWarning when flag is not set."""
person_response = mocker.Mock()
person_response.status_code = 200
person_response.headers = {}
person_response.text = json.dumps({