File: test_vars.py

package info (click to toggle)
ansible-core 2.19.0-1
  • links: PTS, VCS
  • area: main
  • in suites: forky
  • size: 32,752 kB
  • sloc: python: 181,000; cs: 4,929; sh: 4,611; xml: 34; makefile: 21
file content (307 lines) | stat: -rw-r--r-- 11,134 bytes parent folder | download | duplicates (2)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
# (c) 2012-2014, Michael DeHaan <michael.dehaan@gmail.com>
# (c) 2015, Toshio Kuraotmi <tkuratomi@ansible.com>
#
# This file is part of Ansible
#
# Ansible is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# Ansible is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with Ansible.  If not, see <http://www.gnu.org/licenses/>.

from __future__ import annotations

from collections import defaultdict

from unittest import mock

import unittest

from ansible.errors import AnsibleError
from ansible._internal._datatag._tags import Origin
from ansible.parsing.vault import EncryptedString
from ansible.utils.vars import combine_vars, merge_hash, transform_to_native_types
from units.mock.vault_helper import VaultTestHelper


class TestVariableUtils(unittest.TestCase):
    combine_vars_merge_data = (
        dict(
            a=dict(a=1),
            b=dict(b=2),
            result=dict(a=1, b=2),
        ),
        dict(
            a=dict(a=1, c=dict(foo='bar')),
            b=dict(b=2, c=dict(baz='bam')),
            result=dict(a=1, b=2, c=dict(foo='bar', baz='bam'))
        ),
        dict(
            a=defaultdict(a=1, c=defaultdict(foo='bar')),
            b=dict(b=2, c=dict(baz='bam')),
            result=defaultdict(a=1, b=2, c=defaultdict(foo='bar', baz='bam'))
        ),
    )
    combine_vars_replace_data = (
        dict(
            a=dict(a=1),
            b=dict(b=2),
            result=dict(a=1, b=2)
        ),
        dict(
            a=dict(a=1, c=dict(foo='bar')),
            b=dict(b=2, c=dict(baz='bam')),
            result=dict(a=1, b=2, c=dict(baz='bam'))
        ),
        dict(
            a=defaultdict(a=1, c=dict(foo='bar')),
            b=dict(b=2, c=defaultdict(baz='bam')),
            result=defaultdict(a=1, b=2, c=defaultdict(baz='bam'))
        ),
    )

    def test_combine_vars_improper_args(self):
        with mock.patch('ansible.constants.DEFAULT_HASH_BEHAVIOUR', 'replace'):
            with self.assertRaises(AnsibleError):
                combine_vars([1, 2, 3], dict(a=1))
            with self.assertRaises(AnsibleError):
                combine_vars(dict(a=1), [1, 2, 3])

        with mock.patch('ansible.constants.DEFAULT_HASH_BEHAVIOUR', 'merge'):
            with self.assertRaises(AnsibleError):
                combine_vars([1, 2, 3], dict(a=1))
            with self.assertRaises(AnsibleError):
                combine_vars(dict(a=1), [1, 2, 3])

    def test_combine_vars_replace(self):
        with mock.patch('ansible.constants.DEFAULT_HASH_BEHAVIOUR', 'replace'):
            for test in self.combine_vars_replace_data:
                self.assertEqual(combine_vars(test['a'], test['b']), test['result'])

    def test_combine_vars_merge(self):
        with mock.patch('ansible.constants.DEFAULT_HASH_BEHAVIOUR', 'merge'):
            for test in self.combine_vars_merge_data:
                self.assertEqual(combine_vars(test['a'], test['b']), test['result'])

    merge_hash_data = {
        "low_prio": {
            "a": {
                "a'": {
                    "x": "low_value",
                    "y": "low_value",
                    "list": ["low_value"]
                }
            },
            "b": [1, 1, 2, 3]
        },
        "high_prio": {
            "a": {
                "a'": {
                    "y": "high_value",
                    "z": "high_value",
                    "list": ["high_value"]
                }
            },
            "b": [3, 4, 4, {"5": "value"}]
        }
    }

    def test_merge_hash_simple(self):
        for test in self.combine_vars_merge_data:
            self.assertEqual(merge_hash(test['a'], test['b']), test['result'])

        low = self.merge_hash_data['low_prio']
        high = self.merge_hash_data['high_prio']
        expected = {
            "a": {
                "a'": {
                    "x": "low_value",
                    "y": "high_value",
                    "z": "high_value",
                    "list": ["high_value"]
                }
            },
            "b": high['b']
        }
        self.assertEqual(merge_hash(low, high), expected)

    def test_merge_hash_non_recursive_and_list_replace(self):
        low = self.merge_hash_data['low_prio']
        high = self.merge_hash_data['high_prio']
        expected = high
        self.assertEqual(merge_hash(low, high, False, 'replace'), expected)

    def test_merge_hash_non_recursive_and_list_keep(self):
        low = self.merge_hash_data['low_prio']
        high = self.merge_hash_data['high_prio']
        expected = {
            "a": high['a'],
            "b": low['b']
        }
        self.assertEqual(merge_hash(low, high, False, 'keep'), expected)

    def test_merge_hash_non_recursive_and_list_append(self):
        low = self.merge_hash_data['low_prio']
        high = self.merge_hash_data['high_prio']
        expected = {
            "a": high['a'],
            "b": low['b'] + high['b']
        }
        self.assertEqual(merge_hash(low, high, False, 'append'), expected)

    def test_merge_hash_non_recursive_and_list_prepend(self):
        low = self.merge_hash_data['low_prio']
        high = self.merge_hash_data['high_prio']
        expected = {
            "a": high['a'],
            "b": high['b'] + low['b']
        }
        self.assertEqual(merge_hash(low, high, False, 'prepend'), expected)

    def test_merge_hash_non_recursive_and_list_append_rp(self):
        low = self.merge_hash_data['low_prio']
        high = self.merge_hash_data['high_prio']
        expected = {
            "a": high['a'],
            "b": [1, 1, 2] + high['b']
        }
        self.assertEqual(merge_hash(low, high, False, 'append_rp'), expected)

    def test_merge_hash_non_recursive_and_list_prepend_rp(self):
        low = self.merge_hash_data['low_prio']
        high = self.merge_hash_data['high_prio']
        expected = {
            "a": high['a'],
            "b": high['b'] + [1, 1, 2]
        }
        self.assertEqual(merge_hash(low, high, False, 'prepend_rp'), expected)

    def test_merge_hash_recursive_and_list_replace(self):
        low = self.merge_hash_data['low_prio']
        high = self.merge_hash_data['high_prio']
        expected = {
            "a": {
                "a'": {
                    "x": "low_value",
                    "y": "high_value",
                    "z": "high_value",
                    "list": ["high_value"]
                }
            },
            "b": high['b']
        }
        self.assertEqual(merge_hash(low, high, True, 'replace'), expected)

    def test_merge_hash_recursive_and_list_keep(self):
        low = self.merge_hash_data['low_prio']
        high = self.merge_hash_data['high_prio']
        expected = {
            "a": {
                "a'": {
                    "x": "low_value",
                    "y": "high_value",
                    "z": "high_value",
                    "list": ["low_value"]
                }
            },
            "b": low['b']
        }
        self.assertEqual(merge_hash(low, high, True, 'keep'), expected)

    def test_merge_hash_recursive_and_list_append(self):
        low = self.merge_hash_data['low_prio']
        high = self.merge_hash_data['high_prio']
        expected = {
            "a": {
                "a'": {
                    "x": "low_value",
                    "y": "high_value",
                    "z": "high_value",
                    "list": ["low_value", "high_value"]
                }
            },
            "b": low['b'] + high['b']
        }
        self.assertEqual(merge_hash(low, high, True, 'append'), expected)

    def test_merge_hash_recursive_and_list_prepend(self):
        low = self.merge_hash_data['low_prio']
        high = self.merge_hash_data['high_prio']
        expected = {
            "a": {
                "a'": {
                    "x": "low_value",
                    "y": "high_value",
                    "z": "high_value",
                    "list": ["high_value", "low_value"]
                }
            },
            "b": high['b'] + low['b']
        }
        self.assertEqual(merge_hash(low, high, True, 'prepend'), expected)

    def test_merge_hash_recursive_and_list_append_rp(self):
        low = self.merge_hash_data['low_prio']
        high = self.merge_hash_data['high_prio']
        expected = {
            "a": {
                "a'": {
                    "x": "low_value",
                    "y": "high_value",
                    "z": "high_value",
                    "list": ["low_value", "high_value"]
                }
            },
            "b": [1, 1, 2] + high['b']
        }
        self.assertEqual(merge_hash(low, high, True, 'append_rp'), expected)

    def test_merge_hash_recursive_and_list_prepend_rp(self):
        low = self.merge_hash_data['low_prio']
        high = self.merge_hash_data['high_prio']
        expected = {
            "a": {
                "a'": {
                    "x": "low_value",
                    "y": "high_value",
                    "z": "high_value",
                    "list": ["high_value", "low_value"]
                }
            },
            "b": high['b'] + [1, 1, 2]
        }
        self.assertEqual(merge_hash(low, high, True, 'prepend_rp'), expected)


