Debian Codegraph @

docs/contribution.md

raw symbols SCIP
1 ---
2 title: How to contribute to ANTA
3 hide:
4 - tags
5 tags:
6 - Contributing
7 ---
8
9 <!--
10 ~ Copyright (c) 2023-2026 Arista Networks, Inc.
11 ~ Use of this source code is governed by the Apache License 2.0
12 ~ that can be found in the LICENSE file.
13 -->
14
15 Contribution model is based on a fork-model. Don't push to aristanetworks/anta directly. Always do a branch in your forked repository and create a PR.
16
17 To help development, open your PR as soon as possible even in draft mode. It helps others know what you are working on and avoid duplicate PRs.
18
19 ## Create a development environment
20
21 Run the following commands to create an ANTA development environment:
22
23 ```bash
24 # Clone repository
25 $ git clone https://github.com/aristanetworks/anta.git
26 $ cd anta
27
28 # Install ANTA in editable mode and its development tools
29 $ pip install -e . --group dev
30 # To also install the CLI
31 $ pip install -e ".[cli]" --group dev
32 ```
33
34 !!! tip "Verify editable installation"
35 Run `pip list -e` from the repository root to confirm the editable install:
36
37 ```bash
38 $ pip list -e
39 Package Version Editable project location
40 ------- ------- -------------------------
41 anta 1.9.0 /mnt/lab/projects/anta
42 ```
43
44 Then, [`tox`](https://tox.wiki/) is configured with a few environments to run CI locally:
45
46 ```bash
47 $ tox list -d
48 default environments:
49 clean -> Erase previous coverage reports
50 lint -> Check the code style
51 type -> Check typing
52 py310 -> Run pytest with py310
53 py311 -> Run pytest with py311
54 py312 -> Run pytest with py312
55 py313 -> Run pytest with py313
56 py314 -> Run pytest with py314
57 report -> Generate coverage report
58 ```
59
60 ### Code linting
61
62 ```bash
63 tox -e lint
64 [...]
65 lint: commands[0]> ruff check .
66 All checks passed!
67 lint: commands[1]> ruff format . --check
68 224 files already formatted
69 lint: commands[2]> pylint anta
70
71 --------------------------------------------------------------------
72 Your code has been rated at 10.00/10 (previous run: 10.00/10, +0.00)
73
74 lint: commands[3]> pylint tests
75
76 --------------------------------------------------------------------
77 Your code has been rated at 10.00/10 (previous run: 10.00/10, +0.00)
78
79 lint: commands[4]> pylint asynceapi
80
81 --------------------------------------------------------------------
82 Your code has been rated at 10.00/10 (previous run: 10.00/10, +0.00)
83
84 lint: OK (38.75=setup[12.60]+cmd[0.98,0.08,9.51,13.49,2.09] seconds)
85 congratulations :) (38.78 seconds)
86 ```
87
88 ### Code Typing
89
90 ```bash
91 tox -e type
92
93 [...]
94 type: commands[0]> pyright anta
95 0 errors, 0 warnings, 0 informations
96 type: commands[1]> pyright tests
97 0 errors, 0 warnings, 0 informations
98 type: commands[2]> pyright asynceapi
99 0 errors, 0 warnings, 0 informations
100 type: OK (20.77=setup[15.14]+cmd[2.67,2.31,0.64] seconds)
101 congratulations :) (20.79 seconds)
102 ```
103
104 > NOTE: Typing is configured quite strictly, do not hesitate to reach out if you have any questions, struggles, nightmares.
105
106 ## Unit tests with Pytest
107
108 To keep high-quality code, every implemented `AntaTest` must have a corresponding pytest unit test.
109
110 Add the unit test to the appropriate submodule test file under `tests/units/anta_tests/test_<submodule-name>.py`, following the repository convention of adding cases to the module's `DATA` constant and importing the generic `test` function.
111
112 ### How to run unit tests
113
114 To run the unit test suite from an activated development environment:
115
116 ```bash
117 pytest tests/units
118 ```
119
120 To run a specific unit test module or test node:
121
122 ```bash
123 pytest tests/units/anta_tests/test_system.py
124 pytest tests/units/anta_tests/test_system.py::test
125 ```
126
127 If you use [`uv`](https://docs.astral.sh/uv/) for your local workflow, it can create or update the environment before running pytest:
128
129 ```bash
130 uv run --group dev --extra cli pytest tests/units
131 ```
132
133 Use tox when you want to run the unit tests in the same isolated environments used by CI:
134
135 ```bash
136 tox -e py311 -- tests/units
137 tox -e py310,py311,py312,py313,py314 -- tests/units
138 ```
139
140 The `--` separator passes the remaining arguments to pytest, so the same file or test-node selection works with tox:
141
142 ```bash
143 tox -e py311 -- tests/units/anta_tests/system.py
144 tox -e py311 -- tests/units/anta_tests/test_system.py
145 tox -e py311 -- tests/units/anta_tests/test_system.py::test
146 ```
147
148 !!! note "Python versions and tox"
149 The tox environments are mapped to concrete Python versions (`py310`, `py311`, `py312`, `py313`, and `py314`). Running one tox environment requires that matching Python interpreter to be installed and discoverable on your machine; running the full matrix requires all of them.
150
151 `uv` can help install and manage Python interpreters, for example:
152
153 ```bash
154 uv python install 3.10 3.11 3.12 3.13 3.14
155 ```
156
157 This does not replace tox for matrix testing in this repository. It only makes it easier to provide the Python interpreters that tox needs.
158
159 ### How to write a unit test for an AntaTest subclass
160
161 The Python modules in the `tests.units.anta_tests` package define test parameters for AntaTest subclasses unit tests.
162 A generic test function is written for all unit tests of the `AntaTest` subclasses.
163 In order for your unit tests to be correctly collected, you need to import the generic test function even if not used in the Python module.
164
165 The `pytest_generate_tests` function definition in `conftest.py` is called during test collection.
166
167 The `pytest_generate_tests` function will parametrize the generic test function based on the `DATA` constant defined in modules in the `tests.units.anta_tests` package.
168
169 See <https://docs.pytest.org/en/stable/how-to/parametrize.html#basic-pytest-generate-tests-example>
170
171 The `DATA` structure is a dictionary where:
172
173 - Each key is a tuple of size 2 containing:
174 - An AntaTest subclass imported in the test module as first element - e.g. VerifyUptime.
175 - A string used as name displayed by pytest as second element.
176 - Each value is an instance of AntaUnitTest, which is a Python TypedDict.
177
178 A `TypeAlias` called `AntaUnitTestData` has been created for convenience.
179
180 And AntaUnitTest have the following keys:
181
182 - `eos_data` (list[dict]): List of data mocking EOS returned data to be passed to the test.
183 - `inputs` (dict): Dictionary to instantiate the `test` inputs as defined in the class from `test`.
184 - `expected` (dict): Expected test result structure, a dictionary containing a key
185 `result` containing one of the allowed status (`Literal[AntaTestStatus.SUCCESS, AntaTestStatus.FAILURE, AntaTestStatus.SKIPPED]`) and 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.
186
187 ``` python
188 class AtomicResult(TypedDict):
189 """Expected atomic result of a unit test of an AntaTest subclass."""
190
191 description: str # The expected description of this atomic result.
192 result: Literal[AntaTestStatus.SUCCESS, AntaTestStatus.FAILURE, AntaTestStatus.SKIPPED] # The expected status of this atomic result.
193 messages: NotRequired[list[str]] # The expected messages of this atomic result. The strings can be a substrings of the actual messages.
194
195 class UnitTestResult(TypedDict):
196 """Expected result of a unit test of an AntaTest subclass.
197
198 For our AntaTest unit tests we expect only success, failure or skipped.
199 Never unset nor error.
200 """
201
202 result: Literal[AntaTestStatus.SUCCESS, AntaTestStatus.FAILURE, AntaTestStatus.SKIPPED] # The expected status of this unit test.
203 messages: NotRequired[list[str]] # The expected messages of the test. The strings can be a substrings of the actual messages.
204 atomic_results: NotRequired[list[AtomicResult]] # The list of expected atomic results.
205
206 class AntaUnitTest(TypedDict):
207 """The parameters required for a unit test of an AntaTest subclass."""
208
209 inputs: NotRequired[dict[str, Any]] # The test inputs of this unit test.
210 eos_data: list[dict[str, Any] | str] # List of command outputs used to mock EOS commands during this unit test.
211 expected: UnitTestResult # The expected result of this unit test.
212
213 AntaUnitTestData: TypeAlias = dict[tuple[type[AntaTest], str], AntaUnitTest]
214 ```
215
216 Test example for `anta.tests.system.VerifyUptime` AntaTest.
217
218 ``` python
219 # Import your AntaTest
220 from anta.tests.system import VerifyUptime
221
222 # Import the generic test function
223 from tests.units.anta_tests import test
224
225 # Define test parameters
226 DATA: AntaUnitTestData = {
227 (VerifyUptime, "success"): {
228 # JSON output of the 'show uptime' EOS command as defined in VerifyUptime.commands
229 "eos_data": [{"upTime": 1186689.15, "loadAvg": [0.13, 0.12, 0.09], "users": 1, "currentTime": 1683186659.139859}],
230 # Dictionary to instantiate VerifyUptime.Input
231 "inputs": {"minimum": 666},
232 # Expected test result
233 "expected": {"result": AntaTestStatus.SUCCESS},
234 },
235 (VerifyUptime, "failure"): {
236 "eos_data": [{"upTime": 665.15, "loadAvg": [0.13, 0.12, 0.09], "users": 1, "currentTime": 1683186659.139859}],
237 "inputs": {"minimum": 666},
238 # If the test returns messages, it needs to be expected otherwise test will fail.
239 # The expected message can be a substring of the actual message.
240 "expected": {"result": AntaTestStatus.FAILURE, "messages": ["Device uptime is 665.15 seconds"]},
241 }
242 }
243 ```
244
245 Test example for `anta.tests.connectivity.VerifyReachability` AntaTest that contains atomic results.
246
247 ``` python
248 from anta.tests.connectivity import VerifyReachability
249 from tests.units.anta_tests import test
250
251 DATA: AntaUnitTestData = {
252 (VerifyReachability, "failure-ip"): {
253 "inputs": {"hosts": [{"destination": "10.0.0.11", "source": "10.0.0.5"}, {"destination": "10.0.0.2", "source": "10.0.0.5"}]},
254 "eos_data": [
255 {
256 "messages": [
257 "ping: sendmsg: Network is unreachable\n ping: sendmsg: Network is unreachable\n "
258 "PING 10.0.0.11 (10.0.0.11) from 10.0.0.5 : 72(100) bytes of data.\n\n --- 10.0.0.11 ping statistics ---\n"
259 " 2 packets transmitted, 0 received, 100% packet loss, time 10ms\n\n\n "
260 ]
261 },
262 {
263 "messages": [
264 "PING 10.0.0.2 (10.0.0.2) from 10.0.0.5 : 72(100) bytes of data.\n 80 bytes from 10.0.0.2: icmp_seq=1 ttl=64 time=0.247 ms\n"
265 " 80 bytes from 10.0.0.2: icmp_seq=2 ttl=64 time=0.072 ms\n\n --- 10.0.0.2 ping statistics ---\n "
266 "2 packets transmitted, 2 received, 0% packet loss, time 0ms\n rtt min/avg/max/mdev = 0.072/0.159/0.247/0.088 ms,"
267 " ipg/ewma 0.370/0.225 ms\n\n "
268 ]
269 },
270 ],
271 "expected": {
272 "result": AntaTestStatus.FAILURE,
273 "messages": ["Unreachable Host 10.0.0.11 (src: 10.0.0.5, vrf: default, size: 100B, repeat: 2)"],
274 # This test has implemented atomic results.
275 # Expected atomic results must be specified or the test will fail. Order matters.
276 # The atomic results must be defined in the same order.
277 "atomic_results": [
278 {
279 # Expected atomic result description
280 "description": "Destination 10.0.0.11 from 10.0.0.5 in VRF default",
281 # If the atomic result is tied to a subset of the test inputs, it needs to be added here otherwise the test will fail.
282 "inputs": {
283 "destination": "10.0.0.11",
284 "df_bit": False,
285 "repeat": 2,
286 "size": 100,
287 "source": "10.0.0.5",
288 "vrf": "default",
289 },
290 # Expected atomic result status
291 "result": AntaTestStatus.FAILURE,
292 # If the atomic result returns messages, it needs to be expected otherwise test will fail.
293 # The expected message can be a substring of the actual message.
294 # The messages must be defined in the same order.
295 "messages": ["Unreachable Destination 10.0.0.11 from 10.0.0.5 in VRF default"],
296 },
297 {
298 "description": "Host 10.0.0.2 in VRF default",
299 "inputs": {
300 "destination": "10.0.0.2",
301 "df_bit": False,
302 "repeat": 2,
303 "size": 100,
304 "source": "10.0.0.5",
305 "vrf": "default",
306 },
307 "messages": [],
308 "result": AntaTestStatus.SUCCESS,
309 },
310 ],
311 },
312 }
313 }
314 ```
315
316 ## Git Pre-commit hook
317
318 ```bash
319 pip install pre-commit
320 pre-commit install
321 ```
322
323 When running a commit or a pre-commit check:
324
325 ``` bash
326 ❯ pre-commit
327 trim trailing whitespace.................................................Passed
328 fix end of files.........................................................Passed
329 check for added large files..............................................Passed
330 check for merge conflicts................................................Passed
331 Check and insert license on Python files.................................Passed
332 Check and insert license on Markdown files...............................Passed
333 Run Ruff linter..........................................................Passed
334 Run Ruff formatter.......................................................Passed
335 Check code style with pylint.............................................Passed
336 Checks for common misspellings in text files.............................Passed
337 PyRight static type checker..............................................Passed
338 Check for Linting errors on Markdown files...............................Passed
339 Check GitHub Actions with zizmor.........................................Passed
340 Generate examples/tests.yaml.............................................Passed
341 - hook id: examples-test
342 Generate doc snippets....................................................Passed
343 - hook id: doc-snippets
344 ```
345
346 ## Documentation
347
348 [`Zensical`](https://zensical.org/) is used to preview and build the documentation. A PR should always update the documentation to avoid documentation debt.
349
350 Documentation source lives under `docs/` and is built from the repository root. Do not commit rendered `site/` output.
351
352 ### Install documentation requirements
353
354 Run pip to install the documentation requirements from the root of the repo:
355
356 ```bash
357 pip install -e . --group doc -e tools/zensical_extensions
358 ```
359
360 ### Testing documentation
361
362 You can then preview the documentation locally using the following command from the root of the repo:
363
364 ```bash
365 zensical serve
366 ```
367
368 By default, `zensical` listens to <http://127.0.0.1:8000/>, if you need to expose the documentation to another IP or port (for instance all IPs on port 8080), use the following command:
369
370 ```bash
371 zensical serve --dev-addr=0.0.0.0:8080
372 ```
373
374 Run the same build command used by CI before opening a documentation PR:
375
376 ```bash
377 zensical build --strict
378 ```
379
380 Use `zensical build --clean` when you want to remove the previous generated output before building locally:
381
382 ```bash
383 zensical build --clean
384 ```
385
386 ### Generated CLI snippets
387
388 The CLI help blocks published in the documentation are generated from the current Click output. After changing CLI commands, options, or help text, refresh the snippets and verify that the generated files are committed:
389
390 ```bash
391 uv run --extra cli python docs/scripts/generate_doc_snippets.py
392 git diff --exit-code -- docs/snippets
393 test -z "$(git status --porcelain -- docs/snippets)"
394 ```
395
396 The `doc-snippets` pre-commit hook runs the generator for CLI changes, and CI runs the same freshness check before building the documentation.
397
398 ### Curated class diagram
399
400 The class diagram published in the API documentation is a curated Mermaid diagram, not a generated artifact. Generated class diagrams were considered, but the output is either too sparse for documentation or too noisy because it includes implementation details and third-party classes.
401
402 When changing public classes, attributes, methods, inheritance, or relationships in the ANTA API, review and update `docs/api/class-diagram.mmd` in the same PR.
403
404 Keep the diagram focused on the API overview. Include public fields, important properties, class variables, constructors or class methods used by users, and relationships that help explain how the main objects fit together. Avoid adding private implementation details unless they are needed to explain an important relationship.
405
406 Use the existing Mermaid conventions in `docs/api/class-diagram.mmd`:
407
408 - Put classes in the existing namespaces so the diagram keeps the Inventory, Device, Catalog, Test, and Result Manager layout.
409 - Mark Pydantic models with `:::pydantic`.
410 - Mark dataclasses with `:::dataclass`.
411 - Add `<<Dataclass>>` or `<<Frozen Dataclass>>` in the class body for dataclasses.
412 - Keep the color definitions at the bottom of the file in sync with the legend on the API page.
413
414 Build the documentation locally and inspect the rendered diagram after editing it:
415
416 ```bash
417 uv run --group doc --with-editable tools/zensical_extensions zensical build --clean --strict
418 ```
419
420 The rendered diagram has a fullscreen button for readability. Use it to check that labels are visible and that the layout still reads correctly on a screen.
421
422 ### Checking links
423
424 Writing documentation is crucial but managing links can be cumbersome. To be sure there are no dead links, you can use [`muffet`](https://github.com/raviqqe/muffet) with the following command:
425
426 ```bash
427 muffet -c 2 --color=always http://127.0.0.1:8000 -e fonts.gstatic.com -b 8192
428 ```
429
430 ## Continuous Integration
431
432 GitHub actions is used to test git pushes and pull requests. The workflows are defined in this [directory](https://github.com/aristanetworks/anta/tree/main/.github/workflows). The results can be viewed [here](https://github.com/aristanetworks/anta/actions).