Coverage for /var/srv/projects/api.amasfac.comuna18.com/tmp/venv/lib/python3.9/site-packages/pandas/_testing/_warnings.py: 13%
61 statements
« prev ^ index » next coverage.py v6.4.4, created at 2023-07-17 14:22 -0600
« prev ^ index » next coverage.py v6.4.4, created at 2023-07-17 14:22 -0600
1from __future__ import annotations
3from contextlib import (
4 contextmanager,
5 nullcontext,
6)
7import re
8import sys
9from typing import (
10 Literal,
11 Sequence,
12 Type,
13 cast,
14)
15import warnings
18@contextmanager
19def assert_produces_warning(
20 expected_warning: type[Warning] | bool | tuple[type[Warning], ...] | None = Warning,
21 filter_level: Literal[
22 "error", "ignore", "always", "default", "module", "once"
23 ] = "always",
24 check_stacklevel: bool = True,
25 raise_on_extra_warnings: bool = True,
26 match: str | None = None,
27):
28 """
29 Context manager for running code expected to either raise a specific warning,
30 multiple specific warnings, or not raise any warnings. Verifies that the code
31 raises the expected warning(s), and that it does not raise any other unexpected
32 warnings. It is basically a wrapper around ``warnings.catch_warnings``.
34 Parameters
35 ----------
36 expected_warning : {Warning, False, tuple[Warning, ...], None}, default Warning
37 The type of Exception raised. ``exception.Warning`` is the base
38 class for all warnings. To raise multiple types of exceptions,
39 pass them as a tuple. To check that no warning is returned,
40 specify ``False`` or ``None``.
41 filter_level : str or None, default "always"
42 Specifies whether warnings are ignored, displayed, or turned
43 into errors.
44 Valid values are:
46 * "error" - turns matching warnings into exceptions
47 * "ignore" - discard the warning
48 * "always" - always emit a warning
49 * "default" - print the warning the first time it is generated
50 from each location
51 * "module" - print the warning the first time it is generated
52 from each module
53 * "once" - print the warning the first time it is generated
55 check_stacklevel : bool, default True
56 If True, displays the line that called the function containing
57 the warning to show were the function is called. Otherwise, the
58 line that implements the function is displayed.
59 raise_on_extra_warnings : bool, default True
60 Whether extra warnings not of the type `expected_warning` should
61 cause the test to fail.
62 match : str, optional
63 Match warning message.
65 Examples
66 --------
67 >>> import warnings
68 >>> with assert_produces_warning():
69 ... warnings.warn(UserWarning())
70 ...
71 >>> with assert_produces_warning(False):
72 ... warnings.warn(RuntimeWarning())
73 ...
74 Traceback (most recent call last):
75 ...
76 AssertionError: Caused unexpected warning(s): ['RuntimeWarning'].
77 >>> with assert_produces_warning(UserWarning):
78 ... warnings.warn(RuntimeWarning())
79 Traceback (most recent call last):
80 ...
81 AssertionError: Did not see expected warning of class 'UserWarning'.
83 ..warn:: This is *not* thread-safe.
84 """
85 __tracebackhide__ = True
87 with warnings.catch_warnings(record=True) as w:
88 warnings.simplefilter(filter_level)
89 yield w
91 if expected_warning:
92 expected_warning = cast(Type[Warning], expected_warning)
93 _assert_caught_expected_warning(
94 caught_warnings=w,
95 expected_warning=expected_warning,
96 match=match,
97 check_stacklevel=check_stacklevel,
98 )
100 if raise_on_extra_warnings:
101 _assert_caught_no_extra_warnings(
102 caught_warnings=w,
103 expected_warning=expected_warning,
104 )
107def maybe_produces_warning(warning: type[Warning], condition: bool, **kwargs):
108 """
109 Return a context manager that possibly checks a warning based on the condition
110 """
111 if condition:
112 return assert_produces_warning(warning, **kwargs)
113 else:
114 return nullcontext()
117def _assert_caught_expected_warning(
118 *,
119 caught_warnings: Sequence[warnings.WarningMessage],
120 expected_warning: type[Warning],
121 match: str | None,
122 check_stacklevel: bool,
123) -> None:
124 """Assert that there was the expected warning among the caught warnings."""
125 saw_warning = False
126 matched_message = False
127 unmatched_messages = []
129 for actual_warning in caught_warnings:
130 if issubclass(actual_warning.category, expected_warning):
131 saw_warning = True
133 if check_stacklevel:
134 _assert_raised_with_correct_stacklevel(actual_warning)
136 if match is not None:
137 if re.search(match, str(actual_warning.message)):
138 matched_message = True
139 else:
140 unmatched_messages.append(actual_warning.message)
142 if not saw_warning:
143 raise AssertionError(
144 f"Did not see expected warning of class "
145 f"{repr(expected_warning.__name__)}"
146 )
148 if match and not matched_message:
149 raise AssertionError(
150 f"Did not see warning {repr(expected_warning.__name__)} "
151 f"matching '{match}'. The emitted warning messages are "
152 f"{unmatched_messages}"
153 )
156def _assert_caught_no_extra_warnings(
157 *,
158 caught_warnings: Sequence[warnings.WarningMessage],
159 expected_warning: type[Warning] | bool | tuple[type[Warning], ...] | None,
160) -> None:
161 """Assert that no extra warnings apart from the expected ones are caught."""
162 extra_warnings = []
164 for actual_warning in caught_warnings:
165 if _is_unexpected_warning(actual_warning, expected_warning):
166 # GH#38630 pytest.filterwarnings does not suppress these.
167 if actual_warning.category == ResourceWarning:
168 # GH 44732: Don't make the CI flaky by filtering SSL-related
169 # ResourceWarning from dependencies
170 unclosed_ssl = (
171 "unclosed transport <asyncio.sslproto._SSLProtocolTransport",
172 "unclosed <ssl.SSLSocket",
173 )
174 if any(msg in str(actual_warning.message) for msg in unclosed_ssl):
175 continue
176 # GH 44844: Matplotlib leaves font files open during the entire process
177 # upon import. Don't make CI flaky if ResourceWarning raised
178 # due to these open files.
179 if any("matplotlib" in mod for mod in sys.modules):
180 continue
182 extra_warnings.append(
183 (
184 actual_warning.category.__name__,
185 actual_warning.message,
186 actual_warning.filename,
187 actual_warning.lineno,
188 )
189 )
191 if extra_warnings:
192 raise AssertionError(f"Caused unexpected warning(s): {repr(extra_warnings)}")
195def _is_unexpected_warning(
196 actual_warning: warnings.WarningMessage,
197 expected_warning: type[Warning] | bool | tuple[type[Warning], ...] | None,
198) -> bool:
199 """Check if the actual warning issued is unexpected."""
200 if actual_warning and not expected_warning:
201 return True
202 expected_warning = cast(Type[Warning], expected_warning)
203 return bool(not issubclass(actual_warning.category, expected_warning))
206def _assert_raised_with_correct_stacklevel(
207 actual_warning: warnings.WarningMessage,
208) -> None:
209 from inspect import (
210 getframeinfo,
211 stack,
212 )
214 caller = getframeinfo(stack()[4][0])
215 msg = (
216 "Warning not set with correct stacklevel. "
217 f"File where warning is raised: {actual_warning.filename} != "
218 f"{caller.filename}. Warning message: {actual_warning.message}"
219 )
220 assert actual_warning.filename == caller.filename, msg