diff --git a/src/slipcover/__main__.py b/src/slipcover/__main__.py index 9b0007d..91a11f8 100644 --- a/src/slipcover/__main__.py +++ b/src/slipcover/__main__.py @@ -272,6 +272,8 @@ def printit(coverage, outfile): atexit.register(sci_atexit) + return_code = 0 + if args.script: # python 'globals' for the script being executed script_globals: Dict[Any, Any] = dict() @@ -297,20 +299,25 @@ def printit(coverage, outfile): code = sci.instrument(code) with sc.ImportManager(sci, file_matcher): - exec(code, script_globals) - + try: + exec(code, script_globals) + except SystemExit as e: + return_code = e.code if e.code is not None else 0 else: import runpy sys.argv = [*args.module, *args.script_or_module_args] with sc.ImportManager(sci, file_matcher): - runpy.run_module(*args.module, run_name='__main__', alter_sys=True) + try: + runpy.run_module(*args.module, run_name='__main__', alter_sys=True) + except SystemExit as e: + return_code = e.code if e.code is not None else 0 if args.fail_under: cov = sci.get_coverage() if cov['summary']['percent_covered'] < args.fail_under: return 2 - return 0 + return return_code if __name__ == "__main__": diff --git a/tests/branch.py b/tests/branch.py index 05f0511..203245b 100644 --- a/tests/branch.py +++ b/tests/branch.py @@ -2,3 +2,5 @@ def foo(x): if x == 0: x += 1 foo(0) + +raise SystemExit() diff --git a/tests/test_coverage.py b/tests/test_coverage.py index 49cee40..8668ac6 100644 --- a/tests/test_coverage.py +++ b/tests/test_coverage.py @@ -694,14 +694,20 @@ def test_summary_in_output_zero_lines(do_branch): @pytest.mark.parametrize("json_flag", ["", "--json"]) -def test_fail_under(json_flag): +def test_fail_under(tmp_path, json_flag): p = subprocess.run(f"{sys.executable} -m slipcover {json_flag} --fail-under 100 tests/branch.py".split(), check=False) assert 0 == p.returncode - p = subprocess.run(f"{sys.executable} -m slipcover {json_flag} --branch --fail-under 83 tests/branch.py".split(), check=False) + p = subprocess.run(f"{sys.executable} -m slipcover {json_flag} --branch --fail-under 85 tests/branch.py".split(), check=False) assert 0 == p.returncode - p = subprocess.run(f"{sys.executable} -m slipcover {json_flag} --branch --fail-under 84 tests/branch.py".split(), check=False) + p = subprocess.run(f"{sys.executable} -m slipcover {json_flag} --branch --fail-under 86 tests/branch.py".split(), check=False) + assert 2 == p.returncode + + p = subprocess.run(f"{sys.executable} -m slipcover --branch --fail-under 93 -m pytest tests/pyt.py".split(), check=False) + assert 0 == p.returncode + + p = subprocess.run(f"{sys.executable} -m slipcover --branch --fail-under 94 -m pytest tests/pyt.py".split(), check=False) assert 2 == p.returncode