Debian Codegraph @

test/units/parsing/yaml/test_vault.py

raw
1 from __future__ import annotations
2
3 import json
4 import textwrap
5
6 import pytest
7
8 from ansible.errors import AnsibleJSONParserError
9 from ansible.parsing.vault import VaultHelper, EncryptedString
10 from ansible._internal._yaml._errors import AnsibleYAMLParserError
11 from ansible.parsing.utils.yaml import from_yaml
12
13 from ...mock.vault_helper import VaultTestHelper
14
15
16 def test_from_yaml_json_only(_vault_secrets_context: VaultTestHelper) -> None:
17 """Ensure that from_yaml properly yields an `EncryptedString` instance for legacy-profile JSON with encoded vaulted values."""
18 ciphertext = _vault_secrets_context.make_vault_ciphertext('mom')
19
20 data = json.dumps(dict(hi=dict(
21 __ansible_vault=ciphertext,
22 )))
23
24 result = from_yaml(data=data, file_name='/nope.json', json_only=True)
25
26 assert isinstance(result['hi'], EncryptedString)
27 assert result == dict(hi='mom')
28 assert VaultHelper.get_ciphertext(result['hi'], with_tags=False) == ciphertext
29
30
31 def test_from_yaml(_vault_secrets_context: VaultTestHelper) -> None:
32 ciphertext = _vault_secrets_context.make_vault_ciphertext('mom')
33
34 data = f'hi: !vault |\n{textwrap.indent(ciphertext, " ")}'
35
36 result = from_yaml(data=data, file_name='/nope.yml')
37
38 assert result == dict(hi='mom')
39 assert VaultHelper.get_ciphertext(result['hi'], with_tags=False) == ciphertext
40
41
42 def test_from_yaml_invalid_json_vaulted_value() -> None:
43 data = json.dumps(dict(hi=dict(__ansible_vault=1)))
44
45 with pytest.raises(AnsibleJSONParserError, match="__ansible_vault is <class 'int'> not <class 'str'>"):
46 from_yaml(data=data, json_only=True)
47
48
49 def test_from_yaml_invalid_yaml_vaulted_value() -> None:
50 data = 'hi: !vault 1'
51
52 with pytest.raises(AnsibleYAMLParserError, match="The '!vault' tag requires a string value."):
53 from_yaml(data=data)
54
55
56 def test_from_yaml_does_not_recognize_json_vaulted_value() -> None:
57 value = dict(hi=dict(__ansible_vault=dict(value_does_not_matter=True)))
58 data = json.dumps(value)
59
60 assert from_yaml(data=data) == value