Files
wx-win-agent/tests/WxAgent.Service.Tests/EventPumpTests.cs
T
2026-09-07 19:07:16 +08:00

42 lines
2.1 KiB
C#

using System.Runtime.CompilerServices;
using System.Text.Json;
using WxAgent.Service;
using Xunit;
namespace WxAgent.Service.Tests;
public sealed class EventPumpTests
{
private sealed class SourceBackend : IAgentBackend, IAgentEventSource
{
public IReadOnlyList<AgentCapability> Capabilities => [new("listener-events", true, true, true, true, false, "read", false, 30, null, [])];
public Task<object> StatusAsync(CancellationToken ct) => Task.FromResult<object>(new { ok = true });
public async IAsyncEnumerable<AgentEvent> ListenAsync([EnumeratorCancellation] CancellationToken ct)
{ yield return new AgentEvent("evt", "ui-current", "session", "message", "summary", DateTimeOffset.UtcNow); await Task.Delay(Timeout.Infinite, ct); }
}
[Fact]
public async Task PumpForwardsOnlyToAuthorizedPrincipals()
{
var dir = Path.Combine(Path.GetTempPath(), Guid.NewGuid().ToString("N")); Directory.CreateDirectory(dir);
var options = new ServiceOptions { DataDirectory = dir, CredentialFile = Path.Combine(dir, "credentials.json") };
File.WriteAllText(options.CredentialFile, JsonSerializer.Serialize(new[]
{
new ServiceCredential("alice", new string('A', 64), ["read"], []),
new ServiceCredential("scoped", new string('B', 64), ["read"], ["other-account"])
}));
try
{
var hub = new EventHub(); var all = hub.Subscribe("alice", null); var scoped = hub.Subscribe("scoped", null);
using var pump = new EventPump(new SourceBackend(), hub, options);
await pump.StartAsync(default);
var ct = new CancellationTokenSource(TimeSpan.FromSeconds(5));
while (!hub.TryGet(all.SubscriptionId, "alice", out var alice) || !alice.Channel.Reader.TryRead(out _))
await Task.Delay(10, ct.Token);
Assert.False(hub.TryGet(scoped.SubscriptionId, "scoped", out var no) && no.Channel.Reader.TryRead(out _));
await pump.StopAsync(default);
}
finally { Microsoft.Data.Sqlite.SqliteConnection.ClearAllPools(); Directory.Delete(dir, true); }
}
}