Debian Codegraph @

test/units/_internal/_json/test_json.py

raw
1 from __future__ import annotations
2
3 import typing as t
4
5 import pytest
6
7 from ansible._internal._json import AnsibleVariableVisitor, EncryptedStringBehavior
8 from ansible.errors import AnsibleVariableTypeError
9 from ansible.parsing.vault import EncryptedString, AnsibleVaultError
10 from units.mock.vault_helper import VaultTestHelper
11
12
13 @pytest.mark.parametrize("behavior, decryptable, expected", (
14 (EncryptedStringBehavior.PRESERVE, True, None),
15 (EncryptedStringBehavior.PRESERVE, False, None),
16 (EncryptedStringBehavior.DECRYPT, True, "plaintext"),
17 (EncryptedStringBehavior.DECRYPT, False, AnsibleVaultError("no vault secrets")),
18 (EncryptedStringBehavior.REDACT, True, "<redacted>"),
19 (EncryptedStringBehavior.REDACT, False, "<redacted>"),
20 (EncryptedStringBehavior.FAIL, True, AnsibleVariableTypeError("unsupported for variable storage")),
21 (EncryptedStringBehavior.FAIL, False, AnsibleVariableTypeError("unsupported for variable storage")),
22 ), ids=str)
23 def test_encrypted_string_behavior(
24 behavior: EncryptedStringBehavior,
25 decryptable: bool,
26 expected: t.Any,
27 _vault_secrets_context: None,
28 ) -> None:
29 if decryptable:
30 value = VaultTestHelper.make_encrypted_string('plaintext')
31 else:
32 # valid ciphertext with intentionally unavailable secret
33 value = EncryptedString(ciphertext=(
34 '$ANSIBLE_VAULT;1.1;AES256\n'
35 '333665623864636331356364306535613231613833616662656130613665336561316435393736366636663864396636326330626530643238653462333562350a396162623230643'
36 '037396430383335386663363534353733386430643764303062633738613533336135653563313139373038333964316264633265376435370a326137363231646261303036356636'
37 '37346430303361316436306130663461393832656134346639326365633830373361376236343961386164323538353962'
38 ))
39
40 avv = AnsibleVariableVisitor(encrypted_string_behavior=behavior)
41
42 if isinstance(expected, Exception):
43 with pytest.raises(type(expected), match=expected.args[0]):
44 avv.visit(value)
45 else:
46 result = avv.visit(value)
47
48 if expected is None:
49 assert result is value
50 else:
51 assert result == expected