def test_transform_to_native_types() -> None:
    """Verify that transform_to_native_types results in native types for both keys and values, with default redaction."""
    value = {
        Origin(description="blah").tag("tagged_key"): Origin(description="blah").tag("value with tagged key"),
        # use a bogus EncryptedString instance with no VaultSecretsContext active; ensures that transform with redaction does not attempt decryption
        "redact_this": EncryptedString(ciphertext="bogus")
    }

    result = transform_to_native_types(value)

    assert result == dict(tagged_key="value with tagged key", redact_this='<redacted>')

    assert all(type(key) is str for key in result.keys())  # pylint: disable=unidiomatic-typecheck
    assert all(type(value) is str for value in result.values())  # pylint: disable=unidiomatic-typecheck


def test_transform_to_native_types_unredacted(_vault_secrets_context: None) -> None:
    """Verify that transform with redaction disabled returns a plain string decrypted value."""
    plaintext = "hello"
    value = dict(enc=VaultTestHelper.make_encrypted_string(plaintext))
    result = transform_to_native_types(value, redact=False)

    assert result == dict(enc=plaintext)
    assert all(type(key) is str for key in result.keys())  # pylint: disable=unidiomatic-typecheck
    assert all(type(value) is str for value in result.values())  # pylint: disable=unidiomatic-typecheck