"""使用编译器导出的 manifest,驱动真实 SDK 子进程。""" import json from decimal import Decimal import pathlib import select import struct import subprocess import sys import tempfile import time import unittest MANIFEST = pathlib.Path(sys.argv[1]) SDK = pathlib.Path(sys.argv[2]) LANGUAGE = sys.argv[3] CONTRACT = json.loads(MANIFEST.read_text()) sys.argv[1:] = [] class WorkerProtocol(unittest.TestCase): def setUp(self): self.directory = tempfile.TemporaryDirectory() self.addCleanup(self.directory.cleanup) self.marker = pathlib.Path(self.directory.name) / "started" entry = pathlib.Path(__file__).with_name("python_worker.py" if LANGUAGE == "python" else "javascript_worker.mjs") command = [sys.executable, "-I", "-B", str(entry)] if LANGUAGE == "python" else ["node", str(entry)] if LANGUAGE == "go": command = [str(SDK)] self.process = subprocess.Popen( command + [str(MANIFEST), str(SDK)], stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE, ) self.addCleanup(self.close) hello = {name: CONTRACT[name] for name in ("port", "schema", "adapter", "operations", "capabilities")} hello.update(kind="hello", version="dever-component-1", setting={"marker": str(self.marker)}) self.send(hello) hello.pop("setting") hello["kind"] = "ready" self.assertEqual(self.receive(), hello) self.send({"kind": "health", "id": 0}) self.assertEqual(self.receive(), {"kind": "health", "id": 0}) def close(self): if self.process.poll() is None: self.process.kill() self.process.communicate(timeout=3) def send(self, value): body = json.dumps(value, ensure_ascii=False).encode() self.process.stdin.write(struct.pack(">I", len(body)) + body) self.process.stdin.flush() def receive(self): self.assertTrue(select.select([self.process.stdout], [], [], 3)[0], "Worker did not reply") prefix = self.process.stdout.read(4) self.assertEqual(len(prefix), 4, "Worker closed protocol output") return json.loads(self.process.stdout.read(struct.unpack(">I", prefix)[0]), parse_float=Decimal) def call(self, identity, operation, payload): self.send(dict(kind="call", id=identity, operation=operation, payload=payload)) return self.receive() def test_typed_values_business_error_and_reuse(self): for identity, value in enumerate([-(2**63), 2**63 - 1], 1): reply = self.call(identity, "echo", dict(value=value, label="中文", items=[value])) self.assertEqual(reply, dict(kind="result", id=identity, payload=dict(out=value, name="中文"))) reply = self.call(3, "fail", {}) self.assertEqual(reply, dict(kind="error", id=3, error="demo.service.port.Error.Rejected", payload=dict(message="business rejection"))) reply = self.call(4, "echo", dict(value=42, label=None, items=[])) self.assertEqual(reply["payload"], dict(out=42, name=None)) self.send(dict(kind="shutdown")) self.assertEqual(self.receive(), dict(kind="shutdown")) self.assertEqual(self.process.wait(timeout=3), 0) def test_cancel_drains_handler_and_allows_next_call(self): self.send(dict(kind="call", id=1, operation="hang", payload={})) deadline = time.monotonic() + 3 while not self.marker.exists() and time.monotonic() < deadline: time.sleep(0.002) self.assertTrue(self.marker.exists()) self.send(dict(kind="cancel", id=1)) self.assertEqual(self.receive(), dict(kind="error", id=1, error="dever.cancelled", payload=None)) self.assertTrue(self.marker.with_suffix(".stopped").exists()) self.assertEqual(self.call(2, "echo", dict(value=42, label=None, items=[]))["payload"]["out"], 42) def test_json_numbers_remain_exact_and_float_fields_are_numeric(self): body = b'{"kind":"call","id":1,"operation":"raw","payload":{"value":{"tiny":1e-9999,"precise":0.1234567890123456789012345678901234,"large":1e9999,"integer":123456789012345678901234567890123456789}}}' self.process.stdin.write(struct.pack(">I", len(body)) + body) self.process.stdin.flush() expected = json.loads(body, parse_float=Decimal)["payload"]["value"] self.assertEqual(self.receive()["payload"]["out"], expected) self.assertEqual(self.call(2, "floating", dict(value=1.25))["payload"]["out"], Decimal("1.5")) def rejected(self, operation, payload, message): self.send(dict(kind="call", id=1, operation=operation, payload=payload)) self.assertNotEqual(self.process.wait(timeout=3), 0) self.assertIn(message, self.process.stderr.read().decode()) self.assertEqual(self.process.stdout.read(), b"") def test_missing_nullable_field_is_rejected(self): self.rejected("echo", dict(value=42, items=[]), "record fields") def test_enum_values_roundtrip_in_nullable_fields_and_lists(self): reply = self.call(1, "tool", dict(value="Multiply", maybe="Add", items=["Add", "Multiply"])) self.assertEqual(reply["payload"], {"out": "Multiply"}) reply = self.call(2, "tool", dict(value="Add", maybe=None, items=[])) self.assertEqual(reply["payload"], {"out": "Add"}) def test_unknown_enum_is_rejected_at_boundary(self): self.rejected("tool", dict(value="Divide", maybe=None, items=[]), "unknown enum value") def test_integer_type_is_not_guessed(self): self.rejected("echo", dict(value=True, label=None, items=[]), "signed 64-bit") def test_output_range_is_rejected(self): self.rejected("invalid", {}, "declared range") def test_duplicate_protocol_keys_are_rejected(self): body = b'{"kind":"health","id":0,"id":0}' self.process.stdin.write(struct.pack(">I",len(body)) + body) self.process.stdin.flush() self.assertNotEqual(self.process.wait(timeout=3), 0) self.assertIn("duplicate JSON field", self.process.stderr.read().decode()) unittest.main()