Debian Codegraph @

test/units/parsing/test_ajson.py

raw
1 # Copyright 2018, Matt Martz <[email protected]>
2 # Copyright 2019, Andrew Klychkov @Andersson007 <[email protected]>
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 os
8 import json
9 import pathlib
10
11 import pytest
12
13 from collections.abc import Mapping
14 from datetime import date, datetime, timezone, timedelta
15
16 from ansible._internal._json._legacy_encoder import LegacyControllerJSONEncoder
17 from ansible.module_utils.common.json import get_encoder, get_decoder
18 from ansible.parsing.vault import EncryptedString, AnsibleVaultError
19 from ansible._internal._datatag._tags import TrustedAsTemplate
20 from ansible._internal._json._profiles import _legacy
21
22
23 def test_AnsibleJSONDecoder_vault(_empty_vault_secrets_context):
24 profile = _legacy
25
26 with open(os.path.join(os.path.dirname(__file__), 'fixtures/ajson.json')) as f:
27 data = json.load(f, cls=get_decoder(profile))
28
29 assert isinstance(data['password'], EncryptedString)
30 with pytest.raises(AnsibleVaultError):
31 str(data['password'])
32
33 assert isinstance(data['bar']['baz'][0]['password'], EncryptedString)
34 with pytest.raises(AnsibleVaultError):
35 str(data['bar']['baz'][0]['password'])
36
37 assert isinstance(data['foo']['password'], EncryptedString)
38 with pytest.raises(AnsibleVaultError):
39 str(data['foo']['password'])
40
41
42 def vault_data():
43 """
44 Prepare vault test data for AnsibleJSONEncoder.default().
45
46 Return a list of tuples (input, expected).
47 """
48
49 profile = _legacy
50
51 raw_data = TrustedAsTemplate().tag((pathlib.Path(__file__).parent / 'fixtures/ajson.json').read_text())
52 data = json.loads(raw_data, cls=get_decoder(profile))
53
54 data_0 = data['password']
55 data_1 = data['bar']['baz'][0]['password']
56
57 expected_0 = (u'$ANSIBLE_VAULT;1.1;AES256\n34646264306632313333393636316'
58 '562356435376162633631326264383934326565333633366238\n3863'
59 '373264326461623132613931346165636465346337310a32643431383'
60 '0316337393263616439\n646539373134633963666338613632666334'
61 '65663730303633323534363331316164623237363831\n35363335613'
62 '93238370a313330316263373938326162386433313336613532653538'
63 '376662306435\n3339\n')
64
65 expected_1 = (u'$ANSIBLE_VAULT;1.1;AES256\n34646264306632313333393636316'
66 '562356435376162633631326264383934326565333633366238\n3863'
67 '373264326461623132613931346165636465346337310a32643431383'
68 '0316337393263616439\n646539373134633963666338613632666334'
69 '65663730303633323534363331316164623237363831\n35363335613'
70 '93238370a313330316263373938326162386433313336613532653538'
71 '376662306435\n3338\n')
72
73 return [
74 (data_0, expected_0),
75 (data_1, expected_1),
76 ]
77
78
79 class TestAnsibleJSONEncoder:
80
81 """
82 Namespace for testing AnsibleJSONEncoder.
83 """
84
85 @pytest.fixture(scope='class')
86 def mapping(self, request):
87 """
88 Returns object of Mapping mock class.
89
90 The object is used for testing handling of Mapping objects
91 in AnsibleJSONEncoder.default().
92 Using a plain dictionary instead is not suitable because
93 it is handled by default encoder of the superclass (json.JSONEncoder).
94 """
95
96 class M(Mapping):
97
98 """Mock mapping class."""
99
100 def __init__(self, *args, **kwargs):
101 self.__dict__.update(*args, **kwargs)
102
103 def __getitem__(self, key):
104 return self.__dict__[key]
105
106 def __iter__(self):
107 return iter(self.__dict__)
108
109 def __len__(self):
110 return len(self.__dict__)
111
112 mapping = M(request.param)
113
114 assert isinstance(len(mapping), int) # ensure coverage of __len__
115
116 return mapping
117
118 @pytest.fixture
119 def ansible_json_encoder(self):
120 """Return AnsibleJSONEncoder object."""
121 return LegacyControllerJSONEncoder()
122
123 ###############
124 # Test methods:
125
126 @pytest.mark.parametrize(
127 'test_input,expected',
128 [
129 (datetime(2019, 5, 14, 13, 39, 38, 569047), '2019-05-14T13:39:38.569047'),
130 (datetime(2019, 5, 14, 13, 47, 16, 923866), '2019-05-14T13:47:16.923866'),
131 (date(2019, 5, 14), '2019-05-14'),
132 (date(2020, 5, 14), '2020-05-14'),
133 (datetime(2019, 6, 15, 14, 45, tzinfo=timezone.utc), '2019-06-15T14:45:00+00:00'),
134 (datetime(2019, 6, 15, 14, 45, tzinfo=timezone(timedelta(hours=1, minutes=40))), '2019-06-15T14:45:00+01:40'),
135 ]
136 )
137 def test_date_datetime(self, ansible_json_encoder, test_input, expected):
138 """
139 Test for passing datetime.date or datetime.datetime objects to AnsibleJSONEncoder.default().
140 """
141 assert ansible_json_encoder.default(test_input) == expected
142
143 @pytest.mark.parametrize(
144 'mapping,expected',
145 [
146 ({'1': 1}, {'1': 1}),
147 ({'2': 2}, {'2': 2}),
148 ({'1': 2}, {'1': 2}),
149 ({'2': 1}, {'2': 1}),
150 ], indirect=['mapping'],
151 )
152 def test_mapping(self, ansible_json_encoder, mapping, expected):
153 """
154 Test for passing Mapping object to AnsibleJSONEncoder.default().
155 """
156 assert ansible_json_encoder.default(mapping) == expected
157
158 @pytest.mark.parametrize('test_input,expected', vault_data())
159 def test_ansible_json_encoder_vault(self, test_input, expected):
160 """
161 Test for passing vaulted values to AnsibleJSONEncoder.default().
162 """
163 profile = _legacy
164 assert json.dumps(test_input, cls=get_encoder(profile)) == '{"__ansible_vault": "%s"}' % expected.replace('\n', '\\n')
165
166 @pytest.mark.parametrize(
167 'test_input,expected',
168 [
169 ({'1': 'first'}, {'1': 'first'}),
170 ({'2': 'second'}, {'2': 'second'}),
171 ]
172 )
173 def test_default_encoder(self, ansible_json_encoder, test_input, expected):
174 """
175 Test for the default encoder of AnsibleJSONEncoder.default().
176
177 If objects of different classes that are not tested above were passed,
178 AnsibleJSONEncoder.default() invokes 'default()' method of json.JSONEncoder superclass.
179 """
180 assert ansible_json_encoder.default(test_input) == expected
181
182
183 @pytest.mark.parametrize("trust_input_str", (
184 True,
185 False
186 ))
187 def test_string_trust_propagation(trust_input_str: bool) -> None:
188 """Verify that input trust propagation behaves as expected. The presence of trust on the input string determines if trust is applied to outputs."""
189 data = '{"foo": "bar"}'
190
191 if trust_input_str:
192 data = TrustedAsTemplate().tag(data)
193
194 res = json.loads(data, cls=_legacy.Decoder)
195
196 assert trust_input_str == TrustedAsTemplate.is_tagged_on(res['foo'])