| 1 |
|
| 2 |
|
| 3 |
|
| 4 |
"""Test anta.reporter.md_reporter.py.""" |
| 5 |
|
| 6 |
from __future__ import annotations |
| 7 |
|
| 8 |
from datetime import datetime, timedelta, timezone |
| 9 |
from io import StringIO |
| 10 |
from pathlib import Path |
| 11 |
from typing import TYPE_CHECKING, ClassVar |
| 12 |
from unittest.mock import patch |
| 13 |
|
| 14 |
import pytest |
| 15 |
|
| 16 |
|
| 17 |
from anta.reporter.md_reporter import MDReportBase, MDReportGenerator |
| 18 |
from anta.reporter.md_reporter import TestResults as MDTestResults |
| 19 |
from anta.result_manager import ResultManager |
| 20 |
from anta.result_manager.models import AntaTestStatus |
| 21 |
from anta.tools import convert_categories |
| 22 |
|
| 23 |
if TYPE_CHECKING: |
| 24 |
from collections.abc import Generator |
| 25 |
|
| 26 |
from tests.units.result_manager.conftest import ResultManagerFactoryProtocol |
| 27 |
|
| 28 |
DATA_DIR: Path = Path(__file__).parent.parent.parent.resolve() / "data" |
| 29 |
|
| 30 |
|
| 31 |
class FailedTestResultsSummary(MDReportBase): |
| 32 |
"""Test-only class used for simulating behavior in unit tests. |
| 33 |
|
| 34 |
Generates the `## Failed Test Results Summary` section of the markdown report. |
| 35 |
""" |
| 36 |
|
| 37 |
TABLE_HEADING: ClassVar[list[str]] = [ |
| 38 |
"| Device Under Test | Categories | Test | Description | Custom Field | Result | Messages |", |
| 39 |
"| ----------------- | ---------- | ---- | ----------- | ------------ | ------ | -------- |", |
| 40 |
] |
| 41 |
|
| 42 |
def generate_rows(self) -> Generator[str, None, None]: |
| 43 |
"""Generate the rows of the all test results table.""" |
| 44 |
for result in self.results.results: |
| 45 |
messages = self.safe_markdown(result.messages[0]) if len(result.messages) == 1 else self.safe_markdown("<br>".join(result.messages)) |
| 46 |
categories = ", ".join(sorted(convert_categories(result.categories))) |
| 47 |
yield ( |
| 48 |
f"| {result.name or '-'} | {categories or '-'} | {result.test or '-'} " |
| 49 |
f"| {result.description or '-'} | {self.safe_markdown(result.custom_field) or '-'} | {result.result or '-'} | {messages or '-'} |\n" |
| 50 |
) |
| 51 |
|
| 52 |
def generate_section(self) -> None: |
| 53 |
"""Generate the `## Failed Test Results Summary` section of the markdown report.""" |
| 54 |
self.write_heading(heading_level=2) |
| 55 |
self.write_table(table_heading=self.TABLE_HEADING) |
| 56 |
|
| 57 |
|
| 58 |
def test_md_report_generator_generate(tmp_path: Path, result_manager: ResultManager) -> None: |
| 59 |
"""Test the MDReportGenerator.generate() class method.""" |
| 60 |
md_filename = tmp_path / "test.md" |
| 61 |
expected_report = "test_md_report.md" |
| 62 |
|
| 63 |
|
| 64 |
MDReportGenerator.generate(result_manager.sort(sort_by=["name", "categories", "test"]), md_filename) |
| 65 |
assert md_filename.exists() |
| 66 |
|
| 67 |
|
| 68 |
with (DATA_DIR / expected_report).open("r", encoding="utf-8") as f: |
| 69 |
expected_content = f.read() |
| 70 |
|
| 71 |
|
| 72 |
content = md_filename.read_text(encoding="utf-8") |
| 73 |
|
| 74 |
assert content == expected_content |
| 75 |
|
| 76 |
|
| 77 |
def test_md_report_generator_generate_with_extra_data(tmp_path: Path, result_manager: ResultManager) -> None: |
| 78 |
"""Test the MDReportGenerator.generate() class method with extra_data.""" |
| 79 |
md_filename = tmp_path / "test.md" |
| 80 |
expected_report = "test_md_report_extra_data.md" |
| 81 |
|
| 82 |
|
| 83 |
start_time = datetime(2025, 5, 20, 8, 30, 0, tzinfo=timezone.utc) |
| 84 |
end_time = datetime(2025, 5, 20, 8, 35, 30, 500000, tzinfo=timezone.utc) |
| 85 |
extra_data = { |
| 86 |
"anta_version": "v1.4.0", |
| 87 |
"test_execution_start_time": start_time, |
| 88 |
"test_execution_end_time": end_time, |
| 89 |
"total_duration": end_time - start_time, |
| 90 |
"total_devices_in_inventory": 4, |
| 91 |
"devices_unreachable_at_setup": ["s1-spine2"], |
| 92 |
"devices_filtered_at_setup": ["s1-leaf1", "s1-leaf2"], |
| 93 |
"filters_applied": {"tags": ["spine"]}, |
| 94 |
"custom_metric": "Created by Arista", |
| 95 |
} |
| 96 |
|
| 97 |
|
| 98 |
extra_data["_report_options"] = {"expand_results": True} |
| 99 |
|
| 100 |
|
| 101 |
MDReportGenerator.generate(result_manager.sort(sort_by=["name", "categories", "test"]), md_filename, extra_data) |
| 102 |
assert md_filename.exists() |
| 103 |
|
| 104 |
|
| 105 |
with (DATA_DIR / expected_report).open("r", encoding="utf-8") as f: |
| 106 |
expected_content = f.read() |
| 107 |
|
| 108 |
|
| 109 |
content = md_filename.read_text(encoding="utf-8") |
| 110 |
|
| 111 |
assert content == expected_content |
| 112 |
|
| 113 |
|
| 114 |
def test_md_report_generator_generate_sections(tmp_path: Path, result_manager: ResultManager) -> None: |
| 115 |
"""Test the MDReportGenerator.generate_sections() class method.""" |
| 116 |
md_filename = tmp_path / "test.md" |
| 117 |
expected_report = "test_md_report_custom_sections.md" |
| 118 |
rm = result_manager.sort(sort_by=["name", "categories", "test"]) |
| 119 |
|
| 120 |
sections = [(section, rm) for section in MDReportGenerator.DEFAULT_SECTIONS] |
| 121 |
|
| 122 |
failed_section = (FailedTestResultsSummary, rm.filter({AntaTestStatus.SUCCESS, AntaTestStatus.ERROR, AntaTestStatus.SKIPPED, AntaTestStatus.UNSET})) |
| 123 |
sections.insert(-1, failed_section) |
| 124 |
|
| 125 |
|
| 126 |
MDReportGenerator.generate_sections(sections, md_filename) |
| 127 |
assert md_filename.exists() |
| 128 |
|
| 129 |
|
| 130 |
with (DATA_DIR / expected_report).open("r", encoding="utf-8") as f: |
| 131 |
expected_content = f.read() |
| 132 |
|
| 133 |
|
| 134 |
content = md_filename.read_text(encoding="utf-8") |
| 135 |
|
| 136 |
assert content == expected_content |
| 137 |
|
| 138 |
|
| 139 |
def test_md_report_generator_generate_expand_results(tmp_path: Path, result_manager_factory: ResultManagerFactoryProtocol) -> None: |
| 140 |
"""Test the MDReportGenerator.generate() class method with expand_results.""" |
| 141 |
md_filename = tmp_path / "test.md" |
| 142 |
expected_report = "test_md_report_expand_results.md" |
| 143 |
|
| 144 |
statuses = [AntaTestStatus.SUCCESS, AntaTestStatus.FAILURE, AntaTestStatus.ERROR, AntaTestStatus.SKIPPED] |
| 145 |
result_manager = result_manager_factory(size=5, atomic_results_status=statuses, distinct_tests=True, distinct_devices=True) |
| 146 |
|
| 147 |
|
| 148 |
MDReportGenerator.generate(result_manager.sort(sort_by=["name", "categories", "test"]), md_filename, extra_data={"_report_options": {"expand_results": True}}) |
| 149 |
assert md_filename.exists() |
| 150 |
|
| 151 |
|
| 152 |
with (DATA_DIR / expected_report).open("r", encoding="utf-8") as f: |
| 153 |
expected_content = f.read() |
| 154 |
|
| 155 |
|
| 156 |
content = md_filename.read_text(encoding="utf-8") |
| 157 |
|
| 158 |
assert content == expected_content |
| 159 |
|
| 160 |
|
| 161 |
def test_md_report_generator_generate_no_custom_field(tmp_path: Path, result_manager_factory: ResultManagerFactoryProtocol) -> None: |
| 162 |
"""Test the MDReportGenerator.generate() class method with no custom field.""" |
| 163 |
md_filename = tmp_path / "test.md" |
| 164 |
expected_report = "test_md_report_no_custom_field.md" |
| 165 |
|
| 166 |
result_manager = result_manager_factory(size=5, distinct_tests=True, distinct_devices=True) |
| 167 |
|
| 168 |
|
| 169 |
MDReportGenerator.generate( |
| 170 |
result_manager.sort(sort_by=["name", "categories", "test"]), md_filename, extra_data={"_report_options": {"render_custom_field": False}} |
| 171 |
) |
| 172 |
assert md_filename.exists() |
| 173 |
|
| 174 |
|
| 175 |
with (DATA_DIR / expected_report).open("r", encoding="utf-8") as f: |
| 176 |
expected_content = f.read() |
| 177 |
|
| 178 |
|
| 179 |
content = md_filename.read_text(encoding="utf-8") |
| 180 |
|
| 181 |
assert content == expected_content |
| 182 |
|
| 183 |
|
| 184 |
def test_md_report_generator_generate_expand_results_no_custom_field(tmp_path: Path, result_manager_factory: ResultManagerFactoryProtocol) -> None: |
| 185 |
"""Test the MDReportGenerator.generate() class method with expand_results and no custom field.""" |
| 186 |
md_filename = tmp_path / "test.md" |
| 187 |
expected_report = "test_md_report_expand_results_no_custom_field.md" |
| 188 |
|
| 189 |
statuses = [AntaTestStatus.SUCCESS, AntaTestStatus.FAILURE, AntaTestStatus.ERROR, AntaTestStatus.SKIPPED] |
| 190 |
result_manager = result_manager_factory(size=5, atomic_results_status=statuses, distinct_tests=True, distinct_devices=True) |
| 191 |
|
| 192 |
|
| 193 |
MDReportGenerator.generate( |
| 194 |
result_manager.sort(sort_by=["name", "categories", "test"]), |
| 195 |
md_filename, |
| 196 |
extra_data={"_report_options": {"expand_results": True, "render_custom_field": False}}, |
| 197 |
) |
| 198 |
assert md_filename.exists() |
| 199 |
|
| 200 |
|
| 201 |
with (DATA_DIR / expected_report).open("r", encoding="utf-8") as f: |
| 202 |
expected_content = f.read() |
| 203 |
|
| 204 |
|
| 205 |
content = md_filename.read_text(encoding="utf-8") |
| 206 |
|
| 207 |
assert content == expected_content |
| 208 |
|
| 209 |
|
| 210 |
def test_md_report_generator_generate_sections_expand_results(tmp_path: Path, result_manager_factory: ResultManagerFactoryProtocol) -> None: |
| 211 |
"""Test the MDReportGenerator.generate_sections() class method with expand_results.""" |
| 212 |
md_filename = tmp_path / "test.md" |
| 213 |
expected_report = "test_md_report_custom_sections_expand_results.md" |
| 214 |
|
| 215 |
statuses = [AntaTestStatus.SUCCESS, AntaTestStatus.FAILURE, AntaTestStatus.ERROR, AntaTestStatus.SKIPPED] |
| 216 |
result_manager = result_manager_factory(size=5, atomic_results_status=statuses, distinct_tests=True, distinct_devices=True) |
| 217 |
|
| 218 |
sections: list[tuple[type[MDReportBase], ResultManager]] = [(MDTestResults, result_manager.sort(sort_by=["name", "categories", "test"]))] |
| 219 |
|
| 220 |
|
| 221 |
MDReportGenerator.generate_sections(sections, md_filename, extra_data={"_report_options": {"expand_results": True}}) |
| 222 |
assert md_filename.exists() |
| 223 |
|
| 224 |
|
| 225 |
with (DATA_DIR / expected_report).open("r", encoding="utf-8") as f: |
| 226 |
expected_content = f.read() |
| 227 |
|
| 228 |
|
| 229 |
content = md_filename.read_text(encoding="utf-8") |
| 230 |
|
| 231 |
assert content == expected_content |
| 232 |
|
| 233 |
|
| 234 |
def test_md_report_generator_generate_sections_no_custom_field(tmp_path: Path, result_manager_factory: ResultManagerFactoryProtocol) -> None: |
| 235 |
"""Test the MDReportGenerator.generate_sections() class method with no custom field.""" |
| 236 |
md_filename = tmp_path / "test.md" |
| 237 |
expected_report = "test_md_report_custom_sections_no_custom_field.md" |
| 238 |
|
| 239 |
result_manager = result_manager_factory(size=5, distinct_tests=True, distinct_devices=True) |
| 240 |
|
| 241 |
sections: list[tuple[type[MDReportBase], ResultManager]] = [(MDTestResults, result_manager.sort(sort_by=["name", "categories", "test"]))] |
| 242 |
|
| 243 |
|
| 244 |
MDReportGenerator.generate_sections(sections, md_filename, extra_data={"_report_options": {"render_custom_field": False}}) |
| 245 |
assert md_filename.exists() |
| 246 |
|
| 247 |
|
| 248 |
with (DATA_DIR / expected_report).open("r", encoding="utf-8") as f: |
| 249 |
expected_content = f.read() |
| 250 |
|
| 251 |
|
| 252 |
content = md_filename.read_text(encoding="utf-8") |
| 253 |
|
| 254 |
assert content == expected_content |
| 255 |
|
| 256 |
|
| 257 |
def test_md_report_generator_generate_sections_expand_results_custom_columns(tmp_path: Path, result_manager_factory: ResultManagerFactoryProtocol) -> None: |
| 258 |
"""Test the MDReportGenerator.generate_sections() class method with expand_results and custom columns.""" |
| 259 |
md_filename = tmp_path / "test.md" |
| 260 |
expected_report = "test_md_report_custom_sections_expand_results_custom_columns.md" |
| 261 |
|
| 262 |
statuses = [AntaTestStatus.SUCCESS, AntaTestStatus.FAILURE, AntaTestStatus.ERROR, AntaTestStatus.SKIPPED] |
| 263 |
result_manager = result_manager_factory(size=5, atomic_results_status=statuses, distinct_tests=True, distinct_devices=True) |
| 264 |
|
| 265 |
custom_columns = ["DUT", "CAT", "TEST", "DESC", "RES", "MSGS"] |
| 266 |
with patch("anta.reporter.md_reporter.TestResults._TABLE_COLUMNS", custom_columns): |
| 267 |
sections: list[tuple[type[MDReportBase], ResultManager]] = [(MDTestResults, result_manager.sort(sort_by=["name", "categories", "test"]))] |
| 268 |
|
| 269 |
|
| 270 |
MDReportGenerator.generate_sections(sections, md_filename, extra_data={"_report_options": {"expand_results": True, "render_custom_field": False}}) |
| 271 |
|
| 272 |
assert md_filename.exists() |
| 273 |
|
| 274 |
|
| 275 |
with (DATA_DIR / expected_report).open("r", encoding="utf-8") as f: |
| 276 |
expected_content = f.read() |
| 277 |
|
| 278 |
|
| 279 |
content = md_filename.read_text(encoding="utf-8") |
| 280 |
|
| 281 |
assert content == expected_content |
| 282 |
|
| 283 |
|
| 284 |
def test_md_report_base() -> None: |
| 285 |
"""Test the MDReportBase class.""" |
| 286 |
|
| 287 |
class FakeMDReportBase(MDReportBase): |
| 288 |
"""Fake MDReportBase class.""" |
| 289 |
|
| 290 |
def generate_section(self) -> None: |
| 291 |
pass |
| 292 |
|
| 293 |
results = ResultManager() |
| 294 |
|
| 295 |
with StringIO() as mock_file: |
| 296 |
report = FakeMDReportBase(mock_file, results) |
| 297 |
assert report.generate_heading_name() == "Fake MD Report Base" |
| 298 |
|
| 299 |
with pytest.raises(NotImplementedError, match="Subclasses should implement this method"): |
| 300 |
report.generate_rows() |
| 301 |
|
| 302 |
|
| 303 |
@pytest.mark.parametrize( |
| 304 |
("value", "expected_output"), |
| 305 |
[ |
| 306 |
pytest.param("hello_world", "Hello World", id="snake_to_title_case"), |
| 307 |
pytest.param("anta_version", "ANTA Version", id="anta_acronym_handling"), |
| 308 |
pytest.param("bgp_protocol", "BGP Protocol", id="bgp_acronym_handling"), |
| 309 |
pytest.param("", "", id="empty_string"), |
| 310 |
pytest.param("name", "Name", id="single_word"), |
| 311 |
pytest.param("this_is_a_test", "This Is A Test", id="multiple_underscores"), |
| 312 |
pytest.param("_leading_underscore", " Leading Underscore", id="leading_underscore"), |
| 313 |
pytest.param("mixed_CASE_string", "Mixed Case String", id="mixed_case_parts"), |
| 314 |
], |
| 315 |
) |
| 316 |
def test_md_report_base_format_snake_case_to_title_case(value: str, expected_output: str) -> None: |
| 317 |
"""Test the MDReportBase.format_snake_case_to_title_casey() method.""" |
| 318 |
|
| 319 |
class FakeMDReportBase(MDReportBase): |
| 320 |
"""Fake MDReportBase class.""" |
| 321 |
|
| 322 |
def generate_section(self) -> None: |
| 323 |
pass |
| 324 |
|
| 325 |
results = ResultManager() |
| 326 |
|
| 327 |
with StringIO() as mock_file: |
| 328 |
report = FakeMDReportBase(mock_file, results) |
| 329 |
assert report.format_snake_case_to_title_case(value) == expected_output |
| 330 |
|
| 331 |
|
| 332 |
@pytest.mark.parametrize( |
| 333 |
("value", "expected_output"), |
| 334 |
[ |
| 335 |
|
| 336 |
pytest.param(datetime(2023, 1, 15, 10, 30, 45, 123456, tzinfo=timezone.utc), "2023-01-15 10:30:45.123+00:00", id="datetime_with_milliseconds"), |
| 337 |
pytest.param(datetime(2024, 7, 20, 14, 0, 0, tzinfo=timezone.utc), "2024-07-20 14:00:00.000+00:00", id="datetime_without_milliseconds"), |
| 338 |
|
| 339 |
pytest.param(timedelta(hours=1, minutes=5, seconds=30, milliseconds=500), "1 hour, 5 minutes, 30 seconds", id="timedelta_full"), |
| 340 |
pytest.param(timedelta(days=2), "48 hours", id="timedelta_only_days"), |
| 341 |
pytest.param(timedelta(hours=2), "2 hours", id="timedelta_only_hours"), |
| 342 |
pytest.param(timedelta(minutes=1), "1 minute", id="timedelta_only_minute"), |
| 343 |
pytest.param(timedelta(seconds=45), "45 seconds", id="timedelta_only_seconds"), |
| 344 |
pytest.param(timedelta(milliseconds=100), "100 milliseconds", id="timedelta_only_milliseconds"), |
| 345 |
pytest.param(timedelta(microseconds=100000), "100 milliseconds", id="timedelta_only_microseconds"), |
| 346 |
pytest.param(timedelta(microseconds=999), "0 seconds", id="timedelta_sub_milliseconds"), |
| 347 |
pytest.param(timedelta(0), "0 seconds", id="timedelta_zero"), |
| 348 |
pytest.param(timedelta(seconds=-10), "Invalid duration", id="timedelta_negative"), |
| 349 |
pytest.param(timedelta(days=1, hours=3, minutes=20), "27 hours, 20 minutes", id="timedelta_days_to_hours"), |
| 350 |
|
| 351 |
pytest.param(["apple", "banana", "cherry"], "apple, banana, cherry", id="list_of_strings"), |
| 352 |
pytest.param([1, 2, 3], "1, 2, 3", id="list_of_integers"), |
| 353 |
pytest.param(["text", 123, True], "text, 123, True", id="list_of_mixed_types"), |
| 354 |
pytest.param([], "", id="empty_list"), |
| 355 |
|
| 356 |
pytest.param("simple string", "simple string", id="string_value"), |
| 357 |
pytest.param(123, "123", id="integer_value"), |
| 358 |
pytest.param(3.14, "3.14", id="float_value"), |
| 359 |
pytest.param(True, "True", id="boolean_value"), |
| 360 |
pytest.param(None, "None", id="none_value"), |
| 361 |
], |
| 362 |
) |
| 363 |
def test_md_report_base_format_value(value: str, expected_output: str) -> None: |
| 364 |
"""Test the MDReportBase.format_value() method.""" |
| 365 |
|
| 366 |
class FakeMDReportBase(MDReportBase): |
| 367 |
"""Fake MDReportBase class.""" |
| 368 |
|
| 369 |
def generate_section(self) -> None: |
| 370 |
pass |
| 371 |
|
| 372 |
results = ResultManager() |
| 373 |
|
| 374 |
with StringIO() as mock_file: |
| 375 |
report = FakeMDReportBase(mock_file, results) |
| 376 |
assert report.format_value(value) == expected_output |
| 377 |
|
| 378 |
|
| 379 |
def test_md_report_error(result_manager: ResultManager) -> None: |
| 380 |
"""Test the MDReportGenerator class to OSError to be raised.""" |
| 381 |
md_filename = Path("non_existent_directory/non_existent_file.md") |
| 382 |
rm = result_manager.sort(sort_by=["name", "categories", "test"]) |
| 383 |
|
| 384 |
sections = [(section, rm) for section in MDReportGenerator.DEFAULT_SECTIONS] |
| 385 |
|
| 386 |
with pytest.raises(OSError, match="No such file or directory"): |
| 387 |
MDReportGenerator.generate_sections(sections, md_filename) |
| 388 |
|
| 389 |
with pytest.raises(OSError, match="No such file or directory"): |
| 390 |
MDReportGenerator.generate(result_manager, md_filename) |