Debian Codegraph @

tests/benchmark/utils.py

raw symbols SCIP
1 # Copyright (c) 2023-2026 Arista Networks, Inc.
2 # Use of this source code is governed by the Apache License 2.0
3 # that can be found in the LICENSE file.
4 """Utils for the ANTA benchmark tests."""
5
6 from __future__ import annotations
7
8 import asyncio
9 import copy
10 import importlib
11 import json
12 import pkgutil
13 from typing import TYPE_CHECKING, Any
14
15 import httpx
16
17 from anta.catalog import AntaCatalog, AntaTestDefinition
18 from anta.models import AntaCommand, AntaTest
19
20 if TYPE_CHECKING:
21 from collections.abc import Generator
22 from types import ModuleType
23
24 from anta.device import AntaDevice
25
26
27 async def collect(self: AntaTest) -> None:
28 """Patched anta.models.AntaTest.collect() method.
29
30 When generating the catalog, we inject a unit test case name in the custom_field input to be able to retrieve the eos_data for this specific test.
31 We use this unit test case name in the eAPI request ID.
32 """
33 if self.inputs.result_overwrite is None or self.inputs.result_overwrite.custom_field is None:
34 msg = f"The custom_field input is not present for test {self.name}"
35 raise RuntimeError(msg)
36 await self.device.collect_commands(self.instance_commands, collection_id=f"{self.name}:{self.inputs.result_overwrite.custom_field}")
37
38
39 async def collect_commands(self: AntaDevice, commands: list[AntaCommand], collection_id: str) -> None:
40 """Patched anta.device.AntaDevice.collect_commands() method.
41
42 For the same reason as above, we inject the command index of the test to the eAPI request ID.
43 """
44 await asyncio.gather(*(self.collect(command=command, collection_id=f"{collection_id}:{idx}") for idx, command in enumerate(commands)))
45
46
47 class AntaMockEnvironment: # pylint: disable=too-few-public-methods
48 """Generate an ANTA test catalog from the unit tests data. It can be accessed using the `catalog` attribute of this class instance.
49
50 Also provide the attribute 'eos_data_catalog` with the output of all the commands used in the test catalog.
51
52 Each module in `tests.units.anta_tests` has a `DATA` constant.
53
54 The `DATA` structure is a dictionary where:
55 - Each key is a tuple of size 2 containing:
56 - An AntaTest subclass imported in the test module as first element - e.g. VerifyUptime.
57 - A string used as name displayed by pytest as second element.
58 - Each value is an instance of AntaUnitTest, which is a Python TypedDict.
59
60 And AntaUnitTest have the following keys:
61 - `eos_data` (list[dict]): List of data mocking EOS returned data to be passed to the test.
62 - `inputs` (dict): Dictionary to instantiate the `test` inputs as defined in the class from `test`.
63 - `expected` (dict): Expected test result structure, a dictionary containing a key `result` containing one of the allowed status
64 (`Literal[AntaTestStatus.SUCCESS, AntaTestStatus.FAILURE, AntaTestStatus.SKIPPED]`) and
65 optionally a key `messages` which is a list(str) and each message is expected to be a substring of one of the actual messages in the TestResult object.
66
67 The keys of `eos_data_catalog` is the tuple (AntaTest subclass, A string used as name displayed by pytest). The values are `eos_data`.
68 """
69
70 def __init__(self) -> None:
71 self._catalog, self.eos_data_catalog = self._generate_catalog()
72 self.tests_count = len(self._catalog.tests)
73
74 @property
75 def catalog(self) -> AntaCatalog:
76 """AntaMockEnvironment object will always return a new AntaCatalog object based on the initial parsing.
77
78 This is because AntaCatalog objects store indexes when tests are run and we want a new object each time a test is run.
79 """
80 return copy.deepcopy(self._catalog)
81
82 def _generate_catalog(self) -> tuple[AntaCatalog, dict[tuple[str, str], list[dict[str, Any]]]]:
83 """Generate the `catalog` and `eos_data_catalog` attributes."""
84
85 def import_test_modules() -> Generator[ModuleType, None, None]:
86 """Yield all test modules from the given package."""
87 package = importlib.import_module("tests.units.anta_tests")
88 prefix = package.__name__ + "."
89 for _, module_name, is_pkg in pkgutil.walk_packages(package.__path__, prefix):
90 if not is_pkg and module_name.split(".")[-1].startswith("test_"):
91 module = importlib.import_module(module_name)
92 if hasattr(module, "DATA"):
93 yield module
94
95 test_definitions = []
96 eos_data_catalog = {}
97 for module in import_test_modules():
98 for (test, name), test_data in module.DATA.items():
99 # Extract the test class, name and test data from a nested tuple structure:
100 # unit test: Tuple[Tuple[Type[AntaTest], str], AntaUnitTest]
101 result_overwrite = AntaTest.Input.ResultOverwrite(custom_field=name)
102 if test_data.get("inputs") is None:
103 inputs = test.Input(result_overwrite=result_overwrite)
104 else:
105 inputs = test.Input(**test_data["inputs"], result_overwrite=result_overwrite)
106 test_definition = AntaTestDefinition(
107 test=test,
108 inputs=inputs,
109 )
110 eos_data_catalog[(test.__name__, name)] = test_data["eos_data"]
111 test_definitions.append(test_definition)
112
113 return (AntaCatalog(tests=test_definitions), eos_data_catalog)
114
115 def eapi_response(self, request: httpx.Request) -> httpx.Response:
116 """Mock eAPI response.
117
118 If the eAPI request ID has the format `ANTA-{test name}:{unit test name}:{command index}-{command ID}`,
119 the function will return the eos_data from the unit test case.
120
121 Otherwise, it will mock 'show version' command or raise an Exception.
122 """
123 words_count = 3
124
125 def parse_req_id(req_id: str) -> tuple[str, str, int] | None:
126 """Parse the patched request ID from the eAPI request."""
127 req_id = req_id.removeprefix("ANTA-").rpartition("-")[0]
128 words = req_id.split(":", words_count)
129 if len(words) == words_count:
130 test_name, unit_test_name, command_index = words
131 return test_name, unit_test_name, int(command_index)
132 return None
133
134 jsonrpc = json.loads(request.content)
135 assert jsonrpc["method"] == "runCmds"
136 commands = jsonrpc["params"]["cmds"]
137 ofmt = jsonrpc["params"]["format"]
138 req_id: str = jsonrpc["id"]
139 result = None
140
141 # Extract the test name, unit test name, and command index from the request ID
142 if (words := parse_req_id(req_id)) is not None:
143 test_name, unit_test_name, idx = words
144
145 # This should never happen, but better be safe than sorry
146 if (test_name, unit_test_name) not in self.eos_data_catalog:
147 msg = f"Error while generating a mock response for unit test {unit_test_name} of test {test_name}: eos_data not found"
148 raise RuntimeError(msg)
149
150 eos_data = self.eos_data_catalog[(test_name, unit_test_name)]
151
152 # This could happen if the unit test data is not correctly defined
153 if idx >= len(eos_data):
154 msg = f"Error while generating a mock response for unit test {unit_test_name} of test {test_name}: missing test case in eos_data"
155 raise RuntimeError(msg)
156 result = {"output": eos_data[idx]} if ofmt == "text" else eos_data[idx]
157 elif {"cmd": "show version"} in commands and ofmt == "json":
158 # Mock 'show version' request performed during inventory refresh.
159 result = {
160 "modelName": "pytest",
161 }
162
163 if result is not None:
164 return httpx.Response(
165 status_code=200,
166 json={
167 "jsonrpc": "2.0",
168 "id": req_id,
169 "result": [result],
170 },
171 )
172 msg = f"The following eAPI Request has not been mocked: {jsonrpc}"
173 raise NotImplementedError(msg)