plcsharp/Tests/PLCSharp.Tests/TaskToolTests.cs
tfarcraw 57c6dd9234 修复视觉步骤假超时:CTS 建了却从未传给 Task.Run,超时形同虚设
- VisionFunction.RunAllAsync case 3:原来新建 CancellationTokenSource(5s) 但 await Task.Run(...) 没有传 token,
  于是 catch (OperationCanceledException) when (cts.IsCancellationRequested) 永远不命中;相机掉线或算法卡死时
  RunAllAsync 永不返回,且硬编码 5 秒与文案里读的 Flow.TimeoutSeconds 不一致(该配置项此前完全无效)。
- 新增 Core/Tools/TaskTool.RunWithTimeoutAsync:Task.Run + Task.WaitAsync 真实限时,
  <=0 作为显式关闭超时的逃生门;超时后明确按「步骤被放弃、结果不可信」处理。
- 超时改用 FlowModel.TimeoutSeconds(单步超时现在是可配置的)。
- 新增 6 个 TaskTool 回归测试(含「等待必须停在超时点」的时间断言)。构建 0 error,测试 49/49 通过。
2026-11-17 23:14:32 +08:00

77 lines
2.3 KiB
C#
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

#nullable enable
using PLCSharp.Core.Tools;
using System.Diagnostics;
namespace PLCSharp.Tests;
/// <summary>
/// TaskTool.RunWithTimeoutAsync 行为测试(回归:VisionFunction 曾经建了 CancellationTokenSource
/// 却没把 Token 传给 Task.Run,导致「5 秒超时」完全不生效)。
/// </summary>
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<TimeoutException>(() =>
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<OperationCanceledException>(() =>
TaskTool.RunWithTimeoutAsync(() =>
{
Thread.Sleep(3000);
return "never";
}, 30, cts.Token));
}
[Fact]
public async Task RunWithTimeoutAsync_工作抛异常_应原样冒泡()
{
await Assert.ThrowsAsync<InvalidOperationException>(() =>
TaskTool.RunWithTimeoutAsync<string>(() => throw new InvalidOperationException("boom"), 5));
}
[Fact]
public async Task RunWithTimeoutAsync_work为null_应抛ArgumentNullException()
{
await Assert.ThrowsAsync<ArgumentNullException>(() =>
TaskTool.RunWithTimeoutAsync<int>(null!, 5));
}
}