From 05f329aec23844b891ce0d333135b75151b42b32 Mon Sep 17 00:00:00 2001 From: Joe Shimkus <35382397+jshimkus-rh@users.noreply.github.com> Date: Thu, 30 Nov 2023 21:39:43 -0500 Subject: [PATCH] fix: pretty-printing event respects value of key (#624) Signed-off-by: Joe Shimkus --- ansible_rulebook/action/print_event.py | 2 +- tests/unit/action/test_print_event.py | 59 ++++++++++++++++++++++++++ 2 files changed, 60 insertions(+), 1 deletion(-) diff --git a/ansible_rulebook/action/print_event.py b/ansible_rulebook/action/print_event.py index d85fa9f6..2de0c39a 100644 --- a/ansible_rulebook/action/print_event.py +++ b/ansible_rulebook/action/print_event.py @@ -33,7 +33,7 @@ def __init__(self, metadata: Metadata, control: Control, **action_args): async def __call__(self): print_fn: Callable = print - if "pretty" in self.action_args: + if self.action_args.get("pretty", False): print_fn = pprint var_name = ( diff --git a/tests/unit/action/test_print_event.py b/tests/unit/action/test_print_event.py index 2cff0d18..5d455da2 100644 --- a/tests/unit/action/test_print_event.py +++ b/tests/unit/action/test_print_event.py @@ -89,3 +89,62 @@ async def test_print_event(): assert action["matching_events"] == {"m": {"a": 1}} assert len(set(action.keys()).difference(required_keys)) == 0 + + +@freeze_time("2023-11-30 14:51:30") +@pytest.mark.asyncio +async def test_pretty_print_event(capsys): + # Use a large payload so pretty printing will produce multiline output. + payload = { + "aaaaaaaaaaaaaaaaaaaa": "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", + "bbbbbbbbbbbbbbbbbbbb": "bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb", + "cccccccccccccccccccc": "cccccccccccccccccccccccccccccccccccccccc", + "dddddddddddddddddddd": "dddddddddddddddddddddddddddddddddddddddd", + "eeeeeeeeeeeeeeeeeeee": "eeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee", + } + queue = asyncio.Queue() + metadata = Metadata( + rule="r1", + rule_set="rs1", + rule_uuid=RULE_UUID, + rule_set_uuid=RULE_SET_UUID, + rule_run_at=RULE_RUN_AT, + ) + control = Control( + queue=queue, + inventory="abc", + hosts=["all"], + variables={"event": payload}, + project_data_file="", + ) + + # The not pretty-printed event. + action_args = dict(pretty=False) + + with patch("uuid.uuid4", return_value=DUMMY_UUID): + await PrintEvent(metadata, control, **action_args)() + + while not queue.empty(): + event = queue.get_nowait() + if event["type"] == "Action": + unpretty_action = event + + unpretty = capsys.readouterr() + assert len(unpretty.out.strip().splitlines()) == 1 + + # The pretty-printed event. + action_args = dict(pretty=True) + + with patch("uuid.uuid4", return_value=DUMMY_UUID): + await PrintEvent(metadata, control, **action_args)() + + while not queue.empty(): + event = queue.get_nowait() + if event["type"] == "Action": + pretty_action = event + + pretty = capsys.readouterr() + assert len(pretty.out.strip().splitlines()) > 1 + + # Assert there was no difference in content. + assert pretty_action == unpretty_action