junction/tests/Junction.Tests/Unit/PollingEngineTests.cs
dtrentin 507753f82e init: scaffold Junction multi-protocol machine monitor (M1 walking skeleton)
Greenfield C# app reading industrial machine data over pluggable protocols.
M1 walking skeleton: MTConnect plugin polls a machine, Avalonia dashboard
shows live last datum. Build 0 warn/0 err on net48 + net8.0 (Linux),
115 unit tests + 2 docker-gated integration tests.

Projects:
- Junction.Domain (netstandard2.0): Result<T>, models, IProtocolDriver,
  IMachineRepository, plugin manifest. Zero package deps.
- Junction.Core (netstandard2.0): PollingEngine, PluginLoader
  (Assembly.LoadFrom), MachineMonitor, DI extensions.
- Junction.Persistence (netstandard2.0): SqliteMachineRepository (Dapper),
  schema, connection factory. Provider-swap seam to SQL Server.
- Junction.Protocols.MTConnect (netstandard2.0): HTTP driver + namespace-
  version-agnostic parser (MTConnect 1.7 + 2.0). Runtime plugin.
- Junction.App (net48;net8.0): Avalonia MVVM, live dashboard, NLog, DI root.
- Junction.Tests (net8.0): xUnit + Moq, 117 tests.
- mock/: docker-compose MTConnect agent (ladder99/agent).

Target net48 for Windows 7/8 fleet compatibility. Avalonia pinned 11.3.x.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-07-21 23:32:56 +02:00

166 lines
5.9 KiB
C#

using System;
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
using Junction.Core.Polling;
using Junction.Domain;
using Junction.Domain.Models;
using Junction.Domain.Protocols;
using Microsoft.Extensions.Logging.Abstractions;
using Xunit;
namespace Junction.Tests.Unit
{
/// <summary>
/// Behavior tests for <see cref="PollingEngine"/> using a hand-rolled fake driver.
/// Timings are deliberately generous to avoid CI flake.
/// </summary>
public class PollingEngineTests
{
private static PollingEngine NewEngine() =>
new PollingEngine(NullLogger<PollingEngine>.Instance);
private static Machine MachineWithInterval(TimeSpan interval) =>
new Machine(Guid.NewGuid(), "M1", "fake", null, interval);
private static MachineSnapshot Snapshot(Guid machineId) =>
new MachineSnapshot(
machineId,
DateTimeOffset.UtcNow,
ConnectionState.Connected,
Array.Empty<DataItem>());
[Fact]
public async Task RunAsync_PollsRepeatedly_OverShortInterval()
{
var machine = MachineWithInterval(TimeSpan.FromMilliseconds(25));
var driver = new FakeDriver(m => Result<MachineSnapshot>.Ok(Snapshot(machine.Id)));
int count = 0;
using var cts = new CancellationTokenSource();
var loop = NewEngine().RunAsync(machine, driver, _ => Interlocked.Increment(ref count), cts.Token);
await Task.Delay(200);
cts.Cancel();
await loop;
Assert.True(count >= 2, $"expected >= 2 polls, got {count}");
}
[Fact]
public async Task RunAsync_Cancellation_StopsLoop_NoException()
{
var machine = MachineWithInterval(TimeSpan.FromMilliseconds(20));
var driver = new FakeDriver(m => Result<MachineSnapshot>.Ok(Snapshot(machine.Id)));
using var cts = new CancellationTokenSource();
var loop = NewEngine().RunAsync(machine, driver, _ => { }, cts.Token);
await Task.Delay(60);
cts.Cancel();
// Must complete promptly and without propagating any exception.
var completed = await Task.WhenAny(loop, Task.Delay(1000)) == loop;
Assert.True(completed, "loop did not stop promptly after cancellation");
await loop; // would rethrow if it faulted
Assert.True(loop.IsCompletedSuccessfully);
}
[Fact]
public async Task RunAsync_DriverFail_DoesNotEmit_AndKeepsLooping()
{
var machine = MachineWithInterval(TimeSpan.FromMilliseconds(25));
int calls = 0;
var emitted = new List<MachineSnapshot>();
// Fail on cycle 1, succeed thereafter. Proves the loop survives a fault.
var driver = new FakeDriver(m =>
{
int c = Interlocked.Increment(ref calls);
if (c == 1)
{
return Result<MachineSnapshot>.Fail(OperationError.Of("fake", "boom"));
}
return Result<MachineSnapshot>.Ok(Snapshot(machine.Id));
});
using var cts = new CancellationTokenSource();
var loop = NewEngine().RunAsync(machine, driver, s =>
{
lock (emitted) { emitted.Add(s); }
}, cts.Token);
await Task.Delay(200);
cts.Cancel();
await loop;
Assert.True(calls >= 2, $"expected loop to continue past the failed cycle, calls={calls}");
lock (emitted)
{
// First (failed) cycle emitted nothing; a later Ok cycle did.
Assert.NotEmpty(emitted);
Assert.True(emitted.Count < calls, "a failed cycle must not have emitted a snapshot");
}
}
[Fact]
public async Task RunAsync_Ok_ForwardsSnapshotIntact()
{
var machine = MachineWithInterval(TimeSpan.FromMilliseconds(20));
var expected = Snapshot(machine.Id);
var driver = new FakeDriver(m => Result<MachineSnapshot>.Ok(expected));
MachineSnapshot? received = null;
using var cts = new CancellationTokenSource();
var loop = NewEngine().RunAsync(machine, driver, s =>
{
received = s;
cts.Cancel();
}, cts.Token);
await loop;
Assert.Same(expected, received);
}
[Fact]
public async Task RunAsync_DriverReturnsCancelled_StopsLoop()
{
var machine = MachineWithInterval(TimeSpan.FromMilliseconds(20));
int calls = 0;
var driver = new FakeDriver(m =>
{
Interlocked.Increment(ref calls);
return Result<MachineSnapshot>.Cancelled();
});
using var cts = new CancellationTokenSource();
var loop = NewEngine().RunAsync(machine, driver, _ => { }, cts.Token);
var completed = await Task.WhenAny(loop, Task.Delay(1000)) == loop;
Assert.True(completed, "loop did not stop on cancelled result");
await loop;
Assert.Equal(1, calls);
}
/// <summary>Hand-rolled fake driver; behavior supplied by a delegate.</summary>
private sealed class FakeDriver : IProtocolDriver
{
private readonly Func<Machine, Result<MachineSnapshot>> _behavior;
public FakeDriver(Func<Machine, Result<MachineSnapshot>> behavior)
{
_behavior = behavior;
}
public string ProtocolId => "fake";
public Task<Result<MachineSnapshot>> ReadCurrentAsync(CancellationToken cancellationToken)
{
cancellationToken.ThrowIfCancellationRequested();
return Task.FromResult(_behavior(null!));
}
}
}
}