Skip to content

Commit c43bfe2

Browse files
authored
fix: apply warning filters during configuration (#974)
1 parent 10c352d commit c43bfe2

4 files changed

Lines changed: 93 additions & 7 deletions

File tree

‎CHANGELOG.md‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -7,6 +7,7 @@ releases are available on [PyPI](https://pypi.org/project/pytask) and
77

88
## Unreleased
99

10+
- Configured warning filters now apply to warnings emitted by configuration hooks.
1011
- [#973](https://github.com/pytask-dev/pytask/pull/973) enables navigating chained
1112
exceptions in post-mortem PDB sessions on Python 3.13 and newer.
1213
- [#969](https://github.com/pytask-dev/pytask/pull/969) initializes readline before

‎src/_pytask/config.py‎

Lines changed: 8 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -12,6 +12,7 @@
1212
from _pytask.shared import parse_markers
1313
from _pytask.shared import parse_paths
1414
from _pytask.shared import to_list
15+
from _pytask.warnings_utils import catch_configured_warnings
1516

1617
if TYPE_CHECKING:
1718
from pluggy import PluginManager
@@ -73,8 +74,13 @@ def pytask_configure(pm: PluginManager, raw_config: dict[str, Any]) -> dict[str,
7374
config = {"pm": pm, "markers": {}} | raw_config
7475
config["markers"] = parse_markers(markers)
7576

76-
pm.hook.pytask_parse_config(config=config)
77-
pm.hook.pytask_post_parse(config=config)
77+
with catch_configured_warnings(config, record=False):
78+
pm.hook.pytask_parse_config(config=config)
79+
80+
# Start a new context so filters normalized during parsing apply to post-parse
81+
# hooks.
82+
with catch_configured_warnings(config, record=False):
83+
pm.hook.pytask_post_parse(config=config)
7884

7985
return config
8086

‎src/_pytask/warnings_utils.py‎

Lines changed: 16 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -9,6 +9,7 @@
99
import warnings
1010
from contextlib import contextmanager
1111
from typing import TYPE_CHECKING
12+
from typing import Any
1213
from typing import NamedTuple
1314
from typing import cast
1415

@@ -17,13 +18,15 @@
1718

1819
if TYPE_CHECKING:
1920
from collections.abc import Generator
21+
from collections.abc import Mapping
2022

2123
from _pytask.node_protocols import PTask
2224
from _pytask.session import Session
2325

2426

2527
__all__ = [
2628
"WarningReport",
29+
"catch_configured_warnings",
2730
"catch_warnings_for_item",
2831
"parse_filterwarnings",
2932
"parse_warning_filter",
@@ -154,6 +157,18 @@ def parse_filterwarnings(x: str | list[str] | None) -> list[str]:
154157
raise TypeError(msg)
155158

156159

160+
@contextmanager
161+
def catch_configured_warnings(
162+
config: Mapping[str, Any], *, record: bool
163+
) -> Generator[list[warnings.WarningMessage] | None, None, None]:
164+
"""Apply configured warning filters in a warnings-catching context."""
165+
with warnings.catch_warnings(record=record) as log:
166+
for arg in parse_filterwarnings(config.get("filterwarnings")):
167+
warnings.filterwarnings(*parse_warning_filter(arg, escape=False))
168+
169+
yield log
170+
171+
157172
@contextmanager
158173
def catch_warnings_for_item(
159174
session: Session,
@@ -165,13 +180,9 @@ def catch_warnings_for_item(
165180
``item`` can be None if we are not in the context of an item execution.
166181
167182
"""
168-
with warnings.catch_warnings(record=True) as log:
169-
# mypy can't infer that record=True means log is not None; help it.
183+
with catch_configured_warnings(session.config, record=True) as log:
170184
assert log is not None
171185

172-
for arg in session.config["filterwarnings"]:
173-
warnings.filterwarnings(*parse_warning_filter(arg, escape=False))
174-
175186
# apply filters from "filterwarnings" marks
176187
if task is not None:
177188
for mark in get_marks(task, "filterwarnings"):

‎tests/test_warnings.py‎

Lines changed: 68 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,18 +1,37 @@
11
from __future__ import annotations
22

3+
import importlib
34
import sys
45
import textwrap
6+
import warnings
57
from types import SimpleNamespace
8+
from typing import Any
69

710
import pytest
811

12+
from _pytask.pluginmanager import hookimpl
913
from _pytask.warnings_utils import _resolve_warning_category
1014
from pytask import ExitCode
1115
from pytask import build
1216
from pytask import cli
1317
from tests.conftest import run_in_subprocess
1418

1519

20+
def _register_plugin_for_build(monkeypatch: pytest.MonkeyPatch, plugin: object) -> None:
21+
"""Add a plugin to the fresh plugin manager created by ``build``."""
22+
build_module = importlib.import_module("_pytask.build")
23+
get_plugin_manager = build_module.get_plugin_manager
24+
25+
def get_plugin_manager_with_plugin():
26+
plugin_manager = get_plugin_manager()
27+
plugin_manager.register(plugin)
28+
return plugin_manager
29+
30+
monkeypatch.setattr(
31+
build_module, "get_plugin_manager", get_plugin_manager_with_plugin
32+
)
33+
34+
1635
def test_resolve_warning_category_uses_import_module(monkeypatch):
1736
class CustomWarning(Warning):
1837
pass
@@ -236,3 +255,52 @@ def test_wrong_value_in_config_in_filterwarnings(tmp_path, runner):
236255
result = runner.invoke(cli, [tmp_path.as_posix()])
237256
assert result.exit_code == ExitCode.CONFIGURATION_FAILED
238257
assert "'filterwarnings' must be a str, list[str] or None." in result.output
258+
259+
260+
@pytest.mark.parametrize("hook_name", ["pytask_parse_config", "pytask_post_parse"])
261+
@pytest.mark.parametrize("tryfirst", [True, False])
262+
def test_filterwarnings_apply_to_configuration_hooks(
263+
monkeypatch: pytest.MonkeyPatch,
264+
tmp_path,
265+
hook_name: str,
266+
tryfirst: bool,
267+
) -> None:
268+
"""Configured filters apply to early and regular configuration hooks."""
269+
270+
def emit_warning(config: dict[str, Any]) -> None: # noqa: ARG001
271+
warnings.warn("from configuration hook", UserWarning, stacklevel=1)
272+
273+
plugin = SimpleNamespace()
274+
setattr(plugin, hook_name, hookimpl(tryfirst=tryfirst)(emit_warning))
275+
_register_plugin_for_build(monkeypatch, plugin)
276+
277+
with warnings.catch_warnings(record=True) as records:
278+
warnings.simplefilter("always")
279+
session = build(
280+
paths=tmp_path,
281+
filterwarnings=["ignore::UserWarning"],
282+
)
283+
284+
assert session.exit_code == ExitCode.OK
285+
assert not any(
286+
str(record.message) == "from configuration hook" for record in records
287+
)
288+
289+
290+
def test_error_filter_applies_to_configuration_hooks(
291+
monkeypatch: pytest.MonkeyPatch, tmp_path
292+
) -> None:
293+
"""An error filter turns configuration warnings into configuration failures."""
294+
295+
def emit_warning(config: dict[str, Any]) -> None: # noqa: ARG001
296+
warnings.warn("from configuration hook", UserWarning, stacklevel=1)
297+
298+
plugin = SimpleNamespace(pytask_post_parse=hookimpl(emit_warning))
299+
_register_plugin_for_build(monkeypatch, plugin)
300+
301+
session = build(
302+
paths=tmp_path,
303+
filterwarnings=["error::UserWarning"],
304+
)
305+
306+
assert session.exit_code == ExitCode.CONFIGURATION_FAILED

0 commit comments

Comments
 (0)