Skip to content

Commit 53425b5

Browse files
committed
tests(util): Verify isatty() mocking behavior
1 parent 91cac7e commit 53425b5

File tree

1 file changed

+45
-0
lines changed

1 file changed

+45
-0
lines changed

tests/test_util.py

Lines changed: 45 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,7 @@
22

33
from __future__ import annotations
44

5+
import pathlib
56
import sys
67
import typing as t
78

@@ -36,6 +37,50 @@ def test_run_before_script_raise_BeforeLoadScriptError_if_retcode() -> None:
3637
run_before_script(script_file)
3738

3839

40+
@pytest.fixture
41+
def temp_script(tmp_path: pathlib.Path) -> pathlib.Path:
42+
"""Fixture of an example script that prints "Hello, world!"."""
43+
script = tmp_path / "test_script.sh"
44+
script.write_text(
45+
"""#!/bin/sh
46+
echo "Hello, World!"
47+
exit 0
48+
"""
49+
)
50+
script.chmod(0o755)
51+
return script
52+
53+
54+
@pytest.mark.parametrize(
55+
["isatty_value", "expected_output"],
56+
[
57+
(True, "Hello, World!"), # if stdout is a TTY, output should be passed through
58+
(False, ""), # if not a TTY, output is not written to sys.stdout
59+
],
60+
)
61+
def test_run_before_script_isatty(
62+
temp_script: pathlib.Path,
63+
monkeypatch: pytest.MonkeyPatch,
64+
capsys: pytest.CaptureFixture[str],
65+
isatty_value: bool,
66+
expected_output: str,
67+
) -> None:
68+
"""Verify behavior of ``isatty()``, which we mock in `run_before_script()`."""
69+
# Mock sys.stdout.isatty() to return the desired value.
70+
monkeypatch.setattr(sys.stdout, "isatty", lambda: isatty_value)
71+
72+
# Run the script.
73+
returncode = run_before_script(temp_script)
74+
75+
# Assert that the script ran successfully.
76+
assert returncode == 0
77+
78+
out, _err = capsys.readouterr()
79+
80+
# In TTY mode, we expect the output; in non-TTY mode, we expect it to be suppressed.
81+
assert expected_output in out
82+
83+
3984
def test_return_stdout_if_ok(
4085
capsys: pytest.CaptureFixture[str],
4186
monkeypatch: pytest.MonkeyPatch,

0 commit comments

Comments
 (0)