testutil: add new mock_command context manager

The new `testutil.mock_command` context manager can be used to
mock commands in PATH and replace them with arbitrary shell
scripts. This is useful in testing to e.g. simulate exact error
conditions that would be hard to trigger otherwise or to replace
long running commands with faked results.

Example:
```
fake_cmd = textwrap.dedent("""\
do-something
""")
with mock_command("some-cmd", fake_cmd):
   your_code
```
This commit is contained in:
Michael Vogt 2024-02-08 09:42:29 +01:00 committed by Brian C. Lane
parent 291f5cc29e
commit 7b5d6e4bd9
2 changed files with 49 additions and 0 deletions

View file

@ -0,0 +1,29 @@
#
# Tests for the 'osbuild.util.testutil.mock_command' module.
#
import os
import subprocess
import textwrap
from osbuild.testutil import mock_command
def test_mock_command_integration():
output = subprocess.check_output(["echo", "hello"])
assert output == b"hello\n"
fake_echo = textwrap.dedent("""\
#!/bin/sh
echo i-am-not-echo
""")
with mock_command("echo", fake_echo):
output = subprocess.check_output(["echo", "hello"])
assert output == b"i-am-not-echo\n"
output = subprocess.check_output(["echo", "hello"])
assert output == b"hello\n"
def test_mock_command_environ_is_modified_and_restored():
orig_path = os.environ["PATH"]
with mock_command("something", "#!/bin/sh\ntrue\n"):
assert os.environ["PATH"] != orig_path
assert os.environ["PATH"] == orig_path