Skip to content

Commit e686580

Browse files
committed
Fix --fail-under for pytest
pytest raises SystemExit when it running as runpy.run_module and code block with --fail-under never ran before.
1 parent 03f0468 commit e686580

File tree

2 files changed

+13
-5
lines changed

2 files changed

+13
-5
lines changed

src/slipcover/__main__.py

Lines changed: 8 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -272,6 +272,8 @@ def printit(coverage, outfile):
272272

273273
atexit.register(sci_atexit)
274274

275+
return_code = 0
276+
275277
if args.script:
276278
# python 'globals' for the script being executed
277279
script_globals: Dict[Any, Any] = dict()
@@ -303,14 +305,17 @@ def printit(coverage, outfile):
303305
import runpy
304306
sys.argv = [*args.module, *args.script_or_module_args]
305307
with sc.ImportManager(sci, file_matcher):
306-
runpy.run_module(*args.module, run_name='__main__', alter_sys=True)
308+
try:
309+
runpy.run_module(*args.module, run_name='__main__', alter_sys=True)
310+
except SystemExit as e:
311+
return_code = e.code
307312

308313
if args.fail_under:
309314
cov = sci.get_coverage()
310315
if cov['summary']['percent_covered'] < args.fail_under:
311316
return 2
312-
313-
return 0
317+
318+
return return_code
314319

315320

316321
if __name__ == "__main__":

tests/test_coverage.py

Lines changed: 5 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -704,6 +704,11 @@ def test_fail_under(json_flag):
704704
p = subprocess.run(f"{sys.executable} -m slipcover {json_flag} --branch --fail-under 84 tests/branch.py".split(), check=False)
705705
assert 2 == p.returncode
706706

707+
p = subprocess.run(f"{sys.executable} -m slipcover --branch --fail-under 93 -m pytest tests/pyt.py".split(), check=False)
708+
assert 0 == p.returncode
709+
710+
p = subprocess.run(f"{sys.executable} -m slipcover --branch --fail-under 94 -m pytest tests/pyt.py".split(), check=False)
711+
assert 2 == p.returncode
707712

708713
def test_reports_on_other_sources(tmp_path):
709714
out_file = tmp_path / "out.json"
@@ -1286,7 +1291,6 @@ def test_xml_flag_with_pytest(tmp_path):
12861291
assert lines[7].get('branch') is None
12871292
assert lines[7].get('condition-coverage') is None
12881293
assert lines[7].get('missing-branches') is None
1289-
12901294
assert lines[8].get('number') == '10'
12911295
assert lines[8].get('hits') == '1'
12921296
assert lines[8].get('branch') is None
@@ -1399,7 +1403,6 @@ def test_xml_flag_with_branches_and_pytest(tmp_path):
13991403
assert lines[7].get('branch') is None
14001404
assert lines[7].get('condition-coverage') is None
14011405
assert lines[7].get('missing-branches') is None
1402-
14031406
assert lines[8].get('number') == '10'
14041407
assert lines[8].get('hits') == '1'
14051408
assert lines[8].get('branch') is None

0 commit comments

Comments
 (0)