Files
computer-playbook/tests/unit/cli/create/test_credentials.py
T
kevinveenbirkenbachandClaude Opus 4.7 623035618c refactor(cache): route every yaml call in tests/ through utils.cache.yaml
Stops every direct `yaml.safe_load`/`safe_load_all`/`safe_dump`/`dump`
call across the test corpus from re-parsing files the production cache
already holds. Each migrated test loads role meta, group_vars, inventory
fixtures, etc. through the shared cache, so a single `make test` run
parses every YAML file at most once across all suites.

Cache module changes (utils/cache/yaml.py):
  - Unify single- and multi-doc cache: one `_CACHE: Dict[sig, list]`
    holding the `safe_load_all` payload. Single-doc helpers
    (load_yaml / load_yaml_any) unwrap docs[0] and raise on >1
    document, preserving the old strict semantics. A file consumed
    both as single-doc and multi-doc is now parsed exactly once.
  - Add load_yaml_all (path-cached) and load_yaml_all_str (string,
    no cache) so multi-doc consumers no longer need a direct
    `yaml.safe_load_all` plus a separate file read.
  - dump_yaml now accepts any safe-dumpable structure (dict, list,
    scalar) so test fixtures writing list-of-tasks YAML can use it.

Lint guard (tests/lint/repository/test_no_direct_yaml_calls.py):
  - Extend the scanned tree to include `tests/` so future test code
    is forced through the cache, with the existing
    `# noqa: direct-yaml` per-call opt-out for genuine raw-yaml
    fixture needs.

Test corpus:
  - 89 test files migrated to load_yaml / load_yaml_any /
    load_yaml_str / load_yaml_all / load_yaml_all_str / dump_yaml /
    dump_yaml_str. No `# noqa` shortcuts.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-05 12:16:20 +02:00

170 lines
7.1 KiB
Python

