|
1 | 1 | """Test interrupt handling functionality.""" |
2 | 2 |
|
| 3 | +import builtins |
| 4 | +import runpy |
3 | 5 | import signal |
4 | 6 | import subprocess |
5 | 7 | import sys |
|
10 | 12 | import pytest |
11 | 13 |
|
12 | 14 |
|
| 15 | +def test_module_entrypoint_handles_interrupt_during_cli_import( |
| 16 | + monkeypatch: pytest.MonkeyPatch, capsys: pytest.CaptureFixture[str] |
| 17 | +) -> None: |
| 18 | + """Startup Ctrl+C should not leak a raw import traceback.""" |
| 19 | + original_import = builtins.__import__ |
| 20 | + |
| 21 | + def interrupt_cli_import( |
| 22 | + name: str, |
| 23 | + globals: dict[str, object] | None = None, |
| 24 | + locals: dict[str, object] | None = None, |
| 25 | + fromlist: tuple[str, ...] = (), |
| 26 | + level: int = 0, |
| 27 | + ) -> object: |
| 28 | + if name == "cli" and level == 1: |
| 29 | + raise KeyboardInterrupt |
| 30 | + return original_import(name, globals, locals, fromlist, level) |
| 31 | + |
| 32 | + monkeypatch.setattr(builtins, "__import__", interrupt_cli_import) |
| 33 | + |
| 34 | + with pytest.raises(SystemExit, match="2"): |
| 35 | + runpy.run_module("modelaudit", run_name="__main__") |
| 36 | + |
| 37 | + assert capsys.readouterr().err == "Scan interrupted by user\n" |
| 38 | + |
| 39 | + |
| 40 | +def test_package_init_defers_scanner_result_imports() -> None: |
| 41 | + """Package discovery must stay lightweight until the startup guard runs.""" |
| 42 | + result = subprocess.run( |
| 43 | + [ |
| 44 | + sys.executable, |
| 45 | + "-c", |
| 46 | + "import modelaudit, sys; assert 'modelaudit.scanner_results' not in sys.modules", |
| 47 | + ], |
| 48 | + capture_output=True, |
| 49 | + text=True, |
| 50 | + check=False, |
| 51 | + ) |
| 52 | + |
| 53 | + assert result.returncode == 0, result.stderr |
| 54 | + |
| 55 | + |
13 | 56 | def test_interrupt_handler_basic(): |
14 | 57 | """Test basic interrupt handler functionality.""" |
15 | 58 | from modelaudit.utils.helpers.interrupt_handler import ( |
|
0 commit comments