Debian Codegraph @

test/units/parsing/yaml/test_errors.py

raw
1 from __future__ import annotations
2
3 import pathlib
4 import tempfile
5
6 from unittest.mock import call
7
8 import typing as t
9
10 import pytest
11 import pytest_mock
12
13 from ansible import constants as C
14 from ansible._internal._errors._error_utils import format_exception_message
15 from ansible._internal._datatag._tags import Origin
16 from ansible.parsing.utils.yaml import from_yaml
17 from ansible._internal._yaml._errors import AnsibleYAMLParserError
18 from ansible.utils.display import Display
19
20
21 @pytest.mark.parametrize("content, expected_message, expect_help_text, line, col", (
22 # cases with multiple permutations due to handling of multiple levels of list and up to one dict level
23
24 ('{{ bar }}', 'This may be an issue with missing quotes around a template block.', True, 1, 1),
25 ('foo: {{ bar }}', 'This may be an issue with missing quotes around a template block.', True, 1, 6),
26 ('- {{ bar }}', 'This may be an issue with missing quotes around a template block.', True, 1, 3),
27 ('- foo: {{ bar }}', 'This may be an issue with missing quotes around a template block.', True, 1, 8),
28 (' - - {{ bar }}', 'This may be an issue with missing quotes around a template block.', True, 1, 7),
29 (' - - foo: {{ bar }}', 'This may be an issue with missing quotes around a template block.', True, 1, 12),
30
31 ('"foo" foo', 'Values starting with a quote must end with the same quote.', True, 1, 1),
32 ('foo: "foo" foo', 'Values starting with a quote must end with the same quote.', True, 1, 6),
33 ('- "foo" foo', 'Values starting with a quote must end with the same quote.', True, 1, 3),
34 ('- foo: "foo" foo', 'Values starting with a quote must end with the same quote.', True, 1, 8),
35 (' - - "foo" foo', 'Values starting with a quote must end with the same quote.', True, 1, 7),
36 (' - - foo: "foo" foo', 'Values starting with a quote must end with the same quote.', True, 1, 12),
37
38 ('"foo" "foo"', 'Values starting with a quote must end with the same quote, and not contain that quote.', True, 1, 1),
39 ('foo: "foo" "foo"', 'Values starting with a quote must end with the same quote, and not contain that quote.', True, 1, 6),
40 ('- "foo" "foo"', 'Values starting with a quote must end with the same quote, and not contain that quote.', True, 1, 3),
41 ('- foo: "foo" "foo"', 'Values starting with a quote must end with the same quote, and not contain that quote.', True, 1, 8),
42 (' - - "foo" "foo"', 'Values starting with a quote must end with the same quote, and not contain that quote.', True, 1, 7),
43 (' - - foo: "foo" "foo"', 'Values starting with a quote must end with the same quote, and not contain that quote.', True, 1, 12),
44
45 # cases without list/dict handling
46
47 ('aaa: bbb:', 'Colons in unquoted values must be followed by a non-space character.', True, 1, 9),
48 ('aaa: bbb: ccc', 'Colons in unquoted values must be followed by a non-space character.', True, 1, 9),
49 ('''- value == "x: 'x' x"''', 'Colons in unquoted values must be followed by a non-space character.', True, 1, 14),
50
51 ('!!map 1\t2\t3', 'Tabs are usually invalid in YAML.', False, 1, 8),
52 ('{a: 1, a: 1}', "Found duplicate mapping key 'a'.", False, 1, 8),
53
54 (1, 'a string or stream input is required', False, None, None), # wrong type (misuse of API)
55
56 # cases where the underling MarkedYAMLError is used
57
58 ('k1: v1\n k2: v2', 'Mapping values are not allowed in this context.', False, 2, 5),
59 ('k1: v1\n k2: ":"', 'Mapping values are not allowed in this context.', False, 2, 5),
60
61 (':', 'While parsing a block mapping did not find expected key.', False, 1, 1),
62 ('!!map 1', 'Expected a mapping node, but found scalar.', False, 1, 1),
63 ('[]: bad', 'While constructing a mapping found unhashable key.', False, 1, 1),
64 ('{}: bad', 'While constructing a mapping found unhashable key.', False, 1, 1),
65 ('"\\"', 'While scanning a quoted scalar found unexpected end of stream.', False, 1, 4),
66
67 # DTFIX-FUTURE: add tests that use comments
68 ))
69 def test_yaml_parser_error(
70 content: t.Any,
71 expected_message: str,
72 expect_help_text: bool,
73 line: int | None,
74 col: int | None,
75 mocker: pytest_mock.MockerFixture,
76 ) -> None:
77 set_duplicate_yaml_dict_key_config(mocker, 'error')
78
79 expected_message = f'YAML parsing failed: {expected_message}'
80
81 with tempfile.TemporaryDirectory() as tempdir:
82 source_path = pathlib.Path(tempdir) / 'source.yml'
83 source_path.write_text(str(content))
84
85 with pytest.raises(AnsibleYAMLParserError) as error:
86 from_yaml(content, file_name=str(source_path))
87
88 assert error.value.message == expected_message
89 assert error.value._original_message == expected_message
90 assert format_exception_message(error.value) == expected_message
91 assert str(error.value) == expected_message
92
93 assert error.value.obj == Origin(path=str(source_path), line_num=line, col_num=col)
94
95 if expect_help_text:
96 assert error.value._help_text is not None # DTFIX-FUTURE: check the content later once it's less volatile
97 else:
98 assert error.value._help_text is None
99
100
101 def test_yaml_duplicate_key_warning(mocker: pytest_mock.MockerFixture) -> None:
102 set_duplicate_yaml_dict_key_config(mocker, 'warn')
103
104 patched_warning = mocker.patch.object(Display(), 'warning')
105
106 assert from_yaml('{a: 1, b: 2, c: 3, b: 4, d: 5, b: 6}', file_name='/hello.yml')
107
108 patched_warning.assert_has_calls((
109 call(msg="Found duplicate mapping key 'b'.", obj="b", help_text="Using last defined value only."),
110 call(msg="Found duplicate mapping key 'b'.", obj="b", help_text="Using last defined value only."),
111 ))
112
113
114 def test_yaml_duplicate_key_ignore(mocker: pytest_mock.MockerFixture) -> None:
115 set_duplicate_yaml_dict_key_config(mocker, 'ignore')
116
117 warning_spy = mocker.spy(Display(), 'warning')
118
119 assert from_yaml('{a: 1, a: 2}', file_name='/hello.yml')
120
121 warning_spy.assert_not_called()
122
123
124 def set_duplicate_yaml_dict_key_config(mocker: pytest_mock.MockerFixture, value: str):
125 original_get_config_value = C.config.get_config_value
126
127 def mocked_get_config_value(config, *args, **kwargs):
128 if config == 'DUPLICATE_YAML_DICT_KEY':
129 return value
130
131 return original_get_config_value(config, *args, **kwargs)
132
133 mocker.patch.object(C.config, 'get_config_value', mocked_get_config_value)