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)
|
||||
Reference in New Issue
Block a user