Skip to content

Commit

Permalink
Modified CLI Output format (#59)
Browse files Browse the repository at this point in the history
  • Loading branch information
ammokhov committed Apr 25, 2024
1 parent 0eb761f commit e4aa9b4
Show file tree
Hide file tree
Showing 11 changed files with 62 additions and 164 deletions.
3 changes: 0 additions & 3 deletions requirements.txt
Original file line number Diff line number Diff line change
@@ -1,10 +1,7 @@
cfn_guard_rs==0.1.2
colorama>=0.4.1
coverage>=4.5.4
deepdiff==5.8.0
Jinja2==3.1.3
jsonschema>=3.0.1,<4.0
markupsafe==2.0.1
pip>=23.3
pre-commit>=2.21.0
pylint>=2.15.10
Expand Down
2 changes: 1 addition & 1 deletion setup.cfg
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@ skip = env
include_trailing_comma = true
combine_as_imports = True
force_grid_wrap = 0
known_third_party = boto3,botocore,cfn_tools,hypothesis,jinja2,jsonschema,nested_lookup,ordered_set,pytest,requests,setuptools,yaml,dpcontracts,aws_lambda_powertools,moto
known_third_party = cfn_guard_rs,coverage,deepdiff,,jsonschema,pytest,pytest-cov,pytest-random-order,rich,StrEnum,wheel

[tool:pytest]
# can't do anything about 3rd part modules, so don't spam us
Expand Down
2 changes: 1 addition & 1 deletion src/cli.py
Original file line number Diff line number Diff line change
Expand Up @@ -73,7 +73,7 @@ def main(args_in=None):
def display(compliance_result: List[GuardRuleSetResult]): # pylint: disable=C0116
for item in compliance_result:
print()
print(item)
item.display()
print()


Expand Down
64 changes: 42 additions & 22 deletions src/rpdk/guard_rail/core/data_types.py
Original file line number Diff line number Diff line change
Expand Up @@ -21,14 +21,8 @@
from dataclasses import dataclass, field
from typing import Any, Dict, List

from colorama import Fore, init
from rpdk.guard_rail.utils.miscellaneous import jinja_loader

init()

FAILED_HEADER = f"{Fore.RED}[FAILED]:{Fore.RESET}"
WARNING_HEADER = f"{Fore.YELLOW}[WARNING]:{Fore.RESET}"
PASSED_HEADER = f"{Fore.GREEN}[PASSED]:{Fore.RESET}"
from rich.console import Console
from rich.table import Table


@dataclass
Expand Down Expand Up @@ -111,23 +105,49 @@ def merge(self, guard_ruleset_result: Any):
**guard_ruleset_result.warning,
}

def __str__(self):
def display(self):
"""Displays a table with compliance results."""
if (
not self.compliant
and not self.non_compliant
and not self.skipped
and not self.warning
):
return "Couldn't retrieve the result"

environment = jinja_loader(__name__)
template = environment.get_template("guard-result-pojo.output")
return template.render(
skipped_rules=self.skipped,
passed_rules=self.compliant,
failed_rules=self.non_compliant,
warning_rules=self.warning,
failed_header=FAILED_HEADER,
warning_header=WARNING_HEADER,
passed_header=PASSED_HEADER,
)
raise ValueError("No Rules have been executed")

table = Table(title="Schema Compliance Report")

table.add_column("Rule Name", justify="right", style="cyan", no_wrap=True)
table.add_column("Check Id", style="magenta")
table.add_column("Message", style="magenta")
table.add_column("Path", style="magenta")
table.add_column("Status", justify="right", style="green")

for rule in self.skipped:
table.add_row(rule, "-", "-", "-", "[white]skipped")

for rule in self.compliant:
table.add_row(rule, "-", "-", "-", "[green]passed")

for rule, checks in self.warning.items():
for check in checks:
table.add_row(
rule,
f"[b]{check.check_id}[/b]",
f"[b]{check.message}[/b]",
"-",
"[yellow]warning",
)

for rule, checks in self.non_compliant.items():
for check in checks:
table.add_row(
rule,
f"[b]{check.check_id}[/b]",
f"[b]{check.message}[/b]",
"-" if not check.path else f"[b][red]{check.path}[/b]",
"[red]failed",
)

console = Console()
console.print(table)
1 change: 1 addition & 0 deletions src/rpdk/guard_rail/core/runner.py
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@
from typing import Any, Dict, Mapping

import cfn_guard_rs

