diff --git a/tests/test_items.py b/tests/test_items.py index 27a1c6e2..b69729a3 100644 --- a/tests/test_items.py +++ b/tests/test_items.py @@ -521,6 +521,26 @@ def test_modify_array_with_comment() -> None: assert doc.as_string() == "x = [\n 2\n]" +@pytest.mark.parametrize( + "content, expected", + [ + ("a = [1\n# end\n]\n", "a = [1,\n# end\n2\n]\n"), + ("a = [1,\n# end\n]\n", "a = [1,\n# end\n2,\n]\n"), + ( + "a = [1 # one\n, # separator\n# end\n]\n", + "a = [1 # one\n, # separator\n# end\n2\n]\n", + ), + ], +) +def test_append_after_standalone_array_comment(content: str, expected: str) -> None: + doc = parse(content) + doc["a"].append(2) + + rendered = api.dumps(doc) + assert rendered == expected + assert parse(rendered)["a"] == [1, 2] + + def test_append_to_multiline_array_with_comment() -> None: doc = parse( """\ diff --git a/tomlkit/items.py b/tomlkit/items.py index 30d8a4f2..e4852782 100644 --- a/tomlkit/items.py +++ b/tomlkit/items.py @@ -1677,6 +1677,18 @@ def insert(self, pos: int, value: Any) -> None: # type: ignore[override] last_item = self._value[idx - 1] if indent is None: indent = last_item.indent + # Skip standalone comments when looking for the preceding separator. + for previous in self._value[:idx][::-1]: + if ( + ( + previous.value is not None + and not isinstance(previous.value, Null) + ) + or previous.comma is not None + or (previous.indent is not None and "," in previous.indent.s) + ): + last_item = previous + break if not isinstance(last_item.value, Null) and "\n" in default_indent: # Copy the comma from the last item if 1) it contains a value and # 2) the array is multiline