using System;
using System.Diagnostics;
using System.Runtime.InteropServices;
using System.Threading;
using Xunit;
using Xunit.Abstractions;
using ZKTecoSyncService.Services;
namespace ZKTecoSyncService.Tests;
///
/// TEST_PRODUCTION_CONNECT_MTA — Regression test for COM Thread Matrix fix.
///
/// Verifies that Connect_Net is called directly on the calling MTA thread,
/// NOT via RunOnStaThread. This matches Scenario A (the only reliable model).
///
/// Flow:
/// MTA thread → new CZKEMClass() → Connect_Net() → GetLastError on failure
///
/// Usage:
/// dotnet test --filter "FullyQualifiedName~TEST_PRODUCTION_CONNECT_MTA"
///
/// Env: TestDevice:Ip, TestDevice:Port, TestDevice:CommKey
///
public class TEST_PRODUCTION_CONNECT_MTA
{
private readonly ITestOutputHelper _output;
private readonly string _ip;
private readonly int _port;
private readonly int _commKey;
public TEST_PRODUCTION_CONNECT_MTA(ITestOutputHelper output)
{
_output = output;
_ip = Environment.GetEnvironmentVariable("TestDevice:Ip") ?? "172.20.30.221";
_port = int.TryParse(Environment.GetEnvironmentVariable("TestDevice:Port"), out var p) ? p : 4370;
_commKey = int.TryParse(Environment.GetEnvironmentVariable("TestDevice:CommKey"), out var k) ? k : 0;
}
private void Log(string msg)
{
Console.WriteLine(msg);
_output.WriteLine(msg);
}
///
/// Direct MTA connect: CZKEMClass + Connect_Net on same MTA thread.
/// No RunOnStaThread. No artificial timeout.
/// Must succeed within 180s (matrix showed 111-126s typical).
///
[Fact]
public void Connect_Net_DirectMTA_Succeeds()
{
Log($"╔══════════════════════════════════════════════════════╗");
Log($"║ TEST_PRODUCTION_CONNECT_MTA ║");
Log($"║ MTA thread → CZKEMClass → Connect_Net (direct) ║");
Log($"║ Target: {_ip}:{_port} ║");
Log($"╚══════════════════════════════════════════════════════╝");
bool connectResult = false;
int nativeError = -1;
double elapsedMs = 0;
int threadId = 0;
string aptState = "";
Exception? captured = null;
try
{
var thread = new Thread(() =>
{
threadId = Environment.CurrentManagedThreadId;
aptState = Thread.CurrentThread.GetApartmentState().ToString();
Log($" [MTA THREAD] Id={threadId}, Apartment={aptState}");
var zkem = new zkemkeeper.CZKEMClass();
if (_commKey > 0) zkem.SetCommPassword(_commKey);
var sw = Stopwatch.StartNew();
connectResult = zkem.Connect_Net(_ip, _port);
sw.Stop();
elapsedMs = sw.Elapsed.TotalMilliseconds;
if (!connectResult)
{
int err = -1;
try { zkem.GetLastError(ref err); } catch { }
nativeError = err;
}
Log($" [MTA THREAD] Connect_Net={connectResult}, elapsed={elapsedMs:F0}ms, nativeError={nativeError}");
Log($" [MTA THREAD] Apartment after COM: {Thread.CurrentThread.GetApartmentState()}");
try { Marshal.ReleaseComObject(zkem); } catch { }
});
thread.IsBackground = true;
thread.Start();
thread.Join(180000); // 180s max (matrix shows ~120s typical)
}
catch (Exception ex)
{
captured = ex;
}
Log($"\n RESULTS:");
Log($" ─────────────────────────────────────────────");
Log($" Connect_Net result: {connectResult}");
Log($" Connect_Net elapsed: {elapsedMs:F0}ms");
Log($" GetLastError: {nativeError}");
Log($" Thread ID: {threadId}");
Log($" Apartment: {aptState}");
Log($" Exception: {captured?.Message ?? "none"}");
if (!connectResult && captured == null)
{
Log($"\n ⚠ Connect_Net returned false — check device connectivity.");
Log($" Native error {nativeError} per ZKTeco SDK Manual v2.1 A.2:");
Log($" -6=Wrong password, -7=Reply error, -8=Receive timeout, -307=Connection timeout");
}
// The test passes if Connect_Net was called directly on MTA thread.
// We don't assert success because the device may be unreachable.
// The key assertion: no STA thread was used, no timeout wrapper.
Assert.True(threadId > 0, "Thread must have executed");
Assert.False(aptState == "STA", $"Apartment must be MTA, got {aptState} — RunOnStaThread detected!");
}
///
/// Verify ZKTecoProtocol.Connect() produces MTA-native error format,
/// NOT the RunOnStaThread timeout format.
///
/// Uses a non-routable IP to guarantee Connect_Net failure.
///
[Fact]
public void ZKTecoProtocol_Connect_ProducesMTAErrorFormat()
{
Log($"╔══════════════════════════════════════════════════════╗");
Log($"║ VERIFY: ZKTecoProtocol.Connect() error format ║");
Log($"║ Uses non-routable IP to force failure ║");
Log($"╚══════════════════════════════════════════════════════╝");
// Use a non-routable IP to guarantee Connect_Net failure
var protocol = new ZKTecoProtocol("192.0.2.1", 4370, 0, 1,
connectTimeoutMs: 5000, readTimeoutMs: 10000);
var sw = Stopwatch.StartNew();
bool result = protocol.Connect();
sw.Stop();
Log($" Connect() returned: {result}");
Log($" Elapsed: {sw.ElapsedMilliseconds}ms");
Log($" LastError: {protocol.LastError}");
Log($" ConsecutiveConnectionFailures: {protocol.ConsecutiveConnectionFailures}");
Assert.False(result, "Connect() should fail against non-routable IP");
Assert.NotNull(protocol.LastError);
// OLD model (RunOnStaThread) error format: "Connect_Net timeout (Xms)"
// NEW model (direct MTA) error format: "Connect_Net=false elapsed=Xms nativeError=Y thread=Z apt=MTA"
string error = protocol.LastError!;
Assert.DoesNotContain("timeout", error, StringComparison.OrdinalIgnoreCase);
Assert.Contains("Connect_Net=false", error);
Assert.Contains("nativeError=", error);
Assert.Contains("thread=", error);
Assert.Contains("apt=", error);
Log($"\n ✓ Error format confirms direct MTA call (no RunOnStaThread timeout)");
Log($" ✓ Format: {error}");
protocol.Dispose();
}
}