From 1a50eb712b6ee21b3674400a915952f46fda12ab Mon Sep 17 00:00:00 2001 From: Ajinkya Udgirkar Date: Thu, 22 Jun 2023 14:46:30 +0530 Subject: [PATCH] Fixed error when sarif file option is provided (#3587) --- .github/workflows/tox.yml | 2 +- src/ansiblelint/app.py | 6 +++++- test/test_formatter_sarif.py | 21 +++++++++++++++++++++ 3 files changed, 27 insertions(+), 2 deletions(-) diff --git a/.github/workflows/tox.yml b/.github/workflows/tox.yml index abba51fc38..b1ce2f6a03 100644 --- a/.github/workflows/tox.yml +++ b/.github/workflows/tox.yml @@ -61,7 +61,7 @@ jobs: WSLENV: FORCE_COLOR:PYTEST_REQPASS:TOXENV:GITHUB_STEP_SUMMARY # Number of expected test passes, safety measure for accidental skip of # tests. Update value if you add/remove tests. - PYTEST_REQPASS: 804 + PYTEST_REQPASS: 805 steps: - name: Activate WSL1 if: "contains(matrix.shell, 'wsl')" diff --git a/src/ansiblelint/app.py b/src/ansiblelint/app.py index 5cc6a3c3a9..52581b3e65 100644 --- a/src/ansiblelint/app.py +++ b/src/ansiblelint/app.py @@ -103,7 +103,11 @@ def render_matches(self, matches: list[MatchError]) -> None: if self.options.sarif_file: sarif = formatters.SarifFormatter(self.options.cwd, True) json = sarif.format_result(matches) - with self.options.sarif_file.open("w", encoding="utf-8") as sarif_file: + with Path.open( + self.options.sarif_file, + "w", + encoding="utf-8", + ) as sarif_file: sarif_file.write(json) def count_results(self, matches: list[MatchError]) -> SummarizedResults: diff --git a/test/test_formatter_sarif.py b/test/test_formatter_sarif.py index 8be8109954..b86257432d 100644 --- a/test/test_formatter_sarif.py +++ b/test/test_formatter_sarif.py @@ -169,3 +169,24 @@ def test_sarif_file(file: str, return_code: int) -> None: assert result.returncode == return_code assert os.path.exists(output_file.name) # noqa: PTH110 assert os.path.getsize(output_file.name) > 0 + + +@pytest.mark.parametrize( + ("file", "return_code"), + (pytest.param("examples/playbooks/valid.yml", 0),), +) +def test_sarif_file_creates_it_if_none_exists(file: str, return_code: int) -> None: + """Test ability to create sarif file if none exists and dump output to it (--sarif-file).""" + sarif_file_name = "test_output.sarif" + cmd = [ + sys.executable, + "-m", + "ansiblelint", + "--sarif-file", + sarif_file_name, + ] + result = subprocess.run([*cmd, file], check=False, capture_output=True) + assert result.returncode == return_code + assert os.path.exists(sarif_file_name) # noqa: PTH110 + assert os.path.getsize(sarif_file_name) > 0 + os.remove(sarif_file_name)