| 1 |
|
| 2 |
|
| 3 |
|
| 4 |
"""Test anta._runner.py.""" |
| 5 |
|
| 6 |
from __future__ import annotations |
| 7 |
|
| 8 |
import logging |
| 9 |
import os |
| 10 |
from collections import defaultdict |
| 11 |
from pathlib import Path |
| 12 |
from typing import ClassVar |
| 13 |
from unittest.mock import AsyncMock, patch |
| 14 |
|
| 15 |
import pytest |
| 16 |
import respx |
| 17 |
from pydantic import ValidationError |
| 18 |
|
| 19 |
from anta._runner import AntaRunContext, AntaRunFilters, AntaRunner |
| 20 |
from anta.catalog import AntaCatalog, AntaTestDefinition |
| 21 |
from anta.device import AsyncEOSDevice |
| 22 |
from anta.inventory import AntaInventory |
| 23 |
from anta.models import AntaCommand, AntaTemplate, AntaTest |
| 24 |
from anta.result_manager import ResultManager |
| 25 |
from anta.result_manager.models import TestResult as AntaTestResult |
| 26 |
from anta.settings import DEFAULT_MAX_CONCURRENCY, DEFAULT_NOFILE, AntaRunnerSettings |
| 27 |
from anta.tests.routing.generic import VerifyRoutingTableEntry |
| 28 |
from tests.units.test_models import FakeTest |
| 29 |
|
| 30 |
DATA_DIR: Path = Path(__file__).parent.parent.resolve() / "data" |
| 31 |
|
| 32 |
|
| 33 |
|
| 34 |
class TestAntaRunner: |
| 35 |
"""Test AntaRunner class.""" |
| 36 |
|
| 37 |
def test_init_with_default_settings(self, caplog: pytest.LogCaptureFixture) -> None: |
| 38 |
"""Test initialization with default settings.""" |
| 39 |
caplog.set_level(logging.DEBUG) |
| 40 |
default_settings = {"nofile": DEFAULT_NOFILE, "max_concurrency": DEFAULT_MAX_CONCURRENCY} |
| 41 |
|
| 42 |
runner = AntaRunner() |
| 43 |
|
| 44 |
assert f"AntaRunner initialized with settings: {default_settings}" in caplog.messages |
| 45 |
assert runner._settings |
| 46 |
|
| 47 |
def test_init_with_custom_env_settings(self, caplog: pytest.LogCaptureFixture, setenvvar: pytest.MonkeyPatch) -> None: |
| 48 |
"""Test initialization with custom env settings.""" |
| 49 |
caplog.set_level(logging.DEBUG) |
| 50 |
desired_settings = {"nofile": 1048576, "max_concurrency": 10000} |
| 51 |
setenvvar.setenv("ANTA_NOFILE", str(desired_settings["nofile"])) |
| 52 |
setenvvar.setenv("ANTA_MAX_CONCURRENCY", str(desired_settings["max_concurrency"])) |
| 53 |
|
| 54 |
runner = AntaRunner() |
| 55 |
|
| 56 |
assert f"AntaRunner initialized with settings: {desired_settings}" in caplog.messages |
| 57 |
assert runner._settings |
| 58 |
|
| 59 |
def test_init_with_provided_settings(self, caplog: pytest.LogCaptureFixture) -> None: |
| 60 |
"""Test initialization with provided settings.""" |
| 61 |
caplog.set_level(logging.DEBUG) |
| 62 |
desired_settings = AntaRunnerSettings(nofile=1048576, max_concurrency=10000) |
| 63 |
|
| 64 |
runner = AntaRunner(settings=desired_settings) |
| 65 |
|
| 66 |
assert f"AntaRunner initialized with settings: {desired_settings.model_dump()}" in caplog.messages |
| 67 |
assert runner._settings |
| 68 |
|
| 69 |
async def test_dry_run(self, caplog: pytest.LogCaptureFixture) -> None: |
| 70 |
"""Test AntaRunner.run() in dry-run.""" |
| 71 |
caplog.set_level(logging.INFO) |
| 72 |
|
| 73 |
inventory = AntaInventory.parse(filename=DATA_DIR / "test_inventory_with_tags.yml", username="anta", password="anta") |
| 74 |
catalog = AntaCatalog.parse(filename=DATA_DIR / "test_catalog_with_tags.yml") |
| 75 |
runner = AntaRunner() |
| 76 |
ctx = await runner.run(inventory, catalog, dry_run=True) |
| 77 |
|
| 78 |
|
| 79 |
assert ctx.selected_inventory == ctx.inventory == inventory |
| 80 |
assert len(ctx.manager) > 0 |
| 81 |
assert ctx.manager.status == "unset" |
| 82 |
assert ctx.total_tests_scheduled > 0 |
| 83 |
assert ctx.total_devices_filtered_by_tags == 0 |
| 84 |
assert ctx.total_devices_unreachable == 0 |
| 85 |
assert ctx.total_devices_selected_for_testing == ctx.total_devices_in_inventory == len(inventory) |
| 86 |
assert ctx.duration is not None |
| 87 |
|
| 88 |
assert "Dry-run mode, exiting before running the tests." in caplog.messages |
| 89 |
|
| 90 |
@pytest.mark.parametrize( |
| 91 |
("filters", "expected_devices", "expected_tests"), |
| 92 |
[ |
| 93 |
pytest.param( |
| 94 |
AntaRunFilters(devices=None, tests=None, tags=None), |
| 95 |
3, |
| 96 |
27, |
| 97 |
id="all-tests", |
| 98 |
), |
| 99 |
pytest.param( |
| 100 |
AntaRunFilters(devices=None, tests=None, tags={"leaf"}), |
| 101 |
2, |
| 102 |
6, |
| 103 |
id="1-tag", |
| 104 |
), |
| 105 |
pytest.param( |
| 106 |
AntaRunFilters(devices=None, tests=None, tags={"leaf", "spine"}), |
| 107 |
3, |
| 108 |
9, |
| 109 |
id="2-tags", |
| 110 |
), |
| 111 |
pytest.param( |
| 112 |
AntaRunFilters(devices=None, tests={"VerifyMlagStatus", "VerifyUptime"}, tags=None), |
| 113 |
3, |
| 114 |
5, |
| 115 |
id="filtered-tests", |
| 116 |
), |
| 117 |
pytest.param( |
| 118 |
AntaRunFilters(devices=None, tests={"VerifyMlagStatus", "VerifyUptime"}, tags={"leaf"}), |
| 119 |
2, |
| 120 |
4, |
| 121 |
id="1-tag-filtered-tests", |
| 122 |
), |
| 123 |
pytest.param( |
| 124 |
AntaRunFilters(devices={"leaf1"}, tests=None, tags=None), |
| 125 |
1, |
| 126 |
9, |
| 127 |
id="filtered-devices", |
| 128 |
), |
| 129 |
pytest.param( |
| 130 |
AntaRunFilters(devices=None, tests=None, tags={"invalid"}), |
| 131 |
0, |
| 132 |
0, |
| 133 |
id="invalid-tag", |
| 134 |
), |
| 135 |
pytest.param( |
| 136 |
AntaRunFilters(devices={"invalid"}, tests=None, tags=None), |
| 137 |
0, |
| 138 |
0, |
| 139 |
id="invalid-device", |
| 140 |
), |
| 141 |
pytest.param( |
| 142 |
AntaRunFilters(devices=None, tests={"invalid"}, tags=None), |
| 143 |
3, |
| 144 |
0, |
| 145 |
id="invalid-test", |
| 146 |
), |
| 147 |
pytest.param( |
| 148 |
AntaRunFilters(devices=None, tests=None, tags={"dc1"}), |
| 149 |
1, |
| 150 |
0, |
| 151 |
id="device-tag-no-tests", |
| 152 |
), |
| 153 |
], |
| 154 |
) |
| 155 |
async def test_run_filters(self, caplog: pytest.LogCaptureFixture, filters: AntaRunFilters, expected_devices: int, expected_tests: int) -> None: |
| 156 |
"""Test AntaRunner.run() with different filters.""" |
| 157 |
caplog.set_level(logging.WARNING) |
| 158 |
|
| 159 |
inventory = AntaInventory.parse(filename=DATA_DIR / "test_inventory_with_tags.yml", username="anta", password="anta") |
| 160 |
catalog = AntaCatalog.parse(filename=DATA_DIR / "test_catalog_with_tags.yml") |
| 161 |
runner = AntaRunner() |
| 162 |
ctx = await runner.run(inventory, catalog, filters=filters, dry_run=True) |
| 163 |
|
| 164 |
|
| 165 |
msg = None |
| 166 |
if expected_devices == 0: |
| 167 |
msg = "The inventory is empty after filtering by tags/devices. " |
| 168 |
if filters.devices: |
| 169 |
msg += f"Devices filter: {', '.join(sorted(filters.devices))}. " |
| 170 |
if filters.tags: |
| 171 |
msg += f"Tags filter: {', '.join(sorted(filters.tags))}. " |
| 172 |
msg += "Exiting ..." |
| 173 |
elif expected_tests == 0: |
| 174 |
msg = "No tests scheduled to run after filtering by tags/tests. " |
| 175 |
if filters.tests: |
| 176 |
msg += f"Tests filter: {', '.join(sorted(filters.tests))}. " |
| 177 |
if filters.tags: |
| 178 |
msg += f"Tags filter: {', '.join(sorted(filters.tags))}. " |
| 179 |
msg += "Exiting ..." |
| 180 |
|
| 181 |
if msg is not None: |
| 182 |
assert msg in ctx.warnings_at_setup |
| 183 |
assert msg in caplog.messages |
| 184 |
|
| 185 |
assert ctx.total_tests_scheduled == expected_tests |
| 186 |
assert ctx.total_devices_selected_for_testing == expected_devices |
| 187 |
|
| 188 |
async def test_run_invalid_filters(self) -> None: |
| 189 |
"""Test AntaRunner.run() with invalid filters.""" |
| 190 |
inventory = AntaInventory() |
| 191 |
catalog = AntaCatalog() |
| 192 |
runner = AntaRunner() |
| 193 |
|
| 194 |
with pytest.raises(ValidationError, match="1 validation error for AntaRunFilters"): |
| 195 |
await runner.run(inventory, catalog, filters=AntaRunFilters(devices="invalid"), dry_run=True) |
| 196 |
|
| 197 |
async def test_run_provided_manager(self) -> None: |
| 198 |
"""Test AntaRunner.run() with a provided ResultManager instance.""" |
| 199 |
inventory = AntaInventory.parse(filename=DATA_DIR / "test_inventory_with_tags.yml", username="anta", password="anta") |
| 200 |
catalog = AntaCatalog.parse(filename=DATA_DIR / "test_catalog_with_tags.yml") |
| 201 |
manager = ResultManager() |
| 202 |
runner = AntaRunner() |
| 203 |
|
| 204 |
ctx = await runner.run(inventory, catalog, manager, dry_run=True) |
| 205 |
assert isinstance(ctx.manager, ResultManager) |
| 206 |
assert ctx.manager is manager |
| 207 |
assert len(manager) == 27 |
| 208 |
|
| 209 |
async def test_run_provided_manager_not_empty(self, caplog: pytest.LogCaptureFixture) -> None: |
| 210 |
"""Test AntaRunner.run() with a provided non-empty ResultManager instance.""" |
| 211 |
caplog.set_level(logging.WARNING) |
| 212 |
|
| 213 |
inventory = AntaInventory.parse(filename=DATA_DIR / "test_inventory_with_tags.yml", username="anta", password="anta") |
| 214 |
catalog = AntaCatalog.parse(filename=DATA_DIR / "test_catalog_with_tags.yml") |
| 215 |
manager = ResultManager() |
| 216 |
test = AntaTestResult(name="DC1-LEAF1A", test="VerifyNTP", categories=["system"], description="NTP Test") |
| 217 |
runner = AntaRunner() |
| 218 |
manager.add(test) |
| 219 |
|
| 220 |
ctx = await runner.run(inventory, catalog, manager, dry_run=True) |
| 221 |
assert isinstance(ctx.manager, ResultManager) |
| 222 |
assert ctx.manager is manager |
| 223 |
assert len(manager) == 28 |
| 224 |
assert len(manager.device_stats) == ctx.total_devices_selected_for_testing + 1 |
| 225 |
|
| 226 |
warning_msg = ( |
| 227 |
"Appending new results to the provided ResultManager which already holds 1 results. Statistics in this run context are for the current execution only." |
| 228 |
) |
| 229 |
assert warning_msg in ctx.warnings_at_setup |
| 230 |
assert warning_msg in caplog.messages |
| 231 |
|
| 232 |
async def test_run_empty_catalog(self, caplog: pytest.LogCaptureFixture) -> None: |
| 233 |
"""Test AntaRunner.run() with an empty AntaCatalog.""" |
| 234 |
caplog.set_level(logging.WARNING) |
| 235 |
|
| 236 |
inventory = AntaInventory.parse(filename=DATA_DIR / "test_inventory_with_tags.yml", username="anta", password="anta") |
| 237 |
catalog = AntaCatalog() |
| 238 |
runner = AntaRunner() |
| 239 |
|
| 240 |
ctx = await runner.run(inventory, catalog) |
| 241 |
|
| 242 |
warning_msg = "The list of tests is empty. Exiting ..." |
| 243 |
assert warning_msg in ctx.warnings_at_setup |
| 244 |
assert warning_msg in caplog.messages |
| 245 |
|
| 246 |
async def test_run_empty_inventory(self, caplog: pytest.LogCaptureFixture) -> None: |
| 247 |
"""Test AntaRunner.run() with an empty AntaInventory.""" |
| 248 |
caplog.set_level(logging.WARNING) |
| 249 |
|
| 250 |
inventory = AntaInventory() |
| 251 |
catalog = AntaCatalog.parse(filename=DATA_DIR / "test_catalog_with_tags.yml") |
| 252 |
runner = AntaRunner() |
| 253 |
|
| 254 |
ctx = await runner.run(inventory, catalog) |
| 255 |
|
| 256 |
warning_msg = "The initial inventory is empty. Exiting ..." |
| 257 |
assert warning_msg in ctx.warnings_at_setup |
| 258 |
assert warning_msg in caplog.messages |
| 259 |
|
| 260 |
@pytest.mark.parametrize("inventory", [{"reachable": False}], indirect=True) |
| 261 |
async def test_run_no_reachable_devices(self, caplog: pytest.LogCaptureFixture, inventory: AntaInventory) -> None: |
| 262 |
"""Test AntaRunner.run() with an empty AntaInventory.""" |
| 263 |
caplog.set_level(logging.WARNING) |
| 264 |
|
| 265 |
catalog = AntaCatalog.parse(filename=DATA_DIR / "test_catalog_with_tags.yml") |
| 266 |
runner = AntaRunner() |
| 267 |
|
| 268 |
ctx = await runner.run(inventory, catalog) |
| 269 |
assert ctx.total_devices_unreachable == ctx.total_devices_in_inventory |
| 270 |
assert "device-0" in ctx.devices_unreachable_at_setup |
| 271 |
|
| 272 |
warning_msg = "No reachable devices found for testing after connectivity checks. Exiting ..." |
| 273 |
assert warning_msg in ctx.warnings_at_setup |
| 274 |
assert warning_msg in caplog.messages |
| 275 |
|
| 276 |
@pytest.mark.parametrize(("inventory"), [{"count": 2, "reachable": False}], indirect=True) |
| 277 |
async def test_run_disconnect_closes_unreachable_devices(self, inventory: AntaInventory) -> None: |
| 278 |
"""Test that disconnect closes devices touched during setup even when none are selected.""" |
| 279 |
catalog = AntaCatalog.parse(filename=DATA_DIR / "test_catalog_with_tags.yml") |
| 280 |
runner = AntaRunner() |
| 281 |
|
| 282 |
ctx = await runner.run(inventory, catalog, disconnect=True) |
| 283 |
|
| 284 |
assert len(ctx.selected_inventory) == 0 |
| 285 |
assert all(isinstance(device, AsyncEOSDevice) and device._client.is_closed for device in inventory.devices) |
| 286 |
|
| 287 |
async def test_run_disconnect_closes_reachable_and_unreachable_devices(self) -> None: |
| 288 |
"""Test that disconnect closes every connected device, not only devices selected for tests.""" |
| 289 |
reachable = AsyncEOSDevice(host="reachable.example.com", username="admin", password="password", name="reachable", disable_cache=True) |
| 290 |
unreachable = AsyncEOSDevice(host="unreachable.example.com", username="admin", password="password", name="unreachable", disable_cache=True) |
| 291 |
inventory = AntaInventory() |
| 292 |
inventory.add_device(reachable) |
| 293 |
inventory.add_device(unreachable) |
| 294 |
catalog = AntaCatalog.from_list([(FakeTest, None)]) |
| 295 |
runner = AntaRunner() |
| 296 |
|
| 297 |
async def refresh_reachable() -> None: |
| 298 |
reachable.is_online = True |
| 299 |
reachable.established = True |
| 300 |
reachable.hw_model = "pytest" |
| 301 |
|
| 302 |
async def refresh_unreachable() -> None: |
| 303 |
unreachable.is_online = False |
| 304 |
unreachable.established = False |
| 305 |
|
| 306 |
with ( |
| 307 |
patch.object(reachable, "refresh", new=AsyncMock(side_effect=refresh_reachable)), |
| 308 |
patch.object(unreachable, "refresh", new=AsyncMock(side_effect=refresh_unreachable)), |
| 309 |
): |
| 310 |
ctx = await runner.run(inventory, catalog, disconnect=True) |
| 311 |
|
| 312 |
assert list(ctx.selected_inventory) == ["reachable"] |
| 313 |
assert len(ctx.manager) == 1 |
| 314 |
assert reachable._client.is_closed |
| 315 |
assert unreachable._client.is_closed |
| 316 |
|
| 317 |
async def test_run_disconnect_excludes_filtered_devices(self) -> None: |
| 318 |
"""Test that disconnect only targets devices matching device/tag filters.""" |
| 319 |
included = AsyncEOSDevice(host="included.example.com", username="admin", password="password", name="included", disable_cache=True) |
| 320 |
excluded = AsyncEOSDevice(host="excluded.example.com", username="admin", password="password", name="excluded", disable_cache=True) |
| 321 |
inventory = AntaInventory() |
| 322 |
inventory.add_device(included) |
| 323 |
inventory.add_device(excluded) |
| 324 |
catalog = AntaCatalog.from_list([(FakeTest, None)]) |
| 325 |
runner = AntaRunner() |
| 326 |
|
| 327 |
async def refresh_included() -> None: |
| 328 |
included.is_online = True |
| 329 |
included.established = True |
| 330 |
included.hw_model = "pytest" |
| 331 |
|
| 332 |
with ( |
| 333 |
patch.object(included, "refresh", new=AsyncMock(side_effect=refresh_included)) as included_refresh, |
| 334 |
patch.object(excluded, "refresh", new=AsyncMock()) as excluded_refresh, |
| 335 |
patch.object(included, "disconnect", new=AsyncMock()) as included_disconnect, |
| 336 |
patch.object(excluded, "disconnect", new=AsyncMock()) as excluded_disconnect, |
| 337 |
): |
| 338 |
ctx = await runner.run(inventory, catalog, filters=AntaRunFilters(devices={"included"}), disconnect=True) |
| 339 |
|
| 340 |
assert list(ctx.selected_inventory) == ["included"] |
| 341 |
assert len(ctx.manager) == 1 |
| 342 |
included_refresh.assert_awaited_once() |
| 343 |
excluded_refresh.assert_not_awaited() |
| 344 |
included_disconnect.assert_awaited_once() |
| 345 |
excluded_disconnect.assert_not_awaited() |
| 346 |
|
| 347 |
async def test_run_disconnect_runs_with_empty_catalog(self, inventory: AntaInventory) -> None: |
| 348 |
"""Test that disconnect still runs when the run exits before inventory setup.""" |
| 349 |
catalog = AntaCatalog() |
| 350 |
runner = AntaRunner() |
| 351 |
|
| 352 |
with patch.object(inventory, "disconnect_inventory", new=AsyncMock()) as disconnect_inventory: |
| 353 |
ctx = await runner.run(inventory, catalog, disconnect=True) |
| 354 |
|
| 355 |
assert len(ctx.selected_inventory) == 0 |
| 356 |
disconnect_inventory.assert_awaited_once() |
| 357 |
|
| 358 |
async def test_run_disconnect_on_test_execution_exception(self) -> None: |
| 359 |
"""Test that disconnect runs when test execution raises unexpectedly.""" |
| 360 |
device = AsyncEOSDevice(host="device.example.com", username="admin", password="password", name="device", disable_cache=True) |
| 361 |
inventory = AntaInventory() |
| 362 |
inventory.add_device(device) |
| 363 |
catalog = AntaCatalog.from_list([(FakeTest, None)]) |
| 364 |
runner = AntaRunner() |
| 365 |
|
| 366 |
async def refresh() -> None: |
| 367 |
device.is_online = True |
| 368 |
device.established = True |
| 369 |
device.hw_model = "pytest" |
| 370 |
|
| 371 |
async def raise_during_execution() -> AntaTestResult: |
| 372 |
msg = "test execution failed" |
| 373 |
raise RuntimeError(msg) |
| 374 |
|
| 375 |
with ( |
| 376 |
patch.object(device, "refresh", new=AsyncMock(side_effect=refresh)), |
| 377 |
patch.object(runner, "_get_test_coroutines", return_value=[raise_during_execution()]), |
| 378 |
pytest.raises(RuntimeError, match="test execution failed"), |
| 379 |
): |
| 380 |
await runner.run(inventory, catalog, disconnect=True) |
| 381 |
|
| 382 |
assert device._client.is_closed |
| 383 |
|
| 384 |
async def test_run_invalid_anta_test(self, caplog: pytest.LogCaptureFixture) -> None: |
| 385 |
"""Test AntaRunner.run() with a provided non-empty ResultManager instance.""" |
| 386 |
caplog.set_level(logging.CRITICAL) |
| 387 |
|
| 388 |
class InvalidTest(AntaTest): |
| 389 |
"""ANTA test that raises an exception when test is called.""" |
| 390 |
|
| 391 |
categories: ClassVar[list[str]] = [] |
| 392 |
commands: ClassVar[list[AntaCommand | AntaTemplate]] = [] |
| 393 |
|
| 394 |
def test(self) -> None: |
| 395 |
"""Test function.""" |
| 396 |
msg = "Test not implemented" |
| 397 |
raise NotImplementedError(msg) |
| 398 |
|
| 399 |
inventory = AntaInventory.parse(filename=DATA_DIR / "test_inventory_with_tags.yml", username="anta", password="anta") |
| 400 |
test_definition = AntaTestDefinition(test=InvalidTest, inputs=None) |
| 401 |
catalog = AntaCatalog(tests=[test_definition]) |
| 402 |
runner = AntaRunner() |
| 403 |
|
| 404 |
ctx = await runner.run(inventory, catalog, dry_run=True) |
| 405 |
assert len(ctx.manager) == 0 |
| 406 |
|
| 407 |
error_msg = ( |
| 408 |
f"There is an error when creating test {__name__}.InvalidTest.\n" |
| 409 |
"If this is not a custom test implementation: " |
| 410 |
"Please reach out to the maintainer team or open an issue on Github: https://github.com/aristanetworks/anta.\n" |
| 411 |
"NotImplementedError: Test not implemented" |
| 412 |
) |
| 413 |
assert error_msg in caplog.messages |
| 414 |
|
| 415 |
async def test_log_run_information_default(self, caplog: pytest.LogCaptureFixture) -> None: |
| 416 |
"""Test AntaRunner._log_run_information with default settings.""" |
| 417 |
caplog.set_level(logging.INFO) |
| 418 |
|
| 419 |
inventory = AntaInventory.parse(filename=DATA_DIR / "test_inventory_with_tags.yml", username="anta", password="anta") |
| 420 |
catalog = AntaCatalog.parse(filename=DATA_DIR / "test_catalog_with_tags.yml") |
| 421 |
runner = AntaRunner() |
| 422 |
await runner.run(inventory, catalog, dry_run=True) |
| 423 |
|
| 424 |
expected_output = [ |
| 425 |
"Initial inventory contains 3 devices", |
| 426 |
"3 devices selected for testing", |
| 427 |
"27 total tests scheduled across all selected devices", |
| 428 |
] |
| 429 |
for line in expected_output: |
| 430 |
assert line in caplog.text |
| 431 |
|
| 432 |
async def test_log_run_information_filters(self, caplog: pytest.LogCaptureFixture) -> None: |
| 433 |
"""Test AntaRunner._log_run_information with filters.""" |
| 434 |
caplog.set_level(logging.INFO) |
| 435 |
|
| 436 |
inventory = AntaInventory.parse(filename=DATA_DIR / "test_inventory_with_tags.yml", username="anta", password="anta") |
| 437 |
catalog = AntaCatalog.parse(filename=DATA_DIR / "test_catalog_with_tags.yml") |
| 438 |
runner = AntaRunner() |
| 439 |
filters = AntaRunFilters(devices={"spine1"}) |
| 440 |
await runner.run(inventory, catalog, filters=filters, dry_run=True) |
| 441 |
|
| 442 |
expected_output = [ |
| 443 |
"Initial inventory contains 3 devices", |
| 444 |
"2 devices excluded by name/tag filters: leaf1, leaf2", |
| 445 |
"1 devices selected for testing", |
| 446 |
"9 total tests scheduled across all selected devices", |
| 447 |
] |
| 448 |
for line in expected_output: |
| 449 |
assert line in caplog.text |
| 450 |
|
| 451 |
async def test_log_run_information_concurrency_limit(self, caplog: pytest.LogCaptureFixture) -> None: |
| 452 |
"""Test AntaRunner._log_run_information with higher tests count than concurrency limit.""" |
| 453 |
caplog.set_level(logging.WARNING) |
| 454 |
|
| 455 |
inventory = AntaInventory.parse(filename=DATA_DIR / "test_inventory_with_tags.yml", username="anta", password="anta") |
| 456 |
catalog = AntaCatalog.parse(filename=DATA_DIR / "test_catalog_with_tags.yml") |
| 457 |
runner_settings = AntaRunnerSettings(max_concurrency=20) |
| 458 |
runner = AntaRunner(settings=runner_settings) |
| 459 |
|
| 460 |
ctx = await runner.run(inventory, catalog, dry_run=True) |
| 461 |
|
| 462 |
warning_msg = "Tests count (27) exceeds concurrent limit (20). Tests will be throttled. Please consult the ANTA FAQ." |
| 463 |
assert warning_msg in ctx.warnings_at_setup |
| 464 |
assert warning_msg in caplog.messages |
| 465 |
|
| 466 |
@pytest.mark.skipif(os.name != "posix", reason="Very unlikely to happen on non-POSIX systems due to sys.maxsize") |
| 467 |
async def test_log_run_information_file_descriptor_limit(self, caplog: pytest.LogCaptureFixture) -> None: |
| 468 |
"""Test AntaRunner._log_run_information with higher connections count than file descriptor limit.""" |
| 469 |
caplog.set_level(logging.WARNING) |
| 470 |
|
| 471 |
inventory = AntaInventory.parse(filename=DATA_DIR / "test_inventory_with_tags.yml", username="anta", password="anta") |
| 472 |
catalog = AntaCatalog.parse(filename=DATA_DIR / "test_catalog_with_tags.yml") |
| 473 |
runner_settings = AntaRunnerSettings(nofile=128) |
| 474 |
runner = AntaRunner(settings=runner_settings) |
| 475 |
|
| 476 |
ctx = await runner.run(inventory, catalog, dry_run=True) |
| 477 |
|
| 478 |
warning_msg = "Potential connections (300) exceeds file descriptor limit (128). Connection errors may occur. Please consult the ANTA FAQ." |
| 479 |
assert warning_msg in ctx.warnings_at_setup |
| 480 |
assert warning_msg in caplog.messages |
| 481 |
|
| 482 |
async def test_log_run_information_from_context(self, caplog: pytest.LogCaptureFixture) -> None: |
| 483 |
"""Test AntaRunner._log_run_information from a fake context.""" |
| 484 |
caplog.set_level(logging.INFO) |
| 485 |
|
| 486 |
inventory = AntaInventory.parse(filename=DATA_DIR / "test_inventory_with_tags.yml", username="anta", password="anta") |
| 487 |
catalog = AntaCatalog.parse(filename=DATA_DIR / "test_catalog_with_tags.yml") |
| 488 |
manager = ResultManager() |
| 489 |
filters = AntaRunFilters() |
| 490 |
context = AntaRunContext( |
| 491 |
inventory=inventory, |
| 492 |
catalog=catalog, |
| 493 |
manager=manager, |
| 494 |
filters=filters, |
| 495 |
) |
| 496 |
context.devices_filtered_at_setup = ["leaf1"] |
| 497 |
context.devices_unreachable_at_setup = ["leaf2"] |
| 498 |
context.selected_inventory.add_device(inventory["spine1"]) |
| 499 |
|
| 500 |
AntaRunner()._log_run_information(context) |
| 501 |
|
| 502 |
expected_output = [ |
| 503 |
"Initial inventory contains 3 devices", |
| 504 |
"1 devices excluded by name/tag filters: leaf1", |
| 505 |
"1 devices found unreachable after connection attempts: leaf2", |
| 506 |
"1 devices selected for testing", |
| 507 |
"0 total tests scheduled across all selected devices", |
| 508 |
] |
| 509 |
for line in expected_output: |
| 510 |
assert line in caplog.text |
| 511 |
|
| 512 |
@pytest.mark.parametrize(("inventory"), [{"count": 3}], indirect=True) |
| 513 |
@respx.mock |
| 514 |
async def test_run(self, inventory: AntaInventory) -> None: |
| 515 |
"""Test AntaRunner.run().""" |
| 516 |
|
| 517 |
respx.post(path="/command-api", headers={"Content-Type": "application/json-rpc"}, json__params__cmds__0__cmd="show ip route vrf default").respond( |
| 518 |
json={"result": [{"vrfs": {"default": {"routes": {}}}}]} |
| 519 |
) |
| 520 |
tests = [AntaTestDefinition(test=VerifyRoutingTableEntry, inputs={"routes": [f"10.1.0.{i}"], "collect": "all"}) for i in range(5)] |
| 521 |
catalog = AntaCatalog(tests=tests) |
| 522 |
runner = AntaRunner() |
| 523 |
|
| 524 |
ctx = await runner.run(inventory, catalog) |
| 525 |
|
| 526 |
assert ctx.total_devices_selected_for_testing == 3 |
| 527 |
assert ctx.total_tests_scheduled == 15 |
| 528 |
assert len(ctx.warnings_at_setup) == 0 |
| 529 |
assert len(ctx.manager) == 15 |
| 530 |
for result in ctx.manager.results: |
| 531 |
assert result.result == "failure" |
| 532 |
|
| 533 |
async def test_run_disconnect_called_when_enabled(self, caplog: pytest.LogCaptureFixture) -> None: |
| 534 |
"""Test that disconnect_inventory is called after the run when disconnect=True.""" |
| 535 |
caplog.set_level(logging.DEBUG) |
| 536 |
inventory = AntaInventory() |
| 537 |
catalog = AntaCatalog() |
| 538 |
runner = AntaRunner() |
| 539 |
|
| 540 |
with patch.object(AntaInventory, "disconnect_inventory", new_callable=AsyncMock) as mock_disconnect: |
| 541 |
await runner.run(inventory, catalog, disconnect=True) |
| 542 |
mock_disconnect.assert_called_once() |
| 543 |
assert "Disconnecting from devices ..." in caplog.messages |
| 544 |
|
| 545 |
async def test_run_disconnect_not_called_when_disabled(self) -> None: |
| 546 |
"""Test that disconnect_inventory is not called when disconnect=False.""" |
| 547 |
inventory = AntaInventory() |
| 548 |
catalog = AntaCatalog() |
| 549 |
runner = AntaRunner() |
| 550 |
|
| 551 |
with patch.object(AntaInventory, "disconnect_inventory", new_callable=AsyncMock) as mock_disconnect: |
| 552 |
await runner.run(inventory, catalog, disconnect=False) |
| 553 |
mock_disconnect.assert_not_called() |
| 554 |
|
| 555 |
|
| 556 |
|
| 557 |
class TestAntaRunContext: |
| 558 |
"""Test AntaRunContext class.""" |
| 559 |
|
| 560 |
def test_init(self) -> None: |
| 561 |
"""Test initialization.""" |
| 562 |
inventory = AntaInventory() |
| 563 |
catalog = AntaCatalog() |
| 564 |
manager = ResultManager() |
| 565 |
filters = AntaRunFilters() |
| 566 |
|
| 567 |
ctx = AntaRunContext(inventory, catalog, manager, filters) |
| 568 |
|
| 569 |
|
| 570 |
assert ctx.inventory is inventory |
| 571 |
assert ctx.catalog is catalog |
| 572 |
assert ctx.manager is manager |
| 573 |
assert ctx.filters is filters |
| 574 |
assert not ctx.dry_run |
| 575 |
assert not ctx.disconnect |
| 576 |
|
| 577 |
assert isinstance(ctx.selected_inventory, AntaInventory) |
| 578 |
assert len(ctx.selected_inventory) == 0 |
| 579 |
assert ctx.filtered_inventory is inventory |
| 580 |
assert isinstance(ctx.selected_tests, defaultdict) |
| 581 |
assert len(ctx.selected_tests) == 0 |
| 582 |
assert isinstance(ctx.devices_filtered_at_setup, list) |
| 583 |
assert len(ctx.devices_filtered_at_setup) == 0 |
| 584 |
assert isinstance(ctx.devices_unreachable_at_setup, list) |
| 585 |
assert len(ctx.devices_unreachable_at_setup) == 0 |
| 586 |
assert isinstance(ctx.warnings_at_setup, list) |
| 587 |
assert len(ctx.warnings_at_setup) == 0 |
| 588 |
assert ctx.start_time is None |
| 589 |
assert ctx.end_time is None |
| 590 |
|
| 591 |
|
| 592 |
assert ctx.total_devices_in_inventory == 0 |
| 593 |
assert ctx.total_devices_filtered_by_tags == 0 |
| 594 |
assert ctx.total_devices_unreachable == 0 |
| 595 |
assert ctx.total_devices_selected_for_testing == 0 |
| 596 |
assert ctx.total_tests_scheduled == 0 |
| 597 |
assert ctx.duration is None |