Initial commit

This commit is contained in:
mdaleo404 committed 2026-11-11 10:35:11 +00:00
1 parent 43ecc9db8c
commit ad14160b1f
42 files changed
+17460

No files matched your search

+6
View File
@@ -0,0 +1,6 @@
---
collections:
- name: community.docker
version: 5.4.0
- name: community.sops
version: 2.5.0
+69
View File
@@ -0,0 +1,69 @@
"""Adapters that let one-shot SSH test stubs serve the framed source session."""
from __future__ import annotations
from pathlib import Path
from shlex import quote
def legacy_source_session_bridge(legacy_ssh: Path) -> str:
"""Wrap a one-shot SSH fake so the resolver can keep one real source session open."""
return f"""\
#!/bin/sh
legacy={quote(str(legacy_ssh))}
case "$*" in
*"sh -s")
IFS= read -r first_line || exit 97
if [ "$first_line" != '# compose2role-source-session-v1' ]; then
(printf '%s\\n' "$first_line"; cat) | "$legacy" "$@"
exit $?
fi
while IFS= read -r line; do
[ "$line" = '# compose2role-source-session-ready' ] && break
done
IFS= read -r invocation || exit 97
[ "$invocation" = main ] || exit 97
printf '%s\\n' ready
while IFS=' ' read -r marker request_id operation extra; do
[ "$marker" = request ] || exit 97
[ -n "$request_id" ] && [ -z "$extra" ] || exit 97
IFS= read -r path || exit 97
IFS= read -r root || exit 97
IFS= read -r trailer || exit 97
[ "$trailer" = "end $request_id" ] || exit 97
encoded=$(printf '%s\\n%s\\n%s\\n' "$operation" "$path" "$root" | base64 | tr -d '\\n')
response=$(printf '%s\\n%s\\n%s\\n' x "$encoded" y | "$legacy" "$@")
status=$?
[ "$status" -eq 0 ] || exit "$status"
case "$operation" in
stat)
case "$response" in
escape|file|missing|other|symlink)
printf 'result %s %s\\nend %s\\n' "$request_id" "$response" "$request_id"
;;
*) exit 97 ;;
esac
;;
capture)
header=$(printf '%s\\n' "$response" | sed -n '1p')
case "$header" in
file[[:space:]]*)
content=$(printf '%s\\n' "$response" | sed '1d')
printf 'result %s %s\\n%s\\nend %s\\n' \
"$request_id" "$header" "$content" "$request_id"
;;
escape|missing|other|symlink)
printf 'result %s %s\\nend %s\\n' "$request_id" "$header" "$request_id"
;;
*) exit 97 ;;
esac
;;
*) exit 97 ;;
esac
done
exit 0
;;
*) exec "$legacy" "$@" ;;
esac
"""
+60
View File
@@ -0,0 +1,60 @@
from __future__ import annotations
from pathlib import Path
import pytest
from click.testing import CliRunner
from compose2role.cli import main
@pytest.mark.parametrize("command", ("generate", "audit"))
def test_local_invocation_exits_with_a_usage_error(command: str) -> None:
result = CliRunner().invoke(main, [command])
assert result.exit_code == 2
assert "was removed" in result.output
assert "--host" in result.output
@pytest.mark.parametrize("command", ("generate", "audit"))
def test_local_source_is_rejected(command: str, tmp_path: Path) -> None:
source = tmp_path / "compose.yaml"
source.write_text("services: {}\n", encoding="utf-8")
result = CliRunner().invoke(main, [command, str(source)])
assert result.exit_code == 2
assert "Got unexpected extra argument" in result.output
@pytest.mark.parametrize("command", ("generate", "audit"))
def test_help_lists_only_remote_options(command: str) -> None:
result = CliRunner().invoke(main, [command, "--help"])
assert result.exit_code == 0
for option in (
"--file",
"--project-dir",
"--env-file",
"--resolve-with",
"--name",
"--sops-pgp",
):
assert option not in result.output
@pytest.mark.parametrize(
"arguments",
(
("--playbook",),
("--playbook-dir", "playbooks"),
),
)
def test_generate_no_longer_offers_playbook_options(arguments: tuple[str, ...]) -> None:
result = CliRunner().invoke(
main, ["generate", "--host", "web1", "--project", "my-app", *arguments]
)
assert result.exit_code == 2
assert "No such option" in result.output
+145
View File
@@ -0,0 +1,145 @@
from __future__ import annotations
from pathlib import Path
import pytest
from compose2role.config import (
HostProfile,
find_repository_config,
load_repository_config,
)
from compose2role.errors import ConfigurationError
def _write(path: Path, content: str) -> Path:
path.parent.mkdir(parents=True, exist_ok=True)
path.write_text(content, encoding="utf-8")
return path
def test_explicit_config_wins_over_environment_and_discovery(
tmp_path: Path, monkeypatch: pytest.MonkeyPatch
) -> None:
repository = tmp_path / "repository"
_write(repository / ".compose2role.toml", "[defaults]\noutput = 'discovered'\n")
environment_config = _write(
tmp_path / "environment.toml", "[defaults]\noutput = 'environment'\n"
)
explicit_config = _write(tmp_path / "explicit.toml", "[defaults]\noutput = 'explicit'\n")
monkeypatch.setenv("COMPOSE2ROLE_CONFIG", str(environment_config))
config = load_repository_config(explicit_config, start=repository)
assert config.path == explicit_config
assert config.output == explicit_config.parent / "explicit"
def test_environment_config_wins_over_discovered_config(
tmp_path: Path, monkeypatch: pytest.MonkeyPatch
) -> None:
repository = tmp_path / "repository"
_write(repository / ".compose2role.toml", "[defaults]\noutput = 'discovered'\n")
environment_config = _write(
tmp_path / "environment.toml", "[defaults]\noutput = 'environment'\n"
)
monkeypatch.setenv("COMPOSE2ROLE_CONFIG", str(environment_config))
config = load_repository_config(start=repository)
assert config.path == environment_config
assert config.output == environment_config.parent / "environment"
def test_nearest_compose2role_config_is_discovered_walking_up(tmp_path: Path) -> None:
repository = tmp_path / "repository"
discovered = _write(
repository / ".compose2role.toml", "[defaults]\noutput = 'ansible/roles'\n"
)
nested = repository / "stacks" / "web"
config = load_repository_config(start=nested, environ={})
assert config.path == discovered
assert config.output == repository / "ansible" / "roles"
def test_ansible_cfg_is_the_fallback_configuration_root(tmp_path: Path) -> None:
repository = tmp_path / "repository"
ansible_config = _write(repository / "ansible.cfg", "[defaults]\n")
nested = repository / "stacks" / "web"
config = load_repository_config(start=nested, environ={})
assert config.path == ansible_config
assert config.root == repository
def test_compose2role_config_beats_a_closer_ansible_cfg(tmp_path: Path) -> None:
_write(tmp_path / "ansible.cfg", "[defaults]\n")
discovered = _write(tmp_path / "stacks" / ".compose2role.toml", "[defaults]\n")
assert find_repository_config(tmp_path / "stacks" / "web") == discovered
def test_defaults_and_host_profiles_are_parsed(tmp_path: Path) -> None:
config_path = _write(
tmp_path / ".compose2role.toml",
"""\
[defaults]
output = "ansible/roles"
sops_config = "ansible/.sops.yaml"
secret_policy = "ansible/policy.toml"
[hosts.web1]
sudo = true
docker_context = "rootless"
""",
)
config = load_repository_config(config_path, environ={})
assert config.output == tmp_path / "ansible" / "roles"
assert config.sops_config == tmp_path / "ansible" / ".sops.yaml"
assert config.secret_policy == tmp_path / "ansible" / "policy.toml"
assert config.host("web1") == HostProfile(sudo=True, docker_context="rootless")
assert config.host("unknown") == HostProfile()
def test_host_docker_context_is_parsed(tmp_path: Path) -> None:
config_path = _write(
tmp_path / ".compose2role.toml",
'[hosts."web1"]\ndocker_context = "rootless"\n',
)
config = load_repository_config(config_path, environ={})
assert config.host("web1").docker_context == "rootless"
assert config.host("web1").sudo is None
@pytest.mark.parametrize(
"content",
(
"[defaults\n",
"[unknown]\nvalue = true\n",
"[defaults]\nbogus = true\n",
"[defaults]\nplaybook = 'yes'\n",
"[defaults]\nplaybook = true\n",
"[defaults]\nplaybook_dir = 'playbooks'\n",
"[defaults]\noutput = 1\n",
"[hosts.web1]\nbogus = true\n",
"[hosts.web1]\nsudo = 'yes'\n",
"[hosts.web1]\ndocker_context = 5\n",
),
)
def test_invalid_configuration_is_a_configuration_error(tmp_path: Path, content: str) -> None:
config_path = _write(tmp_path / ".compose2role.toml", content)
with pytest.raises(ConfigurationError):
load_repository_config(config_path, environ={})
def test_missing_explicit_configuration_is_a_configuration_error(tmp_path: Path) -> None:
with pytest.raises(ConfigurationError):
load_repository_config(tmp_path / "missing.toml", environ={})
+384
View File
@@ -0,0 +1,384 @@
"""Docker context selection at the command-line and generated-role seams."""
from __future__ import annotations
import base64
import json
import os
from pathlib import Path
import pytest
from click.testing import CliRunner
from ruamel.yaml import YAML
from ssh_stub import legacy_source_session_bridge
from compose2role.cli import main
_SOURCE_DOCUMENT = """\
services:
web:
image: "web:1"
"""
_CANONICAL_DOCUMENT = {"services": {"web": {"image": "web:1"}}}
_SOPS_CONFIG = """\
creation_rules:
- path_regex: vars/secrets\\.sops\\.yml$
"""
_SSH_STUB = """\
#!/bin/sh
request=$(cat)
if [ -n "${C2R_SSH_LOG:-}" ]; then
printf '%s\\n' "$*" >> "$C2R_SSH_LOG"
case "$request" in
*"docker --context rootless compose --project-name"*)
printf 'canonicalized\\n' >> "$C2R_SSH_LOG"
;;
esac
fi
case "$*" in
*"compose ls --all --format json"*)
printf '[{"Name":"my-app","Status":"running(1)","ConfigFiles":"/srv/my-app/compose.yaml"}]\\n'
exit 0
;;
*" ps --all --format "*)
printf '%s' "${C2R_WORKING_DIRECTORY_LABEL:-}"
exit 0
;;
esac
encoded=$(printf '%s\\n' "$request" | tail -n 2 | head -n 1)
payload=$(printf '%s' "$encoded" | base64 -d)
operation=$(printf '%s\\n' "$payload" | head -n 1)
case "$operation" in
capture)
printf '%s\\n' 'file 640 0 0'
printf '%s\\n' "$C2R_SOURCE_DOCUMENT"
;;
stat)
printf '%s\\n' missing
;;
config)
printf '%s\\n' "$C2R_CANONICAL_DOCUMENT"
;;
*)
exit 97
;;
esac
"""
def _install(bin_directory: Path, name: str, script: str) -> Path:
executable = bin_directory / name
executable.write_text(script, encoding="utf-8")
executable.chmod(0o755)
return executable
def _environment(
tmp_path: Path, monkeypatch: pytest.MonkeyPatch, *, hosts: str = ""
) -> tuple[Path, Path]:
"""Return the repository and SSH log for one isolated run."""
bin_directory = tmp_path / "bin"
bin_directory.mkdir()
legacy_ssh = _install(bin_directory, "ssh-legacy", _SSH_STUB)
_install(bin_directory, "ssh", legacy_source_session_bridge(legacy_ssh))
_install(bin_directory, "sops", "#!/bin/sh\nexit 99\n")
monkeypatch.setenv("PATH", f"{bin_directory}:{os.environ['PATH']}")
ssh_log = tmp_path / "ssh.log"
monkeypatch.setenv("C2R_SSH_LOG", str(ssh_log))
monkeypatch.setenv(
"C2R_SOURCE_DOCUMENT",
base64.b64encode(_SOURCE_DOCUMENT.encode("utf-8")).decode("ascii"),
)
monkeypatch.setenv("C2R_CANONICAL_DOCUMENT", json.dumps(_CANONICAL_DOCUMENT))
sops_config = tmp_path / "sops.yaml"
sops_config.write_text(_SOPS_CONFIG, encoding="utf-8")
monkeypatch.setenv("COMPOSE2ROLE_SOPS_CONFIG", str(sops_config))
repository = tmp_path / "repository"
repository.mkdir()
(repository / ".compose2role.toml").write_text(
f'[defaults]\noutput = "roles"\n\n{hosts}', encoding="utf-8"
)
return repository, ssh_log
def _lines(ssh_log: Path) -> list[str]:
if not ssh_log.exists():
return []
return ssh_log.read_text(encoding="utf-8").splitlines()
def test_discover_passes_the_context_to_the_discovery_command(
tmp_path: Path, monkeypatch: pytest.MonkeyPatch
) -> None:
repository, ssh_log = _environment(tmp_path, monkeypatch)
result = CliRunner().invoke(
main,
[
"discover",
"--host",
"web1",
"--docker-context",
"rootless",
"--config",
str(repository / ".compose2role.toml"),
],
)
assert result.exit_code == 0, result.output
assert "-- web1 docker --context rootless compose ls --all --format json" in _lines(
ssh_log
)
def test_discover_without_a_context_keeps_the_plain_argv(
tmp_path: Path, monkeypatch: pytest.MonkeyPatch
) -> None:
repository, ssh_log = _environment(tmp_path, monkeypatch)
result = CliRunner().invoke(
main,
["discover", "--host", "web1", "--config", str(repository / ".compose2role.toml")],
)
assert result.exit_code == 0, result.output
assert "-- web1 docker compose ls --all --format json" in _lines(ssh_log)
def test_the_configured_context_applies_when_the_flag_is_absent(
tmp_path: Path, monkeypatch: pytest.MonkeyPatch
) -> None:
repository, ssh_log = _environment(
tmp_path, monkeypatch, hosts='[hosts."web1"]\ndocker_context = "rootless"\n'
)
result = CliRunner().invoke(
main,
["discover", "--host", "web1", "--config", str(repository / ".compose2role.toml")],
)
assert result.exit_code == 0, result.output
assert "-- web1 docker --context rootless compose ls --all --format json" in _lines(
ssh_log
)
def test_the_flag_wins_over_the_configured_context(
tmp_path: Path, monkeypatch: pytest.MonkeyPatch
) -> None:
repository, ssh_log = _environment(
tmp_path, monkeypatch, hosts='[hosts."web1"]\ndocker_context = "production"\n'
)
result = CliRunner().invoke(
main,
[
"discover",
"--host",
"web1",
"--docker-context",
"rootless",
"--config",
str(repository / ".compose2role.toml"),
],
)
assert result.exit_code == 0, result.output
lines = _lines(ssh_log)
assert "-- web1 docker --context rootless compose ls --all --format json" in lines
assert not any("production" in line for line in lines)
def test_audit_uses_the_context_for_the_working_directory_listing(
tmp_path: Path, monkeypatch: pytest.MonkeyPatch
) -> None:
repository, ssh_log = _environment(tmp_path, monkeypatch)
result = CliRunner().invoke(
main,
[
"audit",
"--host",
"web1",
"--all",
"--docker-context",
"rootless",
"--config",
str(repository / ".compose2role.toml"),
],
)
assert result.exit_code == 0, result.output
lines = _lines(ssh_log)
assert "-- web1 docker --context rootless compose ls --all --format json" in lines
assert any("docker --context rootless ps --all --format " in line for line in lines)
def test_generate_uses_the_context_for_discovery_and_canonicalization(
tmp_path: Path, monkeypatch: pytest.MonkeyPatch
) -> None:
repository, ssh_log = _environment(tmp_path, monkeypatch)
result = CliRunner().invoke(
main,
[
"generate",
"--host",
"web1",
"--project",
"my-app",
"--docker-context",
"rootless",
"--config",
str(repository / ".compose2role.toml"),
],
)
assert result.exit_code == 0, result.output
lines = _lines(ssh_log)
assert "-- web1 docker --context rootless compose ls --all --format json" in lines
assert "canonicalized" in lines
def test_generate_without_a_context_uses_the_plain_argv(
tmp_path: Path, monkeypatch: pytest.MonkeyPatch
) -> None:
repository, ssh_log = _environment(tmp_path, monkeypatch)
result = CliRunner().invoke(
main,
[
"generate",
"--host",
"web1",
"--project",
"my-app",
"--config",
str(repository / ".compose2role.toml"),
],
)
assert result.exit_code == 0, result.output
lines = _lines(ssh_log)
assert "-- web1 docker compose ls --all --format json" in lines
assert "canonicalized" not in lines
@pytest.mark.parametrize(
"arguments",
(
("discover", "--host", "web1"),
("audit", "--host", "web1", "--all"),
("generate", "--host", "web1", "--project", "my-app"),
("doctor", "--host", "web1"),
),
)
def test_an_invalid_context_name_is_a_usage_error_before_ssh(
arguments: tuple[str, ...], tmp_path: Path, monkeypatch: pytest.MonkeyPatch
) -> None:
repository, ssh_log = _environment(tmp_path, monkeypatch)
result = CliRunner().invoke(
main,
[
*arguments,
"--docker-context",
"not a context",
"--config",
str(repository / ".compose2role.toml"),
],
)
assert result.exit_code == 2, result.output
assert "not a context" in result.output
assert _lines(ssh_log) == []
def _generate(tmp_path: Path, repository: Path, output: str, *extra: str) -> object:
return CliRunner().invoke(
main,
[
"generate",
"--host",
"web1",
"--project",
"my-app",
"--output",
str(tmp_path / output),
"--config",
str(repository / ".compose2role.toml"),
*extra,
],
)
def test_a_generation_records_the_context_in_the_role(
tmp_path: Path, monkeypatch: pytest.MonkeyPatch
) -> None:
repository, _ssh_log = _environment(tmp_path, monkeypatch)
result = _generate(tmp_path, repository, "context-roles", "--docker-context", "rootless")
assert result.exit_code == 0, result.output
role = tmp_path / "context-roles" / "my_app"
defaults = YAML(typ="safe").load(
(role / "defaults" / "main.yml").read_text(encoding="utf-8")
)
tasks = YAML(typ="safe").load(
(role / "tasks" / "main.yml").read_text(encoding="utf-8")
)
assert defaults["my_app_docker_context"] == "rootless"
compose = next(task for task in tasks if task["name"] == "Deploy my_app Compose project")
assert compose["community.docker.docker_compose_v2"]["cli_context"] == (
"{{ my_app_docker_context }}"
)
assert "docker_context" not in (role / ".compose2role.json").read_text(encoding="utf-8")
def test_a_context_free_generation_leaves_every_other_file_unchanged(
tmp_path: Path, monkeypatch: pytest.MonkeyPatch
) -> None:
repository, _ssh_log = _environment(tmp_path, monkeypatch)
plain = _generate(tmp_path, repository, "plain-roles")
contextual = _generate(
tmp_path, repository, "context-roles", "--docker-context", "rootless"
)
assert plain.exit_code == 0, plain.output
assert contextual.exit_code == 0, contextual.output
plain_role = tmp_path / "plain-roles" / "my_app"
context_role = tmp_path / "context-roles" / "my_app"
plain_defaults = (plain_role / "defaults" / "main.yml").read_text(encoding="utf-8")
plain_tasks = (plain_role / "tasks" / "main.yml").read_text(encoding="utf-8")
assert plain_defaults == (
"---\n"
'my_app_project_dir: "/srv/my-app"\n'
'my_app_compose_project_name: "my-app"\n'
'my_app_web_image: "web"\n'
'my_app_web_image_tag: "1"\n'
)
assert "docker_context" not in plain_defaults
assert "cli_context" not in plain_tasks
plain_files = {
path.relative_to(plain_role): path.read_bytes()
for path in plain_role.rglob("*")
if path.is_file()
}
context_files = {
path.relative_to(context_role): path.read_bytes()
for path in context_role.rglob("*")
if path.is_file()
}
assert set(plain_files) == set(context_files)
for relative, content in plain_files.items():
if str(relative) in {"defaults/main.yml", "tasks/main.yml"}:
assert context_files[relative] != content
continue
assert context_files[relative] == content, relative
+606
View File
@@ -0,0 +1,606 @@
"""Doctor diagnostics at the command-line seam."""
from __future__ import annotations
import hashlib
import json
from pathlib import Path
import pytest
from click.testing import CliRunner
from compose2role import doctor as doctor_module
from compose2role.cli import main
_SOPS_STUB = """\
#!/bin/sh
printf 'sops 3.9.0\\n'
exit 0
"""
_GPG_STUB = """\
#!/bin/sh
exit 0
"""
_GALAXY_STUB = """\
#!/bin/sh
if [ "$*" = "collection list --format json" ]; then
printf '%s' '{"collections": {'
printf '%s' '"community.docker": {"version": "5.4.0"}, '
printf '%s' '"community.sops": {"version": "2.5.0"}}}'
exit 0
fi
exit 1
"""
_EMPTY_STUB = """\
#!/bin/sh
exit 0
"""
_SSH_STUB = """\
#!/bin/sh
if [ -n "${DOCTOR_SSH_LOG:-}" ]; then
printf '%s\\n' "$*" >> "$DOCTOR_SSH_LOG"
fi
case "$*" in
-G*)
printf 'hostname web1\\nuser operator\\nport 2222\\n'
exit 0
;;
*" info --format "*)
printf '%s\\n' "${DOCTOR_DOCKER_INFO:-\"\"}"
exit "${DOCTOR_DOCKER_INFO_STATUS:-0}"
;;
*"compose ls --all --format json"*)
printf '%s\\n' "${DOCTOR_COMPOSE_LS:-[]}"
exit 0
;;
*"compose version"*)
printf 'Docker Compose version %s\\n' "${DOCTOR_COMPOSE_VERSION:-v2.30.0}"
exit 0
;;
esac
exit 1
"""
_SOPS_CONFIG = """\
creation_rules:
- path_regex: vars/secrets\\.sops\\.yml$
"""
def _install(bin_directory: Path, name: str, script: str) -> Path:
executable = bin_directory / name
executable.write_text(script, encoding="utf-8")
executable.chmod(0o755)
return executable
def _install_ansible_tools(bin_directory: Path) -> None:
_install(bin_directory, "ansible-galaxy", _GALAXY_STUB)
_install(bin_directory, "ansible-lint", _EMPTY_STUB)
_install(bin_directory, "ansible-playbook", _EMPTY_STUB)
def _isolate(monkeypatch: pytest.MonkeyPatch, bin_directory: Path) -> None:
monkeypatch.setenv("PATH", str(bin_directory))
for name in (
"COMPOSE2ROLE_SSH_BIN",
"COMPOSE2ROLE_SOPS_BIN",
"COMPOSE2ROLE_ANSIBLE_BIN",
"COMPOSE2ROLE_SSH_LOG",
"DOCTOR_SSH_LOG",
"DOCTOR_DOCKER_INFO",
"DOCTOR_DOCKER_INFO_STATUS",
"DOCTOR_COMPOSE_LS",
"DOCTOR_COMPOSE_VERSION",
"ANSIBLE_COLLECTIONS_PATH",
):
monkeypatch.delenv(name, raising=False)
def _set_os_release(monkeypatch: pytest.MonkeyPatch, tmp_path: Path, content: str) -> None:
path = tmp_path / "os-release"
path.write_text(content, encoding="utf-8")
monkeypatch.setattr(doctor_module, "OS_RELEASE_PATH", path)
def _repository(tmp_path: Path, output: str = "roles", extra: str = "") -> Path:
repository = tmp_path / "repository"
repository.mkdir()
(repository / ".compose2role.toml").write_text(
f'[defaults]\noutput = "{output}"\n{extra}', encoding="utf-8"
)
return repository
def _invoke(arguments: list[str]) -> object:
return CliRunner().invoke(main, ["doctor", *arguments])
def _checks(result: object) -> dict[str, dict[str, object]]:
assert getattr(result, "exit_code") in {0, 1}
payload = json.loads(getattr(result, "output"))
return {check["name"]: check for check in payload["checks"]}
def test_doctor_local_reports_every_check(
tmp_path: Path, monkeypatch: pytest.MonkeyPatch
) -> None:
repository = _repository(tmp_path)
(repository / "roles").mkdir()
bin_directory = tmp_path / "bin"
bin_directory.mkdir()
_install(bin_directory, "sops", _SOPS_STUB)
_install(bin_directory, "gpg", _GPG_STUB)
_install_ansible_tools(bin_directory)
_isolate(monkeypatch, bin_directory)
_set_os_release(monkeypatch, tmp_path, "ID=debian\nID_LIKE=debian\n")
result = _invoke(["--config", str(repository / ".compose2role.toml")])
assert getattr(result, "exit_code") == 0
output = getattr(result, "output")
assert "✓ config:" in output
assert "✓ layout:" in output
assert "✓ sops: sops 3.9.0" in output
assert "✓ ansible collections: found" in output
assert "0 warnings, 0 errors" in output
def test_doctor_controller_mode_keeps_its_check_set(
tmp_path: Path, monkeypatch: pytest.MonkeyPatch
) -> None:
repository = _repository(tmp_path)
(repository / "roles").mkdir()
bin_directory = tmp_path / "bin"
bin_directory.mkdir()
_install(bin_directory, "sops", _SOPS_STUB)
_install(bin_directory, "gpg", _GPG_STUB)
_install_ansible_tools(bin_directory)
_isolate(monkeypatch, bin_directory)
_set_os_release(monkeypatch, tmp_path, "ID=debian\n")
result = _invoke(
["--config", str(repository / ".compose2role.toml"), "--format", "json"]
)
assert getattr(result, "exit_code") == 0, getattr(result, "output")
payload = json.loads(getattr(result, "output"))
assert [check["name"] for check in payload["checks"]] == [
"config",
"layout",
"secret policy",
"output",
"sops",
"gpg",
"sops rule",
"ansible-galaxy",
"ansible collections",
"ansible-lint",
"ansible-playbook",
"roles",
"drift",
"backups",
]
def test_doctor_host_mode_requires_ssh_and_reports_no_controller_checks(
tmp_path: Path, monkeypatch: pytest.MonkeyPatch
) -> None:
repository = _repository(tmp_path)
(repository / "roles").mkdir()
bin_directory = tmp_path / "bin"
bin_directory.mkdir()
_isolate(monkeypatch, bin_directory)
_set_os_release(monkeypatch, tmp_path, 'ID="rhel"\nID_LIKE="fedora"\n')
result = _invoke(
["--host", "web1", "--config", str(repository / ".compose2role.toml"), "--format", "json"]
)
checks = _checks(result)
assert getattr(result, "exit_code") == 1
assert set(checks) == {"ssh"}
assert checks["ssh"]["status"] == "error"
assert checks["ssh"]["required"] is True
assert "sudo dnf install openssh-clients" in checks["ssh"]["hint"]
assert json.loads(getattr(result, "output"))["summary"]["failed"] is True
def test_doctor_remote_resolves_ssh_and_checks_remote_compose(
tmp_path: Path, monkeypatch: pytest.MonkeyPatch
) -> None:
repository = _repository(tmp_path)
(repository / "roles").mkdir()
ssh_log = tmp_path / "ssh.log"
bin_directory = tmp_path / "bin"
bin_directory.mkdir()
_install(bin_directory, "ssh", _SSH_STUB)
_isolate(monkeypatch, bin_directory)
monkeypatch.setenv("DOCTOR_SSH_LOG", str(ssh_log))
_set_os_release(monkeypatch, tmp_path, "ID=debian\n")
result = _invoke(
["--host", "web1", "--config", str(repository / ".compose2role.toml")]
)
assert getattr(result, "exit_code") == 0
output = getattr(result, "output")
assert "✓ ssh resolution: ssh -G web1 resolved hostname web1, user operator, port 2222" in (
output
)
assert "✓ remote docker:" in output
assert "✓ remote compose: remote docker compose v2.30.0" in output
assert "sops" not in output
invocations = ssh_log.read_text(encoding="utf-8").splitlines()
assert "-G -- web1" in invocations
assert "-- web1 docker compose version" in invocations
def _host_environment(
tmp_path: Path, monkeypatch: pytest.MonkeyPatch, **environment: str
) -> Path:
"""Install the host-mode stubs and return the repository root."""
repository = _repository(tmp_path)
(repository / "roles").mkdir()
bin_directory = tmp_path / "bin"
bin_directory.mkdir()
_install(bin_directory, "ssh", _SSH_STUB)
_install(bin_directory, "sops", _SOPS_STUB)
_install(bin_directory, "gpg", _GPG_STUB)
_install_ansible_tools(bin_directory)
_isolate(monkeypatch, bin_directory)
for name, value in environment.items():
monkeypatch.setenv(name, value)
_set_os_release(monkeypatch, tmp_path, "ID=debian\n")
return repository
def test_doctor_remote_sudo_prefixes_every_remote_command(
tmp_path: Path, monkeypatch: pytest.MonkeyPatch
) -> None:
repository = _host_environment(tmp_path, monkeypatch, DOCTOR_SSH_LOG=str(tmp_path / "ssh.log"))
result = _invoke(
["--host", "web1", "--sudo", "--config", str(repository / ".compose2role.toml")]
)
assert getattr(result, "exit_code") == 0, getattr(result, "output")
invocations = (tmp_path / "ssh.log").read_text(encoding="utf-8")
assert "-- web1 sudo -n docker info" in invocations
assert "-- web1 sudo -n docker compose version" in invocations
def test_doctor_host_mode_applies_the_docker_context(
tmp_path: Path, monkeypatch: pytest.MonkeyPatch
) -> None:
repository = _host_environment(
tmp_path, monkeypatch, DOCTOR_SSH_LOG=str(tmp_path / "ssh.log")
)
result = _invoke(
[
"--host",
"web1",
"--docker-context",
"rootless",
"--config",
str(repository / ".compose2role.toml"),
]
)
assert getattr(result, "exit_code") == 0, getattr(result, "output")
invocations = (tmp_path / "ssh.log").read_text(encoding="utf-8")
assert "-- web1 docker --context rootless info" in invocations
assert "-- web1 docker --context rootless compose version" in invocations
def test_doctor_quotes_the_docker_info_format_for_the_remote_shell(
tmp_path: Path, monkeypatch: pytest.MonkeyPatch
) -> None:
repository = _host_environment(
tmp_path, monkeypatch, DOCTOR_SSH_LOG=str(tmp_path / "ssh.log")
)
result = _invoke(
["--host", "web1", "--config", str(repository / ".compose2role.toml")]
)
assert getattr(result, "exit_code") == 0, getattr(result, "output")
invocations = (tmp_path / "ssh.log").read_text(encoding="utf-8")
assert "-- web1 docker info --format '{{json .}}'" in invocations
def test_doctor_host_mode_reports_only_the_host_check_set(
tmp_path: Path, monkeypatch: pytest.MonkeyPatch
) -> None:
repository = _host_environment(tmp_path, monkeypatch)
result = _invoke(
["--host", "web1", "--format", "json", "--config", str(repository / ".compose2role.toml")]
)
assert getattr(result, "exit_code") == 0, getattr(result, "output")
payload = json.loads(getattr(result, "output"))
assert [check["name"] for check in payload["checks"]] == [
"ssh",
"ssh resolution",
"remote docker",
"remote compose",
]
def test_doctor_host_mode_fails_when_the_daemon_is_unreachable(
tmp_path: Path, monkeypatch: pytest.MonkeyPatch
) -> None:
repository = _host_environment(tmp_path, monkeypatch, DOCTOR_DOCKER_INFO_STATUS="1")
result = _invoke(
["--host", "web1", "--format", "json", "--config", str(repository / ".compose2role.toml")]
)
checks = _checks(result)
assert getattr(result, "exit_code") == 1
assert checks["remote docker"]["status"] == "error"
assert checks["remote docker"]["required"] is True
assert "not reachable" in str(checks["remote docker"]["detail"])
def test_doctor_host_mode_reports_the_daemon_mode_and_project_count(
tmp_path: Path, monkeypatch: pytest.MonkeyPatch
) -> None:
repository = _host_environment(
tmp_path,
monkeypatch,
DOCTOR_DOCKER_INFO='{"SecurityOptions":["name=rootless"]}',
DOCTOR_COMPOSE_LS='[{"Name":"one"},{"Name":"two"}]',
)
result = _invoke(
["--host", "web1", "--format", "json", "--config", str(repository / ".compose2role.toml")]
)
check = _checks(result)["remote docker"]
assert check["status"] == "ok"
assert "rootless" in str(check["detail"])
assert "2 visible Compose project(s)" in str(check["detail"])
def test_doctor_host_mode_accepts_compose_v5(
tmp_path: Path, monkeypatch: pytest.MonkeyPatch
) -> None:
repository = _host_environment(tmp_path, monkeypatch, DOCTOR_COMPOSE_VERSION="v5.7.0")
result = _invoke(
["--host", "web1", "--format", "json", "--config", str(repository / ".compose2role.toml")]
)
checks = _checks(result)
assert getattr(result, "exit_code") == 0
assert checks["remote compose"]["status"] == "ok"
assert "v5.7.0" in str(checks["remote compose"]["detail"])
def test_doctor_host_mode_rejects_compose_v1(
tmp_path: Path, monkeypatch: pytest.MonkeyPatch
) -> None:
repository = _host_environment(tmp_path, monkeypatch, DOCTOR_COMPOSE_VERSION="v1.29.2")
result = _invoke(
["--host", "web1", "--format", "json", "--config", str(repository / ".compose2role.toml")]
)
checks = _checks(result)
assert getattr(result, "exit_code") == 1
assert checks["remote compose"]["status"] == "error"
assert "v1.29.2" in str(checks["remote compose"]["detail"])
def test_doctor_finds_repo_local_collections(
tmp_path: Path, monkeypatch: pytest.MonkeyPatch
) -> None:
repository = _repository(tmp_path)
(repository / "roles").mkdir()
snapshot = repository / "collections" / "ansible_collections"
for name in ("community/docker", "community/sops"):
collection = snapshot / name
collection.mkdir(parents=True)
(collection / "galaxy.yml").write_text("namespace: community\n", encoding="utf-8")
bin_directory = tmp_path / "bin"
bin_directory.mkdir()
_install(
bin_directory,
"ansible-galaxy",
"#!/bin/sh\nif [ \"$*\" = 'collection list --format json' ]; then\n"
" printf '%s' '{}'\n exit 0\nfi\nexit 1\n",
)
_install(bin_directory, "ansible-lint", _EMPTY_STUB)
_install(bin_directory, "ansible-playbook", _EMPTY_STUB)
_isolate(monkeypatch, bin_directory)
_set_os_release(monkeypatch, tmp_path, "ID=debian\n")
result = _invoke(["--config", str(repository / ".compose2role.toml")])
assert getattr(result, "exit_code") == 0, getattr(result, "output")
assert "✓ ansible collections: found community.docker, community.sops" in (
getattr(result, "output")
)
def test_doctor_honours_the_ansible_collections_path(
tmp_path: Path, monkeypatch: pytest.MonkeyPatch
) -> None:
repository = _repository(tmp_path)
(repository / "roles").mkdir()
external = tmp_path / "external-collections"
for name in ("community/docker", "community/sops"):
collection = external / "ansible_collections" / name
collection.mkdir(parents=True)
(collection / "galaxy.yml").write_text("namespace: community\n", encoding="utf-8")
bin_directory = tmp_path / "bin"
bin_directory.mkdir()
_install(
bin_directory,
"ansible-galaxy",
"#!/bin/sh\nif [ \"$*\" = 'collection list --format json' ]; then\n"
" printf '%s' '{}'\n exit 0\nfi\nexit 1\n",
)
_install(bin_directory, "ansible-lint", _EMPTY_STUB)
_install(bin_directory, "ansible-playbook", _EMPTY_STUB)
_isolate(monkeypatch, bin_directory)
monkeypatch.setenv("ANSIBLE_COLLECTIONS_PATH", str(external))
_set_os_release(monkeypatch, tmp_path, "ID=debian\n")
result = _invoke(["--config", str(repository / ".compose2role.toml")])
assert getattr(result, "exit_code") == 0, getattr(result, "output")
assert "✓ ansible collections: found" in getattr(result, "output")
def test_doctor_distro_hints_name_the_package_manager(
tmp_path: Path, monkeypatch: pytest.MonkeyPatch
) -> None:
repository = _repository(tmp_path)
(repository / "roles").mkdir()
bin_directory = tmp_path / "bin"
bin_directory.mkdir()
_isolate(monkeypatch, bin_directory)
_set_os_release(monkeypatch, tmp_path, 'ID="rocky"\nID_LIKE="rhel centos fedora"\n')
result = _invoke(["--config", str(repository / ".compose2role.toml")])
output = getattr(result, "output")
assert "sudo dnf install sops (EPEL)" in output
assert "sudo dnf install gnupg2" in output
def test_doctor_reports_configuration_and_secret_policy_failures(
tmp_path: Path, monkeypatch: pytest.MonkeyPatch
) -> None:
bin_directory = tmp_path / "bin"
bin_directory.mkdir()
_isolate(monkeypatch, bin_directory)
_set_os_release(monkeypatch, tmp_path, "ID=debian\n")
invalid_config = tmp_path / "invalid.toml"
invalid_config.write_text("this is not = toml", encoding="utf-8")
config_result = _invoke(["--config", str(invalid_config)])
assert getattr(config_result, "exit_code") == 2
assert "✗ config:" in getattr(config_result, "output")
repository = _repository(tmp_path, extra='secret_policy = "policy.toml"\n')
(repository / "roles").mkdir()
(repository / "policy.toml").write_text("rules = 5\n", encoding="utf-8")
secret_policy_result = _invoke(["--config", str(repository / ".compose2role.toml")])
assert getattr(secret_policy_result, "exit_code") == 0
assert "! secret policy: secret policy must define rules" in getattr(
secret_policy_result, "output"
)
def test_doctor_reports_an_unwritable_output_directory(
tmp_path: Path, monkeypatch: pytest.MonkeyPatch
) -> None:
repository = _repository(tmp_path, output="blocked/roles")
(repository / "blocked").write_text("not a directory", encoding="utf-8")
bin_directory = tmp_path / "bin"
bin_directory.mkdir()
_isolate(monkeypatch, bin_directory)
_set_os_release(monkeypatch, tmp_path, "ID=debian\n")
result = _invoke(["--config", str(repository / ".compose2role.toml")])
assert getattr(result, "exit_code") == 1
assert "✗ output: roles directory is not writable" in getattr(result, "output")
def test_doctor_validates_a_configured_sops_rule(
tmp_path: Path, monkeypatch: pytest.MonkeyPatch
) -> None:
repository = _repository(tmp_path)
(repository / "roles").mkdir()
invalid_config = tmp_path / "invalid-sops.yaml"
invalid_config.write_text("creation_rules: []\n", encoding="utf-8")
bin_directory = tmp_path / "bin"
bin_directory.mkdir()
_install(bin_directory, "sops", _SOPS_STUB)
_isolate(monkeypatch, bin_directory)
_set_os_release(monkeypatch, tmp_path, "ID=debian\n")
result = _invoke(
[
"--config",
str(repository / ".compose2role.toml"),
"--sops-config",
str(invalid_config),
]
)
assert getattr(result, "exit_code") == 1
assert "✗ sops rule:" in getattr(result, "output")
def _write_role(roles_directory: Path, project_root: Path, content: bytes) -> Path:
project_root.mkdir()
(project_root / "compose.yaml").write_bytes(content)
role_directory = roles_directory / "my_app"
role_directory.mkdir()
provenance = {
"files": {
"compose.yaml": {
"redacted": False,
"sha256": hashlib.sha256(content).hexdigest(),
}
},
"generator": "compose2role",
"mode": "local",
"project": "my-app",
"role": "my_app",
"source": {
"config_files": [str(project_root / "compose.yaml")],
"root": str(project_root),
},
"structural_hash": "fixture",
"version": "0.1.0",
}
(role_directory / ".compose2role.json").write_text(
json.dumps(provenance), encoding="utf-8"
)
return role_directory
def test_doctor_reports_roles_drift_and_backups(
tmp_path: Path, monkeypatch: pytest.MonkeyPatch
) -> None:
repository = _repository(tmp_path)
roles_directory = repository / "roles"
roles_directory.mkdir()
project_root = tmp_path / "project"
_write_role(roles_directory, project_root, b"services:\n web:\n image: web:1\n")
backup = roles_directory / ".compose2role" / "backups" / "my_app-20260101T000000Z"
backup.mkdir(parents=True)
(backup / "compose.yaml").write_bytes(b"x" * 2048)
bin_directory = tmp_path / "bin"
bin_directory.mkdir()
_isolate(monkeypatch, bin_directory)
_set_os_release(monkeypatch, tmp_path, "ID=debian\n")
result = _invoke(["--config", str(repository / ".compose2role.toml")])
assert getattr(result, "exit_code") == 0
output = getattr(result, "output")
assert "✓ roles: 1 generated role(s)" in output
assert "✓ drift: 1 unchanged, 0 source changed, 0 source unavailable" in output
assert "✓ backups: 1 backup(s), 2.0 KiB" in output
assert "prune with: rm -r" in output
(project_root / "compose.yaml").write_bytes(b"services:\n web:\n image: web:2\n")
drifted = _invoke(["--config", str(repository / ".compose2role.toml")])
assert getattr(drifted, "exit_code") == 0
assert "! drift: 0 unchanged, 1 source changed, 0 source unavailable" in getattr(
drifted, "output"
)
+218
View File
@@ -0,0 +1,218 @@
from __future__ import annotations
import json
import os
from importlib.metadata import version as package_version
from pathlib import Path
import pytest
from click.testing import CliRunner
from compose2role.cli import main
def test_version_reports_the_installed_package_version() -> None:
result = CliRunner().invoke(main, ["--version"], prog_name="compose2role")
assert result.exit_code == 0, result.output
assert result.output == f"compose2role {package_version('compose2role')}\n"
def _install_stub_ssh(tmp_path: Path, script: str) -> Path:
bin_directory = tmp_path / "bin"
bin_directory.mkdir()
ssh = bin_directory / "ssh"
ssh.write_text(script, encoding="utf-8")
ssh.chmod(0o755)
return bin_directory
def _ssh_environment(bin_directory: Path, arguments_file: Path | None = None) -> dict[str, str]:
environment = {"PATH": f"{bin_directory}:{os.environ['PATH']}"}
if arguments_file is not None:
environment["C2R_SSH_ARGUMENTS"] = str(arguments_file)
return environment
def test_discover_lists_remote_compose_projects_as_json(tmp_path: Path) -> None:
bin_directory = _install_stub_ssh(
tmp_path,
"""\
#!/bin/sh
printf '%s\\n' '[{"Name":"myapp","Status":"running(1)","ConfigFiles":"/srv/myapp/compose.yaml"}]'
""",
)
result = CliRunner().invoke(
main,
["discover", "--host", "web1", "--format", "json"],
env=_ssh_environment(bin_directory),
)
assert result.exit_code == 0, result.output
assert json.loads(result.output) == {
"projects": [
{
"config_files": ["/srv/myapp/compose.yaml"],
"name": "myapp",
"status": "running(1)",
}
]
}
def test_discover_prints_one_status_line_per_project(tmp_path: Path) -> None:
"""Text discovery streams a status line per project and closes with a count."""
bin_directory = _install_stub_ssh(
tmp_path,
"""\
#!/bin/sh
printf '%s\\n' '[{"Name":"myapp","Status":"running(1)",'
printf '%s\\n' '"ConfigFiles":"/srv/myapp/compose.yaml"}]'
""",
)
result = CliRunner().invoke(
main,
["discover", "--host", "web1"],
env=_ssh_environment(bin_directory),
)
assert result.exit_code == 0, result.output
assert result.output.splitlines() == [
"Discovering projects on web1...",
"✓ myapp running(1) /srv/myapp/compose.yaml",
"",
"1 found",
]
@pytest.mark.parametrize(
("arguments", "expected_ssh_arguments"),
(
(
["discover", "--host", "admin@web1.example:2222", "--format", "json"],
[
"-p",
"2222",
"--",
"admin@web1.example",
"docker",
"compose",
"ls",
"--all",
"--format",
"json",
],
),
(
[
"discover",
"--host",
"admin@web1.example:2222",
"--sudo",
"--format",
"json",
],
[
"-p",
"2222",
"--",
"admin@web1.example",
"sudo",
"-n",
"docker",
"compose",
"ls",
"--all",
"--format",
"json",
],
),
),
)
def test_discover_passes_fixed_ssh_arguments(
tmp_path: Path, arguments: list[str], expected_ssh_arguments: list[str]
) -> None:
arguments_file = tmp_path / "ssh-arguments"
bin_directory = _install_stub_ssh(
tmp_path,
"""\
#!/bin/sh
printf '%s\\n' "$@" > "$C2R_SSH_ARGUMENTS"
printf '%s\\n' '[]'
""",
)
result = CliRunner().invoke(
main,
arguments,
env=_ssh_environment(bin_directory, arguments_file),
)
assert result.exit_code == 0, result.output
assert arguments_file.read_text(encoding="utf-8").splitlines() == expected_ssh_arguments
@pytest.mark.parametrize(
("arguments", "expected_message"),
(
(
["discover", "--host", "web1", "--sudo"],
"ensure the SSH user has passwordless sudo access to Docker",
),
(
["discover", "--host", "web1"],
"join the docker group",
),
),
)
def test_discover_explains_remote_docker_access_failures(
tmp_path: Path, arguments: list[str], expected_message: str
) -> None:
bin_directory = _install_stub_ssh(tmp_path, "#!/bin/sh\nexit 1\n")
result = CliRunner().invoke(
main,
arguments,
env=_ssh_environment(bin_directory),
)
assert result.exit_code == 1
assert expected_message in result.output
def test_discover_enumerates_the_access_remedies_without_recommending_one(
tmp_path: Path,
) -> None:
bin_directory = _install_stub_ssh(tmp_path, "#!/bin/sh\nexit 1\n")
result = CliRunner().invoke(
main,
["discover", "--host", "web1"],
env=_ssh_environment(bin_directory),
)
assert result.exit_code == 1
assert "join the docker group" in result.output
assert "configure passwordless sudo" in result.output
assert "--docker-context" in result.output
assert "--sudo" not in result.output
def test_discover_reports_ssh_connection_failures_without_a_sudo_hint(tmp_path: Path) -> None:
bin_directory = _install_stub_ssh(
tmp_path,
"#!/bin/sh\nprintf '%s\\n' 'Host key verification failed.' >&2\nexit 255\n",
)
result = CliRunner().invoke(
main,
["discover", "--host", "web1", "--sudo"],
env=_ssh_environment(bin_directory),
)
assert result.exit_code == 1
assert "SSH connection or remote command failed" in result.output
assert "Host key verification failed." in result.output
assert "passwordless sudo" not in result.output
+200
View File
@@ -0,0 +1,200 @@
from __future__ import annotations
from pathlib import Path
import pytest
from click.testing import CliRunner
from compose2role.cli import main
from compose2role.config import RepositoryConfig, load_repository_config
from compose2role.layout import discover_layout, find_ansible_config, load_ansible_config
from compose2role.naming import normalize_compose_project_name, normalize_role_name
def _write(path: Path, content: str) -> Path:
path.parent.mkdir(parents=True, exist_ok=True)
path.write_text(content, encoding="utf-8")
return path
def _config(tmp_path: Path, content: str) -> RepositoryConfig:
return load_repository_config(_write(tmp_path / ".compose2role.toml", content), environ={})
def test_roles_directory_prefers_explicit_output(tmp_path: Path) -> None:
layout = discover_layout(
RepositoryConfig(root=tmp_path),
start=tmp_path,
explicit_output=tmp_path / "explicit",
environ={},
)
assert layout.roles_directory == tmp_path / "explicit"
def test_roles_directory_uses_config_defaults_before_ansible_cfg(tmp_path: Path) -> None:
_write(tmp_path / "ansible.cfg", "[defaults]\nroles_path = ansible/roles\n")
config = _config(tmp_path, "[defaults]\noutput = 'configured/roles'\n")
layout = discover_layout(config, start=tmp_path, environ={})
assert layout.roles_directory == tmp_path / "configured" / "roles"
def test_roles_directory_uses_the_first_ansible_cfg_roles_path_entry(tmp_path: Path) -> None:
_write(
tmp_path / "ansible.cfg",
"[defaults]\nroles_path = ansible/roles:extra/roles\n",
)
layout = discover_layout(RepositoryConfig(root=tmp_path), start=tmp_path, environ={})
assert layout.roles_directory == tmp_path / "ansible" / "roles"
def test_roles_directory_falls_back_to_existing_ansible_roles(tmp_path: Path) -> None:
(tmp_path / "ansible" / "roles").mkdir(parents=True)
layout = discover_layout(RepositoryConfig(root=tmp_path), start=tmp_path, environ={})
assert layout.roles_directory == tmp_path / "ansible" / "roles"
def test_roles_directory_falls_back_to_existing_roles(tmp_path: Path) -> None:
(tmp_path / "roles").mkdir()
layout = discover_layout(RepositoryConfig(root=tmp_path), start=tmp_path, environ={})
assert layout.roles_directory == tmp_path / "roles"
def test_roles_directory_falls_back_to_config_root_roles(tmp_path: Path) -> None:
layout = discover_layout(RepositoryConfig(root=tmp_path), start=tmp_path, environ={})
assert layout.roles_directory == tmp_path / "roles"
def test_ansible_cfg_only_reads_the_documented_defaults_keys(tmp_path: Path) -> None:
_write(
tmp_path / "ansible.cfg",
"""\
[defaults]
roles_path = documented/roles
unknown = ignored
[other]
roles_path = ignored/roles
""",
)
layout = discover_layout(RepositoryConfig(root=tmp_path), start=tmp_path, environ={})
assert layout.roles_directory == tmp_path / "documented" / "roles"
def test_ansible_cfg_paths_resolve_relative_to_the_config_file(tmp_path: Path) -> None:
ansible_config = _write(
tmp_path / "ansible.cfg",
"""\
[defaults]
roles_path = roles
collections_path = collections:more-collections
inventory = inventory/hosts.ini:inventory/extra.ini
""",
)
parsed = load_ansible_config(ansible_config)
assert parsed.roles_path == (tmp_path / "roles",)
assert parsed.collections_path == (tmp_path / "collections", tmp_path / "more-collections")
assert parsed.inventory == (
tmp_path / "inventory" / "hosts.ini",
tmp_path / "inventory" / "extra.ini",
)
def test_inventory_directory_is_discovered_without_ansible_cfg(tmp_path: Path) -> None:
inventory = tmp_path / "inventory"
inventory.mkdir()
layout = discover_layout(RepositoryConfig(root=tmp_path), start=tmp_path, environ={})
assert layout.inventory == (inventory,)
def test_find_ansible_config_walks_up(tmp_path: Path) -> None:
ansible_config = _write(tmp_path / "ansible.cfg", "[defaults]\n")
nested = tmp_path / "stacks" / "web"
assert find_ansible_config(nested) == ansible_config
def test_sops_config_precedence(tmp_path: Path) -> None:
config = RepositoryConfig(root=tmp_path, sops_config=tmp_path / "configured.yaml")
explicit = discover_layout(
config,
start=tmp_path,
explicit_sops_config=tmp_path / "explicit.yaml",
environ={},
)
environment = discover_layout(
config,
start=tmp_path,
environ={"COMPOSE2ROLE_SOPS_CONFIG": str(tmp_path / "environment.yaml")},
)
configured = discover_layout(config, start=tmp_path, environ={})
assert explicit.sops_config == tmp_path / "explicit.yaml"
assert environment.sops_config == tmp_path / "environment.yaml"
assert configured.sops_config == tmp_path / "configured.yaml"
def test_secret_policy_precedence(tmp_path: Path) -> None:
config = RepositoryConfig(root=tmp_path, secret_policy=tmp_path / "configured.toml")
explicit = discover_layout(
config,
start=tmp_path,
explicit_secret_policy=tmp_path / "explicit.toml",
environ={},
)
environment = discover_layout(
config,
start=tmp_path,
environ={"COMPOSE2ROLE_SECRET_POLICY": str(tmp_path / "environment.toml")},
)
configured = discover_layout(config, start=tmp_path, environ={})
assert explicit.secret_policy == tmp_path / "explicit.toml"
assert environment.secret_policy == tmp_path / "environment.toml"
assert configured.secret_policy == tmp_path / "configured.toml"
def test_host_profile_is_selected_for_the_target_host(tmp_path: Path) -> None:
config = _config(tmp_path, "[hosts.web1]\nsudo = true\n")
layout = discover_layout(config, start=tmp_path, host="web1", environ={})
other = discover_layout(config, start=tmp_path, host="web2", environ={})
assert layout.host.sudo is True
assert other.host.sudo is None
def test_normalizers_produce_valid_names() -> None:
assert normalize_role_name("My App") == "my_app"
assert normalize_role_name("123") == "compose_123"
assert normalize_compose_project_name("My App") == "myapp"
assert normalize_compose_project_name("---") == "compose"
def test_invalid_configuration_exits_with_usage_status(
tmp_path: Path, monkeypatch: pytest.MonkeyPatch
) -> None:
_write(tmp_path / ".compose2role.toml", "[defaults\n")
monkeypatch.chdir(tmp_path)
result = CliRunner().invoke(main, ["discover", "--host", "web1"])
assert result.exit_code == 2, result.output
assert "configuration" in result.output.lower()
File diff suppressed because it is too large. Load diff
File diff suppressed because it is too large. Load diff
+136
View File
@@ -0,0 +1,136 @@
from __future__ import annotations
from pathlib import Path, PurePosixPath
import pytest
from compose2role.errors import SecretPolicyError
from compose2role.secret_policy import load_secret_policy
def _write_policy(tmp_path: Path, content: str) -> Path:
path = tmp_path / "secret-policy.toml"
path.write_text(content, encoding="utf-8")
return path
def test_secret_policy_key_list_expands_to_one_exact_rule_per_key(tmp_path: Path) -> None:
policy = load_secret_policy(
_write_policy(
tmp_path,
"""\
[[rules]]
project = "myapp"
service = "web"
key = ["API_TOKEN", "DB_PASSWORD"]
decision = "plain"
""",
)
)
assert policy.decision_for("myapp", "web", "API_TOKEN") == "plain"
assert policy.decision_for("myapp", "web", "DB_PASSWORD") == "plain"
assert policy.decision_for("myapp", "web", "OTHER_KEY") is None
assert policy.decision_for("myapp", "worker", "API_TOKEN") is None
def test_secret_policy_dotenv_key_list_expands_to_one_exact_rule_per_key(tmp_path: Path) -> None:
policy = load_secret_policy(
_write_policy(
tmp_path,
"""\
[[dotenv_rules]]
project = "myapp"
source = ".env"
key = ["MAIL_PASSWORD", "SMTP_TOKEN"]
decision = "secret"
""",
)
)
assert policy.dotenv_decision_for("myapp", PurePosixPath(".env"), "MAIL_PASSWORD") == "secret"
assert policy.dotenv_decision_for("myapp", PurePosixPath(".env"), "SMTP_TOKEN") == "secret"
assert policy.dotenv_decision_for("myapp", PurePosixPath(".env"), "OTHER_KEY") is None
assert policy.dotenv_decision_for("myapp", PurePosixPath(".env.local"), "SMTP_TOKEN") is None
def test_secret_policy_single_key_rule_still_matches_exactly(tmp_path: Path) -> None:
policy = load_secret_policy(
_write_policy(
tmp_path,
"""\
[[rules]]
project = "myapp"
service = "web"
key = "API_TOKEN"
decision = "secret"
""",
)
)
assert policy.decision_for("myapp", "web", "API_TOKEN") == "secret"
assert policy.decision_for("myapp", "web", "API_TOKEN_2") is None
@pytest.mark.parametrize(
"key_value",
['[]', '["API_TOKEN", 7]', '["API_TOKEN", ""]', '""', "7"],
)
def test_secret_policy_rejects_invalid_environment_key_values(
tmp_path: Path, key_value: str
) -> None:
policy_path = _write_policy(
tmp_path,
f"""\
[[rules]]
project = "myapp"
service = "web"
key = {key_value}
decision = "secret"
""",
)
with pytest.raises(SecretPolicyError, match="keys must be non-empty strings"):
load_secret_policy(policy_path)
@pytest.mark.parametrize(
"key_value",
['[]', '["MAIL_PASSWORD", 7]', '["MAIL_PASSWORD", ""]', '""', "7"],
)
def test_secret_policy_rejects_invalid_dotenv_key_values(tmp_path: Path, key_value: str) -> None:
policy_path = _write_policy(
tmp_path,
f"""\
[[dotenv_rules]]
project = "myapp"
source = ".env"
key = {key_value}
decision = "secret"
""",
)
with pytest.raises(SecretPolicyError, match="keys must be non-empty strings"):
load_secret_policy(policy_path)
def test_secret_policy_rejects_conflicts_between_list_and_single_rules(tmp_path: Path) -> None:
policy_path = _write_policy(
tmp_path,
"""\
[[rules]]
project = "myapp"
service = "web"
key = ["API_TOKEN", "LOG_LEVEL"]
decision = "secret"
[[rules]]
project = "myapp"
service = "web"
key = "LOG_LEVEL"
decision = "plain"
""",
)
with pytest.raises(SecretPolicyError, match="conflicting exact rules"):
load_secret_policy(policy_path)