From 883715038c7007f621163e74ab94a5d49273efe1 Mon Sep 17 00:00:00 2001 From: Kelly Sovacool Date: Thu, 8 Aug 2024 16:57:35 -0400 Subject: [PATCH] feat: add shell_run() and exec_in_context() + basic tests --- pyproject.toml | 3 ++- src/ccbr_tools/util.py | 20 ++++++++++++++++++++ tests/test_cli.py | 9 +++++++-- tests/test_util.py | 5 +++++ 4 files changed, 34 insertions(+), 3 deletions(-) create mode 100644 src/ccbr_tools/util.py create mode 100644 tests/test_util.py diff --git a/pyproject.toml b/pyproject.toml index 6c5ae50..5e9e1c1 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -34,8 +34,9 @@ classifiers = [ requires-python = ">=3.10" dependencies = [ "biopython", - "pandas", "Click >= 8.1.3", + "pandas", + "requests" ] [project.optional-dependencies] diff --git a/src/ccbr_tools/util.py b/src/ccbr_tools/util.py new file mode 100644 index 0000000..8a24ee8 --- /dev/null +++ b/src/ccbr_tools/util.py @@ -0,0 +1,20 @@ +""" Miscellaneous utility functions """ +import contextlib +import io +import subprocess + + +def shell_run(command_str): + """Run a shell command and return stdout/stderr""" + out = subprocess.run(command_str, capture_output=True, shell=True, text=True) + return "\n".join([out.stdout, out.stderr]) + + +def exec_in_context(func, *args, **kwargs): + """Execute a function in a context manager to capture stdout/stderr""" + with contextlib.redirect_stdout(io.StringIO()) as out_f, contextlib.redirect_stderr( + io.StringIO() + ) as err_f: + func(*args, **kwargs) + out_combined = "\n".join([out_f.getvalue(), err_f.getvalue()]) + return out_combined diff --git a/tests/test_cli.py b/tests/test_cli.py index 813df60..aae7598 100644 --- a/tests/test_cli.py +++ b/tests/test_cli.py @@ -1,2 +1,7 @@ -def test_example(): - assert True +from ccbr_tools.util import shell_run + + +def test_help_jobby(): + assert "Will take your job(s)... and display their information!" in shell_run( + "jobby -h" + ) diff --git a/tests/test_util.py b/tests/test_util.py new file mode 100644 index 0000000..bd1ea28 --- /dev/null +++ b/tests/test_util.py @@ -0,0 +1,5 @@ +from ccbr_tools.util import exec_in_context + + +def test_exec(): + assert exec_in_context(print, "hello", "world") == "hello world\n\n"