using System; using System.Collections.Generic; using System.Diagnostics; using System.Runtime.InteropServices; using System.Threading; using Xunit; namespace ZKTecoSyncService.Tests; /// /// Recovery Boundary Tests — TEST3 / TEST4 / TEST5 /// /// Determines which recovery boundary restores ZK reader functionality: /// TEST3: Same CZKEMClass instance Disconnect/Connect /// TEST4: Dispose/Recreate CZKEMClass (same process) /// TEST5: Fresh child process (new COM runtime) /// /// Device: 172.20.30.220 (default, configurable via TestDevice:Ip) /// /// Usage: /// dotnet test --filter "FullyQualifiedName~TEST3_RecoveryBoundary" /// dotnet test --filter "FullyQualifiedName~TEST3_RecoveryBoundary.Test3" /// dotnet test --filter "FullyQualifiedName~TEST3_RecoveryBoundary.Test4" /// dotnet test --filter "FullyQualifiedName~TEST3_RecoveryBoundary.Test5" /// dotnet test --filter "FullyQualifiedName~TEST3_RecoveryBoundary.RunAll" /// /// Env: TestDevice:Ip (colon separator), TestDevice:Port, TestDevice:CommKey, TestDevice:MachineNumber /// public class TEST3_RecoveryBoundary { private readonly string _ip; private readonly int _port; private readonly int _commKey; private readonly int _machine; public TEST3_RecoveryBoundary() { _ip = Environment.GetEnvironmentVariable("TestDevice:Ip") ?? "172.20.30.220"; _port = int.TryParse(Environment.GetEnvironmentVariable("TestDevice:Port"), out var p) ? p : 4370; _commKey = int.TryParse(Environment.GetEnvironmentVariable("TestDevice:CommKey"), out var k) ? k : 0; _machine = int.TryParse(Environment.GetEnvironmentVariable("TestDevice:MachineNumber"), out var m) ? m : 1; } // ─── Shared helpers ──────────────────────────────────────────────── private static int GetError(zkemkeeper.CZKEMClass zkem) { int err = -999; zkem.GetLastError(ref err); return err; } private static int EnumerateSSR(zkemkeeper.CZKEMClass zkem, int machine, int maxRecords = 100000) { string enroll = ""; int vm = 0, io = 0, y = 0, m = 0, d = 0, h = 0, mi = 0, s = 0, wc = 0; int count = 0; while (count < maxRecords && zkem.SSR_GetGeneralLogData(machine, out enroll, out vm, out io, out y, out m, out d, out h, out mi, out s, ref wc)) count++; return count; } private static void LogStep(string label, bool result, long ms, int getLastError, string extra = "") { var status = result ? "OK" : "FAIL"; var err = getLastError == -999 ? "" : $" GetLastError={getLastError}"; Console.WriteLine($" [{label}] {status} {ms}ms{err}{(extra.Length > 0 ? " " + extra : "")}"); } // ═══════════════════════════════════════════════════════════════════ // TEST 3 — Same CZKEM instance reconnect // // 1. Create COM → Connect → ReadGeneralLogData → SSR → Count-A // 2. Disconnect (same instance, no Dispose) // 3. Connect_Net again on same instance // 4. ReadGeneralLogData → SSR → Count-B // // EXPECTED: Connect both TRUE, Count-A > 0, Count-B > 0, close // ═══════════════════════════════════════════════════════════════════ [Fact] public void Test3() { Console.WriteLine($"TEST3: Same CZKEM Instance Reconnect | Device: {_ip}:{_port}"); Console.WriteLine($"THREAD: id={Environment.CurrentManagedThreadId} apartment={Thread.CurrentThread.GetApartmentState()}\n"); int countA = -1, countB = -1; bool connectA = false, connectB = false; bool readA = false, readB = false; int errA = -999, errB = -999; long msConnectA = 0, msReadA = 0, msSsrA = 0; long msConnectB = 0, msReadB = 0, msSsrB = 0; zkemkeeper.CZKEMClass? zkem = null; try { zkem = new zkemkeeper.CZKEMClass(); if (_commKey > 0) zkem.SetCommPassword(_commKey); // ─── SESSION A ─── Console.WriteLine("─── SESSION A: Initial Connect ───"); var sw = Stopwatch.StartNew(); connectA = zkem.Connect_Net(_ip, _port); sw.Stop(); msConnectA = sw.ElapsedMilliseconds; Console.WriteLine($" [Connect_A] {(connectA ? "OK" : "FAIL")} {msConnectA}ms thread={Environment.CurrentManagedThreadId}({Thread.CurrentThread.GetApartmentState()})"); if (!connectA) { Console.WriteLine($"\nFAIL connect_a\n"); return; } int lcA = 0; zkem.GetDeviceStatus(_machine, 6, ref lcA); Console.WriteLine($" [GetLogCount_A] count={lcA}"); sw.Restart(); readA = zkem.ReadGeneralLogData(_machine); sw.Stop(); msReadA = sw.ElapsedMilliseconds; errA = GetError(zkem); LogStep("ReadGeneralLogData_A", readA, msReadA, errA); sw.Restart(); countA = readA ? EnumerateSSR(zkem, _machine) : 0; sw.Stop(); msSsrA = sw.ElapsedMilliseconds; Console.WriteLine($" [SSR_A] count={countA} {msSsrA}ms"); Console.WriteLine($"\n SESSION_A SUMMARY: Connect={connectA} LogCount={lcA} Read={readA} SSR={countA}\n"); // ─── DISCONNECT (same instance) ─── Console.WriteLine("─── Disconnect (same instance, no Dispose) ───"); sw.Restart(); zkem.Disconnect(); sw.Stop(); Console.WriteLine($" [Disconnect] OK {sw.ElapsedMilliseconds}ms"); Thread.Sleep(1000); // ─── SESSION B ─── Console.WriteLine("\n─── SESSION B: Reconnect same instance ───"); sw.Restart(); connectB = zkem.Connect_Net(_ip, _port); sw.Stop(); msConnectB = sw.ElapsedMilliseconds; Console.WriteLine($" [Connect_B] {(connectB ? "OK" : "FAIL")} {msConnectB}ms thread={Environment.CurrentManagedThreadId}({Thread.CurrentThread.GetApartmentState()})"); if (!connectB) { Console.WriteLine($"\nFAIL connect_b\n"); Console.WriteLine("SAME_INSTANCE_RECONNECT: FAIL"); return; } int lcB = 0; zkem.GetDeviceStatus(_machine, 6, ref lcB); Console.WriteLine($" [GetLogCount_B] count={lcB}"); sw.Restart(); readB = zkem.ReadGeneralLogData(_machine); sw.Stop(); msReadB = sw.ElapsedMilliseconds; errB = GetError(zkem); LogStep("ReadGeneralLogData_B", readB, msReadB, errB); sw.Restart(); countB = readB ? EnumerateSSR(zkem, _machine) : 0; sw.Stop(); msSsrB = sw.ElapsedMilliseconds; Console.WriteLine($" [SSR_B] count={countB} {msSsrB}ms"); Console.WriteLine($"\n SESSION_B SUMMARY: Connect={connectB} LogCount={lcB} Read={readB} SSR={countB}\n"); } finally { if (zkem != null) { try { Marshal.ReleaseComObject(zkem); } catch { } } } // ─── Verdict ─── bool pass = connectA && connectB && readA && readB && countA > 0 && countB > 0; var verdict = pass ? "PASS" : "FAIL"; Console.WriteLine("═══════════════════════════════════════════════════════"); Console.WriteLine($" TEST3 RESULT: {verdict}"); Console.WriteLine($" Count-A={countA} Count-B={countB}"); Console.WriteLine($" Connect_A={connectA} Connect_B={connectB}"); Console.WriteLine($" Read_A={readA}({errA}) Read_B={readB}({errB})"); Console.WriteLine($" Duration: connect={msConnectA}+{msConnectB}ms read={msReadA}+{msReadB}ms ssr={msSsrA}+{msSsrB}ms"); Console.WriteLine("═══════════════════════════════════════════════════════"); if (countA == 0 && countB == 0 && readA && readB) Console.WriteLine(" NOTE: READ_TRUE_ENUM_ZERO on both sessions"); Assert.True(connectA, "Connect_A failed"); Assert.True(connectB, "Connect_B failed"); Assert.True(countA > 0, $"Count-A={countA}, expected > 0"); Assert.True(countB > 0, $"Count-B={countB}, expected > 0"); } // ═══════════════════════════════════════════════════════════════════ // TEST 4 — Dispose/Recreate COM instance (same process) // // 1. instance-A: Create → Connect → ReadGeneralLogData → SSR → Count-C // 2. Disconnect → Dispose/ReleaseComObject // 3. instance-B: new CZKEMClass → Connect → Read → SSR → Count-D // // EXPECTED: Both sessions succeed, Count-C ≈ Count-D // ═══════════════════════════════════════════════════════════════════ [Fact] public void Test4() { Console.WriteLine($"TEST4: Dispose/Recreate COM Instance | Device: {_ip}:{_port}"); Console.WriteLine($"THREAD: id={Environment.CurrentManagedThreadId} apartment={Thread.CurrentThread.GetApartmentState()}\n"); int countC = -1, countD = -1; bool connectC = false, connectD = false; bool readC = false, readD = false; int errC = -999, errD = -999; long msConnectC = 0, msReadC = 0, msSsrC = 0; long msConnectD = 0, msReadD = 0, msSsrD = 0; zkemkeeper.CZKEMClass? zkemA = null; zkemkeeper.CZKEMClass? zkemB = null; try { // ─── SESSION C: First instance ─── Console.WriteLine("─── SESSION C: First CZKEMClass instance ───"); zkemA = new zkemkeeper.CZKEMClass(); if (_commKey > 0) zkemA.SetCommPassword(_commKey); var sw = Stopwatch.StartNew(); connectC = zkemA.Connect_Net(_ip, _port); sw.Stop(); msConnectC = sw.ElapsedMilliseconds; Console.WriteLine($" [Connect_C] {(connectC ? "OK" : "FAIL")} {msConnectC}ms"); if (!connectC) { Console.WriteLine($"\nFAIL connect_c\n"); return; } int lcC = 0; zkemA.GetDeviceStatus(_machine, 6, ref lcC); Console.WriteLine($" [GetLogCount_C] count={lcC}"); sw.Restart(); readC = zkemA.ReadGeneralLogData(_machine); sw.Stop(); msReadC = sw.ElapsedMilliseconds; errC = GetError(zkemA); LogStep("ReadGeneralLogData_C", readC, msReadC, errC); sw.Restart(); countC = readC ? EnumerateSSR(zkemA, _machine) : 0; sw.Stop(); msSsrC = sw.ElapsedMilliseconds; Console.WriteLine($" [SSR_C] count={countC} {msSsrC}ms"); Console.WriteLine($"\n SESSION_C SUMMARY: Connect={connectC} LogCount={lcC} Read={readC} SSR={countC}\n"); } finally { if (zkemA != null) { Console.WriteLine("─── Dispose instance-A ───"); try { Marshal.ReleaseComObject(zkemA); } catch { } Console.WriteLine(" [Dispose_A] OK"); } } Thread.Sleep(1000); try { // ─── SESSION D: New instance ─── Console.WriteLine("\n─── SESSION D: New CZKEMClass instance ───"); zkemB = new zkemkeeper.CZKEMClass(); if (_commKey > 0) zkemB.SetCommPassword(_commKey); var sw = Stopwatch.StartNew(); connectD = zkemB.Connect_Net(_ip, _port); sw.Stop(); msConnectD = sw.ElapsedMilliseconds; Console.WriteLine($" [Connect_D] {(connectD ? "OK" : "FAIL")} {msConnectD}ms"); if (!connectD) { Console.WriteLine($"\nFAIL connect_d\n"); Console.WriteLine("COM_RECREATE: FAIL"); return; } int lcD = 0; zkemB.GetDeviceStatus(_machine, 6, ref lcD); Console.WriteLine($" [GetLogCount_D] count={lcD}"); sw.Restart(); readD = zkemB.ReadGeneralLogData(_machine); sw.Stop(); msReadD = sw.ElapsedMilliseconds; errD = GetError(zkemB); LogStep("ReadGeneralLogData_D", readD, msReadD, errD); sw.Restart(); countD = readD ? EnumerateSSR(zkemB, _machine) : 0; sw.Stop(); msSsrD = sw.ElapsedMilliseconds; Console.WriteLine($" [SSR_D] count={countD} {msSsrD}ms"); Console.WriteLine($"\n SESSION_D SUMMARY: Connect={connectD} LogCount={lcD} Read={readD} SSR={countD}\n"); } finally { if (zkemB != null) { try { Marshal.ReleaseComObject(zkemB); } catch { } } } // ─── Verdict ─── bool pass = connectC && connectD && readC && readD && countC > 0 && countD > 0; var verdict = pass ? "PASS" : "FAIL"; Console.WriteLine("═══════════════════════════════════════════════════════"); Console.WriteLine($" TEST4 RESULT: {verdict}"); Console.WriteLine($" Count-C={countC} Count-D={countD}"); Console.WriteLine($" Connect_C={connectC} Connect_D={connectD}"); Console.WriteLine($" Read_C={readC}({errC}) Read_D={readD}({errD})"); Console.WriteLine($" Duration: connect={msConnectC}+{msConnectD}ms read={msReadC}+{msReadD}ms ssr={msSsrC}+{msSsrD}ms"); Console.WriteLine("═══════════════════════════════════════════════════════"); if (countC == 0 && countD == 0 && readC && readD) Console.WriteLine(" NOTE: READ_TRUE_ENUM_ZERO on both sessions"); Assert.True(connectC, "Connect_C failed"); Assert.True(connectD, "Connect_D failed"); Assert.True(countC > 0, $"Count-C={countC}, expected > 0"); Assert.True(countD > 0, $"Count-D={countD}, expected > 0"); } // ═══════════════════════════════════════════════════════════════════ // TEST 5 — Fresh Process (new COM runtime) // // Spawns tools/FreshProcessTest as a child process. // Verifies that a completely new process can enumerate records. // ═══════════════════════════════════════════════════════════════════ [Fact] public void Test5() { Console.WriteLine($"TEST5: Fresh Process | Device: {_ip}:{_port}\n"); // Locate the pre-built helper exe var testBinDir = AppContext.BaseDirectory; var helperDir = Path.Combine( Directory.GetParent(Directory.GetParent(Directory.GetParent(testBinDir)!.FullName)!.FullName)!.FullName, "ZKTecoSyncService.Tests", "tools", "FreshProcessTest", "bin", "Debug", "net10.0"); var helperExe = Path.Combine(helperDir, "FreshProcessTest.exe"); var fallbackHelperDir = Path.Combine( Directory.GetParent(testBinDir)!.FullName, "ZKTecoSyncService.Tests", "tools", "FreshProcessTest", "bin", "Debug", "net10.0"); var fallbackExe = Path.Combine(fallbackHelperDir, "FreshProcessTest.exe"); if (!File.Exists(helperExe) && File.Exists(fallbackExe)) helperExe = fallbackExe; if (!File.Exists(helperExe)) { Console.WriteLine($" Helper exe not found at: {helperExe}"); Console.WriteLine(" Building helper..."); BuildHelper(); if (!File.Exists(helperExe)) { Console.WriteLine($" Still not found after build. Skipping."); Console.WriteLine("FRESH_PROCESS_COUNT=-1"); Console.WriteLine("TEST5_FRESH_PROCESS=FAIL"); return; } } Console.WriteLine($" Helper: {helperExe}"); var args = $"{_ip} {_port} {_commKey}"; Console.WriteLine($" Spawning: {helperExe} {args}\n"); var sw = Stopwatch.StartNew(); var (exitCode, stdout) = RunProcess(helperExe, args, timeoutMs: 30000); sw.Stop(); Console.WriteLine(" ─── Child Process Output ───"); foreach (var line in stdout.Split('\n')) Console.WriteLine($" | {line}"); Console.WriteLine($" ─── End (exit={exitCode}, {sw.ElapsedMilliseconds}ms) ───\n"); // Parse result int freshCount = -1; bool freshPass = false; foreach (var line in stdout.Split('\n')) { if (line.StartsWith("SSR_COUNT=")) { var val = line.Split('=')[1].Split(' ')[0]; int.TryParse(val, out freshCount); } if (line.Trim() == "PASS") freshPass = true; } Console.WriteLine($" FRESH_PROCESS_COUNT={freshCount}"); Console.WriteLine($" TEST5_FRESH_PROCESS: {(freshPass ? "PASS" : "FAIL")}"); Assert.True(freshPass, $"Fresh process returned FAIL (exit={exitCode})"); } private static void BuildHelper() { var testDir = Path.GetDirectoryName(typeof(TEST3_RecoveryBoundary).Assembly.Location)!; var helperProj = Path.Combine( Directory.GetParent(Directory.GetParent(Directory.GetParent(testDir)!.FullName)!.FullName)!.FullName, "ZKTecoSyncService.Tests", "tools", "FreshProcessTest", "FreshProcessTest.csproj"); if (!File.Exists(helperProj)) { // Try relative to workspace helperProj = Path.Combine(AppContext.BaseDirectory, "..", "..", "..", "..", "ZKTecoSyncService.Tests", "tools", "FreshProcessTest", "FreshProcessTest.csproj"); } if (!File.Exists(helperProj)) { Console.WriteLine($" Helper project not found: {helperProj}"); return; } Console.WriteLine($" Building: {helperProj}"); var (exitCode, output) = RunProcess("dotnet", $"build \"{helperProj}\" -c Debug --nologo -v q", timeoutMs: 60000); Console.WriteLine($" Build exit={exitCode}"); if (exitCode != 0) { foreach (var line in output.Split('\n').Where(l => l.Contains("error") || l.Contains("Error"))) Console.WriteLine($" {line}"); } } private static (int exitCode, string stdout) RunProcess(string fileName, string arguments, int timeoutMs = 30000) { try { var psi = new ProcessStartInfo { FileName = fileName, Arguments = arguments, RedirectStandardOutput = true, RedirectStandardError = true, UseShellExecute = false, CreateNoWindow = true, }; using var proc = Process.Start(psi)!; var stdout = proc.StandardOutput.ReadToEnd(); var stderr = proc.StandardError.ReadToEnd(); bool exited = proc.WaitForExit(timeoutMs); if (!exited) { try { proc.Kill(); } catch { } return (-1, stdout + "\nSTDERR: " + stderr); } return (proc.ExitCode, stdout); } catch (Exception ex) { return (-2, $"EXCEPTION: {ex.Message}"); } } // ═══════════════════════════════════════════════════════════════════ // RunAll — runs all three tests sequentially for summary // ═══════════════════════════════════════════════════════════════════ [Fact] public void RunAll() { Console.WriteLine($"RECOVERY BOUNDARY TEST SUITE | Device: {_ip}:{_port}\n"); int countA = -1, countB = -1, countC = -1, countD = -1; int freshCount = -1; bool test3Pass = false, test4Pass = false, test5Pass = false; // ─── TEST 3: Same instance reconnect ─── Console.WriteLine("╔══════════════════════════════════════════════════════╗"); Console.WriteLine("║ TEST3: Same CZKEM Instance Reconnect ║"); Console.WriteLine("╚══════════════════════════════════════════════════════╝\n"); zkemkeeper.CZKEMClass? zkem3 = null; try { zkem3 = new zkemkeeper.CZKEMClass(); if (_commKey > 0) zkem3.SetCommPassword(_commKey); var sw = Stopwatch.StartNew(); bool connectA = zkem3.Connect_Net(_ip, _port); sw.Stop(); Console.WriteLine($" [Connect_A] {(connectA ? "OK" : "FAIL")} {sw.ElapsedMilliseconds}ms"); if (!connectA) { Console.WriteLine(" TEST3: FAIL (connect_a)\n"); goto TEST4; } sw.Restart(); bool readA = zkem3.ReadGeneralLogData(_machine); sw.Stop(); int errA = GetError(zkem3); Console.WriteLine($" [Read_A] {(readA ? "OK" : "FAIL")} {sw.ElapsedMilliseconds}ms GetLastError={errA}"); sw.Restart(); countA = readA ? EnumerateSSR(zkem3, _machine) : 0; sw.Stop(); Console.WriteLine($" [SSR_A] count={countA} {sw.ElapsedMilliseconds}ms"); if (!readA && countA == 0) Console.WriteLine(" NOTE: READ_TRUE_ENUM_ZERO"); zkem3.Disconnect(); Thread.Sleep(1000); Console.WriteLine(" [Disconnect] OK"); sw.Restart(); bool connectB = zkem3.Connect_Net(_ip, _port); sw.Stop(); Console.WriteLine($" [Connect_B] {(connectB ? "OK" : "FAIL")} {sw.ElapsedMilliseconds}ms"); if (!connectB) { Console.WriteLine(" TEST3: FAIL (connect_b)\n"); goto TEST4; } sw.Restart(); bool readB = zkem3.ReadGeneralLogData(_machine); sw.Stop(); int errB = GetError(zkem3); Console.WriteLine($" [Read_B] {(readB ? "OK" : "FAIL")} {sw.ElapsedMilliseconds}ms GetLastError={errB}"); sw.Restart(); countB = readB ? EnumerateSSR(zkem3, _machine) : 0; sw.Stop(); Console.WriteLine($" [SSR_B] count={countB} {sw.ElapsedMilliseconds}ms"); if (!readB && countB == 0) Console.WriteLine(" NOTE: READ_TRUE_ENUM_ZERO"); test3Pass = connectA && connectB && readA && readB && countA > 0 && countB > 0; Console.WriteLine($"\n TEST3: {(test3Pass ? "PASS" : "FAIL")} Count-A={countA} Count-B={countB}\n"); } finally { if (zkem3 != null) { try { Marshal.ReleaseComObject(zkem3); } catch { } } } TEST4: // ─── TEST 4: Dispose/Recreate ─── Console.WriteLine("╔══════════════════════════════════════════════════════╗"); Console.WriteLine("║ TEST4: Dispose/Recreate COM Instance ║"); Console.WriteLine("╚══════════════════════════════════════════════════════╝\n"); zkemkeeper.CZKEMClass? zkem4a = null; zkemkeeper.CZKEMClass? zkem4b = null; bool connectC = false, readC = false, connectD = false, readD = false; try { zkem4a = new zkemkeeper.CZKEMClass(); if (_commKey > 0) zkem4a.SetCommPassword(_commKey); var sw = Stopwatch.StartNew(); connectC = zkem4a.Connect_Net(_ip, _port); sw.Stop(); Console.WriteLine($" [Connect_C] {(connectC ? "OK" : "FAIL")} {sw.ElapsedMilliseconds}ms"); if (!connectC) { Console.WriteLine(" TEST4: FAIL (connect_c)\n"); goto TEST5; } sw.Restart(); readC = zkem4a.ReadGeneralLogData(_machine); sw.Stop(); int errC = GetError(zkem4a); Console.WriteLine($" [Read_C] {(readC ? "OK" : "FAIL")} {sw.ElapsedMilliseconds}ms GetLastError={errC}"); sw.Restart(); countC = readC ? EnumerateSSR(zkem4a, _machine) : 0; sw.Stop(); Console.WriteLine($" [SSR_C] count={countC} {sw.ElapsedMilliseconds}ms"); if (!readC && countC == 0) Console.WriteLine(" NOTE: READ_TRUE_ENUM_ZERO"); } finally { if (zkem4a != null) { try { Marshal.ReleaseComObject(zkem4a); } catch { } Console.WriteLine(" [Dispose_A] OK"); } } Thread.Sleep(1000); try { zkem4b = new zkemkeeper.CZKEMClass(); if (_commKey > 0) zkem4b.SetCommPassword(_commKey); var sw = Stopwatch.StartNew(); connectD = zkem4b.Connect_Net(_ip, _port); sw.Stop(); Console.WriteLine($" [Connect_D] {(connectD ? "OK" : "FAIL")} {sw.ElapsedMilliseconds}ms"); if (!connectD) { Console.WriteLine(" TEST4: FAIL (connect_d)\n"); goto TEST5; } sw.Restart(); readD = zkem4b.ReadGeneralLogData(_machine); sw.Stop(); int errD = GetError(zkem4b); Console.WriteLine($" [Read_D] {(readD ? "OK" : "FAIL")} {sw.ElapsedMilliseconds}ms GetLastError={errD}"); sw.Restart(); countD = readD ? EnumerateSSR(zkem4b, _machine) : 0; sw.Stop(); Console.WriteLine($" [SSR_D] count={countD} {sw.ElapsedMilliseconds}ms"); if (!readD && countD == 0) Console.WriteLine(" NOTE: READ_TRUE_ENUM_ZERO"); test4Pass = connectC && connectD && readC && readD && countC > 0 && countD > 0; Console.WriteLine($"\n TEST4: {(test4Pass ? "PASS" : "FAIL")} Count-C={countC} Count-D={countD}\n"); } finally { if (zkem4b != null) { try { Marshal.ReleaseComObject(zkem4b); } catch { } } } TEST5: // ─── TEST 5: Fresh Process ─── Console.WriteLine("╔══════════════════════════════════════════════════════╗"); Console.WriteLine("║ TEST5: Fresh Process (new COM runtime) ║"); Console.WriteLine("╚══════════════════════════════════════════════════════╝\n"); { var testBinDir = AppContext.BaseDirectory; var candidatePaths = new[] { Path.Combine(testBinDir, "..", "..", "..", "..", "ZKTecoSyncService.Tests", "tools", "FreshProcessTest", "bin", "Debug", "net10.0", "FreshProcessTest.exe"), Path.Combine(testBinDir, "tools", "FreshProcessTest", "bin", "Debug", "net10.0", "FreshProcessTest.exe"), }; string? helperExe = null; foreach (var c in candidatePaths) { var full = Path.GetFullPath(c); if (File.Exists(full)) { helperExe = full; break; } } if (helperExe == null) { Console.WriteLine(" Building helper..."); BuildHelper(); foreach (var c in candidatePaths) { var full = Path.GetFullPath(c); if (File.Exists(full)) { helperExe = full; break; } } } if (helperExe == null) { Console.WriteLine(" Helper exe not found. Skipping."); freshCount = -1; test5Pass = false; goto SUMMARY; } Console.WriteLine($" Helper: {helperExe}"); var args = $"{_ip} {_port} {_commKey}"; Console.WriteLine($" Spawning: {Path.GetFileName(helperExe)} {args}\n"); var sw = Stopwatch.StartNew(); var (exitCode, stdout) = RunProcess(helperExe, args, timeoutMs: 30000); sw.Stop(); Console.WriteLine(" ─── Child Process Output ───"); foreach (var line in stdout.Split('\n')) Console.WriteLine($" | {line}"); Console.WriteLine($" ─── End (exit={exitCode}, {sw.ElapsedMilliseconds}ms) ───\n"); foreach (var line in stdout.Split('\n')) { if (line.StartsWith("SSR_COUNT=")) { var val = line.Split('=')[1].Split(' ')[0]; int.TryParse(val, out freshCount); } if (line.Trim() == "PASS") test5Pass = true; } Console.WriteLine($" FRESH_PROCESS_COUNT={freshCount}"); Console.WriteLine($" TEST5: {(test5Pass ? "PASS" : "FAIL")}\n"); } SUMMARY: // ─── Final Summary ─── string recoveryBoundary; if (test3Pass && test4Pass && test5Pass) recoveryBoundary = "SAME_INSTANCE_RECONNECT (all pass — weakest boundary suffices)"; else if (!test3Pass && test4Pass && test5Pass) recoveryBoundary = "COM_RECREATE"; else if (!test3Pass && !test4Pass && test5Pass) recoveryBoundary = "FRESH_PROCESS"; else if (!test3Pass && !test4Pass && !test5Pass) recoveryBoundary = "NONE (all fail — device or network issue)"; else recoveryBoundary = "MIXED (unexpected combination)"; Console.WriteLine("═══════════════════════════════════════════════════════"); Console.WriteLine(" RECOVERY BOUNDARY SUMMARY"); Console.WriteLine("═══════════════════════════════════════════════════════"); Console.WriteLine($"DEVICE={_ip}"); Console.WriteLine($"COUNT_A={countA}"); Console.WriteLine($"COUNT_B={countB}"); Console.WriteLine($"COUNT_C={countC}"); Console.WriteLine($"COUNT_D={countD}"); Console.WriteLine($"FRESH_PROCESS_COUNT={freshCount}"); Console.WriteLine(); Console.WriteLine($"TEST3_SAME_INSTANCE_RECONNECT={(test3Pass ? "PASS" : "FAIL")}"); Console.WriteLine($"TEST4_COM_RECREATE={(test4Pass ? "PASS" : "FAIL")}"); Console.WriteLine($"TEST5_FRESH_PROCESS={(test5Pass ? "PASS" : "FAIL")}"); Console.WriteLine(); Console.WriteLine($"RECOVERY_BOUNDARY={recoveryBoundary}"); Console.WriteLine("═══════════════════════════════════════════════════════"); Assert.True(test3Pass || test4Pass || test5Pass, "All recovery methods failed — device may be unreachable"); } }