my-homelab-configs/tests/jeannie/test_oci_foundation_resolve.py

127 lines
6.6 KiB
Python

"""Offline regressions. Execute on Debian, without OCI or SSH access."""
import contextlib
import importlib.util
import io
import json
import os
from pathlib import Path
from types import SimpleNamespace
import tempfile
import unittest
from unittest.mock import patch
SOURCE = Path(__file__).resolve().parents[2] / "scripts/oci-foundation-resolve.py"
SPEC = importlib.util.spec_from_file_location("oci_resolver", SOURCE)
resolver = importlib.util.module_from_spec(SPEC)
SPEC.loader.exec_module(resolver)
class ResolverTests(unittest.TestCase):
def test_unconfigured_remote_client_does_not_create_files(self):
with tempfile.TemporaryDirectory() as directory, patch.dict(os.environ, {}, clear=True):
root = Path(directory)
config = root / ".config/homelab/oci-foundation.env"
with patch.object(Path, "home", return_value=root):
resolver.load(SimpleNamespace(config=config, repo=root), set())
self.assertFalse(config.parent.exists())
def test_legacy_key_and_repeated_saves(self):
with tempfile.TemporaryDirectory() as directory:
path = Path(directory) / "config.env"
key = "ssh-ed25519" + "\\" * 15 + " AAAA" + "\\" * 15 + " operator"
path.write_text(': "${LAB_OCI_SSH_PUBLIC_KEY:=' + key +
'}"; export LAB_OCI_SSH_PUBLIC_KEY\n')
parsed = resolver.read_config(path, {"LAB_OCI_SSH_PUBLIC_KEY"})
for _ in range(3):
resolver.atomic_write(path, resolver.config_text(parsed))
parsed = resolver.read_config(path, {"LAB_OCI_SSH_PUBLIC_KEY"})
self.assertEqual(parsed["LAB_OCI_SSH_PUBLIC_KEY"], "ssh-ed25519 AAAA operator")
self.assertEqual(path.stat().st_mode & 0o777, 0o600)
def test_config_never_executes(self):
with tempfile.TemporaryDirectory() as directory:
path = Path(directory) / "config.env"
marker = Path(directory) / "must-not-exist"
path.write_text("touch " + str(marker))
with self.assertRaises(ValueError):
resolver.read_config(path, set())
self.assertFalse(marker.exists())
def test_migration_and_repeat_load(self):
with tempfile.TemporaryDirectory() as directory, patch.dict(os.environ, {}, clear=True):
root = Path(directory)
config = root / ".config/homelab/oci-foundation.env"
config.parent.mkdir(parents=True)
fresh = config.with_name("oci-foundation-fresh.env")
state = root / "fresh.tfstate"
state.write_text(json.dumps({
"version": 4, "resources": [{
"mode": "managed", "type": "oci_core_instance", "name": "edge",
"instances": [{"index_key": 0, "attributes": {
"id": "ocid1.instance.current", "compartment_id": "ocid1.compartment.current",
"availability_domain": "AD-1", "shape": "VM.Standard.E2.1.Micro",
"public_ip": "192.0.2.10",
}}],
}],
}))
old = {"LAB_OCI_COMPUTE_ENABLED": "false", "LAB_EDGE_HOST": "192.0.2.1",
"LAB_OCI_BACKUP_BUCKET_ID": "n/test/b/backup"}
alternate = {"LAB_OCI_FOUNDATION_STATE_FILE": str(state),
"LAB_OCI_EDGE_INSTANCE_ID": "ocid1.instance.current",
"LAB_OCI_COMPUTE_ENABLED": "false"}
config.write_text(resolver.config_text(old))
fresh.write_text(resolver.config_text(alternate))
names = set(old) | set(alternate) | {
"LAB_OCI_EDGE_ENABLED", "LAB_OCI_EDGE_EXISTING_INSTANCE_ID",
"LAB_OCI_EDGE_INSTANCE_MANAGED", "LAB_OCI_EDGE_COMPARTMENT_ID",
"LAB_OCI_EDGE_AVAILABILITY_DOMAIN", "LAB_OCI_EDGE_SHAPE",
}
args = SimpleNamespace(config=config, repo=root)
with patch.object(Path, "home", return_value=root), contextlib.redirect_stdout(io.StringIO()):
resolver.load(args, names)
first = config.read_text()
resolver.load(args, names)
merged = resolver.read_config(config, names)
self.assertEqual(merged["LAB_OCI_FOUNDATION_STATE_FILE"], str(state))
self.assertEqual(merged["LAB_OCI_COMPUTE_ENABLED"], "true")
self.assertEqual(merged["LAB_EDGE_HOST"], "192.0.2.10")
self.assertEqual(merged["LAB_OCI_BACKUP_BUCKET_ID"], "n/test/b/backup")
self.assertFalse(fresh.exists())
self.assertEqual(config.read_text(), first)
self.assertTrue(list(config.parent.glob("oci-foundation-archive-*/oci-foundation.env")))
def test_discovery_rejects_ambiguity_and_access_errors(self):
with self.assertRaises(ValueError):
resolver.OCI.unique([{"id": "one"}, {"id": "two"}], "edge")
response = SimpleNamespace(returncode=1, stderr='{"status": 404, "code": "NotAuthorizedOrNotFound"}')
with patch("subprocess.run", return_value=response), self.assertRaises(ValueError):
resolver.OCI().call("compute", "instance", "get", "--instance-id", "recorded")
def test_edge_separates_dns_and_ssh(self):
client = SimpleNamespace(
instance=lambda role: {"id": "ocid1.instance.current", "compartment-id": "owner",
"lifecycle-state": "RUNNING"},
vnic=lambda vm: {"public-ip": "192.0.2.10", "private-ip": "10.50.10.103"},
)
peers = {"Peer": {"peer": {"HostName": "homelab-oci-edge", "Online": True,
"TailscaleIPs": ["100.64.0.10"]}}}
response = SimpleNamespace(stdout=json.dumps(peers))
output = io.StringIO()
with patch.dict(os.environ, {}, clear=True), patch.object(resolver, "OCI", return_value=client), \
patch("subprocess.run", return_value=response), contextlib.redirect_stdout(output):
resolver.resolve_edge()
self.assertIn("export TF_VAR_edge_host=192.0.2.10", output.getvalue())
self.assertIn("export TF_VAR_edge_ssh_host=100.64.0.10", output.getvalue())
def test_plan_rejects_delete_and_replacement(self):
for actions in (["delete"], ["delete", "create"], ["create", "delete"]):
with self.subTest(actions=actions), self.assertRaises(ValueError):
resolver.validate_plan({"resource_changes": [
{"address": "oci_core_instance.edge[0]", "change": {"actions": actions}}]})
resolver.validate_plan({"resource_changes": [
{"address": "new", "change": {"actions": ["create"]}}]})
if __name__ == "__main__":
unittest.main()