From 3fae2470806690d9f33d05818e298697068525f6 Mon Sep 17 00:00:00 2001 From: Jim Garrison Date: Thu, 14 May 2026 15:13:36 -0400 Subject: [PATCH] Flush coverage so that lines are correctly reported as covered This change is sufficient for coverage to be appropriately reported when using this package. Thank you to Microsoft Copilot for helping me diagnose the issue and come up with a fix. --- src/pytest_forked/__init__.py | 27 ++++++++++++++++++++++++++- 1 file changed, 26 insertions(+), 1 deletion(-) diff --git a/src/pytest_forked/__init__.py b/src/pytest_forked/__init__.py index 80f4f25..35dca48 100644 --- a/src/pytest_forked/__init__.py +++ b/src/pytest_forked/__init__.py @@ -5,6 +5,11 @@ import pytest from _pytest import runner +try: + import coverage +except ImportError: + coverage = None + # we know this bit is bad, but we cant help it with the current pytest setup @@ -55,6 +60,20 @@ def pytest_runtest_protocol(item): return True +def flush_coverage(): + if coverage is None: + return + + cov = coverage.Coverage.current() + if cov: + try: + cov.stop() + cov.save() + except Exception: + # Don't let coverage errors interfere with test reporting + pass + + def forked_run_report(item): # for now, we run setup/teardown in the subprocess # XXX optionally allow sharing of setup/teardown @@ -67,8 +86,14 @@ def runforked(): try: reports = runtestprotocol(item, log=False) except KeyboardInterrupt: + flush_coverage() os._exit(EXITSTATUS_TESTEXIT) - return marshal.dumps([serialize_report(x) for x in reports]) + except BaseException: + flush_coverage() + raise + else: + flush_coverage() + return marshal.dumps([serialize_report(x) for x in reports]) ff = py.process.ForkedFunc(runforked) result = ff.waitfinish()