| 1 |
|
| 2 |
|
| 3 |
|
| 4 |
"""See https://docs.pytest.org/en/stable/reference/fixtures.html#conftest-py-sharing-fixtures-across-multiple-files.""" |
| 5 |
|
| 6 |
from __future__ import annotations |
| 7 |
|
| 8 |
import logging |
| 9 |
import shutil |
| 10 |
from typing import TYPE_CHECKING, Any, Literal |
| 11 |
from unittest.mock import patch |
| 12 |
|
| 13 |
import pytest |
| 14 |
from click.testing import CliRunner, Result |
| 15 |
|
| 16 |
import asynceapi |
| 17 |
from anta.cli.console import console |
| 18 |
|
| 19 |
if TYPE_CHECKING: |
| 20 |
from collections.abc import Iterator |
| 21 |
from pathlib import Path |
| 22 |
|
| 23 |
|
| 24 |
logger = logging.getLogger(__name__) |
| 25 |
|
| 26 |
|
| 27 |
MOCK_CLI_JSON: dict[str, asynceapi.EapiCommandError | dict[str, Any]] = { |
| 28 |
"show version": { |
| 29 |
"modelName": "DCS-7280CR3-32P4-F", |
| 30 |
"version": "4.31.1F", |
| 31 |
}, |
| 32 |
"enable": {}, |
| 33 |
"clear counters": {}, |
| 34 |
"clear hardware counter drop": {}, |
| 35 |
"undefined": asynceapi.EapiCommandError( |
| 36 |
passed=[], |
| 37 |
failed="show version", |
| 38 |
errors=["Authorization denied for command 'show version'"], |
| 39 |
errmsg="Invalid command", |
| 40 |
not_exec=[], |
| 41 |
), |
| 42 |
"show interfaces": {"interfaces": {}}, |
| 43 |
"ping": { |
| 44 |
"messages": [ |
| 45 |
( |
| 46 |
"PING 10.0.0.2 (10.0.0.2) from 10.0.0.5 : 72(100) bytes of data.\n" |
| 47 |
"80 bytes from 10.0.0.2: icmp_seq=1 ttl=64 time=0.247 ms\n" |
| 48 |
"80 bytes from 10.0.0.2: icmp_seq=2 ttl=64 time=0.072 ms\n\n" |
| 49 |
"--- 10.0.0.2 ping statistics ---\n" |
| 50 |
"2 packets transmitted, 2 received, 0% packet loss, time 0ms\n" |
| 51 |
"rtt min/avg/max/mdev = 0.072/0.159/0.247/0.088 ms, ipg/ewma 0.370/0.225 ms\n\n" |
| 52 |
) |
| 53 |
] |
| 54 |
}, |
| 55 |
} |
| 56 |
|
| 57 |
MOCK_CLI_TEXT: dict[str, asynceapi.EapiCommandError | str] = { |
| 58 |
"show version": "Arista cEOSLab", |
| 59 |
"bash timeout 10 ls -1t /mnt/flash/schedule/tech-support": "dummy_tech-support_2023-12-01.1115.log.gz\ndummy_tech-support_2023-12-01.1015.log.gz", |
| 60 |
"bash timeout 10 ls -1t /mnt/flash/schedule/tech-support | head -1": "dummy_tech-support_2023-12-01.1115.log.gz", |
| 61 |
"show running-config | include aaa authorization exec default": "aaa authorization exec default local", |
| 62 |
} |
| 63 |
|
| 64 |
|
| 65 |
@pytest.fixture |
| 66 |
def temp_env(anta_env: dict[str, str], tmp_path: Path) -> dict[str, str]: |
| 67 |
"""Fixture that create a temporary ANTA inventory. |
| 68 |
|
| 69 |
The inventory can be overridden and returns the corresponding environment variables. |
| 70 |
""" |
| 71 |
anta_inventory = str(anta_env["ANTA_INVENTORY"]) |
| 72 |
temp_inventory = tmp_path / "test_inventory.yml" |
| 73 |
shutil.copy(anta_inventory, temp_inventory) |
| 74 |
anta_env["ANTA_INVENTORY"] = str(temp_inventory) |
| 75 |
return anta_env |
| 76 |
|
| 77 |
|
| 78 |
@pytest.fixture |
| 79 |
|
| 80 |
def click_runner(capsys: pytest.CaptureFixture[str], anta_env: dict[str, str]) -> Iterator[CliRunner]: |
| 81 |
"""Return a click.CliRunner for cli testing.""" |
| 82 |
|
| 83 |
class AntaCliRunner(CliRunner): |
| 84 |
"""Override CliRunner to inject specific variables for ANTA.""" |
| 85 |
|
| 86 |
def invoke(self, *args: Any, **kwargs: Any) -> Result: |
| 87 |
|
| 88 |
kwargs["env"] = anta_env | kwargs.get("env", {}) |
| 89 |
|
| 90 |
kwargs["env"]["COLUMNS"] = "165" |
| 91 |
|
| 92 |
kwargs["auto_envvar_prefix"] = "ANTA" |
| 93 |
|
| 94 |
with capsys.disabled(): |
| 95 |
result = super().invoke(*args, **kwargs) |
| 96 |
|
| 97 |
print("--- CLI Output ---") |
| 98 |
print(result.output) |
| 99 |
return result |
| 100 |
|
| 101 |
def cli( |
| 102 |
command: str | None = None, |
| 103 |
commands: list[dict[str, Any]] | None = None, |
| 104 |
ofmt: Literal["json", "text"] = "json", |
| 105 |
_version: int | str | None = "latest", |
| 106 |
**_kwargs: Any, |
| 107 |
) -> dict[str, Any] | list[dict[str, Any]]: |
| 108 |
def get_output(command: str | dict[str, Any]) -> dict[str, Any]: |
| 109 |
if isinstance(command, dict): |
| 110 |
command_str: str = command["cmd"] |
| 111 |
else: |
| 112 |
command_str = command |
| 113 |
mock_cli: dict[str, Any] |
| 114 |
if ofmt == "json": |
| 115 |
mock_cli = MOCK_CLI_JSON |
| 116 |
elif ofmt == "text": |
| 117 |
mock_cli = MOCK_CLI_TEXT |
| 118 |
for mock_cmd, output in mock_cli.items(): |
| 119 |
if command_str == mock_cmd or (command_str.startswith("ping") and mock_cmd == "ping"): |
| 120 |
logger.info("Mocking command %s", mock_cmd) |
| 121 |
if isinstance(output, asynceapi.EapiCommandError): |
| 122 |
raise output |
| 123 |
return output |
| 124 |
message = f"Command '{command_str}' is not mocked" |
| 125 |
logger.critical(message) |
| 126 |
raise NotImplementedError(message) |
| 127 |
|
| 128 |
res: dict[str, Any] | list[dict[str, Any]] |
| 129 |
if command is not None: |
| 130 |
logger.debug("Mock input %s", command) |
| 131 |
res = get_output(command) |
| 132 |
elif commands is not None: |
| 133 |
logger.debug("Mock input %s", commands) |
| 134 |
res = list(map(get_output, commands)) |
| 135 |
else: |
| 136 |
msg = "Either 'command' or 'commands' must not be None" |
| 137 |
raise ValueError(msg) |
| 138 |
logger.debug("Mock output %s", res) |
| 139 |
return res |
| 140 |
|
| 141 |
|
| 142 |
with ( |
| 143 |
patch("asynceapi.device.Device.check_api_endpoint", return_value=True), |
| 144 |
patch("asynceapi.device.Device.cli", side_effect=cli), |
| 145 |
patch("asyncssh.connect"), |
| 146 |
patch( |
| 147 |
"asyncssh.scp", |
| 148 |
), |
| 149 |
): |
| 150 |
console._color_system = None |
| 151 |
yield AntaCliRunner() |