Skip to content

Provide an API for passing plugins to the Coverage constructor #1919

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
Feb 16, 2025
Merged
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
23 changes: 20 additions & 3 deletions coverage/control.py
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@
import sys
import threading
import time
import typing
import warnings

from types import FrameType
Expand Down Expand Up @@ -43,14 +44,14 @@
from coverage.misc import DefaultValue, ensure_dir_for_file, isolate_module
from coverage.multiproc import patch_multiprocessing
from coverage.plugin import FileReporter
from coverage.plugin_support import Plugins
from coverage.plugin_support import Plugins, TCoverageInit
from coverage.python import PythonFileReporter
from coverage.report import SummaryReporter
from coverage.report_core import render_report
from coverage.results import Analysis, analysis_from_file_reporter
from coverage.types import (
FilePath, TConfigurable, TConfigSectionIn, TConfigValueIn, TConfigValueOut,
TFileDisposition, TLineNo, TMorf,
TFileDisposition, TLineNo, TMorf
)
from coverage.xmlreport import XmlReporter

Expand Down Expand Up @@ -138,6 +139,7 @@ def __init__( # pylint: disable=too-many-arguments
check_preimported: bool = False,
context: str | None = None,
messages: bool = False,
plugins: Iterable[Callable[..., None]] | None = None,
) -> None:
"""
Many of these arguments duplicate and override values that can be
Expand Down Expand Up @@ -211,6 +213,12 @@ def __init__( # pylint: disable=too-many-arguments
If `messages` is true, some messages will be printed to stdout
indicating what is happening.

If `plugins` are passed, they are an iterable of functions with the
`coverage_init` signature (meaning they take a plugin registry and a
dictionary of configuration options as arguments). When they are
provided, they will override the plugins found in the coverage
configuration file.

.. versionadded:: 4.0
The `concurrency` parameter.

Expand Down Expand Up @@ -260,6 +268,10 @@ def __init__( # pylint: disable=too-many-arguments
self._debug: DebugControl = NoDebugging()
self._inorout: InOrOut | None = None
self._plugins: Plugins = Plugins()
self._plugin_override = typing.cast(
typing.Union[Iterable[TCoverageInit], None],
plugins
)
self._data: CoverageData | None = None
self._core: Core | None = None
self._collector: Collector | None = None
Expand Down Expand Up @@ -340,7 +352,12 @@ def _init(self) -> None:
self._file_mapper = relative_filename

# Load plugins
self._plugins = Plugins.load_plugins(self.config.plugins, self.config, self._debug)
self._plugins = Plugins.load_plugins(
self.config.plugins,
self.config,
self._debug,
plugin_override=self._plugin_override
)

# Run configuring plugins.
for plugin in self._plugins.configurers:
Expand Down
33 changes: 21 additions & 12 deletions coverage/plugin_support.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,13 +11,14 @@

from types import FrameType
from typing import Any
from typing import Callable
from collections.abc import Iterable, Iterator

from coverage.exceptions import PluginError
from coverage.misc import isolate_module
from coverage.plugin import CoveragePlugin, FileTracer, FileReporter
from coverage.types import (
TArc, TConfigurable, TDebugCtl, TLineNo, TPluginConfig, TSourceTokenLines,
TArc, TConfigurable, TDebugCtl, TLineNo, TPluginConfig, TSourceTokenLines, TConfigSectionOut
)

os = isolate_module(os)
Expand All @@ -42,6 +43,7 @@ def load_plugins(
modules: Iterable[str],
config: TPluginConfig,
debug: TDebugCtl | None = None,
plugin_override: Iterable[TCoverageInit] | None = None,
) -> Plugins:
"""Load plugins from `modules`.

Expand All @@ -51,19 +53,23 @@ def load_plugins(
plugins = cls()
plugins.debug = debug

for module in modules:
plugins.current_module = module
__import__(module)
mod = sys.modules[module]
if plugin_override is not None:
for override in plugin_override:
override(plugins, {})
Copy link
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Of course, after merging, thinking about documenting this, I have a hard time explaining why config options are passed to this function but they are always empty. I'm going to change the signature of the plugin function to leave it out.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Ok! I went for consistency with the signature of plugin inits loaded from the config, but that did produce this slightly silly result.

else:
for module in modules:
plugins.current_module = module
__import__(module)
mod = sys.modules[module]

coverage_init = getattr(mod, "coverage_init", None)
if not coverage_init:
raise PluginError(
f"Plugin module {module!r} didn't define a coverage_init function",
)
coverage_init = getattr(mod, "coverage_init", None)
if not coverage_init:
raise PluginError(
f"Plugin module {module!r} didn't define a coverage_init function",
)

options = config.get_plugin_options(module)
coverage_init(plugins, options)
options = config.get_plugin_options(module)
coverage_init(plugins, options)

plugins.current_module = None
return plugins
Expand Down Expand Up @@ -138,6 +144,9 @@ def get(self, plugin_name: str) -> CoveragePlugin:
return self.names[plugin_name]


TCoverageInit = Callable[[Plugins, TConfigSectionOut], None]


class LabelledDebug:
"""A Debug writer, but with labels for prepending to the messages."""

Expand Down
15 changes: 15 additions & 0 deletions tests/test_plugins.py
Original file line number Diff line number Diff line change
Expand Up @@ -272,6 +272,21 @@ def coverage_init(reg, options):
out = self.run_command("coverage html -q") # sneak in a test of -q
assert out == ""

def test_coverage_init_plugins(self) -> None:
called = False
def coverage_init(
reg: Plugins, # pylint: disable=unused-argument
options: TConfigSectionOut # pylint: disable=unused-argument
) -> None:
nonlocal called
called = True

cov = coverage.Coverage(plugins=[coverage_init])
# Calls _init() and loads plugins
cov.sys_info()

assert called


@pytest.mark.skipif(testenv.PLUGINS, reason="This core doesn't support plugins.")
class PluginWarningOnPyTracerTest(CoverageTest):
Expand Down