Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions AUTHORS.rst
Original file line number Diff line number Diff line change
Expand Up @@ -70,3 +70,5 @@ Authors
* Markéta Machová - https://github.com/MeggyCal
* xuu33030 - https://github.com/xuu33030
* dly - https://github.com/xlyy1

* Aditya Sreevatsa K - https://github.com/AdityaSreevatsaK
7 changes: 6 additions & 1 deletion CHANGELOG.rst
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,11 @@ Changelog
Unreleased
----------

* Fixed pytest-xdist coverage merging with custom file tracers when the master
process records unexecuted source files without tracer metadata. Actual
master coverage and contexts are preserved.
See `#642 <https://github.com/pytest-dev/pytest-cov/issues/642>`_.

* Fixed no_cover markers and fixtures when coverage is disabled with --no-cov.
Fixes #590.
* Document the import-path difference between ``coverage run -m pytest`` and ``pytest --cov`` for users migrating from coverage.py.
Expand Down Expand Up @@ -232,7 +237,7 @@ Unreleased
-------------------

* Changed the `toml` requirement to be always be directly required (instead of being required through a coverage extra).
This fixes issues with pip-compile (`pip-tools#1300 <https://github.com/jazzband/pip-tools/issues/1300>`_).
This fixes issues with pip-compile (`pip-tools#1300 <https://github.com/pypa/pip-tools/issues/1300>`_).
Contributed by Sorin Sbarnea in `#472 <https://github.com/pytest-dev/pytest-cov/pull/472>`_.
* Documented ``show_contexts``.
Contributed by Brian Rutledge in `#473 <https://github.com/pytest-dev/pytest-cov/pull/473>`_.
Expand Down
60 changes: 58 additions & 2 deletions src/pytest_cov/engine.py
Original file line number Diff line number Diff line change
Expand Up @@ -291,6 +291,62 @@ def finish(self):
self.node_descs.add(node_desc)


def _discard_unexecuted_files(data: CoverageData) -> bool:
"""Exclude source-discovery placeholders from distributed master coverage.

coverage.py marks unexecuted source files as measured with an empty tracer.
If a worker uses a custom tracer for the same file, the empty master record
causes coverage.py to reject the merge (issue #642). Preserve genuine
master measurements, including their contexts and file tracer metadata.
"""
files = data.measured_files()
has_arcs = data.has_arcs()
executed = {filename for filename in files if (data.arcs(filename) if has_arcs else data.lines(filename))}

if not executed:
# The data object may have written a parallel database during flush.
# Erase only that file, never the other workers' parallel databases.
data.erase()
return False

if executed == files:
return True

tracers = {}
for filename in executed:
tracer = data.file_tracer(filename)
if tracer:
tracers[filename] = tracer

# CoverageData has no public method to remove a file record. Rebuild
# the master data using its public API, retaining each recorded context.
contexts = []
try:
for context in data.measured_contexts():
data.set_query_context(context)
values = {}
for filename in executed:
recorded = data.arcs(filename) if has_arcs else data.lines(filename)
if recorded:
values[filename] = recorded
if values:
contexts.append((context, values))
finally:
data.set_query_context(None)

data.erase()
for context, values in contexts:
data.set_context(context)
if has_arcs:
data.add_arcs(values)
else:
data.add_lines(values)
if tracers:
data.add_file_tracers(tracers)

return True


class DistMaster(CovController):
"""Implementation for distributed master."""

Expand Down Expand Up @@ -370,9 +426,9 @@ def testnodedown(self, node, error):
def finish(self):
"""Combines coverage data and sets the list of coverage objects to report on."""

# Combine all the suffix files into the data file.
self.cov.stop()
self.cov.save()
if _discard_unexecuted_files(self.cov.get_data()):
self.cov.save()
self.cov = self.combining_cov
self.cov.load()
self.cov.combine()
Expand Down
51 changes: 51 additions & 0 deletions tests/test_dist_master_data.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,51 @@
"""Regression coverage for xdist master data merging (#642)."""

import coverage
import pytest

from pytest_cov.engine import _discard_unexecuted_files


@pytest.mark.parametrize('branches', [False, True])
def test_discard_empty_master_records_preserves_executed_data_and_contexts(tmp_path, branches):
master_file = str(tmp_path / '.coverage')
recorded_file = str(tmp_path / 'startup.py')
unexecuted_file = str(tmp_path / 'target.py')
data = coverage.CoverageData(basename=master_file, suffix='master')