import os
import subprocess
import sys
import tempfile
import unittest
import unittest.mock
from cli.create.credentials import ask_for_confirmation, main
from utils.handler.vault import VaultHandler
from utils.cache.yaml import dump_yaml, load_yaml_any
class TestCreateCredentials(unittest.TestCase):
def test_ask_for_confirmation_yes(self):
with unittest.mock.patch("builtins.input", return_value="y"):
self.assertTrue(ask_for_confirmation("test_key"))
def test_ask_for_confirmation_no(self):
with unittest.mock.patch("builtins.input", return_value="n"):
self.assertFalse(ask_for_confirmation("test_key"))
def test_vault_encrypt_string_success(self):
handler = VaultHandler("dummy_pw_file")
# Mock subprocess.run to simulate successful vault encryption
fake_output = "Encrypted data"
completed = subprocess.CompletedProcess(
args=["ansible-vault"], returncode=0, stdout=fake_output, stderr=""
)
with unittest.mock.patch("subprocess.run", return_value=completed) as proc_run:
result = handler.encrypt_string("plain_val", "name")
proc_run.assert_called_once()
self.assertEqual(result, fake_output)
def test_vault_encrypt_string_failure(self):
handler = VaultHandler("dummy_pw_file")
# Mock subprocess.run to simulate failure
completed = subprocess.CompletedProcess(
args=["ansible-vault"], returncode=1, stdout="", stderr="error"
)
with unittest.mock.patch("subprocess.run", return_value=completed):
with self.assertRaises(RuntimeError):
handler.encrypt_string("plain_val", "name")
def test_main_overrides_and_file_writing(self):
# Setup temporary files for role-path vars and inventory
with tempfile.TemporaryDirectory() as tmpdir:
role_path = os.path.join(tmpdir, "role")
os.makedirs(os.path.join(role_path, "meta"))
os.makedirs(os.path.join(role_path, "vars"))
# Create vars/main.yml with application_id
main_vars = {"application_id": "app_test"}
dump_yaml(os.path.join(role_path, "vars", "main.yml"), main_vars)
# Create config/main.yml with features disabled
config = {"features": {"central_database": False}}
dump_yaml(os.path.join(role_path, "meta", "services.yml"), config)
# Create schema.yml defining plain credential
schema = {
"credentials": {
"api_key": {
"description": "API key",
"algorithm": "plain",
"validation": {},
}
}
}
dump_yaml(os.path.join(role_path, "meta", "schema.yml"), schema)
# Prepare inventory file
inventory_file = os.path.join(tmpdir, "inventory.yml")
dump_yaml(inventory_file, {})
vault_pw_file = os.path.join(tmpdir, "pw.txt")
with open(vault_pw_file, "w") as f:
f.write("pw")
# Simulate ansible-vault encrypt_string output for api_key
fake_snippet = "!vault |\n $ANSIBLE_VAULT;1.1;AES256\n ENCRYPTEDVALUE"
completed = subprocess.CompletedProcess(
args=["ansible-vault"], returncode=0, stdout=fake_snippet, stderr=""
)
with unittest.mock.patch("subprocess.run", return_value=completed):
# Run main with override for credentials.api_key and force to skip prompt
sys.argv = [
"create/credentials.py",
"--role-path",
role_path,
"--inventory-file",
inventory_file,
"--vault-password-file",
vault_pw_file,
"--set",
"credentials.api_key=SECRET",
"--force",
]
# Should complete without error
main()
# Verify inventory file updated with vaulted api_key
data = load_yaml_any(inventory_file)
creds = data["applications"]["app_test"]["credentials"]
self.assertIn("api_key", creds)
# VaultScalar serializes to a vault block, safe_load returns a string containing the vault header
self.assertIsInstance(creds["api_key"], str)
self.assertTrue(creds["api_key"].lstrip().startswith("$ANSIBLE_VAULT"))
def test_main_plain_algorithm_allow_empty_plain_sets_empty_string_without_vault(
self,
):
"""
When --allow-empty-plain is used, a 'plain' credential without override
should be set to "" and *not* encrypted (no ansible-vault calls).
"""
with tempfile.TemporaryDirectory() as tmpdir:
role_path = os.path.join(tmpdir, "role")
os.makedirs(os.path.join(role_path, "meta"))
os.makedirs(os.path.join(role_path, "vars"))
# vars/main.yml with application_id
main_vars = {"application_id": "app_empty_plain"}
dump_yaml(os.path.join(role_path, "vars", "main.yml"), main_vars)
# config/main.yml
config = {"features": {"central_database": False}}
dump_yaml(os.path.join(role_path, "meta", "services.yml"), config)
# schema/main.yml: plain credential *without* overrides
schema = {
"credentials": {
"api_key": {
"description": "API key",
"algorithm": "plain",
"validation": {},
}
}
}
dump_yaml(os.path.join(role_path, "meta", "schema.yml"), schema)
# Empty inventory file
inventory_file = os.path.join(tmpdir, "inventory.yml")
dump_yaml(inventory_file, {})
# Vault password file
vault_pw_file = os.path.join(tmpdir, "pw.txt")
with open(vault_pw_file, "w") as f:
f.write("pw")
# Ensure ansible-vault is *not* called at all in this scenario
def fail_run(*_args, **_kwargs):
raise AssertionError(
"ansible-vault must not be called for allow_empty_plain + empty plain"
)
with unittest.mock.patch("subprocess.run", side_effect=fail_run):
sys.argv = [
"create/credentials.py",
"--role-path",
role_path,
"--inventory-file",
inventory_file,
"--vault-password-file",
vault_pw_file,
"--allow-empty-plain",
]
main()
data = load_yaml_any(inventory_file)
creds = data["applications"]["app_empty_plain"]["credentials"]
# api_key should exist and be an empty string, not a vault block
self.assertIn("api_key", creds)
self.assertEqual(creds["api_key"], "")