Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
22 changes: 22 additions & 0 deletions tests/test_items.py
Original file line number Diff line number Diff line change
Expand Up @@ -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"):
Expand Down Expand Up @@ -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)
Expand Down
4 changes: 4 additions & 0 deletions tomlkit/items.py
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand Down Expand Up @@ -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:
Expand Down
Loading