Files
computer-playbook/tests/unit/cli/validate/test_inventory.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

146 lines
4.8 KiB
Python

import unittest
import tempfile
import shutil
import os
from pathlib import Path
import subprocess
import sys
from utils.cache.yaml import dump_yaml_str
SCRIPT_PATH = os.path.abspath(
os.path.join(
os.path.dirname(__file__), "../../../../cli/validate/inventory/__main__.py"
)
)
class TestValidateInventory(unittest.TestCase):
def setUp(self):
self.temp_dir = tempfile.mkdtemp()
self.roles_dir = Path(self.temp_dir) / "roles"
(self.roles_dir / "app1" / "meta").mkdir(parents=True)
(self.roles_dir / "identity" / "meta").mkdir(parents=True)
self.inventory_dir = Path(self.temp_dir) / "inventory"
self.inventory_dir.mkdir()
(self.roles_dir / "app1" / "meta" / "services.yml").write_text(
dump_yaml_str(
{"port": 8080, "enabled": True, "settings": {"theme": "dark"}}
),
encoding="utf-8",
)
# Per req-008 the file root IS the users map (no `users:` wrapper).
(self.roles_dir / "identity" / "meta" / "users.yml").write_text(
dump_yaml_str({"alice": {"email": "alice@example.com"}}),
encoding="utf-8",
)
def tearDown(self):
shutil.rmtree(self.temp_dir)
def run_script(self, expected_code=0):
result = subprocess.run(
[
sys.executable,
SCRIPT_PATH,
str(self.inventory_dir),
"--roles-dir",
str(self.roles_dir),
],
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
encoding="utf-8",
cwd=self.temp_dir,
)
if result.returncode != expected_code:
print("STDOUT:", result.stdout)
print("STDERR:", result.stderr)
return result
def test_valid_inventory(self):
# Per req-008, application defaults derived from meta/services.yml
# surface under `applications.<id>.services.<entity>` (the file root
# is the services map keyed by entity name). The flat keys
# port/enabled/settings the fixture writes into meta/services.yml
# therefore appear as services entries in the defaults dict, and
# the inventory side must mirror that shape.
(self.inventory_dir / "group_vars.yml").write_text(
dump_yaml_str(
{
"applications": {
"app1": {
"services": {
"port": 8080,
"enabled": True,
"settings": {"theme": "dark"},
}
}
},
"users": {
"alice": {
"email": "alice@example.com",
"password": "secret",
}
},
}
),
encoding="utf-8",
)
result = self.run_script(expected_code=0)
self.assertIn("Inventory directory is valid against defaults", result.stdout)
def test_unknown_user_warning(self):
(self.inventory_dir / "invalid_users.yml").write_text(
dump_yaml_str({"users": {"bob": {"email": "bob@example.com"}}}),
encoding="utf-8",
)
result = self.run_script(expected_code=0)
self.assertIn("Warning", result.stderr)
def test_missing_user_key_fails(self):
(self.inventory_dir / "invalid_key.yml").write_text(
dump_yaml_str(
{
"users": {
"alice": {
"email": "alice@example.com",
"extra": "unexpected",
}
}
}
),
encoding="utf-8",
)
result = self.run_script(expected_code=1)
self.assertIn("Missing default for user 'alice': key 'extra'", result.stderr)
def test_missing_application_key_fails(self):
(self.inventory_dir / "missing_key.yml").write_text(
dump_yaml_str(
{
"applications": {
"app1": {
"services": {
"port": 8080,
"enabled": True,
"settings": {"theme": "dark"},
"extra_setting": True,
}
}
}
}
),
encoding="utf-8",
)
result = self.run_script(expected_code=1)
self.assertIn("Missing default for app1: services.extra_setting", result.stdout)
if __name__ == "__main__":
unittest.main()