using System;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.Extensions.Hosting;
using NewLife.Log;
using NewLife.Remoting.Models;
using NewLife.Remoting.Services;
using Stardust.Server.Services;
using Xunit;
namespace ServerTest.Services;
/// <summary>应用与节点会è¯ç®¡ç†å™¨å•元测试。覆盖消æ¯ä¸»é¢˜çº¦å®šä»¥åŠä¼šè¯çš„ç™»è®°ã€æŸ¥è¯¢ä¸Žç§»é™¤</summary>
public class SessionManagerTests
{
/// <summary>ä¼ªé€ åº”ç”¨ç”Ÿå‘½å‘¨æœŸï¼Œæä¾› ApplicationStopping 通知</summary>
private sealed class FakeLifetime : IHostApplicationLifetime
{
private readonly CancellationTokenSource _stopping = new();
public CancellationToken ApplicationStarted => CancellationToken.None;
public CancellationToken ApplicationStopping => _stopping.Token;
public CancellationToken ApplicationStopped => CancellationToken.None;
public void StopApplication() => _stopping.Cancel();
}
/// <summary>åªæä¾› IHostApplicationLifetime çš„æœåС容噍</summary>
private sealed class FakeProvider : IServiceProvider
{
private readonly IHostApplicationLifetime _lifetime = new FakeLifetime();
public Object GetService(Type serviceType) => serviceType == typeof(IHostApplicationLifetime) ? _lifetime : null;
}
/// <summary>æ— çœŸå®žç½‘ç»œè¿žæŽ¥çš„å‘½ä»¤ä¼šè¯</summary>
private sealed class FakeSession : ICommandSession
{
public String Code { get; set; } = null!;
public Boolean Active { get; set; } = true;
public Task HandleAsync(CommandModel command, String message, CancellationToken cancellationToken) => Task.CompletedTask;
public void Dispose() { }
}
[Fact(DisplayName = "节点会è¯ç®¡ç†å™¨ä½¿ç”¨NodeCommands主题")]
public void NodeManager_UsesNodeTopic()
{
using var manager = new NodeSessionManager(new FakeProvider());
Assert.Equal("NodeCommands", manager.Topic);
var session = new FakeSession { Code = "node-1" };
manager.Add(session);
Assert.Same(session, manager.Get("node-1"));
manager.Remove(session);
Assert.Null(manager.Get("node-1"));
}
[Fact(DisplayName = "应用会è¯ç®¡ç†å™¨ä½¿ç”¨AppCommands主题")]
public void AppManager_UsesAppTopic()
{
using var manager = new AppSessionManager(new FakeProvider(), DefaultTracer.Instance, Logger.Null);
Assert.Equal("AppCommands", manager.Topic);
var session = new FakeSession { Code = "app-1" };
manager.Add(session);
Assert.Same(session, manager.Get("app-1"));
manager.Remove(session);
Assert.Null(manager.Get("app-1"));
}
[Fact(DisplayName = "é‡å¤ç™»è®°åŒä¸€æ ‡è¯†æ—¶åŽåŠ å…¥çš„ä¼šè¯è¦†ç›–å‰è€…")]
public void AppManager_AddDuplicateCode_Overwrites()
{
using var manager = new AppSessionManager(new FakeProvider(), DefaultTracer.Instance, Logger.Null);
var first = new FakeSession { Code = "dup" };
var second = new FakeSession { Code = "dup" };
manager.Add(first);
manager.Add(second);
Assert.Same(second, manager.Get("dup"));
}
}
|