from rpdk.guard_rail.core.data_types import (
GuardRuleResult,
GuardRuleSetResult,
Expand Down
3 changes: 2 additions & 1 deletion src/rpdk/guard_rail/core/stateful.py
Original file line number Diff line number Diff line change
Expand Up @@ -24,9 +24,10 @@
from functools import partial
from typing import Any, Dict, Iterable

import strenum
from deepdiff import DeepDiff
from rich.console import Console

import strenum
from rpdk.guard_rail.utils.schema_utils import resolve_schema

console = Console()
Expand Down
33 changes: 0 additions & 33 deletions src/rpdk/guard_rail/core/templates/guard-result-pojo.output

This file was deleted.

30 changes: 0 additions & 30 deletions src/rpdk/guard_rail/utils/miscellaneous.py

This file was deleted.

25 changes: 5 additions & 20 deletions tests/unit/core/test_data_types.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@
"""
Unit test for data_types.py
"""
from typing import Dict, List

from rpdk.guard_rail.core.data_types import GuardRuleResult, GuardRuleSetResult

Expand All @@ -14,26 +13,12 @@ def test_merge():
assert "cannot merge with non GuardRuleSetResult type" == str(e)


def test_result_str():
"""Test GuardRuleSetResult str"""
rule_result: GuardRuleResult = GuardRuleResult(
check_id="id", message="rule message"
)
non_compliant: Dict[str, List[GuardRuleResult]] = {
"non-compliant rule": [rule_result]
}
assert str(
GuardRuleSetResult(non_compliant=non_compliant)
== "[SKIPPED]:\n\nSKIPPED RULE\n\n\x1b[32m[PASSED]:\x1b[39m\n\nCOMPLIANT "
"RULE\n\n\x1b[33m[WARNING]:\x1b[39m\n\nWARNING RULE:\n check-id: id\n "
"message: rule message\n\n\n\x1b[31m[FAILED]:\x1b[39m\n\nNON-COMPLIANT RULE:\n "
" check-id: id\n message: rule message"
)


def test_err_result_str():
"""Test GuardRuleSetResult str fail scenario"""
assert "Couldn't retrieve the result" == str(GuardRuleSetResult())
try:
GuardRuleSetResult().display()
except ValueError as e:
assert "No Rules have been executed" == str(e)


def test_success_result_str():
Expand All @@ -52,5 +37,5 @@ def test_success_result_str():
}
)
)
== "---------\n[SKIPPED]:\n\n\n\x1b[32m[PASSED]:\x1b[39m\n\n\n\x1b[33m[WARNING]:\x1b[39m\n\n\n\x1b[31m[FAILED]:\x1b[39m\n\nENSURE_OLD_PROPERTY_NOT_TURNED_IMMUTABLE:\n check-id: MI007\n message: cannot remove minimum from properties\n path: /minimum/removed\n \n" # pylint: disable=C0301
== "GuardRuleSetResult(compliant=[], non_compliant={'ensure_old_property_not_turned_immutable': {GuardRuleResult(check_id='MI007', message='cannot remove minimum from properties', path='/minimum/removed')}}, warning={}, skipped=[])" # pylint: disable=C0301
)
28 changes: 10 additions & 18 deletions tests/unit/test_cli.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,24 +9,16 @@
from cli import main
from rpdk.guard_rail.core.data_types import GuardRuleResult, GuardRuleSetResult

RULE_RESULT: GuardRuleResult = GuardRuleResult(check_id="id", message="rule message")
NON_COMPLIANT: Dict[str, List[GuardRuleResult]] = {"non-compliant rule": [RULE_RESULT]}

@pytest.fixture(scope="module")
def compliance_result():
"""Fixture function to create GuardRuleSetResult"""
rule_result: GuardRuleResult = GuardRuleResult(
check_id="id", message="rule message"
)
non_compliant: Dict[str, List[GuardRuleResult]] = {
"non-compliant rule": [rule_result]
}
warning: Dict[str, List[GuardRuleResult]] = {"warning rule": [rule_result]}
result = GuardRuleSetResult(
compliant=["compliant rule"],
non_compliant=non_compliant,
warning=warning,
skipped=["skipped rule"],
)
yield result
WARNING: Dict[str, List[GuardRuleResult]] = {"warning rule": [RULE_RESULT]}
COMPLIANCE_RESULT = GuardRuleSetResult(
compliant=["compliant rule"],
non_compliant=NON_COMPLIANT,
warning=WARNING,
skipped=["skipped rule"],
)


@mock.patch("cli.exec_compliance")
Expand Down Expand Up @@ -85,7 +77,7 @@ def test_main_cli(
):
"""Main cli unit test with downstream mocked"""
mock_collect_schemas.return_value = [{"foo": "bar"}, {"foo": "bar"}]
mock_exec_compliance.return_value = [compliance_result]
mock_exec_compliance.return_value = [COMPLIANCE_RESULT]
mock_argument_validation.return_value = True
mock_collect_rules.return_value = []
main(args_in=args)
Expand Down
35 changes: 0 additions & 35 deletions tests/unit/utils/test_miscellaneous.py

This file was deleted.

0 comments on commit e4aa9b4

Please sign in to comment.