Skip to content

Commit 90299d1

Browse files
fix(anta): Remove JSON output when saving to a file (#800)
1 parent 484275d commit 90299d1

File tree

4 files changed

+56
-12
lines changed

4 files changed

+56
-12
lines changed

anta/cli/nrfu/commands.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -42,7 +42,7 @@ def table(ctx: click.Context, group_by: Literal["device", "test"] | None) -> Non
4242
type=click.Path(file_okay=True, dir_okay=False, exists=False, writable=True, path_type=pathlib.Path),
4343
show_envvar=True,
4444
required=False,
45-
help="Path to save report as a file",
45+
help="Path to save report as a JSON file",
4646
)
4747
def json(ctx: click.Context, output: pathlib.Path | None) -> None:
4848
"""ANTA command to check network state with JSON result."""

anta/cli/nrfu/utils.py

Lines changed: 14 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -94,14 +94,21 @@ def print_table(ctx: click.Context, group_by: Literal["device", "test"] | None =
9494

9595

9696
def print_json(ctx: click.Context, output: pathlib.Path | None = None) -> None:
97-
"""Print result in a json format."""
97+
"""Print results as JSON. If output is provided, save to file instead."""
9898
results = _get_result_manager(ctx)
99-
console.print()
100-
console.print(Panel("JSON results", style="cyan"))
101-
rich.print_json(results.json)
102-
if output is not None:
103-
with output.open(mode="w", encoding="utf-8") as fout:
104-
fout.write(results.json)
99+
100+
if output is None:
101+
console.print()
102+
console.print(Panel("JSON results", style="cyan"))
103+
rich.print_json(results.json)
104+
else:
105+
try:
106+
with output.open(mode="w", encoding="utf-8") as file:
107+
file.write(results.json)
108+
console.print(f"JSON results saved to {output} ✅", style="cyan")
109+
except OSError:
110+
console.print(f"Failed to save JSON results to {output} ❌", style="cyan")
111+
ctx.exit(ExitCode.USAGE_ERROR)
105112

106113

107114
def print_text(ctx: click.Context) -> None:

docs/cli/nrfu.md

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -120,7 +120,7 @@ anta nrfu --test VerifyZeroTouch table
120120

121121
## Performing NRFU with JSON rendering
122122

123-
The JSON rendering command in NRFU testing is useful in generating a JSON output that can subsequently be passed on to another tool for reporting purposes.
123+
The JSON rendering command in NRFU testing will generate an output of all test results in JSON format.
124124

125125
### Command overview
126126

@@ -131,12 +131,12 @@ Usage: anta nrfu json [OPTIONS]
131131
ANTA command to check network state with JSON result.
132132

133133
Options:
134-
-o, --output FILE Path to save report as a file [env var:
134+
-o, --output FILE Path to save report as a JSON file [env var:
135135
ANTA_NRFU_JSON_OUTPUT]
136136
--help Show this message and exit.
137137
```
138138

139-
The `--output` option allows you to save the JSON report as a file.
139+
The `--output` option allows you to save the JSON report as a file. If specified, no output will be displayed in the terminal. This is useful for further processing or integration with other tools.
140140

141141
### Example
142142

tests/units/cli/nrfu/test_commands.py

Lines changed: 38 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -8,7 +8,7 @@
88
import json
99
import re
1010
from pathlib import Path
11-
from typing import TYPE_CHECKING
11+
from typing import TYPE_CHECKING, Any
1212
from unittest.mock import patch
1313

1414
from anta.cli import anta
@@ -90,6 +90,43 @@ def test_anta_nrfu_json(click_runner: CliRunner) -> None:
9090
assert res["result"] == "success"
9191

9292

93+
def test_anta_nrfu_json_output(click_runner: CliRunner, tmp_path: Path) -> None:
94+
"""Test anta nrfu json with output file."""
95+
json_output = tmp_path / "test.json"
96+
result = click_runner.invoke(anta, ["nrfu", "json", "--output", str(json_output)])
97+
98+
# Making sure the output is not printed to stdout
99+
match = re.search(r"\[\n {2}{[\s\S]+ {2}}\n\]", result.output)
100+
assert match is None
101+
102+
assert result.exit_code == ExitCode.OK
103+
assert "JSON results saved to" in result.output
104+
assert json_output.exists()
105+
106+
107+
def test_anta_nrfu_json_output_failure(click_runner: CliRunner, tmp_path: Path) -> None:
108+
"""Test anta nrfu json with output file."""
109+
json_output = tmp_path / "test.json"
110+
111+
original_open = Path.open
112+
113+
def mock_path_open(*args: Any, **kwargs: Any) -> Path: # noqa: ANN401
114+
"""Mock Path.open only for the json_output file of this test."""
115+
if args[0] == json_output:
116+
msg = "Simulated OSError"
117+
raise OSError(msg)
118+
119+
# If not the json_output file, call the original Path.open
120+
return original_open(*args, **kwargs)
121+
122+
with patch("pathlib.Path.open", mock_path_open):
123+
result = click_runner.invoke(anta, ["nrfu", "json", "--output", str(json_output)])
124+
125+
assert result.exit_code == ExitCode.USAGE_ERROR
126+
assert "Failed to save JSON results to" in result.output
127+
assert not json_output.exists()
128+
129+
93130
def test_anta_nrfu_template(click_runner: CliRunner) -> None:
94131
"""Test anta nrfu, catalog is given via env."""
95132
result = click_runner.invoke(anta, ["nrfu", "tpl-report", "--template", str(DATA_DIR / "template.j2")])

0 commit comments

Comments
 (0)