Debian Codegraph @

tests/units/cli/nrfu/test_commands.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 """Tests for anta.cli.nrfu.commands."""
5
6 from __future__ import annotations
7
8 import json
9 import re
10 from pathlib import Path
11 from typing import TYPE_CHECKING, Any
12 from unittest.mock import patch
13
14 from anta.cli import anta
15 from anta.cli.utils import ExitCode
16
17 if TYPE_CHECKING:
18 from click.testing import CliRunner
19
20 DATA_DIR: Path = Path(__file__).parents[3].resolve() / "data"
21
22
23 def test_anta_nrfu_table_help(click_runner: CliRunner) -> None:
24 """Test anta nrfu table --help."""
25 result = click_runner.invoke(anta, ["nrfu", "table", "--help"])
26 assert result.exit_code == ExitCode.OK
27 assert "Usage: anta nrfu table" in result.output
28
29
30 def test_anta_nrfu_text_help(click_runner: CliRunner) -> None:
31 """Test anta nrfu text --help."""
32 result = click_runner.invoke(anta, ["nrfu", "text", "--help"])
33 assert result.exit_code == ExitCode.OK
34 assert "Usage: anta nrfu text" in result.output
35
36
37 def test_anta_nrfu_json_help(click_runner: CliRunner) -> None:
38 """Test anta nrfu json --help."""
39 result = click_runner.invoke(anta, ["nrfu", "json", "--help"])
40 assert result.exit_code == ExitCode.OK
41 assert "Usage: anta nrfu json" in result.output
42
43
44 def test_anta_nrfu_template_help(click_runner: CliRunner) -> None:
45 """Test anta nrfu tpl-report --help."""
46 result = click_runner.invoke(anta, ["nrfu", "tpl-report", "--help"])
47 assert result.exit_code == ExitCode.OK
48 assert "Usage: anta nrfu tpl-report" in result.output
49
50
51 def test_anta_nrfu_table(click_runner: CliRunner) -> None:
52 """Test anta nrfu, catalog is given via env."""
53 result = click_runner.invoke(anta, ["nrfu", "table"])
54 assert result.exit_code == ExitCode.OK
55 assert "leaf1 โ”‚ VerifyEOSVersion โ”‚ Verifies the EOS version of the device." in result.output
56
57
58 def test_anta_nrfu_table_group_by_device(click_runner: CliRunner) -> None:
59 """Test anta nrfu, catalog is given via env."""
60 result = click_runner.invoke(anta, ["nrfu", "table", "--group-by", "device"])
61 assert result.exit_code == ExitCode.OK
62 assert "Summary per device" in result.output
63
64
65 def test_anta_nrfu_table_group_by_test(click_runner: CliRunner) -> None:
66 """Test anta nrfu, catalog is given via env."""
67 result = click_runner.invoke(anta, ["nrfu", "table", "--group-by", "test"])
68 assert result.exit_code == ExitCode.OK
69 assert "Summary per test" in result.output
70
71
72 def test_anta_nrfu_table_expand(click_runner: CliRunner) -> None:
73 """Test anta nrfu, catalog is given via env."""
74 with patch("anta.reporter.ReportTable.generate_expanded") as mocked_generate_expanded:
75 result = click_runner.invoke(anta, ["nrfu", "table", "--expand"])
76 assert result.exit_code == ExitCode.OK
77 mocked_generate_expanded.assert_called_once()
78
79
80 def test_anta_nrfu_text(click_runner: CliRunner) -> None:
81 """Test anta nrfu, catalog is given via env."""
82 result = click_runner.invoke(anta, ["nrfu", "text"])
83 assert result.exit_code == ExitCode.OK
84 assert "leaf1 :: VerifyEOSVersion :: SUCCESS" in result.output
85
86
87 def test_anta_nrfu_text_multiple_failures(click_runner: CliRunner) -> None:
88 """Test anta nrfu text with multiple failures, catalog is given via env."""
89 result = click_runner.invoke(anta, ["nrfu", "text"], env={"ANTA_CATALOG": str(DATA_DIR / "test_catalog_double_failure.yml")})
90 assert result.exit_code == ExitCode.TESTS_FAILED
91 assert (
92 """spine1 :: VerifyInterfacesSpeed :: FAILURE
93 Interface: Ethernet2 - Not found
94 Interface: Ethernet3 - Not found
95 Interface: Ethernet4 - Not found"""
96 in result.output
97 )
98
99
100 def test_anta_nrfu_text_expand(click_runner: CliRunner) -> None:
101 """Test anta nrfu, catalog is given via env."""
102 result = click_runner.invoke(anta, ["nrfu", "text", "--expand"], env={"ANTA_CATALOG": str(DATA_DIR / "test_atomic.yml")})
103 assert result.exit_code == ExitCode.TESTS_FAILED
104 assert (
105 """leaf1 :: VerifyReachability :: FAILURE
106 Destination 10.255.255.0 from 10.255.255.1 in VRF default :: SUCCESS
107 Destination 10.255.255.2 from 10.255.255.3 in VRF default :: FAILURE
108 Packet loss detected - Transmitted: 1 Received: 2"""
109 in result.output
110 )
111
112
113 def test_anta_nrfu_json(click_runner: CliRunner) -> None:
114 """Test anta nrfu, catalog is given via env."""
115 result = click_runner.invoke(anta, ["nrfu", "json"])
116 assert result.exit_code == ExitCode.OK
117 assert "JSON results" in result.output
118 match = re.search(r"\[\n {2}{[\s\S]+ {2}}\n\]", result.output)
119 assert match is not None
120 result_list = json.loads(match.group())
121 for res in result_list:
122 if res["name"] == "leaf1":
123 assert res["test"] == "VerifyEOSVersion"
124 assert res["result"] == "success"
125
126
127 def test_anta_nrfu_json_output(click_runner: CliRunner, tmp_path: Path) -> None:
128 """Test anta nrfu json with output file."""
129 json_output = tmp_path / "test.json"
130 result = click_runner.invoke(anta, ["nrfu", "json", "--output", str(json_output)])
131
132 # Making sure the output is not printed to stdout
133 match = re.search(r"\[\n {2}{[\s\S]+ {2}}\n\]", result.output)
134 assert match is None
135
136 assert result.exit_code == ExitCode.OK
137 assert "JSON results saved to" in result.output
138 assert json_output.exists()
139
140
141 def test_anta_nrfu_json_output_failure(click_runner: CliRunner, tmp_path: Path) -> None:
142 """Test anta nrfu json with output file."""
143 json_output = tmp_path / "test.json"
144
145 original_open = Path.open
146
147 def mock_path_open(*args: Any, **kwargs: Any) -> Path: # noqa: ANN401
148 """Mock Path.open only for the json_output file of this test."""
149 if args[0] == json_output:
150 msg = "Simulated OSError"
151 raise OSError(msg)
152
153 # If not the json_output file, call the original Path.open
154 return original_open(*args, **kwargs)
155
156 with patch("pathlib.Path.open", mock_path_open):
157 result = click_runner.invoke(anta, ["nrfu", "json", "--output", str(json_output)])
158
159 assert result.exit_code == ExitCode.USAGE_ERROR
160 assert "Failed to save JSON results to" in result.output
161 assert not json_output.exists()
162
163
164 def test_anta_nrfu_template(click_runner: CliRunner) -> None:
165 """Test anta nrfu, catalog is given via env."""
166 result = click_runner.invoke(anta, ["nrfu", "tpl-report", "--template", str(DATA_DIR / "template.j2")])
167 assert result.exit_code == ExitCode.OK
168 assert "* VerifyEOSVersion is SUCCESS for leaf1" in result.output
169
170
171 def test_anta_nrfu_csv(click_runner: CliRunner, tmp_path: Path) -> None:
172 """Test anta nrfu csv."""
173 csv_output = tmp_path / "test.csv"
174 result = click_runner.invoke(anta, ["nrfu", "csv", "--csv-output", str(csv_output)])
175 assert result.exit_code == ExitCode.OK
176 assert "CSV report saved to" in result.output
177 assert csv_output.exists()
178
179
180 def test_anta_nrfu_csv_failure(click_runner: CliRunner, tmp_path: Path) -> None:
181 """Test anta nrfu csv."""
182 csv_output = tmp_path / "test.csv"
183 with patch("anta.reporter.csv_reporter.ReportCsv.generate", side_effect=OSError()):
184 result = click_runner.invoke(anta, ["nrfu", "csv", "--csv-output", str(csv_output)])
185 assert result.exit_code == ExitCode.USAGE_ERROR
186 assert "Failed to save CSV report to" in result.output
187 assert not csv_output.exists()
188
189
190 def test_anta_nrfu_md_report(click_runner: CliRunner, tmp_path: Path) -> None:
191 """Test anta nrfu md-report."""
192 md_output = tmp_path / "test.md"
193 result = click_runner.invoke(anta, ["nrfu", "md-report", "--md-output", str(md_output)])
194 assert result.exit_code == ExitCode.OK
195 assert "Markdown report saved to" in result.output
196 assert md_output.exists()
197
198
199 def test_anta_nrfu_md_report_expand(click_runner: CliRunner, tmp_path: Path) -> None:
200 """Test anta nrfu md-report."""
201 md_output = tmp_path / "test.md"
202 result = click_runner.invoke(anta, ["nrfu", "md-report", "--md-output", str(md_output), "--expand"])
203 assert result.exit_code == ExitCode.OK
204 assert "Markdown report saved to" in result.output
205 assert md_output.exists()
206
207 with md_output.open("r", encoding="utf-8") as f:
208 content = f.read()
209
210 target_header = '## ๐Ÿ“‰ Test Results Summary <a id="test-results-summary"></a>'
211 target_note = (
212 ">๐Ÿ’ก **Note:** This report was generated with **Expanded Results** enabled. "
213 "The summary sections below aggregate results at the test level, so individual "
214 "checks (atomic results) are not counted in these totals."
215 )
216
217 assert target_header in content
218
219 # Find the position of the header
220 header_index = content.find(target_header)
221
222 # Create a slice of the content starting from the header
223 # This ensures we are only looking "under" or "after" that section title
224 content_after_header = content[header_index:]
225
226 # Assert the note exists in that specific slice
227 assert target_note in content_after_header
228
229
230 def test_anta_nrfu_md_report_failure(click_runner: CliRunner, tmp_path: Path) -> None:
231 """Test anta nrfu md-report failure."""
232 md_output = tmp_path / "test.md"
233 with patch("anta.reporter.md_reporter.MDReportGenerator.generate_sections", side_effect=OSError()):
234 result = click_runner.invoke(anta, ["nrfu", "md-report", "--md-output", str(md_output)])
235
236 assert result.exit_code == ExitCode.USAGE_ERROR
237 assert "Failed to save Markdown report to" in result.output
238 assert not md_output.exists()
239
240
241 def test_anta_nrfu_md_report_with_hide(click_runner: CliRunner, tmp_path: Path) -> None:
242 """Test anta nrfu md-report with the `--hide` option."""
243 md_output = tmp_path / "test.md"
244 result = click_runner.invoke(anta, ["nrfu", "--hide", "success", "md-report", "--md-output", str(md_output)])
245
246 assert result.exit_code == ExitCode.OK
247 assert "Markdown report saved to" in result.output
248 assert md_output.exists()
249
250 with md_output.open("r", encoding="utf-8") as f:
251 content = f.read()
252
253 # Use regex to find the "Total Tests Success" value
254 match = re.search(r"\| (\d+) \| (\d+) \| \d+ \| \d+ \| \d+ \|", content)
255
256 assert match is not None
257
258 total_tests = int(match.group(1))
259 total_tests_success = int(match.group(2))
260
261 assert total_tests == 3
262 assert total_tests_success == 3
263
264 # Collecting the rows inside the Test Results section
265 row_count = 0
266 lines = content.splitlines()
267
268 idx = lines.index('## ๐Ÿงช Test Results <a id="test-results"></a>')
269
270 for line in lines[idx + 1 :]:
271 if line.startswith("|") and ":-" not in line:
272 row_count += 1
273 # Reducing the row count by 1, as above conditions counts the TABLE_HEADING
274 assert (row_count - 1) == 0
275
276
277 def test_anta_nrfu_table_sort(click_runner: CliRunner) -> None:
278 """Test anta nrfu table with --sort-by option."""
279 result = click_runner.invoke(
280 anta, ["nrfu", "table", "--sort-by", "name", "--sort-by", "test"], env={"ANTA_CATALOG": str(DATA_DIR / "test_catalog_table_sort.yml")}
281 )
282 target_line = result.output.splitlines()[-3]
283
284 # Check that device, test, description and status exist on the line
285 # The regex ensures they appear in that specific order
286 assert re.search(r"spine1.*VerifyInterfacesSpeed.*Verifies the speed, lanes, auto-negotiation.*failure", target_line)