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
|
"""Tests for code formatting functionality."""
from __future__ import annotations
import sys
import warnings
from pathlib import Path
from unittest import mock
import pytest
from datamodel_code_generator.format import (
CodeFormatter,
Formatter,
PythonVersion,
PythonVersionMin,
resolve_use_type_checking_imports,
)
EXAMPLE_LICENSE_FILE = str(Path(__file__).parent / "data/python/custom_formatters/license_example.txt")
UN_EXIST_FORMATTER = "tests.data.python.custom_formatters.un_exist"
WRONG_FORMATTER = "tests.data.python.custom_formatters.wrong"
NOT_SUBCLASS_FORMATTER = "tests.data.python.custom_formatters.not_subclass"
ADD_COMMENT_FORMATTER = "tests.data.python.custom_formatters.add_comment"
ADD_LICENSE_FORMATTER = "tests.data.python.custom_formatters.add_license"
FAKE_RUFF_PATH = "/opt/fake-ruff/bin/ruff"
def test_python_version() -> None:
"""Ensure that the python version used for the tests is properly listed."""
_ = PythonVersion("{}.{}".format(*sys.version_info[:2]))
def test_python_version_has_native_deferred_annotations() -> None:
"""Test that has_native_deferred_annotations returns correct values for each Python version."""
assert not PythonVersion.PY_310.has_native_deferred_annotations
assert not PythonVersion.PY_311.has_native_deferred_annotations
assert not PythonVersion.PY_312.has_native_deferred_annotations
assert not PythonVersion.PY_313.has_native_deferred_annotations
assert PythonVersion.PY_314.has_native_deferred_annotations
@pytest.mark.parametrize(
("skip_string_normalization", "expected_output"),
[
(True, "a = 'b'"),
(False, 'a = "b"'),
],
)
def test_format_code_with_skip_string_normalization(
skip_string_normalization: bool,
expected_output: str,
tmp_path: Path,
monkeypatch: pytest.MonkeyPatch,
) -> None:
"""Test code formatting with skip string normalization option."""
monkeypatch.chdir(tmp_path)
formatter = CodeFormatter(
PythonVersionMin,
skip_string_normalization=skip_string_normalization,
formatters=[Formatter.BLACK, Formatter.ISORT],
)
formatted_code = formatter.format_code("a = 'b'")
assert formatted_code == expected_output + "\n"
def test_format_code_un_exist_custom_formatter() -> None:
"""Test error when custom formatter module doesn't exist."""
with pytest.raises(ModuleNotFoundError):
_ = CodeFormatter(
PythonVersionMin,
custom_formatters=[UN_EXIST_FORMATTER],
formatters=[Formatter.BLACK, Formatter.ISORT],
)
def test_format_code_invalid_formatter_name() -> None:
"""Test error when custom formatter has no CodeFormatter class."""
with pytest.raises(NameError):
_ = CodeFormatter(
PythonVersionMin,
custom_formatters=[WRONG_FORMATTER],
formatters=[Formatter.BLACK, Formatter.ISORT],
)
def test_format_code_is_not_subclass() -> None:
"""Test error when custom formatter doesn't inherit CustomCodeFormatter."""
with pytest.raises(TypeError):
_ = CodeFormatter(
PythonVersionMin,
custom_formatters=[NOT_SUBCLASS_FORMATTER],
formatters=[Formatter.BLACK, Formatter.ISORT],
)
def test_format_code_with_custom_formatter_without_kwargs(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None:
"""Test custom formatter that doesn't require kwargs."""
monkeypatch.chdir(tmp_path)
formatter = CodeFormatter(
PythonVersionMin,
custom_formatters=[ADD_COMMENT_FORMATTER],
formatters=[Formatter.BLACK, Formatter.ISORT],
)
formatted_code = formatter.format_code("x = 1\ny = 2")
assert formatted_code == "# a comment\nx = 1\ny = 2" + "\n"
def test_format_code_with_custom_formatter_with_kwargs(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None:
"""Test custom formatter with kwargs."""
monkeypatch.chdir(tmp_path)
formatter = CodeFormatter(
PythonVersionMin,
custom_formatters=[ADD_LICENSE_FORMATTER],
custom_formatters_kwargs={"license_file": EXAMPLE_LICENSE_FILE},
formatters=[Formatter.BLACK, Formatter.ISORT],
)
formatted_code = formatter.format_code("x = 1\ny = 2")
assert (
formatted_code
== """# MIT License
#
# Copyright (c) 2023 Blah-blah
#
x = 1
y = 2
"""
)
def test_format_code_with_two_custom_formatters(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None:
"""Test chaining multiple custom formatters."""
monkeypatch.chdir(tmp_path)
formatter = CodeFormatter(
PythonVersionMin,
custom_formatters=[
ADD_COMMENT_FORMATTER,
ADD_LICENSE_FORMATTER,
],
custom_formatters_kwargs={"license_file": EXAMPLE_LICENSE_FILE},
formatters=[Formatter.BLACK, Formatter.ISORT],
)
formatted_code = formatter.format_code("x = 1\ny = 2")
assert (
formatted_code
== """# MIT License
#
# Copyright (c) 2023 Blah-blah
#
# a comment
x = 1
y = 2
"""
)
def test_format_code_ruff_format_formatter(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None:
"""Test ruff format formatter."""
monkeypatch.chdir(tmp_path)
formatter = CodeFormatter(
PythonVersionMin,
formatters=[Formatter.RUFF_FORMAT],
)
with (
mock.patch.object(formatter, "_find_ruff_path", return_value=FAKE_RUFF_PATH),
mock.patch("subprocess.run") as mock_run,
):
mock_run.return_value.stdout = b"output"
formatted_code = formatter.format_code("input")
assert formatted_code == "output"
mock_run.assert_called_once_with(
(FAKE_RUFF_PATH, "format", "-"),
input=b"input",
capture_output=True,
check=False,
cwd=str(tmp_path),
)
def test_format_code_ruff_check_formatter(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None:
"""Test ruff check formatter with auto-fix."""
monkeypatch.chdir(tmp_path)
formatter = CodeFormatter(
PythonVersionMin,
formatters=[Formatter.RUFF_CHECK],
)
with (
mock.patch.object(formatter, "_find_ruff_path", return_value=FAKE_RUFF_PATH),
mock.patch("subprocess.run") as mock_run,
):
mock_run.return_value.stdout = b"output"
formatted_code = formatter.format_code("input")
assert formatted_code == "output"
mock_run.assert_called_once_with(
(FAKE_RUFF_PATH, "check", "--fix", "--unsafe-fixes", "-"),
input=b"input",
capture_output=True,
check=False,
cwd=str(tmp_path),
)
def test_format_code_ruff_check_formatter_without_type_checking_imports(
tmp_path: Path, monkeypatch: pytest.MonkeyPatch
) -> None:
"""Test ruff check formatter keeps runtime imports when requested."""
monkeypatch.chdir(tmp_path)
formatter = CodeFormatter(
PythonVersionMin,
formatters=[Formatter.RUFF_CHECK],
use_type_checking_imports=False,
)
with (
mock.patch.object(formatter, "_find_ruff_path", return_value=FAKE_RUFF_PATH),
mock.patch("subprocess.run") as mock_run,
):
mock_run.return_value.stdout = b"output"
formatted_code = formatter.format_code("input")
assert formatted_code == "output"
mock_run.assert_called_once_with(
(FAKE_RUFF_PATH, "check", "--fix", "--unsafe-fixes", "--unfixable", "TC001,TC002,TC003", "-"),
input=b"input",
capture_output=True,
check=False,
cwd=str(tmp_path),
)
@pytest.mark.parametrize("explicit_value", [True, False])
def test_resolve_use_type_checking_imports_respects_explicit_value(explicit_value: bool) -> None:
"""Test explicit TYPE_CHECKING import settings are preserved."""
assert (
resolve_use_type_checking_imports(
explicit_value,
is_multi_module_output=True,
formatters=[Formatter.RUFF_CHECK, Formatter.RUFF_FORMAT],
requires_runtime_imports_with_ruff_check=True,
)
is explicit_value
)
def test_resolve_use_type_checking_imports_defaults_to_runtime_imports_for_deferred_pydantic_ruff() -> None:
"""Test deferred Ruff formatting keeps runtime imports for modular Pydantic output by default."""
assert not resolve_use_type_checking_imports(
None,
is_multi_module_output=True,
formatters=[Formatter.RUFF_CHECK, Formatter.RUFF_FORMAT],
requires_runtime_imports_with_ruff_check=True,
)
def test_resolve_use_type_checking_imports_keeps_existing_default_outside_deferred_pydantic_ruff() -> None:
"""Test non-modular or non-Pydantic output keeps TYPE_CHECKING imports enabled by default."""
assert resolve_use_type_checking_imports(
None,
is_multi_module_output=False,
formatters=[Formatter.RUFF_CHECK, Formatter.RUFF_FORMAT],
requires_runtime_imports_with_ruff_check=True,
)
assert resolve_use_type_checking_imports(
None,
is_multi_module_output=True,
formatters=[Formatter.RUFF_CHECK],
requires_runtime_imports_with_ruff_check=False,
)
assert resolve_use_type_checking_imports(
None,
is_multi_module_output=True,
formatters=[Formatter.RUFF_FORMAT],
requires_runtime_imports_with_ruff_check=True,
)
def test_format_code_ruff_check_and_format_uses_resolved_ruff_path(
tmp_path: Path, monkeypatch: pytest.MonkeyPatch
) -> None:
"""Test combined Ruff formatting reuses the resolved Ruff executable."""
monkeypatch.chdir(tmp_path)
formatter = CodeFormatter(
PythonVersionMin,
formatters=[Formatter.RUFF_CHECK, Formatter.RUFF_FORMAT],
)
with (
mock.patch.object(formatter, "_find_ruff_path", return_value=FAKE_RUFF_PATH) as mock_find_ruff_path,
mock.patch("subprocess.run") as mock_run,
):
mock_run.side_effect = [
mock.Mock(stdout=b"checked"),
mock.Mock(stdout=b"formatted"),
]
formatted_code = formatter.format_code("input")
assert formatted_code == "formatted"
mock_find_ruff_path.assert_called_once_with()
assert mock_run.call_args_list == [
mock.call(
(FAKE_RUFF_PATH, "check", "--fix", "--unsafe-fixes", "-"),
input=b"input",
capture_output=True,
check=False,
cwd=str(tmp_path),
),
mock.call(
(FAKE_RUFF_PATH, "format", "-"),
input=b"checked",
capture_output=True,
check=False,
cwd=str(tmp_path),
),
]
def test_settings_path_with_existing_file(tmp_path: Path) -> None:
"""Test settings_path with existing file uses parent directory."""
pyproject = tmp_path / "pyproject.toml"
pyproject.write_text("[tool.black]\nline-length = 60\n", encoding="utf-8")
existing_file = tmp_path / "existing.py"
existing_file.write_text("", encoding="utf-8")
formatter = CodeFormatter(
PythonVersionMin, settings_path=existing_file, formatters=[Formatter.BLACK, Formatter.ISORT]
)
assert formatter.settings_path == str(tmp_path)
def test_settings_path_with_nonexistent_file(tmp_path: Path) -> None:
"""Test settings_path with nonexistent file uses existing parent."""
pyproject = tmp_path / "pyproject.toml"
pyproject.write_text("[tool.black]\nline-length = 60\n", encoding="utf-8")
nonexistent_file = tmp_path / "nonexistent.py"
formatter = CodeFormatter(
PythonVersionMin, settings_path=nonexistent_file, formatters=[Formatter.BLACK, Formatter.ISORT]
)
assert formatter.settings_path == str(tmp_path)
def test_settings_path_with_deeply_nested_nonexistent_path(tmp_path: Path) -> None:
"""Test settings_path with deeply nested nonexistent path finds existing ancestor."""
pyproject = tmp_path / "pyproject.toml"
pyproject.write_text("[tool.black]\nline-length = 60\n", encoding="utf-8")
nested_path = tmp_path / "a" / "b" / "c" / "nonexistent.py"
formatter = CodeFormatter(
PythonVersionMin, settings_path=nested_path, formatters=[Formatter.BLACK, Formatter.ISORT]
)
assert formatter.settings_path == str(tmp_path)
def test_format_directory_ruff_check(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None:
"""Test format_directory with ruff check."""
monkeypatch.chdir(tmp_path)
formatter = CodeFormatter(
PythonVersionMin,
formatters=[Formatter.RUFF_CHECK],
)
output_dir = tmp_path / "output"
output_dir.mkdir()
with (
mock.patch.object(formatter, "_find_ruff_path", return_value=FAKE_RUFF_PATH),
mock.patch("subprocess.run") as mock_run,
):
formatter.format_directory(output_dir)
mock_run.assert_called_once_with(
(FAKE_RUFF_PATH, "check", "--fix", "--unsafe-fixes", str(output_dir)),
capture_output=True,
check=False,
cwd=str(tmp_path),
)
def test_format_directory_ruff_format(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None:
"""Test format_directory with ruff format."""
monkeypatch.chdir(tmp_path)
formatter = CodeFormatter(
PythonVersionMin,
formatters=[Formatter.RUFF_FORMAT],
)
output_dir = tmp_path / "output"
output_dir.mkdir()
with (
mock.patch.object(formatter, "_find_ruff_path", return_value=FAKE_RUFF_PATH),
mock.patch("subprocess.run") as mock_run,
):
formatter.format_directory(output_dir)
mock_run.assert_called_once_with(
(FAKE_RUFF_PATH, "format", str(output_dir)),
capture_output=True,
check=False,
cwd=str(tmp_path),
)
def test_format_directory_both_ruff_formatters(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None:
"""Test format_directory with both ruff check and format."""
monkeypatch.chdir(tmp_path)
formatter = CodeFormatter(
PythonVersionMin,
formatters=[Formatter.RUFF_CHECK, Formatter.RUFF_FORMAT],
)
output_dir = tmp_path / "output"
output_dir.mkdir()
with (
mock.patch.object(formatter, "_find_ruff_path", return_value=FAKE_RUFF_PATH),
mock.patch("subprocess.run") as mock_run,
):
formatter.format_directory(output_dir)
assert mock_run.call_count == 2
mock_run.assert_any_call(
(FAKE_RUFF_PATH, "check", "--fix", "--unsafe-fixes", str(output_dir)),
capture_output=True,
check=False,
cwd=str(tmp_path),
)
mock_run.assert_any_call(
(FAKE_RUFF_PATH, "format", str(output_dir)),
capture_output=True,
check=False,
cwd=str(tmp_path),
)
def test_format_directory_ruff_check_without_type_checking_imports(
tmp_path: Path, monkeypatch: pytest.MonkeyPatch
) -> None:
"""Test format_directory keeps runtime imports when requested."""
monkeypatch.chdir(tmp_path)
formatter = CodeFormatter(
PythonVersionMin,
formatters=[Formatter.RUFF_CHECK],
use_type_checking_imports=False,
)
output_dir = tmp_path / "output"
output_dir.mkdir()
with (
mock.patch.object(formatter, "_find_ruff_path", return_value=FAKE_RUFF_PATH),
mock.patch("subprocess.run") as mock_run,
):
formatter.format_directory(output_dir)
mock_run.assert_called_once_with(
(FAKE_RUFF_PATH, "check", "--fix", "--unsafe-fixes", "--unfixable", "TC001,TC002,TC003", str(output_dir)),
capture_output=True,
check=False,
cwd=str(tmp_path),
)
def test_format_directory_both_ruff_formatters_without_type_checking_imports(
tmp_path: Path, monkeypatch: pytest.MonkeyPatch
) -> None:
"""Test format_directory keeps runtime imports with both Ruff formatters."""
monkeypatch.chdir(tmp_path)
formatter = CodeFormatter(
PythonVersionMin,
formatters=[Formatter.RUFF_CHECK, Formatter.RUFF_FORMAT],
use_type_checking_imports=False,
)
output_dir = tmp_path / "output"
output_dir.mkdir()
with (
mock.patch.object(formatter, "_find_ruff_path", return_value=FAKE_RUFF_PATH),
mock.patch("subprocess.run") as mock_run,
):
formatter.format_directory(output_dir)
assert mock_run.call_count == 2
mock_run.assert_any_call(
(FAKE_RUFF_PATH, "check", "--fix", "--unsafe-fixes", "--unfixable", "TC001,TC002,TC003", str(output_dir)),
capture_output=True,
check=False,
cwd=str(tmp_path),
)
mock_run.assert_any_call(
(FAKE_RUFF_PATH, "format", str(output_dir)),
capture_output=True,
check=False,
cwd=str(tmp_path),
)
def test_defer_formatting_skips_ruff_in_format_code(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None:
"""Test that defer_formatting=True skips ruff in format_code."""
monkeypatch.chdir(tmp_path)
formatter = CodeFormatter(
PythonVersionMin,
formatters=[Formatter.BLACK, Formatter.RUFF_CHECK, Formatter.RUFF_FORMAT],
defer_formatting=True,
)
with mock.patch("subprocess.run") as mock_run:
formatted_code = formatter.format_code("x = 1")
mock_run.assert_not_called()
assert "x = 1" in formatted_code
def test_generate_with_ruff_batch_formatting(tmp_path: Path) -> None:
"""Test that generate uses batch ruff formatting for directory output."""
from datamodel_code_generator import ModuleSplitMode, generate
schema = """
{
"type": "object",
"properties": {
"name": {"type": "string"}
}
}
"""
output_dir = tmp_path / "output"
with (
mock.patch("datamodel_code_generator.format.CodeFormatter._find_ruff_path", return_value=FAKE_RUFF_PATH),
mock.patch("datamodel_code_generator.format.subprocess.run") as mock_run,
):
generate(
input_=schema,
output=output_dir,
formatters=[Formatter.RUFF_CHECK, Formatter.RUFF_FORMAT],
module_split_mode=ModuleSplitMode.Single,
)
assert mock_run.call_count == 2
mock_run.assert_any_call(
(
FAKE_RUFF_PATH,
"check",
"--fix",
"--unsafe-fixes",
"--unfixable",
"TC001,TC002,TC003",
str(output_dir),
),
capture_output=True,
check=False,
cwd=mock.ANY,
)
mock_run.assert_any_call(
(FAKE_RUFF_PATH, "format", str(output_dir)),
capture_output=True,
check=False,
cwd=mock.ANY,
)
def test_generate_with_ruff_batch_formatting_and_explicit_type_checking_imports(tmp_path: Path) -> None:
"""Test explicit TYPE_CHECKING imports override the modular Pydantic Ruff default."""
from datamodel_code_generator import ModuleSplitMode, generate
schema = """
{
"type": "object",
"properties": {
"name": {"type": "string"}
}
}
"""
output_dir = tmp_path / "output"
with (
mock.patch("datamodel_code_generator.format.CodeFormatter._find_ruff_path", return_value=FAKE_RUFF_PATH),
mock.patch("datamodel_code_generator.format.subprocess.run") as mock_run,
):
generate(
input_=schema,
output=output_dir,
formatters=[Formatter.RUFF_CHECK, Formatter.RUFF_FORMAT],
module_split_mode=ModuleSplitMode.Single,
use_type_checking_imports=True,
)
assert mock_run.call_count == 2
mock_run.assert_any_call(
(FAKE_RUFF_PATH, "check", "--fix", "--unsafe-fixes", str(output_dir)),
capture_output=True,
check=False,
cwd=mock.ANY,
)
mock_run.assert_any_call(
(FAKE_RUFF_PATH, "format", str(output_dir)),
capture_output=True,
check=False,
cwd=mock.ANY,
)
def test_code_formatter_warns_when_formatters_is_none(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None:
"""Test that FutureWarning is emitted when formatters is None (default)."""
monkeypatch.chdir(tmp_path)
with pytest.warns(FutureWarning, match="default formatters"):
CodeFormatter(PythonVersionMin)
def test_code_formatter_no_warning_when_formatters_explicit(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None:
"""Test that no warning is emitted when formatters is explicitly specified."""
monkeypatch.chdir(tmp_path)
with warnings.catch_warnings():
warnings.simplefilter("error")
CodeFormatter(PythonVersionMin, formatters=[Formatter.BLACK, Formatter.ISORT])
def test_code_formatter_no_warning_when_formatters_empty(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None:
"""Test that no warning is emitted when formatters is empty list."""
monkeypatch.chdir(tmp_path)
with warnings.catch_warnings():
warnings.simplefilter("error")
CodeFormatter(PythonVersionMin, formatters=[])
|