From 751b0db0c40d3ee62ccee2e113b69479d91399bd Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jiri=20Dan=C4=9Bk?= Date: Fri, 12 Apr 2024 19:55:36 +0200 Subject: [PATCH] Refine `execute_command` function for printing aligned tabbed tables MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The commit adds type hints to parameters and return type of the `execute_command` function in util.py script. It also introduces a change in printing logic to handle tabs. Further, new test cases are added in test_util.py script to confirm this behavior. ### Before ``` 10:31:54 >: Cluster Admin: true 10:31:54 >: Organization: N/A 10:31:54 >: Creator: N/A 10:31:54 >: Email: N/A 10:31:54 >: AccountNumber: N/A 10:31:54 >: Created: 2024-04-12T08:31:54Z 10:31:54 >: Expiration: 2024-04-13T20:31:53Z ``` ### After ``` 20:02:16 >: Cluster Admin: true 20:02:16 >: Organization: N/A 20:02:16 >: Creator: N/A 20:02:16 >: Email: N/A 20:02:16 >: AccountNumber: N/A 20:02:16 >: Created: 2024-04-12T18:02:16Z 20:02:16 >: Expiration: 2024-04-14T06:02:15Z ``` Signed-off-by: Jiri Daněk --- ods_ci/selftests/utils/scripts/test_util.py | 11 +++++++++++ ods_ci/utils/scripts/util.py | 4 ++-- 2 files changed, 13 insertions(+), 2 deletions(-) diff --git a/ods_ci/selftests/utils/scripts/test_util.py b/ods_ci/selftests/utils/scripts/test_util.py index 16ac653ad..2524295f1 100644 --- a/ods_ci/selftests/utils/scripts/test_util.py +++ b/ods_ci/selftests/utils/scripts/test_util.py @@ -70,6 +70,17 @@ def test_stdout(self): def test_stderr(self): assert util.execute_command("echo stderr >&2") == "stderr\n" + def test_output_printing_spaces(self): + with contextlib.redirect_stdout(io.StringIO()) as output: + assert util.execute_command("echo hello world") == "hello world\n" + assert output.getvalue() == ">: hello world\n" + + def test_output_printing_tab(self): + with contextlib.redirect_stdout(io.StringIO()) as output: + # use echo binary, not the shell builtin, because some shells (e.g. /bin/sh on Ubuntu) don't support -e + assert util.execute_command("/usr/bin/echo -e 'hello\tworld'") == "hello\tworld\n" + assert output.getvalue() == ">: hello world\n" + def test_string_cmd(self): assert util.execute_command("echo hello world", print_stdout=False) == "hello world\n" diff --git a/ods_ci/utils/scripts/util.py b/ods_ci/utils/scripts/util.py index 477f44514..6236594a8 100644 --- a/ods_ci/utils/scripts/util.py +++ b/ods_ci/utils/scripts/util.py @@ -53,7 +53,7 @@ def read_yaml(filename): return None -def execute_command(cmd, print_stdout=True): +def execute_command(cmd: str, print_stdout: bool = True) -> str | None: """ Executes command in the local node, and print real-time output """ @@ -72,7 +72,7 @@ def execute_command(cmd, print_stdout=True): for line in p.stdout: output.append(line) if print_stdout: - print(">:", line, end="") + print(">:", line.expandtabs(tabsize=8), end="") sys.stdout.flush() return "".join(output) except Exception as e: