plcsharp/Tests/PLCSharp.Tests/TaskToolTests.cs
tfarcraw 24325d2535 补齐文件编码:把编辑过程中被丢掉的 UTF-8 BOM 和 LF 行尾归一回仓库约定
本仓库的 .cs 都是 UTF-8 with BOM + CRLF。前面几个提交里,编辑工具把 App.xaml.cs、LoginModel.cs、VisionFunction.cs 首行的 BOM 掉了(表现为每个提交都多出一行无关的 -using/+using diff);新建的 TaskTool.cs、WorkerGuard.cs 及三个测试文件则是无 BOM 的 LF。

这里统一补回 BOM、行尾归一为 CRLF。改动只是编码,逐文件 diff 都只有首行一处,无代码变化。
2026-11-17 23:30:49 +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));
}
}