diff --git a/src/robocop/formatter/formatters/ReplaceWithVAR.py b/src/robocop/formatter/formatters/ReplaceWithVAR.py index 6b392e757..ce5473da5 100644 --- a/src/robocop/formatter/formatters/ReplaceWithVAR.py +++ b/src/robocop/formatter/formatters/ReplaceWithVAR.py @@ -191,9 +191,27 @@ def restore_comments( else: node.tokens = [*node.tokens[:-1], Token(Token.SEPARATOR, " "), comments[0], node.tokens[-1]] # type: ignore[union-attr] return node - comment_nodes = [Comment.from_params(comment=comment.value, indent=indent) for comment in comments] + comment_nodes = [ + Comment.from_params(comment=comment, indent=indent) for comment in self.merge_comment_values(comments) + ] return *comment_nodes, node + @staticmethod + def merge_comment_values(comments: list[Token]) -> list[str]: + """ + Merge comment tokens that belong to the same comment. + + A single inline comment is tokenized into one token per cell, and only the first one starts with ``#``. + Emitting the remaining cells as separate comments would turn them into executable lines. + """ + merged: list[str] = [] + for comment in comments: + if merged and not comment.value.startswith("#"): + merged[-1] = f"{merged[-1]} {comment.value}" + else: + merged.append(comment.value) + return merged + @staticmethod def resolve_variable_name(name: str) -> str | None: name = name.removeprefix("\\") diff --git a/tests/formatter/formatters/ReplaceWithVAR/test_formatter.py b/tests/formatter/formatters/ReplaceWithVAR/test_formatter.py index 003e44a77..6414b428b 100644 --- a/tests/formatter/formatters/ReplaceWithVAR/test_formatter.py +++ b/tests/formatter/formatters/ReplaceWithVAR/test_formatter.py @@ -1,3 +1,7 @@ +import pytest +import typer + +from robocop.run import format_files from tests.formatter import FormatterAcceptanceTest @@ -53,3 +57,23 @@ def test_match_assignment(self): def test_item_access(self): self.compare(source="item_access.robot", not_modified=True) + + @pytest.mark.parametrize( + ("keyword_call", "expected_comment"), + [ + ( + "&{task_dict} Create Dictionary # Task State=Task Name Subtask Status=Subtask Name", + " # Task State=Task Name Subtask Status=Subtask Name", + ), + ("@{list} Create List value # comment with cells", " # comment with cells"), + ], + ) + def test_inline_comment_is_not_split_into_keyword_calls(self, keyword_call, expected_comment, tmp_path): + """Cells of a single inline comment must stay in one comment line (#1715).""" + source = tmp_path / "inline_comment.robot" + source.write_text(f"*** Test Cases ***\nTest\n {keyword_call}\n", encoding="utf-8") + + with pytest.raises(typer.Exit): + format_files(sources=[source], select=[self.FORMATTER_NAME], overwrite=True, cache=False) + + assert source.read_text(encoding="utf-8").splitlines()[2] == expected_comment