diff --git a/AUTHORS.rst b/AUTHORS.rst index 561367d7..ba35d56a 100644 --- a/AUTHORS.rst +++ b/AUTHORS.rst @@ -70,3 +70,4 @@ Authors * Markéta Machová - https://github.com/MeggyCal * xuu33030 - https://github.com/xuu33030 * dly - https://github.com/xlyy1 +* terminalchai - https://github.com/terminalchai diff --git a/CHANGELOG.rst b/CHANGELOG.rst index cf403789..91b15f05 100644 --- a/CHANGELOG.rst +++ b/CHANGELOG.rst @@ -5,6 +5,10 @@ Changelog Unreleased ---------- +* Report an actionable usage error for ``--cov-context=test`` when the selected + coverage core does not support dynamic contexts, instead of losing context + data or issuing warnings during tests. Fixes #755. + * 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. diff --git a/docs/contexts.rst b/docs/contexts.rst index 2b447463..3d6144d9 100644 --- a/docs/contexts.rst +++ b/docs/contexts.rst @@ -6,6 +6,20 @@ Coverage.py 5.0 can record separate coverage data for `different contexts`_ duri one run of a test suite. Pytest-cov can use this feature to record coverage data for each test individually, with the ``--cov-context=test`` option. +This requires a coverage core that supports dynamic contexts. If the selected +core does not support them, pytest-cov reports a usage error before running +tests. For example, coverage.py's ``sysmon`` core currently does not support +dynamic contexts and is the default on Python 3.14 and newer. Select a compatible +core in ``.coveragerc``:: + + [run] + core = ctrace + +Or in ``pyproject.toml``:: + + [tool.coverage.run] + core = "ctrace" + .. _different contexts: https://coverage.readthedocs.io/en/latest/contexts.html The context name recorded in the coverage.py database is the pytest test id, diff --git a/src/pytest_cov/plugin.py b/src/pytest_cov/plugin.py index 9f23a890..be184952 100644 --- a/src/pytest_cov/plugin.py +++ b/src/pytest_cov/plugin.py @@ -287,6 +287,18 @@ class Config: self.cov_controller = controller_cls(self.options, config, nodeid, self.rootdir) self.cov_controller.start() + if self.options.cov_context == 'test': + core = self.cov_controller.cov._core + supports_contexts = getattr(core, 'supports_dynamic_contexts', None) + if supports_contexts is None: + # Older coverage versions only support contexts with the sys.settrace cores. + supports_contexts = core.systrace + if not supports_contexts: + self.cov_controller.pause() + raise pytest.UsageError( + '--cov-context=test requires a coverage core that supports dynamic contexts.\n' + 'Configure [run] core = ctrace in .coveragerc (or [tool.coverage.run] core = "ctrace" in pyproject.toml).' + ) self._started = True self._start_path = Path.cwd() cov_config = self.cov_controller.cov.config diff --git a/tests/test_pytest_cov.py b/tests/test_pytest_cov.py index 098dc3fd..0fca13e6 100644 --- a/tests/test_pytest_cov.py +++ b/tests/test_pytest_cov.py @@ -2056,14 +2056,15 @@ def find_labels(text, pattern): @xdist_params -def test_contexts(pytester, testdir, opts): +@pytest.mark.parametrize('core', ['ctrace', 'pytrace']) +def test_contexts(pytester, testdir, opts, core): with Path(__file__).parent.joinpath('contextful.py').open() as f: contextual_tests = f.read() script = testdir.makepyfile(contextual_tests) - testdir.tmpdir.join('.coveragerc').write("""[run] -core = ctrace""") + testdir.tmpdir.join('.coveragerc').write(f"""[run] +core = {core}""") - result = testdir.runpytest('-v', f'--cov={script.dirpath()}', '--cov-context=test', script, *opts.split()) + result = testdir.runpytest('-v', '-Werror', f'--cov={script.dirpath()}', '--cov-context=test', script, *opts.split()) assert result.ret == 0 result.stdout.fnmatch_lines( [ @@ -2088,7 +2089,68 @@ def test_contexts(pytester, testdir, opts): assert line_data[label] == actual, f'Wrong lines for context {context!r}' +@pytest.mark.skipif(sys.version_info < (3, 14), reason='Requires the sys.monitoring core') +@pytest.mark.parametrize('core', ['sysmon', None]) +@pytest.mark.parametrize('opts', ['', '-n 2']) +def test_contexts_unsupported_core(testdir, core, opts): + script = testdir.makepyfile('def test_example(): pass') + if core: + testdir.tmpdir.join('.coveragerc').write(f'[run]\ncore = {core}\n') + result = testdir.runpytest('-Werror', '--cov=.', '--cov-context=test', script, *opts.split()) + assert result.ret == pytest.ExitCode.USAGE_ERROR + result.stderr.fnmatch_lines( + [ + 'ERROR: --cov-context=test requires a coverage core that supports dynamic contexts.*', + '*core = ctrace*', + ] + ) + assert 'no-sysmon-context' not in result.stdout.str() + result.stderr.str() + + +@pytest.mark.parametrize( + ('core', 'supported'), + [ + (SimpleNamespace(supports_dynamic_contexts=True), True), + (SimpleNamespace(supports_dynamic_contexts=False, systrace=True), False), + (SimpleNamespace(systrace=True), True), + (SimpleNamespace(systrace=False), False), + ], +) +def test_contexts_core_capability(core, supported): + paused = [] + + class Controller: + def __init__(self, *args): + self.cov = SimpleNamespace(_core=core, config=SimpleNamespace()) + + def start(self): + pass + + def pause(self): + paused.append(True) + + options = SimpleNamespace(cov_source=['.'], cov_report=['term'], cov_context='test', cov_fail_under=None, cov_precision=None) + plugin = pytest_cov.plugin.CovPlugin(options, None, start=False) + if supported: + plugin.start(Controller) + assert plugin._started + assert not paused + else: + with pytest.raises(pytest.UsageError, match='requires a coverage core that supports dynamic contexts'): + plugin.start(Controller) + assert not plugin._started + assert paused == [True] + + +def test_contexts_disabled(testdir): + script = testdir.makepyfile('def test_example(): pass') + result = testdir.runpytest('--cov=.', '--cov-context=test', '--no-cov', script) + result.assert_outcomes(passed=1) + assert 'requires a coverage core' not in result.stderr.str() + + def test_contexts_no_cover(testdir): + testdir.tmpdir.join('.coveragerc').write('[run]\ncore = ctrace\n') script = testdir.makepyfile(""" import pytest