diff --git a/tests/test_items.py b/tests/test_items.py index b785a5e..45b1245 100644 --- a/tests/test_items.py +++ b/tests/test_items.py @@ -515,6 +515,13 @@ def test_array_add_line() -> None: ) +def test_array_add_line_multiline_comment_is_rejected() -> None: + t = api.array() + with pytest.raises(ValueError, match="line breaks"): + t.add_line(1, 2, 3, comment="first line\nsecond line") + assert t.as_string() == "[]" + + def test_array_add_line_invalid_value() -> None: t = api.array() with pytest.raises(ValueError, match="is not allowed"): @@ -887,6 +894,21 @@ def test_trim_comments_when_building_inline_table() -> None: assert table.as_string() == '{foo = "bar", baz = "foobaz"}' +def test_comment_method_multiline_comment_is_rejected() -> None: + doc = api.document() + doc["x"] = 1 + with pytest.raises(ValueError, match="line breaks"): + doc["x"].comment("first line\nsecond line") + assert doc.as_string() == "x = 1\n" + + +def test_comment_method_keeps_existing_hash_prefix() -> None: + doc = api.document() + doc["x"] = 1 + doc["x"].comment("# already a comment") + assert doc.as_string() == "x = 1 # already a comment\n" + + def test_append_table_to_inline_table_raises() -> None: table = api.table() table.append("a", 1) diff --git a/tomlkit/items.py b/tomlkit/items.py index e9fdaff..c82c781 100644 --- a/tomlkit/items.py +++ b/tomlkit/items.py @@ -500,6 +500,8 @@ def unwrap(self) -> Any: def comment(self, comment: str) -> Item: """Attach a comment to this item""" + if "\n" in comment or "\r" in comment: + raise ValueError("Comment cannot contain line breaks") if not comment.strip().startswith("#"): comment = "# " + comment @@ -1521,6 +1523,8 @@ def add_line( 4, 5, 6, ] """ + if comment and ("\n" in comment or "\r" in comment): + raise ValueError("Comment cannot contain line breaks") new_values: list[Item] = [] first_indent = f"\n{indent}" if newline else indent if first_indent: