Files
computer-playbook/tests/unit/cli/administration/inventory/validate/test_main.py
T
kevinveenbirkenbachandClaude Opus 4.7 5a8fe64cc7 fix(inventory/validate): accept variants.yml keys + split CLI by concern
The inventory validator at cli/administration/inventory/validate
walked `recursive_keys(host_vars) ⊆ recursive_keys(application_defaults)`
and flagged any extra key with "Missing default for <app>: <key>".
After commit 10cb02461 ("bake only variants.yml overrides into
matrix-deploy --vars") host_vars carry every key the active
variants.yml overlay declares. Since 29377e1bd
(`_build_application_defaults` reads only `meta/<topic>.yml`, not
variants.yml — to keep the variant-0 service-key leak closed), the
defaults' allow-set is artificially narrower than the role contract:
roles/web-opt-rdr-www declares `services.dashboard.{enabled,shared}`
exclusively in `meta/variants.yml`, so the validator rejects the
baked host_vars with three "Missing default" entries before
ansible-playbook even starts (job 77797115291 on run 26428083128,
distro=debian; distro-agnostic per the matrix).

Widen the validator's legal-key set per app to

    recursive_keys(defaults[app]) ∪ ⋃ recursive_keys(variants[app][i])

variants.yml IS part of the role contract; the validator's previous
"defaults only" view was incomplete. Runtime
`_build_application_defaults` stays narrow (so 29377e1bd's
variant-0-leak fix stays in place) — only the validator widens. Typos
not declared by any variant remain caught: a new
`test_key_typo_in_variants_still_rejected` unit test pins that.

Package split (KISS/DRY/SPOT), mirroring the credentials/ refactor:

`validate/__main__.py` carried six orthogonal concerns plus
orchestration in 175 LoC. Split:

- `validate/keys.py`: `recursive_keys` (pure helper).
- `validate/loaders.py`: `load_yaml_file` (with vault-block stripping)
  and `load_inventory_files` (directory scan).
- `validate/applications.py`: `compare_application_keys` (the widened
  variants-aware logic).
- `validate/users.py`: `compare_user_keys`.
- `validate/hosts.py`: `validate_host_keys`.
- `validate/__main__.py`: thin orchestrator — argparse + load defaults/
  variants/users + invoke compare_* + exit code. 75 LoC.

`validate/__init__.py` re-exports the public API
(`main`, `compare_application_keys`, `compare_user_keys`,
`load_inventory_files`, `load_yaml_file`, `recursive_keys`,
`validate_host_keys`, `PROJECT_ROOT`). External callers
(`tests/unit/cli/administration/inventory/validate/test_main.py`,
`tests/unit/cli/administration/inventory/validate/test_hosts.py`)
keep working unchanged via this re-export.

`__main__.py` uses ABSOLUTE imports (`from cli.administration.inventory.
validate.applications import ...`) instead of relative because it's
invoked as a subprocess by tests and by the deploy entrypoint; the
sys.path bootstrap at the top of the file makes `cli.…` resolvable
in that mode.

Test layout follows the split — one test file per module:

- `test_keys.py` (6 tests: empty/non-dict/flat/nested/deep/prefix).
- `test_loaders.py` (8 tests: vault stripping, missing file, broken
  YAML, top-level + recursive directory scan, empty-block skip).
- `test_applications.py` (9 tests: all-keys-match, unknown app, extra
  key, credentials skip, variants legal, variants union, no-variants
  fallback, source path in error, typo still rejected).
- `test_users.py` (5 tests: match, unknown user warn, missing default,
  password skip, credentials skip).
- `test_hosts.py` (renamed from test_inventory_hosts.py — unit tests
  for `validate_host_keys`).
- `test_main.py` (renamed from test_inventory.py — end-to-end
  subprocess tests for `main()`, including the
  `test_variants_only_key_is_accepted` regression guard for this fix).

Coverage: 36 tests, all green. `make test` green across all 5 targets.

Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
2026-05-26 13:25:14 +02:00

194 lines
6.3 KiB
Python

import shutil
import subprocess
import sys
import tempfile
import unittest
from pathlib import Path
from utils.cache.yaml import dump_yaml_str
from utils.roles.mapping import (
ROLE_FILE_META_SERVICES,
ROLE_FILE_META_USERS,
ROLE_FILE_META_VARIANTS,
)
from . import PROJECT_ROOT
SCRIPT_PATH = str(
(
PROJECT_ROOT
/ "cli"
/ "administration"
/ "inventory"
/ "validate"
/ "__main__.py"
).resolve()
)
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" / ROLE_FILE_META_SERVICES).write_text(
dump_yaml_str(
{"port": 8080, "enabled": True, "settings": {"theme": "dark"}}
),
encoding="utf-8",
)
# Per the file root IS the users map (no `users:` wrapper).
(self.roles_dir / "identity" / ROLE_FILE_META_USERS).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),
],
capture_output=True,
encoding="utf-8",
cwd=self.temp_dir,
check=False,
)
if result.returncode != expected_code:
print("STDOUT:", result.stdout)
print("STDERR:", result.stderr)
return result
def test_valid_inventory(self):
# Per, 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)
def test_variants_only_key_is_accepted(self):
"""Regression for web-opt-rdr-www failure on run 26428083128:
variants.yml declares service-keys absent from meta/services.yml,
the matrix-deploy bake floats those keys into host_vars, and the
validator must treat them as legal because variants.yml is part
of the role contract."""
(self.roles_dir / "app1" / ROLE_FILE_META_VARIANTS).write_text(
dump_yaml_str(
[
{"services": {"dashboard": {"enabled": True, "shared": True}}},
{"services": {"dashboard": {"enabled": False, "shared": False}}},
]
),
encoding="utf-8",
)
(self.inventory_dir / "variants_only.yml").write_text(
dump_yaml_str(
{
"applications": {
"app1": {
"services": {
"port": 8080,
"enabled": True,
"settings": {"theme": "dark"},
"dashboard": {"enabled": True, "shared": True},
}
}
}
}
),
encoding="utf-8",
)
result = self.run_script(expected_code=0)
self.assertNotIn("Missing default", result.stdout)
if __name__ == "__main__":
unittest.main()