1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227
|
"""Test the codeclimate JSON formatter."""
from __future__ import annotations
import json
import os
import pathlib
import subprocess
import sys
from tempfile import NamedTemporaryFile
import pytest
from ansiblelint.app import get_app
from ansiblelint.errors import MatchError
from ansiblelint.file_utils import Lintable
from ansiblelint.formatters import SarifFormatter
from ansiblelint.rules import AnsibleLintRule, RulesCollection
class TestSarifFormatter:
"""Unit test for SarifFormatter."""
rule1 = AnsibleLintRule()
rule2 = AnsibleLintRule()
matches: list[MatchError] = []
formatter: SarifFormatter | None = None
collection = RulesCollection(app=get_app(offline=True))
collection.register(rule1)
collection.register(rule2)
def setup_class(self) -> None:
"""Set up few MatchError objects."""
self.rule1.id = "TCF0001"
self.rule1.severity = "VERY_HIGH"
self.rule1.description = "This is the rule description."
self.rule1.link = "https://rules/help#TCF0001"
self.rule1.tags = ["tag1", "tag2"]
self.rule2.id = "TCF0002"
self.rule2.severity = "MEDIUM"
self.rule2.link = "https://rules/help#TCF0002"
self.rule2.tags = ["tag3", "tag4"]
self.matches.extend(
[
MatchError(
message="message1",
lineno=1,
column=10,
details="details1",
lintable=Lintable("filename1.yml", content=""),
rule=self.rule1,
tag="yaml[test1]",
ignored=False,
),
MatchError(
message="message2",
lineno=2,
details="",
lintable=Lintable("filename2.yml", content=""),
rule=self.rule1,
tag="yaml[test2]",
ignored=True,
),
MatchError(
message="message3",
lineno=666,
column=667,
details="details3",
lintable=Lintable("filename3.yml", content=""),
rule=self.rule2,
tag="yaml[test3]",
ignored=False,
),
],
)
self.formatter = SarifFormatter(pathlib.Path.cwd(), display_relative_path=True)
def test_sarif_format_list(self) -> None:
"""Test if the return value is a string."""
assert isinstance(self.formatter, SarifFormatter)
assert isinstance(self.formatter.format_result(self.matches), str)
def test_sarif_result_is_json(self) -> None:
"""Test if returned string value is a JSON."""
assert isinstance(self.formatter, SarifFormatter)
output = self.formatter.format_result(self.matches)
json.loads(output)
# https://github.com/ansible/ansible-navigator/issues/1490
assert "\n" not in output
def test_sarif_single_match(self) -> None:
"""Test negative case. Only lists are allowed. Otherwise, a RuntimeError will be raised."""
assert isinstance(self.formatter, SarifFormatter)
with pytest.raises(TypeError):
self.formatter.format_result(self.matches[0]) # type: ignore[arg-type]
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"]) == 3
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."""
assert isinstance(self.formatter, SarifFormatter)
sarif = json.loads(self.formatter.format_result(self.matches))
assert sarif["$schema"] == SarifFormatter.SARIF_SCHEMA
assert sarif["version"] == SarifFormatter.SARIF_SCHEMA_VERSION
driver = sarif["runs"][0]["tool"]["driver"]
assert driver["name"] == SarifFormatter.TOOL_NAME
assert driver["informationUri"] == SarifFormatter.TOOL_URL
rules = driver["rules"]
assert len(rules) == 3
assert rules[0]["id"] == self.matches[0].tag
assert rules[0]["name"] == self.matches[0].tag
assert rules[0]["shortDescription"]["text"] == self.matches[0].message
assert rules[0]["defaultConfiguration"][
"level"
] == SarifFormatter.get_sarif_rule_severity_level(self.matches[0].rule)
assert rules[0]["help"]["text"] == self.matches[0].rule.description
assert rules[0]["properties"]["tags"] == self.matches[0].rule.tags
assert rules[0]["helpUri"] == self.matches[0].rule.url
results = sarif["runs"][0]["results"]
assert len(results) == 3
for i, result in enumerate(results):
assert result["ruleId"] == self.matches[i].tag
assert (
result["locations"][0]["physicalLocation"]["artifactLocation"]["uri"]
== self.matches[i].filename
)
assert (
result["locations"][0]["physicalLocation"]["artifactLocation"][
"uriBaseId"
]
== SarifFormatter.BASE_URI_ID
)
assert (
result["locations"][0]["physicalLocation"]["region"]["startLine"]
== self.matches[i].lineno
)
if self.matches[i].column:
assert (
result["locations"][0]["physicalLocation"]["region"]["startColumn"]
== self.matches[i].column
)
else:
assert (
"startColumn"
not in result["locations"][0]["physicalLocation"]["region"]
)
assert result["level"] == SarifFormatter.get_sarif_result_severity_level(
self.matches[i],
)
assert sarif["runs"][0]["originalUriBaseIds"][SarifFormatter.BASE_URI_ID]["uri"]
assert results[0]["message"]["text"] == self.matches[0].details
assert results[1]["message"]["text"] == self.matches[1].message
def test_sarif_parsable_ignored() -> None:
"""Test that -p option does not alter SARIF format."""
cmd = [
sys.executable,
"-m",
"ansiblelint",
"-v",
"-p",
]
file = "examples/playbooks/empty_playbook.yml"
result = subprocess.run([*cmd, file], check=False)
result2 = subprocess.run([*cmd, "-p", file], check=False)
assert result.returncode == result2.returncode
assert result.stdout == result2.stdout
@pytest.mark.parametrize(
("file", "return_code"),
(
pytest.param("examples/playbooks/valid.yml", 0, id="0"),
pytest.param("playbook.yml", 2, id="1"),
),
)
def test_sarif_file(file: str, return_code: int) -> None:
"""Test ability to dump sarif file (--sarif-file)."""
with NamedTemporaryFile(
mode="w", suffix=".sarif", prefix="output", encoding="utf-8"
) as output_file:
cmd = [
sys.executable,
"-m",
"ansiblelint",
"--sarif-file",
str(output_file.name),
]
result = subprocess.run([*cmd, file], check=False, capture_output=True)
assert result.returncode == return_code
assert os.path.exists(output_file.name) # noqa: PTH110
assert pathlib.Path(output_file.name).stat().st_size > 0
@pytest.mark.parametrize(
("file", "return_code"),
(pytest.param("examples/playbooks/valid.yml", 0, id="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 pathlib.Path(sarif_file_name).stat().st_size > 0
pathlib.Path.unlink(pathlib.Path(sarif_file_name))
|