-
-
Notifications
You must be signed in to change notification settings - Fork 430
Expand file tree
/
Copy pathtest_main_general.py
More file actions
2342 lines (1953 loc) · 84.2 KB
/
test_main_general.py
File metadata and controls
2342 lines (1953 loc) · 84.2 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
"""General integration tests for main code generation functionality."""
from __future__ import annotations
import warnings
from argparse import ArgumentTypeError, Namespace
from typing import TYPE_CHECKING
import black
import pydantic
import pytest
from inline_snapshot import snapshot
import datamodel_code_generator
from datamodel_code_generator import (
AllExportsScope,
DataModelType,
Error,
GeneratedModules,
InputFileType,
SchemaParseError,
chdir,
generate,
snooper_to_methods,
)
from datamodel_code_generator.__main__ import Config, Exit
from datamodel_code_generator.arguments import _dataclass_arguments
from datamodel_code_generator.config import GenerateConfig
from datamodel_code_generator.format import CodeFormatter, PythonVersion
from datamodel_code_generator.model.pydantic_v2 import UnionMode
from datamodel_code_generator.parser.openapi import OpenAPIParser
from datamodel_code_generator.util import is_pydantic_v2
from tests.conftest import assert_output, create_assert_file_content, freeze_time
from tests.main.conftest import (
DATA_PATH,
DEFAULT_VALUES_DATA_PATH,
EXPECTED_MAIN_PATH,
JSON_SCHEMA_DATA_PATH,
OPEN_API_DATA_PATH,
PYTHON_DATA_PATH,
TIMESTAMP,
run_main_and_assert,
run_main_with_args,
)
if TYPE_CHECKING:
from pathlib import Path
from pytest_mock import MockerFixture
assert_file_content = create_assert_file_content(EXPECTED_MAIN_PATH)
def test_debug(mocker: MockerFixture) -> None:
"""Test debug flag functionality."""
with pytest.raises(expected_exception=SystemExit):
run_main_with_args(["--debug", "--help"])
# Simulate pysnooper not being installed by making import fail
mocker.patch.dict("sys.modules", {"pysnooper": None})
with pytest.raises(expected_exception=SystemExit):
run_main_with_args(["--debug", "--help"])
def test_snooper_to_methods_without_pysnooper(mocker: MockerFixture) -> None:
"""Test snooper_to_methods function without pysnooper installed."""
# Simulate pysnooper not being installed by making import fail
mocker.patch.dict("sys.modules", {"pysnooper": None})
mock = mocker.Mock()
assert snooper_to_methods()(mock) == mock
@pytest.mark.parametrize(argnames="no_color", argvalues=[False, True])
def test_show_help(no_color: bool, capsys: pytest.CaptureFixture[str]) -> None:
"""Test help output with and without color."""
args = ["--no-color"] if no_color else []
args += ["--help"]
with pytest.raises(expected_exception=SystemExit) as context:
run_main_with_args(args)
assert context.value.code == Exit.OK
output = capsys.readouterr().out
assert ("\x1b" not in output) == no_color
def test_show_help_when_no_input(mocker: MockerFixture) -> None:
"""Test help display when no input is provided."""
print_help_mock = mocker.patch("datamodel_code_generator.__main__.arg_parser.print_help")
isatty_mock = mocker.patch("sys.stdin.isatty", return_value=True)
return_code: Exit = run_main_with_args([], expected_exit=Exit.ERROR)
assert return_code == Exit.ERROR
assert isatty_mock.called
assert print_help_mock.called
def test_no_args_has_default(monkeypatch: pytest.MonkeyPatch) -> None:
"""No argument should have a default value set because it would override pyproject.toml values.
Default values are set in __main__.Config class.
"""
namespace = Namespace()
monkeypatch.setattr("datamodel_code_generator.__main__.namespace", namespace)
run_main_with_args([], expected_exit=Exit.ERROR)
for field in Config.get_fields():
assert getattr(namespace, field, None) is None
def test_space_and_special_characters_dict(output_file: Path) -> None:
"""Test dict input with space and special characters."""
run_main_and_assert(
input_path=PYTHON_DATA_PATH / "space_and_special_characters_dict.py",
output_path=output_file,
input_file_type="dict",
assert_func=assert_file_content,
)
@freeze_time("2024-12-14")
def test_direct_input_dict(tmp_path: Path) -> None:
"""Test direct dict input code generation."""
output_file = tmp_path / "output.py"
generate(
{"foo": 1, "bar": {"baz": 2}},
input_file_type=InputFileType.Dict,
output=output_file,
output_model_type=DataModelType.PydanticV2BaseModel,
snake_case_field=True,
)
assert_file_content(output_file)
@freeze_time(TIMESTAMP)
@pytest.mark.parametrize(
("keyword_only", "target_python_version", "expected_file"),
[
(False, PythonVersion.PY_310, "frozen_dataclasses.py"),
(True, PythonVersion.PY_310, "frozen_dataclasses_keyword_only.py"),
],
)
def test_frozen_dataclasses(
tmp_path: Path,
keyword_only: bool,
target_python_version: PythonVersion,
expected_file: str,
) -> None:
"""Test --frozen-dataclasses flag functionality."""
output_file = tmp_path / "output.py"
generate(
DATA_PATH / "jsonschema" / "simple_frozen_test.json",
input_file_type=InputFileType.JsonSchema,
output=output_file,
output_model_type=DataModelType.DataclassesDataclass,
frozen_dataclasses=True,
keyword_only=keyword_only,
target_python_version=target_python_version,
)
assert_file_content(output_file, expected_file)
@pytest.mark.cli_doc(
options=["--frozen-dataclasses"],
option_description="""Generate frozen dataclasses with optional keyword-only fields.
The `--frozen-dataclasses` flag generates dataclass instances that are immutable
(frozen=True). Combined with `--keyword-only` (Python 3.10+), all fields become
keyword-only arguments.""",
input_schema="jsonschema/simple_frozen_test.json",
cli_args=["--output-model-type", "dataclasses.dataclass", "--frozen-dataclasses"],
golden_output="frozen_dataclasses.py",
related_options=["--keyword-only", "--output-model-type"],
)
@freeze_time(TIMESTAMP)
@pytest.mark.parametrize(
("extra_args", "expected_file"),
[
(["--output-model-type", "dataclasses.dataclass", "--frozen-dataclasses"], "frozen_dataclasses.py"),
(
[
"--output-model-type",
"dataclasses.dataclass",
"--frozen-dataclasses",
"--keyword-only",
"--target-python-version",
"3.10",
],
"frozen_dataclasses_keyword_only.py",
),
],
)
def test_frozen_dataclasses_command_line(output_file: Path, extra_args: list[str], expected_file: str) -> None:
"""Generate frozen dataclasses with optional keyword-only fields.
The `--frozen-dataclasses` flag generates dataclass instances that are immutable
(frozen=True). Combined with `--keyword-only` (Python 3.10+), all fields become
keyword-only arguments.
"""
run_main_and_assert(
input_path=DATA_PATH / "jsonschema" / "simple_frozen_test.json",
output_path=output_file,
input_file_type="jsonschema",
assert_func=assert_file_content,
expected_file=expected_file,
extra_args=extra_args,
)
@freeze_time(TIMESTAMP)
def test_class_decorators(tmp_path: Path) -> None:
"""Test --class-decorators flag functionality."""
output_file = tmp_path / "output.py"
generate(
DATA_PATH / "jsonschema" / "simple_frozen_test.json",
input_file_type=InputFileType.JsonSchema,
output=output_file,
output_model_type=DataModelType.DataclassesDataclass,
class_decorators=["@dataclass_json"],
additional_imports=["dataclasses_json.dataclass_json"],
)
assert_file_content(output_file, "class_decorators_dataclass.py")
@pytest.mark.cli_doc(
options=["--class-decorators"],
option_description="""Add custom decorators to generated model classes.
The `--class-decorators` option adds custom decorators to all generated model classes.
This is useful for integrating with serialization libraries like `dataclasses_json`.
Use with `--additional-imports` to add the required imports for the decorators.
The `@` prefix is optional and will be added automatically if missing.""",
input_schema="jsonschema/simple_frozen_test.json",
cli_args=[
"--output-model-type",
"dataclasses.dataclass",
"--class-decorators",
"@dataclass_json",
"--additional-imports",
"dataclasses_json.dataclass_json",
],
golden_output="class_decorators_dataclass.py",
related_options=["--additional-imports", "--output-model-type"],
)
@freeze_time(TIMESTAMP)
def test_class_decorators_command_line(output_file: Path) -> None:
"""Add custom decorators to generated model classes.
The `--class-decorators` option adds custom decorators to all generated model classes.
This is useful for integrating with serialization libraries like `dataclasses_json`.
Use with `--additional-imports` to add the required imports for the decorators.
The `@` prefix is optional and will be added automatically if missing.
"""
run_main_and_assert(
input_path=DATA_PATH / "jsonschema" / "simple_frozen_test.json",
output_path=output_file,
input_file_type="jsonschema",
assert_func=assert_file_content,
expected_file="class_decorators_dataclass.py",
extra_args=[
"--output-model-type",
"dataclasses.dataclass",
"--class-decorators",
"@dataclass_json",
"--additional-imports",
"dataclasses_json.dataclass_json",
],
)
@freeze_time(TIMESTAMP)
def test_class_decorators_without_at_prefix(output_file: Path) -> None:
"""Test --class-decorators auto-adds @ prefix when missing."""
run_main_and_assert(
input_path=DATA_PATH / "jsonschema" / "simple_frozen_test.json",
output_path=output_file,
input_file_type="jsonschema",
assert_func=assert_file_content,
expected_file="class_decorators_dataclass.py",
extra_args=[
"--output-model-type",
"dataclasses.dataclass",
"--class-decorators",
"dataclass_json",
"--additional-imports",
"dataclasses_json.dataclass_json",
],
)
@freeze_time(TIMESTAMP)
def test_class_decorators_with_empty_entries(output_file: Path) -> None:
"""Test --class-decorators filters out empty entries from comma-separated list."""
run_main_and_assert(
input_path=DATA_PATH / "jsonschema" / "simple_frozen_test.json",
output_path=output_file,
input_file_type="jsonschema",
assert_func=assert_file_content,
expected_file="class_decorators_dataclass.py",
extra_args=[
"--output-model-type",
"dataclasses.dataclass",
"--class-decorators",
"@dataclass_json, ,",
"--additional-imports",
"dataclasses_json.dataclass_json",
],
)
@freeze_time(TIMESTAMP)
@pytest.mark.parametrize(
("output_model_type", "expected_file"),
[
("pydantic.BaseModel", "class_decorators_pydantic_BaseModel.py"),
("pydantic_v2.BaseModel", "class_decorators_pydantic_v2_BaseModel.py"),
("pydantic_v2.dataclass", "class_decorators_pydantic_v2_dataclass.py"),
("dataclasses.dataclass", "class_decorators_dataclasses_dataclass.py"),
("msgspec.Struct", "class_decorators_msgspec_Struct.py"),
# Note: TypedDict is excluded because its template doesn't support decorators
],
ids=[
"pydantic_v1",
"pydantic_v2",
"pydantic_v2_dataclass",
"dataclasses",
"msgspec",
],
)
def test_class_decorators_all_output_types(output_file: Path, output_model_type: str, expected_file: str) -> None:
"""Test --class-decorators works with all output model types that support decorators."""
run_main_and_assert(
input_path=DATA_PATH / "jsonschema" / "simple_frozen_test.json",
output_path=output_file,
input_file_type="jsonschema",
assert_func=assert_file_content,
expected_file=expected_file,
extra_args=[
"--output-model-type",
output_model_type,
"--class-decorators",
"@my_decorator",
"--additional-imports",
"my_module.my_decorator",
],
)
@freeze_time(TIMESTAMP)
def test_use_attribute_docstrings(tmp_path: Path) -> None:
"""Test --use-attribute-docstrings flag functionality."""
output_file = tmp_path / "output.py"
generate(
DATA_PATH / "jsonschema" / "use_attribute_docstrings_test.json",
input_file_type=InputFileType.JsonSchema,
output=output_file,
output_model_type=DataModelType.PydanticV2BaseModel,
use_field_description=True,
use_attribute_docstrings=True,
)
assert_file_content(output_file)
@freeze_time(TIMESTAMP)
@pytest.mark.cli_doc(
options=["--use-attribute-docstrings"],
option_description="""Generate field descriptions as attribute docstrings instead of Field descriptions.
The `--use-attribute-docstrings` flag places field descriptions in Python docstring
format (PEP 224 attribute docstrings) rather than in Field(..., description=...).
This provides better IDE support for hovering over attributes. Requires
`--use-field-description` to be enabled.""",
input_schema="jsonschema/use_attribute_docstrings_test.json",
cli_args=[
"--output-model-type",
"pydantic_v2.BaseModel",
"--use-field-description",
"--use-attribute-docstrings",
],
golden_output="use_attribute_docstrings.py",
related_options=["--use-field-description"],
)
def test_use_attribute_docstrings_command_line(output_file: Path) -> None:
"""Generate field descriptions as attribute docstrings instead of Field descriptions.
The `--use-attribute-docstrings` flag places field descriptions in Python docstring
format (PEP 224 attribute docstrings) rather than in Field(..., description=...).
This provides better IDE support for hovering over attributes. Requires
`--use-field-description` to be enabled.
"""
run_main_and_assert(
input_path=DATA_PATH / "jsonschema" / "use_attribute_docstrings_test.json",
output_path=output_file,
input_file_type="jsonschema",
assert_func=assert_file_content,
expected_file="use_attribute_docstrings.py",
extra_args=[
"--output-model-type",
"pydantic_v2.BaseModel",
"--use-field-description",
"--use-attribute-docstrings",
],
)
def test_filename_with_newline_injection(tmp_path: Path) -> None:
"""Test that filenames with newlines cannot inject code into generated files."""
schema_content = """{"type": "object", "properties": {"name": {"type": "string"}}}"""
malicious_filename = """schema.json
# INJECTED CODE:
import os
os.system('echo INJECTED')
# END INJECTION"""
output_path = tmp_path / "output.py"
generate(
input_=schema_content,
input_filename=malicious_filename,
input_file_type=InputFileType.JsonSchema,
output=output_path,
)
generated_content = output_path.read_text()
assert "# filename: schema.json # INJECTED CODE: import os" in generated_content, (
"Filename not properly sanitized"
)
assert not any(
line.strip().startswith("import os") and not line.strip().startswith("#")
for line in generated_content.split("\n")
)
assert not any("os.system" in line and not line.strip().startswith("#") for line in generated_content.split("\n"))
compile(generated_content, str(output_path), "exec")
def test_filename_with_various_control_characters(tmp_path: Path) -> None:
"""Test that various control characters in filenames are properly sanitized."""
schema_content = """{"type": "object", "properties": {"test": {"type": "string"}}}"""
test_cases = [
("newline", "schema.json\nimport os; os.system('echo INJECTED')"),
("carriage_return", "schema.json\rimport os; os.system('echo INJECTED')"),
("crlf", "schema.json\r\nimport os; os.system('echo INJECTED')"),
("tab_newline", "schema.json\t\nimport os; os.system('echo TAB')"),
("form_feed", "schema.json\f\nimport os; os.system('echo FF')"),
("vertical_tab", "schema.json\v\nimport os; os.system('echo VT')"),
("unicode_line_separator", "schema.json\u2028import os; os.system('echo U2028')"),
("unicode_paragraph_separator", "schema.json\u2029import os; os.system('echo U2029')"),
("multiple_newlines", "schema.json\n\n\nimport os; os.system('echo MULTI')"),
("mixed_characters", "schema.json\n\r\t\nimport os; os.system('echo MIXED')"),
]
for test_name, malicious_filename in test_cases:
output_path = tmp_path / "output.py"
generate(
input_=schema_content,
input_filename=malicious_filename,
input_file_type=InputFileType.JsonSchema,
output=output_path,
)
generated_content = output_path.read_text()
assert not any(
line.strip().startswith("import ") and not line.strip().startswith("#")
for line in generated_content.split("\n")
), f"Injection found for {test_name}"
assert not any(
"os.system" in line and not line.strip().startswith("#") for line in generated_content.split("\n")
), f"System call found for {test_name}"
compile(generated_content, str(output_path), "exec")
def test_generate_with_nonexistent_file(tmp_path: Path) -> None:
"""Test that generating from a nonexistent file raises an error."""
nonexistent_file = tmp_path / "nonexistent.json"
output_file = tmp_path / "output.py"
with pytest.raises(Error, match="File not found"):
generate(
input_=nonexistent_file,
output=output_file,
)
def test_generate_with_invalid_file_format(tmp_path: Path) -> None:
"""Test that generating from an invalid file format raises an error."""
invalid_file = tmp_path / "invalid.txt"
invalid_file.write_text("this is not valid json or yaml or anything")
output_file = tmp_path / "output.py"
with pytest.raises(Error, match="Invalid file format"):
generate(
input_=invalid_file,
output=output_file,
)
def test_schema_parse_error_includes_path(tmp_path: Path) -> None:
"""Test that schema parse errors include the schema path context."""
invalid_schema = tmp_path / "invalid_schema.json"
invalid_schema.write_text("""{
"type": "object",
"properties": {
"myField": {
"type": "integer",
"minimum": "not_a_number"
}
}
}""")
output_file = tmp_path / "output.py"
with pytest.raises(SchemaParseError, match="Error at schema path"):
generate(
input_=invalid_schema,
output=output_file,
)
def test_schema_parse_error_includes_nested_path(tmp_path: Path) -> None:
"""Test that schema parse errors include nested schema path context."""
invalid_schema = tmp_path / "invalid_nested_schema.json"
invalid_schema.write_text("""{
"$defs": {
"MyModel": {
"type": "object",
"properties": {
"nestedField": {
"type": "number",
"maximum": "invalid_value"
}
}
}
},
"type": "object",
"properties": {
"ref": {"$ref": "#/$defs/MyModel"}
}
}""")
output_file = tmp_path / "output.py"
with pytest.raises(SchemaParseError, match=r"\$defs/MyModel"):
generate(
input_=invalid_schema,
output=output_file,
)
def test_schema_parse_error_original_error(tmp_path: Path) -> None:
"""Test that SchemaParseError preserves the original error."""
invalid_schema = tmp_path / "invalid_schema.json"
invalid_schema.write_text("""{
"type": "integer",
"minimum": "not_a_number"
}""")
output_file = tmp_path / "output.py"
with pytest.raises(SchemaParseError) as exc_info:
generate(
input_=invalid_schema,
output=output_file,
)
assert exc_info.value.original_error is not None
assert exc_info.value.path is not None
def test_schema_parse_error_without_path() -> None:
"""Test SchemaParseError message formatting without path."""
error = SchemaParseError("Test error message")
assert error.message == "Test error message"
assert error.path == []
assert error.original_error is None
def test_generate_cli_command_with_no_use_specialized_enum(tmp_path: Path, capsys: pytest.CaptureFixture[str]) -> None:
"""Test --generate-cli-command with use-specialized-enum = false."""
pyproject_toml = """
[tool.datamodel-codegen]
input = "schema.yaml"
use-specialized-enum = false
"""
(tmp_path / "pyproject.toml").write_text(pyproject_toml)
with chdir(tmp_path):
run_main_with_args(
["--generate-cli-command"],
capsys=capsys,
expected_stdout_path=EXPECTED_MAIN_PATH / "generate_cli_command" / "no_use_specialized_enum.txt",
)
def test_generate_cli_command_with_false_boolean(tmp_path: Path, capsys: pytest.CaptureFixture[str]) -> None:
"""Test --generate-cli-command with regular boolean set to false (should be skipped)."""
pyproject_toml = """
[tool.datamodel-codegen]
input = "schema.yaml"
snake-case-field = false
"""
(tmp_path / "pyproject.toml").write_text(pyproject_toml)
with chdir(tmp_path):
run_main_with_args(
["--generate-cli-command"],
capsys=capsys,
expected_stdout_path=EXPECTED_MAIN_PATH / "generate_cli_command" / "false_boolean.txt",
)
def test_generate_cli_command_with_true_boolean(tmp_path: Path, capsys: pytest.CaptureFixture[str]) -> None:
"""Test --generate-cli-command with boolean set to true."""
pyproject_toml = """
[tool.datamodel-codegen]
input = "schema.yaml"
snake-case-field = true
"""
(tmp_path / "pyproject.toml").write_text(pyproject_toml)
with chdir(tmp_path):
run_main_with_args(
["--generate-cli-command"],
capsys=capsys,
expected_stdout_path=EXPECTED_MAIN_PATH / "generate_cli_command" / "true_boolean.txt",
)
def test_generate_cli_command_with_list_option(tmp_path: Path, capsys: pytest.CaptureFixture[str]) -> None:
"""Test --generate-cli-command with list option."""
pyproject_toml = """
[tool.datamodel-codegen]
input = "schema.yaml"
strict-types = ["str", "int"]
"""
(tmp_path / "pyproject.toml").write_text(pyproject_toml)
with chdir(tmp_path):
run_main_with_args(
["--generate-cli-command"],
capsys=capsys,
expected_stdout_path=EXPECTED_MAIN_PATH / "generate_cli_command" / "list_option.txt",
)
@pytest.mark.parametrize(
("json_str", "expected"),
[
('{"frozen": true, "slots": true}', {"frozen": True, "slots": True}),
("{}", {}),
],
)
def test_dataclass_arguments_valid(json_str: str, expected: dict) -> None:
"""Test that valid JSON is parsed correctly."""
assert _dataclass_arguments(json_str) == expected
@pytest.mark.parametrize(
("json_str", "match"),
[
("not-valid-json", "Invalid JSON:"),
("[1, 2, 3]", "Expected a JSON dictionary, got list"),
('"just a string"', "Expected a JSON dictionary, got str"),
("42", "Expected a JSON dictionary, got int"),
('{"invalid_key": true}', "Invalid keys:"),
('{"frozen": "not_bool"}', "Expected bool for 'frozen', got str"),
],
)
def test_dataclass_arguments_invalid(json_str: str, match: str) -> None:
"""Test that invalid input raises ArgumentTypeError."""
with pytest.raises(ArgumentTypeError, match=match):
_dataclass_arguments(json_str)
@pytest.mark.cli_doc(
options=["--type-overrides"],
option_description="""Replace schema model types with custom Python types via JSON mapping.
This option is useful for importing models from external libraries (like `geojson-pydantic`)
instead of generating them.
**Override Formats:**
| Format | Description |
|--------|-------------|
| `{"ModelName": "package.Type"}` | Model-level: Skip generating `ModelName` and import from `package` |
| `{"Model.field": "package.Type"}` | Scoped: Override only specific field in specific model |
!!! note "Model-level overrides skip generation"
When you specify a model-level override (without a dot in the key), the generator will
**skip generating that model entirely** and import it from the specified package instead.
**Common Use Cases:**
| Use Case | Example Override |
|----------|------------------|
| GeoJSON types | `{"Feature": "geojson_pydantic.Feature"}` |
| Custom datetime | `{"Timestamp": "pendulum.DateTime"}` |
| MongoDB ObjectId | `{"ObjectId": "bson.ObjectId"}` |
| Custom validators | `{"Email": "my_app.types.ValidatedEmail"}` |
""",
input_schema="jsonschema/type_overrides_test.json",
cli_args=["--type-overrides", '{"CustomType": "my_app.types.CustomType"}'],
golden_output="main/type_overrides_model_level.py",
primary=True,
)
@freeze_time(TIMESTAMP)
def test_type_overrides_model_level(output_file: Path) -> None:
"""Replace schema model types with custom Python types via JSON mapping."""
run_main_and_assert(
input_path=JSON_SCHEMA_DATA_PATH / "type_overrides_test.json",
output_path=output_file,
input_file_type="jsonschema",
assert_func=assert_file_content,
extra_args=[
"--type-overrides",
'{"CustomType": "my_app.types.CustomType"}',
],
)
@pytest.mark.cli_doc(
options=["--type-overrides"],
option_description="""Replace schema model types with custom Python types via JSON mapping.""",
input_schema="jsonschema/type_overrides_external_lib.json",
cli_args=[
"--type-overrides",
'{"Feature": "geojson_pydantic.Feature", "FeatureCollection": "geojson_pydantic.FeatureCollection"}',
],
golden_output="main/type_overrides_external_lib.py",
)
@freeze_time(TIMESTAMP)
def test_type_overrides_external_lib(output_file: Path) -> None:
"""Test --type-overrides with external library types like geojson-pydantic."""
run_main_and_assert(
input_path=JSON_SCHEMA_DATA_PATH / "type_overrides_external_lib.json",
output_path=output_file,
input_file_type="jsonschema",
assert_func=assert_file_content,
extra_args=[
"--type-overrides",
'{"Feature": "geojson_pydantic.Feature", "FeatureCollection": "geojson_pydantic.FeatureCollection"}',
],
)
@freeze_time(TIMESTAMP)
def test_type_overrides_scoped(output_file: Path) -> None:
"""Test --type-overrides with scoped override replaces specific field only."""
run_main_and_assert(
input_path=JSON_SCHEMA_DATA_PATH / "type_overrides_scoped.json",
output_path=output_file,
input_file_type="jsonschema",
assert_func=assert_file_content,
extra_args=[
"--type-overrides",
'{"User.address": "my_app.Address"}',
],
)
@freeze_time(TIMESTAMP)
def test_type_overrides_nested_types(output_file: Path) -> None:
"""Test --type-overrides with nested types like List[CustomType]."""
run_main_and_assert(
input_path=JSON_SCHEMA_DATA_PATH / "type_overrides_nested.json",
output_path=output_file,
input_file_type="jsonschema",
assert_func=assert_file_content,
extra_args=[
"--type-overrides",
'{"Tag": "my_app.Tag"}',
],
)
def test_skip_root_model(tmp_path: Path) -> None:
"""Test --skip-root-model flag functionality using generate()."""
output_file = tmp_path / "output.py"
generate(
DATA_PATH / "jsonschema" / "skip_root_model_test.json",
input_file_type=InputFileType.JsonSchema,
output=output_file,
output_model_type=DataModelType.PydanticV2BaseModel,
skip_root_model=True,
)
assert_file_content(output_file, "skip_root_model.py")
@pytest.mark.cli_doc(
options=["--skip-root-model"],
option_description="""Skip generation of root model when schema contains nested definitions.
The `--skip-root-model` flag prevents generating a model for the root schema object
when the schema primarily contains reusable definitions. This is useful when the root
object is just a container for $defs and not a meaningful model itself.""",
input_schema="jsonschema/skip_root_model_test.json",
cli_args=["--output-model-type", "pydantic_v2.BaseModel", "--skip-root-model"],
golden_output="skip_root_model.py",
)
def test_skip_root_model_command_line(output_file: Path) -> None:
"""Skip generation of root model when schema contains nested definitions.
The `--skip-root-model` flag prevents generating a model for the root schema object
when the schema primarily contains reusable definitions. This is useful when the root
object is just a container for $defs and not a meaningful model itself.
"""
run_main_and_assert(
input_path=DATA_PATH / "jsonschema" / "skip_root_model_test.json",
output_path=output_file,
input_file_type="jsonschema",
assert_func=assert_file_content,
expected_file="skip_root_model.py",
extra_args=["--output-model-type", "pydantic_v2.BaseModel", "--skip-root-model"],
)
@pytest.mark.cli_doc(
options=["--check"],
option_description="""Verify generated code matches existing output without modifying files.
The `--check` flag compares the generated output with existing files and exits with
a non-zero status if they differ. Useful for CI/CD validation to ensure schemas
and generated code stay in sync. Works with both single files and directory outputs.""",
input_schema="jsonschema/person.json",
cli_args=["--disable-timestamp", "--check"],
golden_output="person.py",
)
def test_check_file_matches(output_file: Path) -> None:
"""Verify generated code matches existing output without modifying files.
The `--check` flag compares the generated output with existing files and exits with
a non-zero status if they differ. Useful for CI/CD validation to ensure schemas
and generated code stay in sync. Works with both single files and directory outputs.
"""
input_path = DATA_PATH / "jsonschema" / "person.json"
run_main_and_assert(
input_path=input_path,
output_path=output_file,
input_file_type="jsonschema",
extra_args=["--disable-timestamp"],
)
run_main_and_assert(
input_path=input_path,
output_path=output_file,
input_file_type="jsonschema",
extra_args=["--disable-timestamp", "--check"],
expected_exit=Exit.OK,
)
def test_check_file_does_not_exist(tmp_path: Path) -> None:
"""Test --check returns DIFF when file does not exist."""
run_main_and_assert(
input_path=DATA_PATH / "jsonschema" / "person.json",
output_path=tmp_path / "nonexistent.py",
input_file_type="jsonschema",
extra_args=["--disable-timestamp", "--check"],
expected_exit=Exit.DIFF,
)
def test_check_file_differs(output_file: Path) -> None:
"""Test --check returns DIFF when file content differs."""
output_file.write_text("# Different content\n", encoding="utf-8")
run_main_and_assert(
input_path=DATA_PATH / "jsonschema" / "person.json",
output_path=output_file,
input_file_type="jsonschema",
extra_args=["--disable-timestamp", "--check"],
expected_exit=Exit.DIFF,
)
def test_check_with_stdout_output(capsys: pytest.CaptureFixture[str]) -> None:
"""Test --check with stdout output returns error."""
run_main_and_assert(
input_path=DATA_PATH / "jsonschema" / "person.json",
output_path=None,
input_file_type="jsonschema",
extra_args=["--check"],
expected_exit=Exit.ERROR,
capsys=capsys,
expected_stderr_contains="--check cannot be used with stdout",
)
def test_check_with_nonexistent_input(tmp_path: Path) -> None:
"""Test --check with nonexistent input file returns error."""
run_main_and_assert(
input_path=tmp_path / "nonexistent.json",
output_path=tmp_path / "output.py",
input_file_type="jsonschema",
extra_args=["--check"],
expected_exit=Exit.ERROR,
)
def test_check_normalizes_line_endings(output_file: Path) -> None:
"""Test --check normalizes line endings (CRLF vs LF)."""
input_path = DATA_PATH / "jsonschema" / "person.json"
run_main_and_assert(
input_path=input_path,
output_path=output_file,
input_file_type="jsonschema",
extra_args=["--disable-timestamp"],
)
content = output_file.read_text(encoding="utf-8")
output_file.write_bytes(content.replace("\n", "\r\n").encode("utf-8"))
run_main_and_assert(
input_path=input_path,
output_path=output_file,
input_file_type="jsonschema",
extra_args=["--disable-timestamp", "--check"],
expected_exit=Exit.OK,
)
def test_check_directory_matches(output_dir: Path) -> None:
"""Test --check returns OK when directory matches."""
input_path = OPEN_API_DATA_PATH / "modular.yaml"
run_main_and_assert(
input_path=input_path,
output_path=output_dir,
input_file_type="openapi",
extra_args=["--disable-timestamp"],
)
run_main_and_assert(
input_path=input_path,
output_path=output_dir,
input_file_type="openapi",
extra_args=["--disable-timestamp", "--check"],
expected_exit=Exit.OK,
)
def test_check_directory_file_differs(output_dir: Path) -> None:
"""Test --check returns DIFF when a file in directory differs."""
input_path = OPEN_API_DATA_PATH / "modular.yaml"
run_main_and_assert(
input_path=input_path,
output_path=output_dir,
input_file_type="openapi",
extra_args=["--disable-timestamp"],
)
py_files = list(output_dir.rglob("*.py"))
py_files[0].write_text("# Modified content\n", encoding="utf-8")
run_main_and_assert(
input_path=input_path,
output_path=output_dir,
input_file_type="openapi",
extra_args=["--disable-timestamp", "--check"],
expected_exit=Exit.DIFF,
)
def test_check_directory_missing_file(output_dir: Path) -> None:
"""Test --check returns DIFF when a generated file is missing."""
input_path = OPEN_API_DATA_PATH / "modular.yaml"
run_main_and_assert(
input_path=input_path,
output_path=output_dir,
input_file_type="openapi",
extra_args=["--disable-timestamp"],
)
py_files = list(output_dir.rglob("*.py"))
py_files[0].unlink()
run_main_and_assert(
input_path=input_path,
output_path=output_dir,
input_file_type="openapi",
extra_args=["--disable-timestamp", "--check"],
expected_exit=Exit.DIFF,
)
def test_check_directory_extra_file(output_dir: Path) -> None:
"""Test --check returns DIFF when an extra file exists."""
input_path = OPEN_API_DATA_PATH / "modular.yaml"
run_main_and_assert(
input_path=input_path,
output_path=output_dir,
input_file_type="openapi",
extra_args=["--disable-timestamp"],
)
(output_dir / "extra_model.py").write_text("# Extra file\n", encoding="utf-8")
run_main_and_assert(
input_path=input_path,
output_path=output_dir,
input_file_type="openapi",
extra_args=["--disable-timestamp", "--check"],
expected_exit=Exit.DIFF,
)