Debian Codegraph @

docs/advanced_usages/custom-tests.md

raw symbols SCIP
1 ---
2 title: Developing ANTA tests
3 hide:
4 - tags
5 tags:
6 - Custom Tests
7 - Python
8 - API
9 ---
10
11 <!--
12 ~ Copyright (c) 2023-2026 Arista Networks, Inc.
13 ~ Use of this source code is governed by the Apache License 2.0
14 ~ that can be found in the LICENSE file.
15 -->
16
17 !!! info
18 This documentation applies for both creating tests in ANTA or creating your own test package.
19
20 ANTA is not only a Python library with a CLI and a collection of built-in tests, it is also a framework you can extend by building your own tests.
21
22 ## Generic approach
23
24 A test is a Python class where a test function is defined and will be run by the framework.
25
26 ANTA provides an abstract class [AntaTest](../api/tests/anta_test.md#anta.models.AntaTest). This class does the heavy lifting and provide the logic to define, collect and test data. The code below is an example of a simple test in ANTA, which is an [AntaTest](../api/tests/anta_test.md#anta.models.AntaTest) subclass:
27
28 ````python
29 from anta.models import AntaTest, AntaCommand
30 from anta.decorators import skip_on_platforms
31
32
33 class VerifyTemperature(AntaTest):
34 """Verifies if the device temperature is within acceptable limits.
35
36 Expected Results
37 ----------------
38 * Success: The test will pass if the device temperature is currently OK: 'temperatureOk'.
39 * Failure: The test will fail if the device temperature is NOT OK.
40
41 Examples
42 --------
43 ```yaml
44 anta.tests.hardware:
45 - VerifyTemperature:
46 ```
47 """
48
49 categories: ClassVar[list[str]] = ["hardware"]
50 commands: ClassVar[list[AntaCommand | AntaTemplate]] = [AntaCommand(command="show system environment temperature", revision=1)]
51
52 @skip_on_platforms(["cEOSLab", "vEOS-lab", "cEOSCloudLab"])
53 @AntaTest.anta_test
54 def test(self) -> None:
55 """Main test function for VerifyTemperature."""
56 command_output = self.instance_commands[0].json_output
57 temperature_status = command_output.get("systemStatus", "")
58 if temperature_status == "temperatureOk":
59 self.result.is_success()
60 else:
61 self.result.is_failure(f"Device temperature exceeds acceptable limits. Current system status: '{temperature_status}'")
62 ````
63
64 [AntaTest](../api/tests/anta_test.md#anta.models.AntaTest) also provide more advanced capabilities like [AntaCommand](../api/commands.md#anta.models.AntaCommand) templating using the [AntaTemplate](../api/commands.md#anta.models.AntaTemplate) class or test inputs definition and validation using [AntaTest.Input](../api/tests/anta_test.md#anta.models.AntaTest.Input) [pydantic](https://docs.pydantic.dev/latest/) model. This will be discussed in the sections below.
65
66 ## AntaTest structure
67
68 Full AntaTest API documentation is available in the [API documentation section](../api/tests/anta_test.md#anta.models.AntaTest)
69
70 ### Class Attributes
71
72 - `name` (`str`, `optional`): Name of the test. Used during reporting. By default set to the Class name.
73 - `description` (`str`, `optional`): A human readable description of your test. By default set to the first line of the docstring.
74 - `categories` (`list[str]`): A list of categories in which the test belongs.
75 - `commands` (`[list[AntaCommand | AntaTemplate]]`): A list of command to collect from devices. This list **must** be a list of [AntaCommand](../api/commands.md#anta.models.AntaCommand) or [AntaTemplate](../api/commands.md#anta.models.AntaTemplate) instances. Rendering [AntaTemplate](../api/commands.md#anta.models.AntaTemplate) instances will be discussed later.
76
77 !!! info
78 All these class attributes are mandatory. If any attribute is missing, a `NotImplementedError` exception will be raised during class instantiation.
79
80 ### Instance Attributes
81
82 ::: anta.models.AntaTest
83 options:
84 show_docstring_attributes: true
85 show_root_heading: false
86 show_bases: false
87 show_docstring_description: false
88 show_docstring_examples: false
89 show_docstring_parameters: false
90 members: false
91 show_source: false
92 show_root_toc_entry: false
93 heading_level: 10
94
95 !!! note
96
97 - **Logger object**
98
99 ANTA already provides comprehensive logging at every steps of a test execution. The [AntaTest](../api/tests/anta_test.md#anta.models.AntaTest) class also provides a `logger` attribute that is a Python logger specific to the test instance. See [Python documentation](https://docs.python.org/3/library/logging.html) for more information.
100
101 - **AntaDevice object**
102
103 Even if `device` is not a private attribute, you should not need to access this object in your code.
104
105 ### Test Inputs
106
107 [AntaTest.Input](../api/tests/anta_test.md#anta.models.AntaTest.Input) is a [pydantic model](https://docs.pydantic.dev/latest/usage/models/) that allow test developers to define their test inputs. [pydantic](https://docs.pydantic.dev/latest/) provides out of the box [error handling](https://docs.pydantic.dev/latest/usage/models/#error-handling) for test input validation based on the type hints defined by the test developer.
108
109 The base definition of [AntaTest.Input](../api/tests/anta_test.md#anta.models.AntaTest.Input) provides common test inputs for all [AntaTest](../api/tests/anta_test.md#anta.models.AntaTest) instances:
110
111 #### Input model
112
113 Full `Input` model documentation is available in [API documentation section](../api/tests/anta_test.md#anta.models.AntaTest.Input)
114
115 ::: anta.models.AntaTest.Input
116 options:
117 show_docstring_attributes: true
118 show_root_heading: false
119 show_category_heading: false
120 show_bases: false
121 show_docstring_description: false
122 show_docstring_examples: false
123 show_docstring_parameters: false
124 show_source: false
125 members: false
126 show_root_toc_entry: false
127 heading_level: 10
128
129 #### ResultOverwrite model
130
131 Full `ResultOverwrite` model documentation is available in [API documentation section](../api/tests/anta_test.md#anta.models.AntaTest.Input.ResultOverwrite)
132
133 ::: anta.models.AntaTest.Input.ResultOverwrite
134 options:
135 show_docstring_attributes: true
136 show_root_heading: false
137 show_category_heading: false
138 show_bases: false
139 show_docstring_description: false
140 show_docstring_examples: false
141 show_docstring_parameters: false
142 show_source: false
143 show_root_toc_entry: false
144 heading_level: 10
145
146 !!! note
147 The pydantic model is configured using the [`extra=forbid`](https://docs.pydantic.dev/latest/usage/model_config/#extra-attributes) that will fail input validation if extra fields are provided.
148
149 ### Methods
150
151 - [test(self) -> None](../api/tests/anta_test.md#anta.models.AntaTest.test): This is an abstract method that **must** be implemented. It contains the test logic that can access the collected command outputs using the `instance_commands` instance attribute, access the test inputs using the `inputs` instance attribute and **must** set the `result` instance attribute accordingly. It must be implemented using the `AntaTest.anta_test` decorator that provides logging and will collect commands before executing the `test()` method.
152 - [render(self, template: AntaTemplate) -> list[AntaCommand]](../api/tests/anta_test.md#anta.models.AntaTest.render): This method only needs to be implemented if [AntaTemplate](../api/commands.md#anta.models.AntaTemplate) instances are present in the `commands` class attribute. It will be called for every [AntaTemplate](../api/commands.md#anta.models.AntaTemplate) occurrence and **must** return a list of [AntaCommand](../api/commands.md#anta.models.AntaCommand) using the [AntaTemplate.render()](../api/commands.md#anta.models.AntaTemplate.render) method. It can access test inputs using the `inputs` instance attribute.
153
154 ## Test execution
155
156 Below is a high level description of the test execution flow in ANTA:
157
158 1. ANTA will parse the test catalog to get the list of [AntaTest](../api/tests/anta_test.md#anta.models.AntaTest) subclasses to instantiate and their associated input values. We consider a single [AntaTest](../api/tests/anta_test.md#anta.models.AntaTest) subclass in the following steps.
159
160 2. ANTA will instantiate the [AntaTest](../api/tests/anta_test.md#anta.models.AntaTest) subclass and a single device will be provided to the test instance. The `Input` model defined in the class will also be instantiated at this moment. If any [ValidationError](https://docs.pydantic.dev/latest/errors/errors/) is raised, the test execution will be stopped.
161
162 3. If there is any [AntaTemplate](../api/commands.md#anta.models.AntaTemplate) instance in the `commands` class attribute, [render()](../api/tests/anta_test.md#anta.models.AntaTest.render) will be called for every occurrence. At this moment, the `instance_commands` attribute has been initialized. If any rendering error occurs, the test execution will be stopped.
163
164 4. The `AntaTest.anta_test` decorator will collect the commands from the device and update the `instance_commands` attribute with the outputs. If any collection error occurs, the test execution will be stopped.
165
166 5. The [test()](../api/tests/anta_test.md#anta.models.AntaTest.test) method is executed.
167
168 ## Writing an AntaTest subclass
169
170 In this section, we will go into all the details of writing an [AntaTest](../api/tests/anta_test.md#anta.models.AntaTest) subclass.
171
172 ### Class definition
173
174 Import [anta.models.AntaTest](../api/tests/anta_test.md#anta.models.AntaTest) and define your own class.
175 Define the mandatory class attributes using [anta.models.AntaCommand](../api/commands.md#anta.models.AntaCommand), [anta.models.AntaTemplate](../api/commands.md#anta.models.AntaTemplate) or both.
176
177 !!! note
178 Caching can be disabled per `AntaCommand` or `AntaTemplate` by setting the `use_cache` argument to `False`. For more details about how caching is implemented in ANTA, please refer to [Caching in ANTA](../advanced_usages/caching.md).
179
180 ```python
181 from anta.models import AntaTest, AntaCommand, AntaTemplate
182
183
184 class <YourTestName>(AntaTest):
185 """
186 <a docstring description of your test, the first line is used as description of the test by default>
187 """
188
189 # name = <override> # uncomment to override default behavior of name=Class Name
190 # description = <override> # uncomment to override default behavior of description=first line of docstring
191 categories = ["<arbitrary category>", "<another arbitrary category>"]
192 commands = [
193 AntaCommand(
194 command="<EOS command to run>",
195 ofmt="<command format output>",
196 version="<eAPI version to use>",
197 revision="<revision to use for the command>", # revision has precedence over version
198 use_cache="<Use cache for the command>",
199 ),
200 AntaTemplate(
201 template="<Python f-string to render an EOS command>",
202 ofmt="<command format output>",
203 version="<eAPI version to use>",
204 revision="<revision to use for the command>", # revision has precedence over version
205 use_cache="<Use cache for the command>",
206 )
207 ]
208 ```
209
210 !!! tip
211 **Command revision and version**
212
213 - Most of EOS commands return a JSON structure according to a model (some commands may not be modeled hence the necessity to use `text` outformat sometimes.
214 - The model can change across time (adding feature, ... ) and when the model is changed in a non backward-compatible way, the **revision** number is bumped. The initial model starts with **revision** 1.
215 - A **revision** applies to a particular CLI command whereas a **version** is global to an eAPI call. The **version** is internally translated to a specific **revision** for each CLI command in the RPC call. The currently supported **version** values are `1` and `latest`.
216 - A **revision takes precedence over a version** (e.g. if a command is run with version="latest" and revision=1, the first revision of the model is returned)
217 - By default, eAPI returns the first revision of each model to ensure that when upgrading, integrations with existing tools are not broken. This is done by using by default `version=1` in eAPI calls.
218
219 By default, ANTA uses `version="latest"` in AntaCommand, but when developing tests, the revision MUST be provided when the outformat of the command is `json`. As explained earlier, this is to ensure that the eAPI always returns the same output model and that the test remains always valid from the day it was created. For some commands, you may also want to run them with a different revision or version.
220
221 For instance, the `VerifyBFDPeersHealth` test leverages the first revision of `show bfd peers`:
222
223 ```python
224 # revision 1 as later revision introduce additional nesting for type
225 commands = [AntaCommand(command="show bfd peers", revision=1)]
226 ```
227
228 ### Inputs definition
229
230 If the user needs to provide inputs for your test, you need to define a [pydantic model](https://docs.pydantic.dev/latest/usage/models/) that defines the schema of the test inputs:
231
232 ```python
233 class <YourTestName>(AntaTest):
234 """Verifies ...
235
236 Expected Results
237 ----------------
238 * Success: The test will pass if ...
239 * Failure: The test will fail if ...
240
241 Examples
242 --------
243 ```yaml
244 your.module.path:
245 - YourTestName:
246 field_name: example_field_value
247 ```
248 """
249 ...
250 class Input(AntaTest.Input):
251 """Inputs for my awesome test."""
252 <input field name>: <input field type>
253 """<input field docstring>"""
254 ```
255
256 To define an input field type, refer to the [pydantic documentation](https://docs.pydantic.dev/latest/usage/types/types/) about types.
257 You can also leverage [anta.custom_types](../api/tests/types.md) that provides reusable types defined in ANTA tests.
258
259 Regarding required, optional and nullable fields, refer to this [documentation](https://docs.pydantic.dev/latest/migration/#required-optional-and-nullable-fields) on how to define them.
260
261 !!! note
262 All the `pydantic` features are supported. For instance you can define [validators](https://docs.pydantic.dev/latest/usage/validators/) for complex input validation.
263
264 ### Template rendering
265
266 Define the `render()` method if you have [AntaTemplate](../api/commands.md#anta.models.AntaTemplate) instances in your `commands` class attribute:
267
268 ```python
269 class <YourTestName>(AntaTest):
270 ...
271 def render(self, template: AntaTemplate) -> list[AntaCommand]:
272 return [template.render(<template param>=input_value) for input_value in self.inputs.<input_field>]
273 ```
274
275 You can access test inputs and render as many [AntaCommand](../api/commands.md#anta.models.AntaCommand) as desired.
276
277 ### Test definition
278
279 Implement the `test()` method with your test logic:
280
281 ```python
282 class <YourTestName>(AntaTest):
283 ...
284 @AntaTest.anta_test
285 def test(self) -> None:
286 pass
287 ```
288
289 The logic usually includes the following different stages:
290
291 1. Parse the command outputs using the `self.instance_commands` instance attribute.
292 2. If needed, access the test inputs using the `self.inputs` instance attribute and write your conditional logic.
293 3. Set the `result` instance attribute to reflect the test result by either calling `self.result.is_success()` or `self.result.is_failure("<FAILURE REASON>")`. Sometimes, setting the test result to `skipped` using `self.result.is_skipped("<SKIPPED REASON>")` can make sense (e.g. testing the OSPF neighbor states but no neighbor was found). However, you should not need to catch any exception and set the test result to `error` since the error handling is done by the framework, see below.
294
295 The example below is based on the [VerifyTemperature](../api/tests/hardware.md#anta.tests.hardware.VerifyTemperature) test.
296
297 ```python
298 class VerifyTemperature(AntaTest):
299 ...
300 @AntaTest.anta_test
301 def test(self) -> None:
302 # Grab output of the collected command
303 command_output = self.instance_commands[0].json_output
304
305 # Do your test: In this example we check a specific field of the JSON output from EOS
306 temperature_status = command_output["systemStatus"] if "systemStatus" in command_output.keys() else ""
307 if temperature_status == "temperatureOk":
308 self.result.is_success()
309 else:
310 self.result.is_failure(f"Device temperature exceeds acceptable limits. Current system status: '{temperature_status}'")
311 ```
312
313 As you can see there is no error handling to do in your code. Everything is packaged in the `AntaTest.anta_tests` decorator and below is a simple example of error captured when trying to access a dictionary with an incorrect key:
314
315 ```python
316 class VerifyTemperature(AntaTest):
317 ...
318 @AntaTest.anta_test
319 def test(self) -> None:
320 # Grab output of the collected command
321 command_output = self.instance_commands[0].json_output
322
323 # Access the dictionary with an incorrect key
324 command_output['incorrectKey']
325 ```
326
327 ```bash
328 ERROR Exception raised for test VerifyTemperature (on device 192.168.0.10) - KeyError ('incorrectKey')
329 ```
330
331 !!! info "Get stack trace for debugging"
332 If you want to access to the full exception stack, you can run ANTA in debug mode by setting the `ANTA_DEBUG` environment variable to `true`. Example:
333 ```bash
334 $ ANTA_DEBUG=true anta nrfu --catalog test_custom.yml text
335 ```
336
337 ### Test decorators
338
339 In addition to the required `AntaTest.anta_tests` decorator, ANTA offers a set of optional decorators for further test customization:
340
341 - `anta.decorators.deprecated_test`: Use this to log a message of WARNING severity when a test is deprecated.
342 - `anta.decorators.skip_on_platforms`: Use this to skip tests for functionalities that are not supported on specific platforms.
343
344 ```python
345 from anta.decorators import skip_on_platforms
346
347 class VerifyTemperature(AntaTest):
348 ...
349 @skip_on_platforms(["cEOSLab", "vEOS-lab"])
350 @AntaTest.anta_test
351 def test(self) -> None:
352 pass
353 ```
354
355 ## Access your custom tests in the test catalog
356
357 !!! warning
358 This section is required only if you are not merging your development into ANTA. Otherwise, just follow [contribution guide](../contribution.md).
359
360 For that, you need to create your own Python package as described in this [hitchhiker's guide](https://the-hitchhikers-guide-to-packaging.readthedocs.io/en/latest/) to package Python code. We assume it is well known and we won't focus on this aspect. Thus, your package must be importable by ANTA hence available in the module search path `sys.path` (you can use `PYTHONPATH` for example).
361
362 It is very similar to what is documented in [catalog section](../usage-inventory-catalog.md) but you have to use your own package name.
363
364 Let say the custom Python package is `anta_custom` and the test is defined in `anta_custom.dc_project` Python module, the test catalog would look like:
365
366 ```yaml
367 anta_custom.dc_project:
368 - VerifyFeatureX:
369 minimum: 1
370 ```
371
372 And now you can run your NRFU tests with the CLI:
373
374 ```bash
375 anta nrfu text --catalog test_custom.yml
376 spine01 :: verify_dynamic_vlan :: FAILURE (Device has 0 configured, we expect at least 1)
377 spine02 :: verify_dynamic_vlan :: FAILURE (Device has 0 configured, we expect at least 1)
378 leaf01 :: verify_dynamic_vlan :: SUCCESS
379 leaf02 :: verify_dynamic_vlan :: SUCCESS
380 leaf03 :: verify_dynamic_vlan :: SUCCESS
381 leaf04 :: verify_dynamic_vlan :: SUCCESS
382 ```