#!/usr/bin/env python3 """Remote collector and package tests for the converged CPLD project.""" from __future__ import annotations import json import shutil import subprocess import tempfile import unittest from pathlib import Path ROOT = Path(__file__).resolve().parents[2] class RemoteScriptTests(unittest.TestCase): def test_remote_tools_only_expose_latest_real_fan_ptc_collector(self) -> None: scripts = sorted(path.name for path in (ROOT / "tools" / "remote").glob("*.ps1")) self.assertEqual(scripts, ["collect-j6-host-sensor-real-fan-ptc.ps1"]) self.assertFalse((ROOT / "tools" / "serial_debug_capture.py").exists()) self.assertFalse((ROOT / "tools" / "windows_serial_validation.py").exists()) def test_collect_j6_host_sensor_real_fan_ptc_is_static_allowlisted_host_writer_and_debug_reader(self) -> None: script = (ROOT / "tools" / "remote" / "collect-j6-host-sensor-real-fan-ptc.ps1").read_text( encoding="utf-8" ) for marker in [ "System.IO.Ports.SerialPort", "[ValidatePattern('^COM[0-9]+$')]", "HostPort", "DebugPort", 'if ($HostPort -eq $DebugPort)', 'if ($HostPort -ne "COM8")', 'if ($DebugPort -ne "COM7")', "BaudRate = 115200", "DebugBaud = 921600", "DtrEnable = $false", "RtsEnable = $false", "host-port-raw.bin", "host-port-escaped.txt", "debug-uart-raw.bin", "debug-uart-escaped.txt", "bmc-raw-replay.bin", "host-sensor-report.json", "debug-frame-stream.json", "host-command-transcript.json", "j6-host-sensor-real-fan-ptc-capture-manifest.json", "real-bmc-j6-host-sensor-real-fan-ptc-debug921-v1-receipt-draft.json", "real-bmc-j6-host-sensor-real-fan-ptc-debug921-v1", "J6CMD", "J6RAW", "J6EVT", "J6PWM", "J6MOD", "J6STAT", "J6MAP", "J6TEMP", "SENS", "DIMM", "PTCCH", "FANCH", "SET PTC 01 10", "SET PTC 24 20", "SET FAN 01 40", "SET FAN 04 30", "SET PID ENABLE", "GET STATUS", "GET MAP", "GET SENSOR", "SET PID DISABLE", "DISABLE", "host_port_writes_to_serial", "debug_port_writes_to_serial", "driver_install_attempted = $false", "enumerates_com_ports = $false", "opens_unknown_com_ports = $false", "AssumeManualSramProgrammed", "PROGRAM_SRAM", ]: self.assertIn(marker, script) self.assertIn("$hostSerial.Write", script) self.assertNotIn("$debugSerial.Write", script) for forbidden in [ "SET PTC 00", "SET FAN 00", "SET FAN 05", "SET FAN 06", "GetPortNames", "Win32_SerialPort", "Get-CimInstance", "Get-WmiObject", "pip install", "pyserial", "python", "pnputil", "devcon", "install-driver", "add-windowsdriver", "driverquery", "PROGRAM_FLASH", "ERASE_FLASH", "PROGRAM_SPIBIN", "DIRECT_FLASH_WRITE", "blocked_edit_required", ]: self.assertNotIn(forbidden.lower(), script.lower()) def test_collect_j6_host_sensor_real_fan_ptc_preserves_empty_raw_replay_byte_array(self) -> None: powershell = shutil.which("powershell") if powershell is None: self.skipTest("PowerShell is not available") script_path = ROOT / "tools" / "remote" / "collect-j6-host-sensor-real-fan-ptc.ps1" script = script_path.read_text(encoding="utf-8") helper_start = script.index("function Convert-HexToBytes") helper_end = script.index("$out =") helpers = script[helper_start:helper_end] with tempfile.TemporaryDirectory() as tmp: probe_path = Path(tmp) / "probe.ps1" out_path = Path(tmp) / "empty-replay.bin" probe_path.write_text( helpers + f""" $events = New-Object System.Collections.Generic.List[object] $rawReplayArray = New-BmcRawReplay $events if ($null -eq $rawReplayArray) {{ throw "raw replay array was null" }} if ($rawReplayArray.GetType().FullName -ne "System.Byte[]") {{ throw "raw replay array type was $($rawReplayArray.GetType().FullName)" }} if ($rawReplayArray.Length -ne 0) {{ throw "raw replay array length was $($rawReplayArray.Length)" }} [System.IO.File]::WriteAllBytes("{out_path}", $rawReplayArray) """, encoding="utf-8", ) result = subprocess.run( [powershell, "-NoProfile", "-ExecutionPolicy", "Bypass", "-File", str(probe_path)], cwd=ROOT, text=True, capture_output=True, check=False, ) self.assertEqual(result.returncode, 0, result.stderr + result.stdout) self.assertTrue(out_path.exists()) self.assertEqual(out_path.stat().st_size, 0) def test_collect_j6_host_sensor_real_fan_ptc_parses_two_digit_hex_fields_as_int64(self) -> None: powershell = shutil.which("powershell") if powershell is None: self.skipTest("PowerShell is not available") script_path = ROOT / "tools" / "remote" / "collect-j6-host-sensor-real-fan-ptc.ps1" script = script_path.read_text(encoding="utf-8") helper_start = script.index("function Convert-TokenValue") helper_end = script.index("function Convert-BytesToEscapedText") helpers = script[helper_start:helper_end] with tempfile.TemporaryDirectory() as tmp: probe_path = Path(tmp) / "probe.ps1" probe_path.write_text( helpers + """ $events = New-Object System.Collections.Generic.List[object] $events.Add((Convert-FrameLine "J6PWM seq=0000000A src=hm pid=disabled timeout=1 ptc01=00 ptc24=00 fan01=1E fan04=1E" @("J6PWM"))) | Out-Null $events.Add((Convert-FrameLine "J6TEMP seq=00000003 status=valid valid=1E missing=00 fault=0 host_report_drop=00000000" @("J6TEMP"))) | Out-Null $events.Add((Convert-FrameLine "J6RAW seq=00000001 off=00000000 len=30 sum=00FF data=FFFFFFFF" @("J6RAW"))) | Out-Null foreach ($probe in @( @($events[0].fields.fan01, "fan01"), @($events[0].fields.timeout, "timeout"), @($events[1].fields.valid, "valid"), @($events[1].fields.missing, "missing"), @($events[2].fields.len, "len"), @($events[2].fields.sum, "sum") )) { if ($probe[0].GetType().FullName -ne "System.Int64") { throw "$($probe[1]) parsed as $($probe[0].GetType().FullName)" } } if ([int64]$events[0].fields.fan01 -ne 30) { throw "fan01 was $($events[0].fields.fan01)" } if ([int64]$events[0].fields.timeout -ne 1) { throw "timeout was $($events[0].fields.timeout)" } if ([int64]$events[1].fields.valid -ne 30) { throw "valid was $($events[1].fields.valid)" } if ([int64]$events[1].fields.missing -ne 0) { throw "missing was $($events[1].fields.missing)" } if ([int64]$events[2].fields.len -ne 48) { throw "len was $($events[2].fields.len)" } if ([int64]$events[2].fields.sum -ne 255) { throw "sum was $($events[2].fields.sum)" } """, encoding="utf-8", ) result = subprocess.run( [powershell, "-NoProfile", "-ExecutionPolicy", "Bypass", "-File", str(probe_path)], cwd=ROOT, text=True, capture_output=True, check=False, ) self.assertEqual(result.returncode, 0, result.stderr + result.stdout) def test_collect_j6_host_sensor_real_fan_ptc_keeps_command_tokens_as_strings(self) -> None: powershell = shutil.which("powershell") if powershell is None: self.skipTest("PowerShell is not available") script_path = ROOT / "tools" / "remote" / "collect-j6-host-sensor-real-fan-ptc.ps1" script = script_path.read_text(encoding="utf-8") helper_start = script.index("function Convert-TokenValue") helper_end = script.index("function Convert-BytesToEscapedText") helpers = script[helper_start:helper_end] with tempfile.TemporaryDirectory() as tmp: probe_path = Path(tmp) / "probe.ps1" probe_path.write_text( helpers + """ $events = New-Object System.Collections.Generic.List[object] $events.Add((Convert-FrameLine "J6CMD seq=00000001 cmd=raw text=ipmitool" @("J6CMD"))) | Out-Null $events.Add((Convert-FrameLine "J6EVT seq=00000002 ok=1 err=0 type=PTCCH ch=01 pct=0A" @("J6EVT"))) | Out-Null $events.Add((Convert-FrameLine "OK seq=00000003 cmd=FANCH" @("OK"))) | Out-Null if ($events[0].fields.cmd -ne "raw") { throw "cmd was $($events[0].fields.cmd)" } if ($events[1].fields.type -ne "PTCCH") { throw "type was $($events[1].fields.type)" } if ($events[1].fields.ch.GetType().FullName -ne "System.Int64") { throw "ch type was $($events[1].fields.ch.GetType().FullName)" } if ([int64]$events[1].fields.ch -ne 1) { throw "ch was $($events[1].fields.ch)" } if ([int64]$events[1].fields.pct -ne 10) { throw "pct was $($events[1].fields.pct)" } if ($events[2].fields.cmd -ne "FANCH") { throw "ack cmd was $($events[2].fields.cmd)" } """, encoding="utf-8", ) result = subprocess.run( [powershell, "-NoProfile", "-ExecutionPolicy", "Bypass", "-File", str(probe_path)], cwd=ROOT, text=True, capture_output=True, check=False, ) self.assertEqual(result.returncode, 0, result.stderr + result.stdout) def test_j6_host_sensor_real_fan_ptc_package_script_creates_two_executable_profile_packages(self) -> None: script = (ROOT / "tools" / "package_j6_host_sensor_real_fan_ptc_debug921.ps1").read_text( encoding="utf-8" ) for marker in [ "START-HERE.zh-CN.md", "tools\\remote\\collect-j6-host-sensor-real-fan-ptc.ps1", "bitstreams", "td-receipts", "commands", "pin_inventory.fcb_fpga_mcu0611.json", "sha256-inventory.json", "Compress-Archive", ".zip.sha256.txt", "temp-uart-ptc-remap", "formal-uart", "j6-host-sensor-real-fan-ptc-temp-uart-ptc-remap-debug921-v1", "j6-host-sensor-real-fan-ptc-formal-uart-debug921-v1", "SET PTC 01 10", "SET PTC 24 20", "SET FAN 01 40", "SET FAN 04 30", "-AssumeManualSramProgrammed $true", "excluded_self_referential_file", ]: self.assertIn(marker, script) for marker in [ "blocked_pin_conflict_with_locked_debug_uart", "debug115", "swapped", "-ManualSramAttestation", "$att.status", "blocked_edit_required", "collect-com8-host-com7-debug.ps1", r"-Bitstream .\bitstreams\uart_rs232_j6_host_sensor_real_fan_ptc_debug921_primary.bit", "SET PTC 00", "SET FAN 00", "SET FAN 05", "SET FAN 06", "pip install", "pyserial", "python", ]: self.assertNotIn(marker.lower(), script.lower()) def test_j6_host_sensor_real_fan_ptc_package_output_contains_executable_profile_artifacts(self) -> None: powershell = shutil.which("powershell") if powershell is None: self.skipTest("PowerShell is not available") with tempfile.TemporaryDirectory() as tmp: bitstream = Path(tmp) / "fake.bit" td_receipt = Path(tmp) / "td-receipt.json" bitstream.write_bytes(b"fake-sram-bitstream") td_receipt.write_text( json.dumps( { "schema": "td-build-receipt-v1", "status": "pass", "programming_mode": "SRAM-only", "bitstream": {"sha256": "0" * 64}, } ), encoding="utf-8", ) for profile, package_name in [ ("temp-uart-ptc-remap", "j6-host-sensor-real-fan-ptc-temp-uart-ptc-remap-debug921-v1-test"), ("formal-uart", "j6-host-sensor-real-fan-ptc-formal-uart-debug921-v1-test"), ]: with self.subTest(profile=profile): result = subprocess.run( [ powershell, "-NoProfile", "-ExecutionPolicy", "Bypass", "-File", str(ROOT / "tools" / "package_j6_host_sensor_real_fan_ptc_debug921.ps1"), "-OutputDir", tmp, "-PackageName", package_name, "-Profile", profile, "-Bitstream", str(bitstream), "-TdReceipt", str(td_receipt), ], cwd=ROOT, capture_output=True, check=False, ) output = (result.stderr or b"").decode("utf-8", errors="replace") + ( result.stdout or b"" ).decode("utf-8", errors="replace") self.assertEqual(result.returncode, 0, output) stage = Path(tmp) / package_name self.assertTrue((stage / "START-HERE.zh-CN.md").is_file()) self.assertTrue((stage / "collector" / "collect-j6-host-sensor-real-fan-ptc.ps1").is_file()) self.assertTrue((stage / "commands" / "collect-template.ps1").is_file()) self.assertTrue((stage / "bitstreams" / bitstream.name).is_file()) self.assertTrue((stage / "td-receipts" / td_receipt.name).is_file()) self.assertTrue((stage / "config" / "pin_inventory.fcb_fpga_mcu0611.json").is_file()) self.assertTrue((stage / "schemas" / "real_bmc_j6_host_sensor_real_fan_ptc_debug921_v1_receipt.schema.json").is_file()) self.assertFalse((stage / "blocked").exists()) self.assertTrue((Path(tmp) / f"{package_name}.zip").is_file()) self.assertTrue((Path(tmp) / f"{package_name}.zip.sha256.txt").is_file()) start_here = (stage / "START-HERE.zh-CN.md").read_text(encoding="utf-8-sig") self.assertIn("PROGRAM_SRAM", start_here) self.assertIn(f"-Profile {profile}", start_here) self.assertIn(f".\\bitstreams\\{bitstream.name}", start_here) self.assertIn(f".\\td-receipts\\{td_receipt.name}", start_here) self.assertIn( ".\\collector\\collect-j6-host-sensor-real-fan-ptc.ps1 -HostPort COM8 -DebugPort COM7", start_here, ) self.assertNotIn("blocked_pin_conflict_with_locked_debug_uart", start_here) manifest = json.loads((stage / "manifest.json").read_text(encoding="utf-8-sig")) self.assertEqual(manifest["status"], "pass") self.assertEqual(manifest["pin_profile"], profile) self.assertEqual(manifest["programming_mode"], "PROGRAM_SRAM") self.assertIn("host_control_commands", manifest) self.assertIn("pin_map", manifest) self.assertNotIn("pin_conflicts", manifest) inventory = json.loads((stage / "sha256-inventory.json").read_text(encoding="utf-8-sig")) self.assertEqual(inventory["self_hash_policy"], "excluded_self_referential_file") inventory_paths = {item["path"] for item in inventory["inventory"]} self.assertIn("manifest.json", inventory_paths) self.assertIn("START-HERE.zh-CN.md", inventory_paths) self.assertIn("collector/collect-j6-host-sensor-real-fan-ptc.ps1", inventory_paths) self.assertIn("commands/collect-template.ps1", inventory_paths) self.assertNotIn("sha256-inventory.json", inventory_paths) def test_j6_host_sensor_real_fan_ptc_runbook_is_chinese_copy_paste_ready_with_english_paths(self) -> None: runbook = (ROOT / "docs" / "j6-host-sensor-real-fan-ptc-debug921-runbook.zh-CN.md").read_text( encoding="utf-8" ) for marker in [ "J6 Host Sensor Real FAN/PTC Debug921", "START-HERE.zh-CN.md", "temp-uart-ptc-remap", "formal-uart", "PROGRAM_SRAM", "COM8", "COM7", "PTC03", "PTC04", "PTC17", "PTC18", "PTC21", "PTC22", "SET PTC 01 10", "SET PTC 24 20", "SET FAN 01 40", "SET FAN 04 30", "SET PID ENABLE", "GET SENSOR", "SET PID DISABLE", "DISABLE", "PTCCH", "FANCH", "1-based", "SENS", "DIMM", "J6TEMP", "J6RAW", "host-port-escaped.txt", "debug-uart-escaped.txt", "host-sensor-report.json", "bmc-raw-replay.bin", "不安装驱动", "不枚举未知 COM", "不写 DebugPort", ]: self.assertIn(marker, runbook) for forbidden in [ "debug115", "Manual SRAM attestation status must be pass", "blocked_edit_required", "blocked_pin_conflict_with_locked_debug_uart", "当前不要刷机", "Set-ExecutionPolicy -Scope Process -ExecutionPolicy Bypass -Force", r".\commands\collect-com8-host-com7-debug.ps1", r"bitstreams\uart_rs232_j6_host_sensor_real_fan_ptc_debug921_primary.bit", "collector/collect-j6-host-sensor-real-fan-ptc.ps1", "SET PTC 00", "SET FAN 00", "SET FAN 05", "SET FAN 06", r".\collector\采集", ]: self.assertNotIn(forbidden, runbook) def test_j6_host_sensor_real_fan_ptc_schema_requires_sensor_pwm_pid_pinmap_and_debug_artifacts(self) -> None: schema = json.loads( (ROOT / "schemas" / "real_bmc_j6_host_sensor_real_fan_ptc_debug921_v1_receipt.schema.json").read_text( encoding="utf-8" ) ) layers = schema["properties"]["layers"]["properties"] self.assertEqual(schema["properties"]["diagnostic_scope"], {"const": "host_sensor_real_fan_ptc_debug921"}) for layer in [ "host_command_sequence", "host_control_transcript", "host_sensor_reports", "debug_frame_capture", "bmc_raw_sampling", "pid_boundary", "timeout_evidence", "pin_map", "real_fan_ptc_hardware_status", "artifact_hashes", ]: self.assertIn(layer, layers) commands = layers["host_command_sequence"]["properties"]["commands"]["prefixItems"] self.assertEqual(commands[0], {"const": "SET PTC 01 10"}) self.assertEqual(commands[1], {"const": "SET PTC 24 20"}) self.assertEqual(commands[2], {"const": "SET FAN 01 40"}) self.assertEqual(commands[3], {"const": "SET FAN 04 30"}) self.assertIn("host_sensor_report", layers["host_sensor_reports"]["required"]) self.assertIn("debug_frame_stream", layers["debug_frame_capture"]["required"]) self.assertIn("raw_replay", layers["debug_frame_capture"]["required"]) self.assertEqual(layers["pin_map"]["properties"]["ptc_count"], {"const": 24}) self.assertEqual(layers["pin_map"]["properties"]["fan_count"], {"const": 4}) if __name__ == "__main__": unittest.main()