From c2e86d9cb8896f05a959951835502f59fb613027 Mon Sep 17 00:00:00 2001 From: Sorin Sbarnea Date: Wed, 20 Sep 2023 14:45:24 +0100 Subject: [PATCH] Include level in SARIF results (#3758) --- src/ansiblelint/formatters/__init__.py | 9 +++++++++ test/test_formatter_sarif.py | 9 +++++++-- 2 files changed, 16 insertions(+), 2 deletions(-) diff --git a/src/ansiblelint/formatters/__init__.py b/src/ansiblelint/formatters/__init__.py index 9ddca00acc..84868eadb6 100644 --- a/src/ansiblelint/formatters/__init__.py +++ b/src/ansiblelint/formatters/__init__.py @@ -275,8 +275,17 @@ def _to_sarif_rule(self, match: MatchError) -> dict[str, Any]: return rule def _to_sarif_result(self, match: MatchError) -> dict[str, Any]: + # https://docs.oasis-open.org/sarif/sarif/v2.1.0/errata01/os/sarif-v2.1.0-errata01-os-complete.html#_Toc141790898 + if match.level not in ("warning", "error", "note", "none"): + msg = "Unexpected failure to map '%s' level to SARIF." + raise RuntimeError( + msg, + match.level, + ) + result: dict[str, Any] = { "ruleId": match.tag, + "level": match.level, "message": { "text": str(match.details) if str(match.details) diff --git a/test/test_formatter_sarif.py b/test/test_formatter_sarif.py index 68b8e7b898..1b33fda637 100644 --- a/test/test_formatter_sarif.py +++ b/test/test_formatter_sarif.py @@ -74,11 +74,16 @@ def test_single_match(self) -> None: with pytest.raises(RuntimeError): self.formatter.format_result(self.matches[0]) # type: ignore[arg-type] - def test_result_is_list(self) -> None: - """Test if the return SARIF object contains the results with length of 2.""" + def test_sarif_format(self) -> None: + """Test if the return SARIF object contains the expected results.""" assert isinstance(self.formatter, SarifFormatter) sarif = json.loads(self.formatter.format_result(self.matches)) assert len(sarif["runs"][0]["results"]) == 2 + for result in sarif["runs"][0]["results"]: + # Ensure all reported entries have a level + assert "level" in result + # Ensure reported levels are either error or warning + assert result["level"] in ("error", "warning") def test_validate_sarif_schema(self) -> None: """Test if the returned JSON is a valid SARIF report."""