diff --git a/termgraph/termgraph.py b/termgraph/termgraph.py index c8898f5..d7b0bae 100644 --- a/termgraph/termgraph.py +++ b/termgraph/termgraph.py @@ -97,6 +97,23 @@ def init_args() -> dict: def main(): """Main function.""" + try: + try: + _run() + finally: + # Flush even when argument parsing exits for --help or --version. + sys.stdout.flush() + except BrokenPipeError: + # Avoid another failed flush during interpreter shutdown. + devnull = os.open(os.devnull, os.O_WRONLY) + try: + os.dup2(devnull, sys.stdout.fileno()) + finally: + os.close(devnull) + raise SystemExit(1) from None + + +def _run(): args = init_args() if args["version"]: @@ -106,14 +123,11 @@ def main(): data_obj = Data.from_file(args["filename"], args) colors = _extract_colors(data_obj, args) - try: - if args["calendar"]: - # calendar_heatmap still uses old interface - calendar_heatmap(data_obj.data, data_obj.labels, args) - else: - chart(data_obj, args, colors) - except BrokenPipeError: - pass + if args["calendar"]: + # calendar_heatmap still uses old interface + calendar_heatmap(data_obj.data, data_obj.labels, args) + else: + chart(data_obj, args, colors) def chart(data_obj: Data, args: dict, colors: list) -> None: diff --git a/tests/test_init.py b/tests/test_init.py index 9e5b125..5edaa28 100644 --- a/tests/test_init.py +++ b/tests/test_init.py @@ -1,5 +1,42 @@ +import pytest + from termgraph import termgraph as tg def test_init_args(): - tg.init_args() \ No newline at end of file + tg.init_args() + + +@pytest.mark.parametrize( + "rows,options", + [ + (1, ["--width", "10"]), + (300, ["--width", "1000"]), + (1, ["--version"]), + (1, ["--help"]), + ], +) +def test_cli_closed_stdout_pipe(tmp_path, rows, options): + """Exercise interpreter shutdown too, not only errors raised inside draw.""" + import os + import subprocess + import sys + + # One small row fails at the final flush; many wide rows fail while drawing. + data_file = tmp_path / f"pipe-{rows}.dat" + data_file.write_text("item 1\n" * rows) + read_fd, write_fd = os.pipe() + os.close(read_fd) + try: + result = subprocess.run( + [sys.executable, "-m", "termgraph.termgraph", str(data_file), *options], + check=False, + stdout=write_fd, + stderr=subprocess.PIPE, + text=True, + timeout=15, + ) + finally: + os.close(write_fd) + assert result.returncode == 1 + assert result.stderr == ""