Debian Codegraph @

test/units/test_utils/controller/display.py

raw
1 from __future__ import annotations
2
3 import contextlib
4 import re
5 import typing as t
6
7 from ansible._internal import _display_utils
8 from ansible.module_utils._internal import _messages
9
10
11 @contextlib.contextmanager
12 def emits_warnings(
13 warning_pattern: list[str] | str | None = None,
14 deprecation_pattern: list[str] | str | None = None,
15 ignore_boilerplate: bool = True,
16 allow_unmatched_message: bool = False,
17 ) -> t.Iterator[None]:
18 """Assert that the code within the context manager body emits a warning or deprecation warning whose formatted output matches the supplied regex."""
19 with _display_utils.DeferredWarningContext(variables=dict(ansible_deprecation_warnings=True)) as ctx:
20 yield
21
22 deprecations = ctx.get_deprecation_warnings()
23 warnings = ctx.get_warnings()
24
25 if ignore_boilerplate:
26 warnings = [warning for warning in warnings if not warning.event.msg.startswith('Deprecation warnings can be disabled by setting')]
27
28 _check_messages('Warning', warning_pattern, warnings, allow_unmatched_message)
29 _check_messages('Deprecation', deprecation_pattern, deprecations, allow_unmatched_message)
30
31
32 def _check_messages(
33 label: str,
34 patterns: list[str] | str | None,
35 entries: list[_messages.WarningSummary] | list[_messages.DeprecationSummary],
36 allow_unmatched_message: bool,
37 ) -> None:
38 if patterns is None:
39 return
40
41 if isinstance(patterns, str):
42 patterns = [patterns]
43
44 unmatched = set(str(entry) for entry in entries)
45
46 for pattern in patterns:
47 matched = False
48
49 for entry in entries:
50 str_entry = str(entry)
51
52 if re.search(pattern, str_entry):
53 unmatched.discard(str_entry)
54 matched = True
55
56 assert matched, f"{label} pattern {pattern!r} did not match."
57
58 if not allow_unmatched_message:
59 assert not unmatched, f"{label} unmatched: {unmatched}"