Skip to content

Commit 5d237ac

Browse files
DarkaMaulclaude
andauthored
Escape generated pyproject TOML strings (#3436)
* Escape generated pyproject TOML strings * Mark TOML escaping test as allow_direct_assert The assert-helper guard test rejects direct assert statements in guarded modules. This unit test verifies a TOML round-trip rather than comparing generated output via shared helpers, so the narrow marker exception fits. Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com> * Test TOML escaping via e2e golden-file comparison Replace the unit-style direct-assert test with run_main_with_args against a golden fixture, matching the other generate-pyproject-config tests. This exercises the full CLI path and drops the need for the allow_direct_assert marker the assert-helper guard would otherwise require. Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com> --------- Co-authored-by: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
1 parent e68db15 commit 5d237ac

3 files changed

Lines changed: 24 additions & 1 deletion

File tree

src/datamodel_code_generator/__main__.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -629,7 +629,7 @@ def _format_toml_value(value: TomlValue) -> str:
629629
if isinstance(value, bool):
630630
return "true" if value else "false"
631631
if isinstance(value, str):
632-
return f'"{value}"'
632+
return json.dumps(value, ensure_ascii=False)
633633
formatted_items = [_format_toml_value(item) for item in value]
634634
return f"[{', '.join(formatted_items)}]"
635635

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,5 @@
1+
[tool.datamodel-codegen]
2+
custom-file-header = "say \"hi\" on C:\\tmp\nnext"
3+
http-headers = ["Authorization: Bearer \"abc\"", "X-Path: C:\\tmp"]
4+
input = "schema.yaml"
5+

tests/test_main_kr.py

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -827,6 +827,24 @@ def test_generate_pyproject_config_with_enum_option(capsys: pytest.CaptureFixtur
827827
)
828828

829829

830+
def test_generate_pyproject_config_escapes_toml_strings(capsys: pytest.CaptureFixture[str]) -> None:
831+
"""Test --generate-pyproject-config escapes special characters in TOML basic strings."""
832+
run_main_with_args(
833+
[
834+
"--generate-pyproject-config",
835+
"--input",
836+
"schema.yaml",
837+
"--custom-file-header",
838+
'say "hi" on C:\\tmp\nnext',
839+
"--http-headers",
840+
'Authorization: Bearer "abc"',
841+
"X-Path: C:\\tmp",
842+
],
843+
capsys=capsys,
844+
expected_stdout_path=EXPECTED_GENERATE_PYPROJECT_CONFIG_PATH / "escapes_toml_strings.txt",
845+
)
846+
847+
830848
EXPECTED_GENERATE_CLI_COMMAND_PATH = EXPECTED_MAIN_KR_PATH / "generate_cli_command"
831849

832850

0 commit comments

Comments
 (0)