Skip to content

Commit

Permalink
feat(result_manager): Support JSON output and save option (#113)
Browse files Browse the repository at this point in the history
* feat(result_manager): Support JSON output and save option

* doc: Fix typo check-devices script
  • Loading branch information
titom73 committed Sep 8, 2022
1 parent 8c3404b commit 40f6977
Show file tree
Hide file tree
Showing 4 changed files with 60 additions and 2 deletions.
2 changes: 2 additions & 0 deletions README.md
Expand Up @@ -172,7 +172,9 @@ optional arguments:
--test TEST search result for test
--tags TAGS List of device tags to limit scope of testing
--list Display internal data
--json Display data in json format
--table Result represented in tables
--save SAVE Save output to file. Only valid for --list and --json
--all-results Display all test cases results. Default table view (Only valid with --table)
--by-host Provides summary of test results per device (Only valid with --table)
--by-test Provides summary of test results per test case (Only valid with --table)
Expand Down
3 changes: 2 additions & 1 deletion anta/result_manager/__init__.py
Expand Up @@ -10,6 +10,7 @@
from typing import List, Any

from anta.result_manager.models import ListResult, TestResult
from anta.tools import pydantic_to_dict

logger = logging.getLogger(__name__)

Expand Down Expand Up @@ -107,7 +108,7 @@ def get_results(self, output_format: str = "native") -> Any:
return list(self._result_entries)

if output_format == "json":
return json.loads(str([result.json() for result in self._result_entries]))
return json.dumps(pydantic_to_dict(self._result_entries), indent=4)

# Default return for native format.
return self._result_entries
Expand Down
35 changes: 35 additions & 0 deletions anta/tools.py
@@ -0,0 +1,35 @@
#!/usr/bin/python
# coding: utf-8 -*-

"""
Toolkit for ANTA.
"""

import logging
from typing import Union, Any
from .inventory.models import InventoryDevices
from .result_manager.models import ListResult

# pylint: disable=W1309

logger = logging.getLogger(__name__)
logger.setLevel(logging.DEBUG)


def pydantic_to_dict(pydantic_list: Union[InventoryDevices, ListResult]) -> Any:
"""
Convert Pydantic object into a dict
Mimic .dict() option from pydantic but overwrite IPv4Address nodes
Args:
pydantic_list: Iterable pydantic object
Returns:
dict: dictionary object
"""
result = []
for device in pydantic_list:
dev_dict = {k: str(v) for k, v in device}
result.append(dev_dict)
return result
22 changes: 21 additions & 1 deletion scripts/check-devices.py
Expand Up @@ -32,6 +32,7 @@
from rich.logging import RichHandler
from rich.panel import Panel
from rich.pretty import pprint
from rich import print_json

import anta.loader
from anta.inventory import AntaInventory
Expand Down Expand Up @@ -71,7 +72,7 @@ def cli_manager() -> argparse.Namespace:
default='examples/inventory.yml', help='ANTA Inventory file')

parser.add_argument('--catalog', '-c', required=False,
default='examples/tests_custom.yaml', help='ANTA Tests cagtalog')
default='examples/tests_custom.yaml', help='ANTA Tests catalog')

#############################
# Device connectivity
Expand Down Expand Up @@ -106,10 +107,18 @@ def cli_manager() -> argparse.Namespace:
parser.add_argument('--list', required=False, action='store_true',
help='Display internal data')

parser.add_argument('--json', required=False, action='store_true',
help='Display data in json format')

# Display result using a table (default is TRUE)
parser.add_argument('--table', required=False, action='store_true',
help='Result represented in tables')

#############################
# Options for saving outputs
parser.add_argument('--save', required=False,
default=None, help='Save output to file. Only valid for --list and --json')

#############################
# Options for table report

Expand Down Expand Up @@ -181,12 +190,23 @@ def cli_manager() -> argparse.Namespace:
if cli_options.list:
console.print(Panel('List results of all tests', style='cyan'))
pprint(manager.get_results(output_format="list"))
if cli_options.save is not None:
with open(cli_options.save, 'w', encoding='utf-8') as fout:
fout.write(str(manager.get_results(output_format="list")))

if cli_options.json:
console.print(Panel('JSON results of all tests', style='cyan'))
print_json(manager.get_results(output_format="json"))
if cli_options.save is not None:
with open(cli_options.save, 'w', encoding='utf-8') as fout:
fout.write(manager.get_results(output_format="json"))

if cli_options.table:
reporter = ReportTable()
if cli_options.all_results or (not cli_options.by_test and not cli_options.by_host):
console.print(reporter.report_all(result_manager=manager,
host=cli_options.hostip, testcase=cli_options.test))

# To print only report per Test case
if cli_options.by_test:
console.print(reporter.report_summary_tests(
Expand Down

0 comments on commit 40f6977

Please sign in to comment.