This commit is contained in:
tyuXX 2026-10-10 16:40:35 +00:00
commit f25ba8adcd
64 changed files with 5959 additions and 0 deletions

View file

@ -0,0 +1,199 @@
using System;
using System.IO;
using System.Threading.Tasks;
using Microsoft.Extensions.Logging.Abstractions;
using GsDChat.Core.Models;
using GsDChat.Modding;
using GsDChat.Mods.SampleBot;
using GsDChat.Server.Configuration;
using GsDChat.Server.Data;
using GsDChat.Server.Services;
using GsDChat.Server.WebSockets;
using Xunit;
namespace GsDChat.Tests;
public class ModSystemTests : IDisposable
{
private readonly string _testDir;
private readonly ChatDatabase _db;
private readonly ServerOptions _options;
private readonly ChatWebSocketManager _wsManager;
private readonly ModLoaderService _modLoader;
public ModSystemTests()
{
_testDir = Path.Combine(Path.GetTempPath(), "gsdchat_mod_test_" + Guid.NewGuid().ToString("N"));
_options = new ServerOptions
{
DataDirectory = _testDir,
ServerName = "Mod Test Server",
Motd = "Initial MOTD"
};
_db = new ChatDatabase(_testDir);
_db.InitializeAsync().GetAwaiter().GetResult();
_wsManager = new ChatWebSocketManager(_db, _options, NullLogger<ChatWebSocketManager>.Instance);
_modLoader = new ModLoaderService(_options, _wsManager, NullLogger<ModLoaderService>.Instance);
}
public void Dispose()
{
_modLoader.ShutdownModsAsync().GetAwaiter().GetResult();
_db.Dispose();
try
{
if (Directory.Exists(_testDir))
{
Directory.Delete(_testDir, true);
}
}
catch { }
}
[Fact]
public async Task MessagePipeline_ShouldTransformAndAllowChain()
{
var pipeline = new MessagePipeline();
// Middleware 1: Appends "[Verified]"
pipeline.Use(async (ctx, next) =>
{
ctx.Message.Content += " [Verified]";
await next();
});
// Middleware 2: Replaces "foo" with "bar"
pipeline.Use(async (ctx, next) =>
{
ctx.Message.Content = ctx.Message.Content.Replace("foo", "bar");
await next();
});
var msg = new ChatMessage { Content = "This is foo" };
var result = await pipeline.ExecuteAsync(msg);
Assert.False(result.IsCancelled);
Assert.Equal("This is bar [Verified]", result.Message.Content);
}
[Fact]
public async Task MessagePipeline_Cancellation_ShouldDropMessage()
{
var pipeline = new MessagePipeline();
pipeline.Use(async (ctx, next) =>
{
if (ctx.Message.Content.Contains("spam"))
{
ctx.IsCancelled = true;
ctx.CancellationReason = "Spam detected";
return;
}
await next();
});
var msg = new ChatMessage { Content = "Buy cheap spam now!" };
var result = await pipeline.ExecuteAsync(msg);
Assert.True(result.IsCancelled);
Assert.Equal("Spam detected", result.CancellationReason);
}
[Fact]
public async Task SampleBotMod_DirectInitialization_CommandsAndPipeline()
{
var botMod = new SampleBotMod();
var context = new ModContext(
_modLoader.EventBus,
_modLoader.Commands,
_modLoader.Pipeline,
_modLoader.Ui,
Path.Combine(_testDir, "bot_data")
);
await botMod.InitializeAsync(context);
// Test /roll command
var rollResult = await _modLoader.Commands.ExecuteCommandAsync(new CommandContext
{
Command = "roll",
Args = "2d6",
Username = "Alice",
UserRole = UserRoles.Member
});
Assert.NotNull(rollResult);
Assert.True(rollResult.Success);
Assert.Contains("rolled 2d6", rollResult.Output);
// Test /announce command (Member forbidden, Admin allowed)
var memberAnnounce = await _modLoader.Commands.ExecuteCommandAsync(new CommandContext
{
Command = "announce",
Args = "Server restart soon",
Username = "Bob",
UserRole = UserRoles.Member
});
Assert.NotNull(memberAnnounce);
Assert.False(memberAnnounce.Success);
var adminAnnounce = await _modLoader.Commands.ExecuteCommandAsync(new CommandContext
{
Command = "announce",
Args = "Server restart soon",
Username = "Alice",
UserRole = UserRoles.Admin
});
Assert.NotNull(adminAnnounce);
Assert.True(adminAnnounce.Success);
Assert.Contains("OFFICIAL ANNOUNCEMENT", adminAnnounce.Output);
// Test Pipeline transformation (shorthand emoji replacement)
var testMsg = new ChatMessage { Content = "I don't know :shrug: and rage :tableflip: with :heart:" };
var pipelineRes = await _modLoader.Pipeline.ExecuteAsync(testMsg);
Assert.False(pipelineRes.IsCancelled);
Assert.Contains("¯\\_(ツ)_/¯", pipelineRes.Message.Content);
Assert.Contains("(╯°□°)╯︵ ┻━┻", pipelineRes.Message.Content);
Assert.Contains("❤️", pipelineRes.Message.Content);
// Test F5 Screen registration
var ui = _modLoader.Ui.GetUiSync();
Assert.Contains(ui.Screens, s => s.ScreenId == "F5_Custom" && s.Title == "Server Status");
}
[Fact]
public async Task ModLoaderService_LoadsDllFromDirectoryViaAssemblyLoadContext()
{
// Copy built GsDChat.Mods.SampleBot.dll into a temporary mods folder
string modsDir = Path.Combine(_testDir, "mods");
Directory.CreateDirectory(modsDir);
string sampleBotDll = typeof(SampleBotMod).Assembly.Location;
Assert.True(File.Exists(sampleBotDll));
string targetDllPath = Path.Combine(modsDir, "GsDChat.Mods.SampleBot.dll");
File.Copy(sampleBotDll, targetDllPath, overwrite: true);
// Load via ModLoaderService
await _modLoader.LoadModsAsync(modsDir);
// Verify that the command registered via dynamically loaded assembly works
Assert.True(_modLoader.Commands.HasCommand("roll"));
Assert.True(_modLoader.Commands.HasCommand("announce"));
var cmdRes = await _modLoader.Commands.ExecuteCommandAsync(new CommandContext
{
Command = "roll",
Args = "1d20",
Username = "Tester",
UserRole = UserRoles.Member
});
Assert.NotNull(cmdRes);
Assert.True(cmdRes.Success);
Assert.Contains("rolled 1d20", cmdRes.Output);
}
}