Debian Codegraph @

test/units/module_utils/basic/test_sanitize_keys.py

raw
1 # -*- coding: utf-8 -*-
2 # (c) 2020, Red Hat
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 from ansible.module_utils.basic import sanitize_keys
8
9
10 def test_sanitize_keys_non_dict_types():
11 """ Test that non-dict-like objects return the same data. """
12
13 type_exception = 'Unsupported type for key sanitization.'
14 no_log_strings = set()
15
16 assert 'string value' == sanitize_keys('string value', no_log_strings)
17
18 assert sanitize_keys(None, no_log_strings) is None
19
20 assert set(['x', 'y']) == sanitize_keys(set(['x', 'y']), no_log_strings)
21
22 assert not sanitize_keys(False, no_log_strings)
23
24
25 def _run_comparison(obj):
26 no_log_strings = set(['secret', 'password'])
27
28 ret = sanitize_keys(obj, no_log_strings)
29
30 expected = [
31 None,
32 True,
33 100,
34 "some string",
35 set([1, 2]),
36 [1, 2],
37
38 {'key1': ['value1a', 'value1b'],
39 'some-********': 'value-for-some-password',
40 'key2': {'key3': set(['value3a', 'value3b']),
41 'i-have-a-********': {'********-********': 'value-for-secret-password', 'key4': 'value4'}
42 }
43 },
44
45 {'foo': [{'VALUE_SPECIFIED_IN_NO_LOG_PARAMETER': 1}]}
46 ]
47
48 assert ret == expected
49
50
51 def test_sanitize_keys_dict():
52 """ Test that sanitize_keys works with a dict. """
53
54 d = [
55 None,
56 True,
57 100,
58 "some string",
59 set([1, 2]),
60 [1, 2],
61
62 {'key1': ['value1a', 'value1b'],
63 'some-password': 'value-for-some-password',
64 'key2': {'key3': set(['value3a', 'value3b']),
65 'i-have-a-secret': {'secret-password': 'value-for-secret-password', 'key4': 'value4'}
66 }
67 },
68
69 {'foo': [{'secret': 1}]}
70 ]
71
72 _run_comparison(d)
73
74
75 def test_sanitize_keys_with_ignores():
76 """ Test that we can actually ignore keys. """
77
78 no_log_strings = set(['secret', 'rc'])
79 ignore_keys = set(['changed', 'rc', 'status'])
80
81 value = {'changed': True,
82 'rc': 0,
83 'test-rc': 1,
84 'another-secret': 2,
85 'status': 'okie dokie'}
86
87 # We expect to change 'test-rc' but NOT 'rc'.
88 expected = {'changed': True,
89 'rc': 0,
90 'test-********': 1,
91 'another-********': 2,
92 'status': 'okie dokie'}
93
94 ret = sanitize_keys(value, no_log_strings, ignore_keys)
95 assert ret == expected