#nullable enable using PLCSharp.Core.Tools; using System.Diagnostics; namespace PLCSharp.Tests; /// /// TaskTool.RunWithTimeoutAsync 行为测试(回归:VisionFunction 曾经建了 CancellationTokenSource /// 却没把 Token 传给 Task.Run,导致「5 秒超时」完全不生效)。 /// public class TaskToolTests { [Fact] public async Task RunWithTimeoutAsync_正常返回_应回传结果() { var result = await TaskTool.RunWithTimeoutAsync(() => 42, 5); Assert.Equal(42, result); } [Fact] public async Task RunWithTimeoutAsync_工作超时_应抛TimeoutException() { var sw = Stopwatch.StartNew(); await Assert.ThrowsAsync(() => TaskTool.RunWithTimeoutAsync(() => { Thread.Sleep(2000); return "never"; }, 0.2)); sw.Stop(); // 关键断言:等待真的在超时点结束,而不是等工作跑完(2 秒) Assert.True(sw.Elapsed.TotalSeconds < 1.5, $"实际等待 {sw.Elapsed.TotalSeconds:F2} 秒,超时未生效"); } [Fact] public async Task RunWithTimeoutAsync_超时秒数为0_应表示不限时() { var result = await TaskTool.RunWithTimeoutAsync(() => { Thread.Sleep(50); return "ok"; }, 0); Assert.Equal("ok", result); } [Fact] public async Task RunWithTimeoutAsync_外部取消_应抛OperationCanceledException() { using var cts = new CancellationTokenSource(100); await Assert.ThrowsAnyAsync(() => TaskTool.RunWithTimeoutAsync(() => { Thread.Sleep(3000); return "never"; }, 30, cts.Token)); } [Fact] public async Task RunWithTimeoutAsync_工作抛异常_应原样冒泡() { await Assert.ThrowsAsync(() => TaskTool.RunWithTimeoutAsync(() => throw new InvalidOperationException("boom"), 5)); } [Fact] public async Task RunWithTimeoutAsync_work为null_应抛ArgumentNullException() { await Assert.ThrowsAsync(() => TaskTool.RunWithTimeoutAsync(null!, 5)); } }