Debian Codegraph @

test/units/module_utils/common/warnings/test_warn.py

raw
1 # -*- coding: utf-8 -*-
2 # (c) 2019 Ansible Project
3 # GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
4
5 from __future__ import annotations
6
7 import pytest
8 import typing as t
9
10 from ansible.module_utils._internal import _traceback, _messages
11 from ansible.module_utils.basic import AnsibleModule
12 from ansible.module_utils.common import warnings
13
14 from ansible.module_utils.common.warnings import warn
15 from ansible.module_utils.testing import patch_module_args
16 from units.mock.module import ModuleEnvMocker
17
18 pytestmark = pytest.mark.usefixtures("as_target", "module_env_mocker")
19
20
21 def test_warn():
22 warn('Warning message')
23 assert warnings.get_warning_messages() == ('Warning message',)
24 assert warnings.get_warnings() == [_messages.WarningSummary(event=_messages.Event(msg='Warning message'))]
25
26
27 def test_warn_via_module() -> None:
28 with patch_module_args():
29 am = AnsibleModule(argument_spec={})
30
31 am.warn('Warning message')
32
33 assert warnings.get_warning_messages() == ('Warning message',)
34 assert warnings.get_warnings() == [_messages.WarningSummary(event=_messages.Event(msg='Warning message'))]
35
36
37 def test_multiple_warnings():
38 messages = [
39 'First warning',
40 'Second warning',
41 'Third warning',
42 ]
43
44 for w in messages:
45 warn(w)
46
47 assert warnings.get_warning_messages() == tuple(messages)
48 assert warnings.get_warnings() == [_messages.WarningSummary(event=_messages.Event(msg=w)) for w in messages]
49
50
51 def test_dedupe_with_traceback(module_env_mocker: ModuleEnvMocker) -> None:
52 module_env_mocker.set_traceback_config([_traceback.TracebackEvent.WARNING])
53 msg = "a warning message"
54
55 # WarningSummary dataclass object hash is the dedupe key; presence of differing tracebacks or SourceContexts affects de-dupe
56
57 for _i in range(0, 10):
58 warn(msg) # same location, same traceback- should be collapsed to one message
59
60 assert len(warnings.get_warning_messages()) == 1
61 assert len(warnings.get_warnings()) == 1
62
63 for _i in range(0, 10):
64 warn(msg) # with tracebacks on, we should have a different source location than the first loop, but still de-dupe
65
66 assert len(warnings.get_warning_messages()) == 2
67 assert len(warnings.get_warnings()) == 2
68
69
70 @pytest.mark.parametrize(
71 'test_case',
72 (
73 1,
74 True,
75 [1],
76 {'k1': 'v1'},
77 (1, 2),
78 6.62607004,
79 b'bytestr',
80 None,
81 )
82 )
83 def test_warn_failure(test_case: t.Any):
84 with pytest.raises(TypeError, match=f"must be <class 'str'> instead of {type(test_case)}"):
85 warn(test_case)