import sys import subprocess import tempfile import pathlib import textwrap import unittest import contextlib @contextlib.contextmanager def tmp_path(*args, **kwargs): with tempfile.TemporaryDirectory() as tmp_fn: yield pathlib.Path(tmp_fn) def _ham(tmp): ham = tmp / "ham.py" ham.write_text( textwrap.dedent( """\ raise KeyboardInterrupt """ ) ) return ham class TestExit(unittest.TestCase): def run(self, *args, **kwargs): with tmp_path() as tmp: self.ham = ham = tmp / "ham.py" ham.write_text( textwrap.dedent( """\ raise KeyboardInterrupt """ ) ) super().run(*args, **kwargs) def assertSigInt(self, *args, **kwargs): proc = subprocess.run(*args, **kwargs, text=True, stderr=subprocess.PIPE) self.assertTrue(proc.stderr.endswith("\nKeyboardInterrupt\n")) self.assertEqual(proc.returncode, -2) def test_pymain_run_file(self): self.assertSigInt([sys.executable, self.ham]) def test_pymain_run_file_runpy_run_module(self): tmp = self.ham.parent run_module = tmp / "run_module.py" run_module.write_text( textwrap.dedent( """\ import runpy runpy.run_module("ham") """ ) ) self.assertSigInt([sys.executable, run_module], cwd=tmp) def test_pymain_run_file_runpy_run_module_as_main(self): tmp = self.ham.parent run_module_as_main = tmp / "run_module_as_main.py" run_module_as_main.write_text( textwrap.dedent( """\ import runpy runpy._run_module_as_main("ham") """ ) ) self.assertSigInt([sys.executable, run_module_as_main], cwd=tmp) def test_pymain_run_command_run_module(self): self.assertSigInt([sys.executable, "-c", "import runpy; runpy.run_module('ham')"], cwd=self.ham.parent) def test_pymain_run_command(self): self.assertSigInt([sys.executable, "-c", "import ham"], cwd=self.ham.parent) def test_pymain_run_stdin(self): self.assertSigInt([sys.executable], input="import ham", cwd=self.ham.parent) def test_pymain_run_module(self): ham = self.ham self.assertSigInt([sys.executable, "-m", ham.stem], cwd=ham.parent) if __name__ == "__main__": unittest.main()