for context in ('setup', 'teardown'):
data.set_context(context)
if branches:
data.add_arcs({recorded_file: [(-1, 1), (1, 2)]})
else:
data.add_lines({recorded_file: [1, 2]})

data.touch_files([unexecuted_file])
data.add_file_tracers({recorded_file: 'demo_plugin.Plugin'})

assert _discard_unexecuted_files(data)
data.write()

saved = coverage.CoverageData(basename=master_file, suffix='master')
saved.read()
assert saved.measured_files() == {recorded_file}
assert saved.file_tracer(recorded_file) == 'demo_plugin.Plugin'
assert saved.measured_contexts() == {'setup', 'teardown'}

for context in ('setup', 'teardown'):
saved.set_query_context(context)
if branches:
assert saved.arcs(recorded_file) == [(-1, 1), (1, 2)]
else:
assert saved.lines(recorded_file) == [1, 2]


def test_discard_entirely_unexecuted_master_data(tmp_path):
data = coverage.CoverageData(basename=str(tmp_path / '.coverage'), suffix='master')
data.add_arcs({})
data.touch_files([str(tmp_path / 'target.py')])
data.write()

assert not _discard_unexecuted_files(data)
assert data.measured_files() == set()
assert not (tmp_path / '.coverage.master').exists()
73 changes: 73 additions & 0 deletions tests/test_pytest_cov.py
Original file line number Diff line number Diff line change
Expand Up @@ -944,6 +944,79 @@ def test_foo(foo):
assert result.ret == 0


@pytest.mark.skipif(
platform.python_implementation() == 'PyPy' or sys.version_info >= (3, 15),
reason='coverage CTracer is required for custom file tracers and is unavailable on this runtime',
)
@pytest.mark.parametrize('execute_on_master', [False, True], ids=['empty-master', 'master-has-coverage'])
def test_dist_custom_file_tracer_does_not_conflict(testdir, execute_on_master):
"""Only genuine master measurements may be combined with worker tracer records (#642)."""
source = testdir.tmpdir.mkdir('src')
source.join('target.py').write('def answer():\n return 42\n')
testdir.tmpdir.join('demo_plugin.py').write(
"""
from pathlib import Path
from coverage import CoveragePlugin, FileTracer

class Tracer(FileTracer):
def __init__(self, filename):
self.filename = filename

def source_filename(self):
return self.filename

class Plugin(CoveragePlugin):
def file_tracer(self, filename):
if Path(filename).name == 'target.py':
return Tracer(filename)

def file_reporter(self, filename):
return 'python'

def coverage_init(reg, options):
reg.add_file_tracer(Plugin())
"""
)
if execute_on_master:
source.join('startup.py').write('def initialise():\n return 17\ninitialise()\n')
testdir.tmpdir.join('conftest.py').write(
"""
import os
import sys
from pathlib import Path

if 'PYTEST_XDIST_WORKER' not in os.environ:
sys.path.insert(0, str(Path(__file__).parent / 'src'))
import startup
"""
)

# coverage.py's SysMonitor and PyTracer cores do not support custom file tracers.
testdir.tmpdir.join('.coveragerc').write('[run]\ncore = ctrace\nbranch = true\nsource = src\nplugins = demo_plugin\n')
script = testdir.makepyfile(
test_target="""
from pathlib import Path
import sys

sys.path.insert(0, str(Path(__file__).parent / 'src'))
from target import answer

def test_answer():
assert answer() == 42
"""
)
result = testdir.runpytest('-n', '2', '--cov', '--cov-report=term-missing', max_worker_restart_0, script)
assert result.ret == 0, result.stdout.str() + result.stderr.str()
patterns = ['*startup.py*100%*'] if execute_on_master else []
result.stdout.fnmatch_lines([*patterns, '*target.py*100%*', '*1 passed*'])

# Verify the successful merge kept the worker's custom file tracer.
data = coverage.CoverageData(str(testdir.tmpdir.join('.coverage')))
data.read()
tracer_names = {Path(filename).name: data.file_tracer(filename) for filename in data.measured_files()}
assert tracer_names['target.py'] == 'demo_plugin.Plugin'


@pytest.mark.skipif('sys.platform == "win32" and platform.python_implementation() == "PyPy"')
def test_dist_collocated(pytester, testdir, prop):
script = testdir.makepyfile(prop.code)
Expand Down