test: prepare isolated grpc data integration helpers
This commit is contained in:
@@ -0,0 +1,191 @@
|
||||
"""Current CLI text and fake-process units; no subprocess or network is started."""
|
||||
import io
|
||||
from pathlib import Path
|
||||
import subprocess
|
||||
import sys
|
||||
import unittest
|
||||
from unittest.mock import Mock
|
||||
|
||||
sys.path.insert(0, str(Path(__file__).resolve().parents[1]))
|
||||
import cli_gate
|
||||
import processes
|
||||
|
||||
|
||||
NODE = "ns=7;s=unit/device/counter"
|
||||
KEY = "unit-presented-secret"
|
||||
|
||||
|
||||
def result(stdout="", stderr="", returncode=0, timed_out=False, truncated=False):
|
||||
return processes.ProcessResult(argv=("dotnet", "unit.dll"), returncode=returncode,
|
||||
stdout=stdout, stderr=stderr, timed_out=timed_out,
|
||||
truncated=truncated, duration_seconds=0.1)
|
||||
|
||||
|
||||
def summary(total=1, good=1, bad=0, never=0):
|
||||
return ("\n==================== SUMMARY ====================\n"
|
||||
f"Total subscribed: {total}\n"
|
||||
" Ever went BAD during window: 0\n"
|
||||
" NEVER went bad (suspect): 1\n"
|
||||
f" Last status GOOD: {good}\n"
|
||||
f" Last status NOT-GOOD: {bad}\n"
|
||||
f" No update received at all: {never}\n")
|
||||
|
||||
|
||||
def subscription_output(values=(1, 2), attached=1):
|
||||
return (f"Subscribed to {attached}/1 nodes (interval: 200ms). Press Ctrl+C to stop and print summary.\n" +
|
||||
"".join(f"[2026-11-16T00:00:0{index}.0000000Z] {NODE} = {value} (Good)\n"
|
||||
for index, value in enumerate(values)) + summary())
|
||||
|
||||
|
||||
class ProcessSafetyTests(unittest.TestCase):
|
||||
def fake_process(self, stdout=b"output", stderr=b"error", waits=None):
|
||||
process = Mock()
|
||||
process.stdout = io.BytesIO(stdout)
|
||||
process.stderr = io.BytesIO(stderr)
|
||||
process.returncode = 0
|
||||
process.wait.side_effect = waits or [0]
|
||||
return process
|
||||
|
||||
def run_process(self, process, **kwargs):
|
||||
factory = Mock(return_value=process)
|
||||
output = processes.run_process(["dotnet", "unit.dll", "-P", KEY], timeout=1,
|
||||
secrets=[KEY], popen=factory, **kwargs)
|
||||
return output, factory
|
||||
|
||||
def test_argv_is_passed_without_shell_and_capture_is_separate(self):
|
||||
output, factory = self.run_process(self.fake_process())
|
||||
args, options = factory.call_args
|
||||
self.assertEqual(args[0], ["dotnet", "unit.dll", "-P", KEY])
|
||||
self.assertFalse(options.get("shell", False))
|
||||
self.assertEqual(options["stdout"], subprocess.PIPE)
|
||||
self.assertEqual(options["stderr"], subprocess.PIPE)
|
||||
self.assertEqual(output.stdout, "output")
|
||||
self.assertEqual(output.stderr, "error")
|
||||
self.assertNotIn(KEY, repr(output))
|
||||
|
||||
def test_shell_strings_empty_argv_and_unbounded_timeouts_rejected_before_spawn(self):
|
||||
for argv, timeout in (("dotnet unit.dll", 1), ([], 1), (["dotnet"], 0),
|
||||
(["dotnet"], float("inf")), (["dotnet"], float("nan"))):
|
||||
factory = Mock()
|
||||
with self.subTest(argv=argv, timeout=timeout), self.assertRaises(processes.ProcessError):
|
||||
processes.run_process(argv, timeout=timeout, popen=factory)
|
||||
factory.assert_not_called()
|
||||
|
||||
def test_timeout_terminates_then_kills_stubborn_process_with_bounded_waits(self):
|
||||
process = self.fake_process(waits=[subprocess.TimeoutExpired("unit", 1),
|
||||
subprocess.TimeoutExpired("unit", 1), -9])
|
||||
output, _ = self.run_process(process)
|
||||
self.assertTrue(output.timed_out)
|
||||
self.assertEqual(output.returncode, -9)
|
||||
process.terminate.assert_called_once()
|
||||
process.kill.assert_called_once()
|
||||
self.assertTrue(all(call.kwargs.get("timeout", 0) > 0 for call in process.wait.call_args_list))
|
||||
|
||||
def test_nonzero_exit_is_retained(self):
|
||||
output, _ = self.run_process(self.fake_process(waits=[7]))
|
||||
self.assertEqual(output.returncode, 7)
|
||||
self.assertFalse(output.timed_out)
|
||||
|
||||
def test_retained_output_is_bounded_and_both_streams_are_redacted(self):
|
||||
process = self.fake_process(stdout=(KEY + "x" * 4096).encode(), stderr=(KEY + "y" * 4096).encode())
|
||||
output, _ = self.run_process(process, max_output_bytes=128)
|
||||
self.assertTrue(output.truncated)
|
||||
self.assertLessEqual(len(output.stdout.encode()) + len(output.stderr.encode()), 128)
|
||||
self.assertNotIn(KEY, repr(output))
|
||||
|
||||
def test_chunk_boundary_secret_is_redacted_and_password_options_are_always_hidden(self):
|
||||
safe = processes.redact_argv(["dotnet", "unit.dll", "-P", KEY, "--password=another-secret",
|
||||
"--api-key", "third-secret"])
|
||||
self.assertNotIn(KEY, repr(safe))
|
||||
self.assertNotIn("another-secret", repr(safe))
|
||||
self.assertNotIn("third-secret", repr(safe))
|
||||
output, _ = self.run_process(self.fake_process(stdout=("x" * 4090 + KEY).encode()), max_output_bytes=8192)
|
||||
self.assertNotIn(KEY, output.stdout)
|
||||
self.assertIn("[REDACTED]", output.stdout)
|
||||
|
||||
def test_failure_while_waiting_still_cleans_up_owned_child(self):
|
||||
process = self.fake_process(waits=[RuntimeError("wait failed"), -9])
|
||||
with self.assertRaises(processes.ProcessError) as raised:
|
||||
self.run_process(process)
|
||||
self.assertTrue(process.terminate.called or process.kill.called)
|
||||
self.assertNotIn(KEY, str(raised.exception))
|
||||
|
||||
|
||||
class CliContentGateTests(unittest.TestCase):
|
||||
def test_good_read_requires_matching_node_value_status_and_timestamps(self):
|
||||
text = (f"Node: {NODE}\nValue: 42\nStatus: Good\n"
|
||||
"Source Time: 2026-11-16T00:00:00.0000000Z\nServer Time: 2026-11-16T00:00:00.0000000Z\n")
|
||||
evidence = cli_gate.validate_read(result(text), expected_node=NODE)
|
||||
self.assertEqual(evidence["value"], "42")
|
||||
self.assertEqual(evidence["status"], "Good")
|
||||
|
||||
def test_exit_zero_bad_uncertain_or_missing_read_fields_fail(self):
|
||||
for text in (f"Node: {NODE}\nValue: \nStatus: BadUserAccessDenied (BadUserAccessDenied)\n",
|
||||
f"Node: {NODE}\nValue: 42\nStatus: UncertainLastUsableValue\n",
|
||||
"", "Status: Good\n", f"Node: other\nValue: 42\nStatus: Good\n"):
|
||||
with self.subTest(text=text), self.assertRaises(cli_gate.CliGateError):
|
||||
cli_gate.validate_read(result(text), expected_node=NODE)
|
||||
|
||||
def test_write_success_requires_current_cli_confirmation_for_exact_node(self):
|
||||
cli_gate.validate_write(result(f"Write successful: {NODE} = 42\n"), expected_node=NODE)
|
||||
for text in ("Write failed: BadNotWritable\n", "", "Write successful: other = 42\n"):
|
||||
with self.subTest(text=text), self.assertRaises(cli_gate.CliGateError):
|
||||
cli_gate.validate_write(result(text), expected_node=NODE)
|
||||
|
||||
def test_timeout_nonzero_exit_and_truncated_evidence_cannot_pass(self):
|
||||
for output in (result(f"Write successful: {NODE} = 42", returncode=1),
|
||||
result(f"Write successful: {NODE} = 42", timed_out=True),
|
||||
result(f"Write successful: {NODE} = 42", truncated=True)):
|
||||
with self.subTest(output=output), self.assertRaises(cli_gate.CliGateError):
|
||||
cli_gate.validate_write(output, expected_node=NODE)
|
||||
|
||||
def validate_subscription(self, output=None, summary_text=None, **kwargs):
|
||||
return cli_gate.validate_subscription(result(subscription_output() if output is None else output),
|
||||
summary_text=summary() if summary_text is None else summary_text,
|
||||
expected_nodes={NODE}, require_change=True, **kwargs)
|
||||
|
||||
def test_subscription_requires_attachment_summary_and_changing_good_notifications(self):
|
||||
evidence = self.validate_subscription()
|
||||
self.assertGreaterEqual(evidence["notifications"][NODE], 2)
|
||||
|
||||
def test_summary_target_count_does_not_prove_any_item_actually_attached(self):
|
||||
with self.assertRaises(cli_gate.CliGateError):
|
||||
self.validate_subscription(output=subscription_output(attached=0))
|
||||
|
||||
def test_attached_subscription_without_notifications_fails(self):
|
||||
with self.assertRaises(cli_gate.CliGateError):
|
||||
self.validate_subscription(output=subscription_output(values=()))
|
||||
|
||||
def test_unchanged_notifications_and_wrong_node_fail(self):
|
||||
for output in (subscription_output(values=(1, 1)), subscription_output().replace(NODE, "ns=7;s=wrong")):
|
||||
with self.subTest(output=output), self.assertRaises(cli_gate.CliGateError):
|
||||
self.validate_subscription(output=output)
|
||||
|
||||
def test_missing_file_summary_and_stdout_summary_each_fail(self):
|
||||
for summary_text, output in (("", subscription_output()), (summary(), subscription_output().split("====")[0])):
|
||||
with self.subTest(summary_text=summary_text), self.assertRaises(cli_gate.CliGateError):
|
||||
self.validate_subscription(summary_text=summary_text, output=output)
|
||||
|
||||
def test_bad_notifications_partial_item_failure_and_missing_summary_counters_fail(self):
|
||||
for output, text in ((subscription_output().replace("(Good)", "(BadNoCommunication)"), summary()),
|
||||
(" FAILED to subscribe " + NODE + ": denied\n" + subscription_output(), summary()),
|
||||
(subscription_output(), summary(good=0, bad=1)),
|
||||
(subscription_output(), summary(good=0, never=1)),
|
||||
(subscription_output(), "==================== SUMMARY ====================\n")):
|
||||
with self.subTest(output=output, text=text), self.assertRaises(cli_gate.CliGateError):
|
||||
self.validate_subscription(output=output, summary_text=text)
|
||||
|
||||
def test_cli_builder_uses_published_dll_current_flags_and_keeps_secret_out_of_evidence(self):
|
||||
argv = cli_gate.build_cli_argv(Path("/unit/tools/ZB.MOM.WW.OtOpcUa.Client.CLI.dll"), "read",
|
||||
"opc.tcp://127.0.0.1:52113", KEY, node=NODE)
|
||||
self.assertEqual(argv[:3], ["dotnet", "/unit/tools/ZB.MOM.WW.OtOpcUa.Client.CLI.dll", "read"])
|
||||
self.assertEqual(argv[argv.index("-P") + 1], KEY)
|
||||
self.assertEqual(argv[argv.index("-n") + 1], NODE)
|
||||
self.assertNotIn("--json", argv)
|
||||
self.assertNotIn(KEY, repr(processes.redact_argv(argv)))
|
||||
|
||||
def test_cli_builder_rejects_exe_rebuilds_and_remote_endpoint(self):
|
||||
for dll, url in ((Path("/unit/tools/tool.exe"), "opc.tcp://127.0.0.1:52113"),
|
||||
(Path("/unit/tools/tool.dll"), "opc.tcp://10.100.0.35:4840")):
|
||||
with self.subTest(dll=dll, url=url), self.assertRaises(cli_gate.CliGateError):
|
||||
cli_gate.build_cli_argv(dll, "read", url, KEY, node=NODE)
|
||||
@@ -0,0 +1,281 @@
|
||||
"""Safety units only: no Docker, HTTP, DNS, socket, or production fixture calls."""
|
||||
from copy import deepcopy
|
||||
import os
|
||||
from pathlib import Path
|
||||
import stat
|
||||
import sys
|
||||
import tempfile
|
||||
import unittest
|
||||
from unittest.mock import patch
|
||||
|
||||
sys.path.insert(0, str(Path(__file__).resolve().parents[1]))
|
||||
import rig
|
||||
|
||||
|
||||
RUN = "unit-fixture-001"
|
||||
LABELS = {"otopcua.grpc-data.run": RUN,
|
||||
"com.docker.compose.project": f"grpc-data-{RUN}"}
|
||||
|
||||
|
||||
def manifest():
|
||||
return {
|
||||
"schema_version": 1, "run_id": RUN, "project": f"grpc-data-{RUN}",
|
||||
"labels": dict(LABELS),
|
||||
"services": ["sql", "device", "control-1", "control-2", "source-1", "source-2",
|
||||
"consumer-1", "consumer-2"],
|
||||
"endpoints": {
|
||||
"admin": {"scheme": "http", "host": "127.0.0.1", "host_port": 52111,
|
||||
"container_host": "control-1", "container_port": 9000},
|
||||
"source-1": {"scheme": "https", "host": "127.0.0.1", "host_port": 52112,
|
||||
"container_host": "source-1", "container_port": 4057}},
|
||||
"nodes": {"source-1": {"cluster_id": "SOURCE", "application_uri": "urn:unit:source-1"}},
|
||||
"resources": [{"kind": "container", "id": "unit-container", "labels": dict(LABELS)}],
|
||||
}
|
||||
|
||||
|
||||
class LocalDockerSafetyTests(unittest.TestCase):
|
||||
def test_accepts_only_local_unix_and_npipe_transports(self):
|
||||
for endpoint in ("unix:///var/run/docker.sock", "unix:///Users/unit/.docker/run/docker.sock",
|
||||
"npipe:////./pipe/docker_engine"):
|
||||
with self.subTest(endpoint=endpoint):
|
||||
rig.validate_local_docker(endpoint)
|
||||
|
||||
def test_rejects_remote_transports_even_on_loopback(self):
|
||||
for endpoint in ("ssh://unit@localhost", "tcp://127.0.0.1:2375", "tcp://10.100.0.35:2376",
|
||||
"http://localhost:2375", "unix://other-host/var/run/docker.sock", ""):
|
||||
with self.subTest(endpoint=endpoint), self.assertRaises(rig.RigError):
|
||||
rig.validate_local_docker(endpoint)
|
||||
|
||||
def test_context_resolution_cannot_hide_remote_endpoint(self):
|
||||
with self.assertRaises(rig.RigError):
|
||||
rig.validate_docker_context({"Name": "local-looking", "Endpoints": {
|
||||
"docker": {"Host": "ssh://unit@shared-host"}}}, environment={})
|
||||
|
||||
def test_remote_environment_override_rejected_even_with_local_context(self):
|
||||
context = {"Name": "desktop-linux", "Endpoints": {"docker": {"Host": "unix:///tmp/docker.sock"}}}
|
||||
for environment in ({"DOCKER_HOST": "tcp://localhost:2375"},
|
||||
{"DOCKER_CONTEXT": "other-context"}):
|
||||
with self.subTest(environment=environment), self.assertRaises(rig.RigError):
|
||||
rig.validate_docker_context(context, environment=environment)
|
||||
|
||||
def test_local_named_context_and_matching_override_allowed(self):
|
||||
context = {"Name": "desktop-linux", "Endpoints": {"docker": {"Host": "unix:///tmp/docker.sock"}}}
|
||||
rig.validate_docker_context(context, environment={"DOCKER_CONTEXT": "desktop-linux"})
|
||||
|
||||
def test_resolved_fixture_endpoints_allow_only_loopback_and_declared_services(self):
|
||||
document = {"services": {"source-1": {"environment": {
|
||||
"ConnectionStrings__ConfigDb": "Server=sql,1433;Database=fixture;Password=secret",
|
||||
"Mesh__Endpoint": "http://control-1:4055", "Device__Host": "device",
|
||||
"Security__Ldap__Server": "127.0.0.1"}}}}
|
||||
rig.validate_fixture_endpoints(document, local_services=set(manifest()["services"]))
|
||||
|
||||
def test_shared_endpoints_rejected_in_urls_sql_and_plain_host_options(self):
|
||||
for value in ({"url": "https://10.100.0.35:4057"},
|
||||
{"ConnectionStrings__ConfigDb": "Server=shared-db,1433;Database=x"},
|
||||
{"ConnectionStrings__FixturePg": "Host=10.100.0.35;Port=15432"},
|
||||
{"Oracle": "Data Source=10.100.0.35:11521/FREEPDB1"},
|
||||
{"Security__Ldap__Server": "shared-directory"},
|
||||
{"Device__Host": "host.docker.internal"},
|
||||
{"url": "http://[::ffff:10.100.0.35]:9000"},
|
||||
{"url": "http://${SHARED_HOST}:9000"}):
|
||||
with self.subTest(value=value), self.assertRaises(rig.RigError):
|
||||
rig.validate_fixture_endpoints(value, local_services=set(manifest()["services"]))
|
||||
|
||||
|
||||
class ManifestOwnershipTests(unittest.TestCase):
|
||||
def test_valid_manifest_accepts_dynamic_nondefault_loopback_ports(self):
|
||||
rig.validate_manifest(manifest(), expected_run_id=RUN)
|
||||
|
||||
def test_unknown_version_wrong_run_and_unsafe_project_rejected(self):
|
||||
for key, value in (("schema_version", 2), ("run_id", "../other"), ("project", "docker-dev")):
|
||||
candidate = manifest()
|
||||
candidate[key] = value
|
||||
with self.subTest(key=key), self.assertRaises(rig.RigError):
|
||||
rig.validate_manifest(candidate, expected_run_id=RUN)
|
||||
|
||||
def test_public_shared_duplicate_invalid_and_boolean_ports_rejected(self):
|
||||
for key, value in (("host", "0.0.0.0"), ("host", "10.100.0.35"), ("host_port", 52112),
|
||||
("host_port", 0), ("host_port", True), ("container_port", 65536),
|
||||
("container_host", "shared-host")):
|
||||
candidate = manifest()
|
||||
candidate["endpoints"]["admin"][key] = value
|
||||
with self.subTest(key=key, value=value), self.assertRaises(rig.RigError):
|
||||
rig.validate_manifest(candidate)
|
||||
|
||||
def test_missing_endpoint_node_identity_or_exact_ownership_fails(self):
|
||||
for mutate in (lambda m: m.update(endpoints={}), lambda m: m["nodes"]["source-1"].pop("cluster_id"),
|
||||
lambda m: m["labels"].pop("otopcua.grpc-data.run"),
|
||||
lambda m: m["resources"][0]["labels"].update({"otopcua.grpc-data.run": "other"})):
|
||||
candidate = manifest()
|
||||
mutate(candidate)
|
||||
with self.subTest(candidate=candidate), self.assertRaises(rig.RigError):
|
||||
rig.validate_manifest(candidate)
|
||||
|
||||
def test_cleanup_removes_only_recorded_ids_with_matching_run_and_project(self):
|
||||
candidate = manifest()
|
||||
observed = deepcopy(candidate["resources"])
|
||||
observed += [{"kind": "container", "id": "same-labels-unrecorded", "labels": dict(LABELS)},
|
||||
{"kind": "volume", "id": "developer-data", "labels": {}},
|
||||
{"kind": "container", "id": "another-run", "labels": {}}]
|
||||
removed = []
|
||||
rig.cleanup_owned(candidate, observed, remove=lambda kind, resource_id: removed.append((kind, resource_id)))
|
||||
self.assertEqual(removed, [("container", "unit-container")])
|
||||
|
||||
def test_cleanup_checks_all_ownership_before_first_deletion(self):
|
||||
candidate = manifest()
|
||||
candidate["resources"].append({"kind": "volume", "id": "unit-volume", "labels": dict(LABELS)})
|
||||
observed = deepcopy(candidate["resources"])
|
||||
observed[1]["labels"]["com.docker.compose.project"] = "docker-dev"
|
||||
removed = []
|
||||
with self.assertRaises(rig.RigError):
|
||||
rig.cleanup_owned(candidate, observed, remove=lambda *args: removed.append(args))
|
||||
self.assertEqual(removed, [])
|
||||
|
||||
def test_missing_resource_is_idempotent_but_duplicate_observations_fail(self):
|
||||
removed = []
|
||||
rig.cleanup_owned(manifest(), [], remove=lambda *args: removed.append(args))
|
||||
self.assertEqual(removed, [])
|
||||
with self.assertRaises(rig.RigError):
|
||||
rig.cleanup_owned(manifest(), manifest()["resources"] * 2,
|
||||
remove=lambda *args: removed.append(args))
|
||||
self.assertEqual(removed, [])
|
||||
|
||||
|
||||
class RestrictedSecretTests(unittest.TestCase):
|
||||
def setUp(self):
|
||||
self.temp = tempfile.TemporaryDirectory()
|
||||
self.addCleanup(self.temp.cleanup)
|
||||
self.path = Path(self.temp.name) / "credential.key"
|
||||
|
||||
def test_secret_is_restricted_before_atomic_publication(self):
|
||||
seen = []
|
||||
def publish(source, target):
|
||||
seen.append((Path(source).read_text(), stat.S_IMODE(os.stat(source).st_mode)))
|
||||
self.assertFalse(self.path.exists())
|
||||
os.replace(source, target)
|
||||
rig.atomic_write_secret(self.path, "unit-secret", replace=publish)
|
||||
self.assertEqual(seen, [("unit-secret", 0o600)])
|
||||
self.assertEqual(self.path.read_text(), "unit-secret")
|
||||
self.assertEqual(stat.S_IMODE(self.path.stat().st_mode), 0o600)
|
||||
|
||||
def test_failed_publication_keeps_old_secret_and_removes_temporary_file(self):
|
||||
self.path.write_text("old-secret")
|
||||
def interrupted(*args):
|
||||
raise OSError("interrupted")
|
||||
with self.assertRaises(OSError):
|
||||
rig.atomic_write_secret(self.path, "new-secret", replace=interrupted)
|
||||
self.assertEqual(self.path.read_text(), "old-secret")
|
||||
self.assertEqual(list(self.path.parent.iterdir()), [self.path])
|
||||
|
||||
def test_symlink_target_is_rejected_without_touching_destination(self):
|
||||
target = self.path.parent / "outside"
|
||||
target.write_text("untouched")
|
||||
self.path.symlink_to(target)
|
||||
with self.assertRaises(rig.RigError):
|
||||
rig.atomic_write_secret(self.path, "new-secret")
|
||||
self.assertEqual(target.read_text(), "untouched")
|
||||
|
||||
|
||||
class DeploymentPollingTests(unittest.TestCase):
|
||||
def setUp(self):
|
||||
self.calls = []
|
||||
self.now = 0.0
|
||||
self.responses = []
|
||||
self.base = "http://127.0.0.1:52111"
|
||||
self.deployment_id = "45b839a2-dc92-4f63-ad50-14eb9209e5a1"
|
||||
self.location = f"/api/deployments/{self.deployment_id}"
|
||||
|
||||
def request(self, method, url, *, headers, json_body, timeout):
|
||||
self.calls.append((method, url, headers, json_body, timeout))
|
||||
self.assertGreater(timeout, 0)
|
||||
return self.responses.pop(0)
|
||||
|
||||
def sleep(self, seconds):
|
||||
self.now += seconds
|
||||
|
||||
def status(self, state="Sealed", nodes=None):
|
||||
return {"deploymentId": self.deployment_id, "revisionHash": "unit-revision", "status": state,
|
||||
"failureReason": None, "nodes": nodes if nodes is not None else [
|
||||
{"nodeId": node, "status": "Applied", "appliedAtUtc": "2026-11-16T00:00:00Z", "failureReason": None}
|
||||
for node in ("source-1", "source-2")]}
|
||||
|
||||
def invoke(self, **kwargs):
|
||||
return rig.deploy_and_wait(self.base, "unit-deploy-key", {"source-1", "source-2"},
|
||||
request=self.request, clock=lambda: self.now, sleep=self.sleep,
|
||||
timeout=3, poll_interval=1, **kwargs)
|
||||
|
||||
def accepted(self):
|
||||
return (202, {"Location": self.location}, {"outcome": "Accepted", "deploymentId": self.deployment_id,
|
||||
"revisionHash": "unit-revision"})
|
||||
|
||||
def test_posts_created_by_only_once_then_polls_location_and_all_nodes(self):
|
||||
self.responses = [self.accepted(), (200, {}, self.status("AwaitingApplyAcks")),
|
||||
(200, {}, self.status())]
|
||||
result = self.invoke()
|
||||
self.assertEqual(result["revisionHash"], "unit-revision")
|
||||
self.assertEqual([call[0] for call in self.calls], ["POST", "GET", "GET"])
|
||||
self.assertEqual(self.calls[0][1], self.base + "/api/deployments")
|
||||
self.assertEqual(self.calls[0][3], {"createdBy": "grpc-data-local-gate"})
|
||||
self.assertEqual(self.calls[1][1], self.base + self.location)
|
||||
self.assertTrue(all(call[2]["X-Api-Key"] == "unit-deploy-key" for call in self.calls))
|
||||
|
||||
def test_bodyless_trigger_supported_without_artifact_upload(self):
|
||||
self.responses = [self.accepted(), (200, {}, self.status())]
|
||||
self.invoke(created_by=None)
|
||||
self.assertIsNone(self.calls[0][3])
|
||||
|
||||
def test_no_changes_still_polls_existing_deployment_for_apply_evidence(self):
|
||||
self.responses = [(200, {}, {"outcome": "NoChanges", "deploymentId": self.deployment_id,
|
||||
"revisionHash": "unit-revision"}), (200, {}, self.status())]
|
||||
self.invoke()
|
||||
self.assertEqual([call[0] for call in self.calls], ["POST", "GET"])
|
||||
|
||||
def test_no_changes_without_deployment_and_inflight_are_explicit_failures(self):
|
||||
for response in ((200, {}, {"outcome": "NoChanges", "deploymentId": None, "revisionHash": "unit-revision"}),
|
||||
(409, {}, {"outcome": "AnotherDeploymentInFlight"})):
|
||||
self.responses = [response]
|
||||
self.calls.clear()
|
||||
with self.subTest(response=response), self.assertRaises(rig.RigError):
|
||||
self.invoke()
|
||||
self.assertEqual(len(self.calls), 1)
|
||||
|
||||
def test_missing_unexpected_duplicate_failed_and_degraded_nodes_fail(self):
|
||||
base_nodes = self.status()["nodes"]
|
||||
variants = [base_nodes[:1], base_nodes + [dict(base_nodes[0], nodeId="unexpected")],
|
||||
base_nodes + [deepcopy(base_nodes[0])],
|
||||
[dict(base_nodes[0], status="Failed"), base_nodes[1]],
|
||||
[dict(base_nodes[0], failureReason="Applied degraded: unavailable"), base_nodes[1]],
|
||||
[dict(base_nodes[0], appliedAtUtc=None), base_nodes[1]]]
|
||||
for nodes in variants:
|
||||
self.responses = [self.accepted(), (200, {}, self.status(nodes=nodes))]
|
||||
with self.subTest(nodes=nodes), self.assertRaises(rig.RigError):
|
||||
self.invoke()
|
||||
|
||||
def test_deployment_revision_identity_terminal_state_and_remote_location_fail(self):
|
||||
for key, value in (("revisionHash", "wrong"), ("deploymentId", "another"),
|
||||
("status", "PartiallyFailed"), ("status", "Mystery")):
|
||||
status_body = self.status()
|
||||
status_body[key] = value
|
||||
self.responses = [self.accepted(), (200, {}, status_body)]
|
||||
with self.subTest(key=key), self.assertRaises(rig.RigError):
|
||||
self.invoke()
|
||||
response = self.accepted()
|
||||
self.responses = [(response[0], {"Location": "https://shared-host/api/deployments/other"}, response[2])]
|
||||
self.calls.clear()
|
||||
with self.assertRaises(rig.RigError):
|
||||
self.invoke()
|
||||
self.assertEqual(len(self.calls), 1)
|
||||
|
||||
def test_polling_deadline_is_bounded_and_never_reposts(self):
|
||||
self.responses = [self.accepted()] + [(200, {}, self.status("AwaitingApplyAcks"))] * 10
|
||||
with self.assertRaisesRegex(rig.RigError, "timeout|deadline"):
|
||||
self.invoke()
|
||||
self.assertLessEqual(self.now, 3)
|
||||
self.assertEqual(sum(call[0] == "POST" for call in self.calls), 1)
|
||||
|
||||
def test_unwired_production_actions_fail_clearly_without_side_effects(self):
|
||||
for action in ("up", "seed"):
|
||||
with self.subTest(action=action), patch("subprocess.Popen") as popen:
|
||||
with self.assertRaisesRegex(rig.RigError, "prerequisite|not configured|not wired"):
|
||||
rig.require_production_prerequisites(action, {})
|
||||
popen.assert_not_called()
|
||||
Reference in New Issue
Block a user