init
This commit is contained in:
commit
f25ba8adcd
64 changed files with 5959 additions and 0 deletions
136
tests/GsDChat.Tests/AuthServiceTests.cs
Normal file
136
tests/GsDChat.Tests/AuthServiceTests.cs
Normal file
|
|
@ -0,0 +1,136 @@
|
|||
using System;
|
||||
using System.IO;
|
||||
using System.Threading.Tasks;
|
||||
using GsDChat.Core.Models;
|
||||
using GsDChat.Core.Protocol;
|
||||
using GsDChat.Server.Configuration;
|
||||
using GsDChat.Server.Data;
|
||||
using GsDChat.Server.Services;
|
||||
using Xunit;
|
||||
|
||||
namespace GsDChat.Tests;
|
||||
|
||||
public class AuthServiceTests : IDisposable
|
||||
{
|
||||
private readonly string _testDir;
|
||||
private readonly ChatDatabase _db;
|
||||
private readonly ServerOptions _options;
|
||||
private readonly AuthService _auth;
|
||||
|
||||
public AuthServiceTests()
|
||||
{
|
||||
_testDir = Path.Combine(Path.GetTempPath(), "gsdchat_auth_test_" + Guid.NewGuid().ToString("N"));
|
||||
_db = new ChatDatabase(_testDir);
|
||||
_db.InitializeAsync().GetAwaiter().GetResult();
|
||||
_options = new ServerOptions
|
||||
{
|
||||
ServerWidePassword = "SecretServerPass"
|
||||
};
|
||||
_auth = new AuthService(_db, _options);
|
||||
}
|
||||
|
||||
public void Dispose()
|
||||
{
|
||||
_db.Dispose();
|
||||
try
|
||||
{
|
||||
if (Directory.Exists(_testDir))
|
||||
{
|
||||
Directory.Delete(_testDir, true);
|
||||
}
|
||||
}
|
||||
catch { }
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Register_FailsWithInvalidServerPassword()
|
||||
{
|
||||
var req = new RegisterRequest
|
||||
{
|
||||
Username = "TestUser",
|
||||
Password = "Password123!",
|
||||
ServerPassword = "WrongServerPassword"
|
||||
};
|
||||
|
||||
var result = await _auth.RegisterAsync(req);
|
||||
Assert.False(result.Success);
|
||||
Assert.Contains("server-wide password", result.ErrorMessage, StringComparison.OrdinalIgnoreCase);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Register_FirstUserBecomesOwner_SecondUserBecomesMember()
|
||||
{
|
||||
// First user
|
||||
var req1 = new RegisterRequest
|
||||
{
|
||||
Username = "OwnerUser",
|
||||
Password = "Password123!",
|
||||
ServerPassword = "SecretServerPass"
|
||||
};
|
||||
var res1 = await _auth.RegisterAsync(req1);
|
||||
Assert.True(res1.Success);
|
||||
Assert.Equal(UserRoles.Owner, res1.Role);
|
||||
Assert.False(string.IsNullOrWhiteSpace(res1.Token));
|
||||
|
||||
// Second user
|
||||
var req2 = new RegisterRequest
|
||||
{
|
||||
Username = "MemberUser",
|
||||
Password = "Password123!",
|
||||
ServerPassword = "SecretServerPass"
|
||||
};
|
||||
var res2 = await _auth.RegisterAsync(req2);
|
||||
Assert.True(res2.Success);
|
||||
Assert.Equal(UserRoles.Member, res2.Role);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Login_ValidCredentials_ReturnsValidSessionToken()
|
||||
{
|
||||
var reg = new RegisterRequest
|
||||
{
|
||||
Username = "LoginTestUser",
|
||||
Password = "ValidPassword123!",
|
||||
ServerPassword = "SecretServerPass"
|
||||
};
|
||||
var regRes = await _auth.RegisterAsync(reg);
|
||||
Assert.True(regRes.Success);
|
||||
|
||||
var loginReq = new LoginRequest
|
||||
{
|
||||
Username = "LoginTestUser",
|
||||
Password = "ValidPassword123!",
|
||||
ServerPassword = "SecretServerPass"
|
||||
};
|
||||
var loginRes = await _auth.LoginAsync(loginReq);
|
||||
Assert.True(loginRes.Success);
|
||||
Assert.NotNull(loginRes.Token);
|
||||
|
||||
// Validate session token
|
||||
var user = await _auth.ValidateSessionTokenAsync(loginRes.Token);
|
||||
Assert.NotNull(user);
|
||||
Assert.Equal("LoginTestUser", user.Username);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Login_InvalidPassword_Fails()
|
||||
{
|
||||
var reg = new RegisterRequest
|
||||
{
|
||||
Username = "FailUser",
|
||||
Password = "CorrectPassword123!",
|
||||
ServerPassword = "SecretServerPass"
|
||||
};
|
||||
await _auth.RegisterAsync(reg);
|
||||
|
||||
var loginReq = new LoginRequest
|
||||
{
|
||||
Username = "FailUser",
|
||||
Password = "WrongPassword",
|
||||
ServerPassword = "SecretServerPass"
|
||||
};
|
||||
var loginRes = await _auth.LoginAsync(loginReq);
|
||||
Assert.False(loginRes.Success);
|
||||
Assert.Equal("Invalid username or password.", loginRes.ErrorMessage);
|
||||
}
|
||||
}
|
||||
61
tests/GsDChat.Tests/CryptoTests.cs
Normal file
61
tests/GsDChat.Tests/CryptoTests.cs
Normal file
|
|
@ -0,0 +1,61 @@
|
|||
using GsDChat.Core.Security;
|
||||
using Xunit;
|
||||
|
||||
namespace GsDChat.Tests;
|
||||
|
||||
public class CryptoTests
|
||||
{
|
||||
[Fact]
|
||||
public void HashPassword_ShouldReturnValidHashAndSalt()
|
||||
{
|
||||
var password = "SuperSecretPassword123!";
|
||||
var (hash, salt) = PasswordHasher.HashPassword(password);
|
||||
|
||||
Assert.False(string.IsNullOrWhiteSpace(hash));
|
||||
Assert.False(string.IsNullOrWhiteSpace(salt));
|
||||
Assert.Equal(128, hash.Length); // 64 bytes hex
|
||||
Assert.Equal(64, salt.Length); // 32 bytes hex
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void VerifyPassword_ShouldSucceedForCorrectPassword()
|
||||
{
|
||||
var password = "MyP@ssw0rd!#2026";
|
||||
var (hash, salt) = PasswordHasher.HashPassword(password);
|
||||
|
||||
bool isValid = PasswordHasher.VerifyPassword(password, hash, salt);
|
||||
Assert.True(isValid);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void VerifyPassword_ShouldFailForIncorrectPassword()
|
||||
{
|
||||
var password = "CorrectPassword";
|
||||
var (hash, salt) = PasswordHasher.HashPassword(password);
|
||||
|
||||
bool isValid = PasswordHasher.VerifyPassword("WrongPassword", hash, salt);
|
||||
Assert.False(isValid);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void HashPassword_SamePassword_ShouldGenerateDifferentSaltsAndHashes()
|
||||
{
|
||||
var password = "IdenticalPassword";
|
||||
var (hash1, salt1) = PasswordHasher.HashPassword(password);
|
||||
var (hash2, salt2) = PasswordHasher.HashPassword(password);
|
||||
|
||||
Assert.NotEqual(salt1, salt2);
|
||||
Assert.NotEqual(hash1, hash2);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void GenerateSecureToken_ShouldGenerateUniqueHexStrings()
|
||||
{
|
||||
var token1 = TokenGenerator.GenerateSecureToken(32);
|
||||
var token2 = TokenGenerator.GenerateSecureToken(32);
|
||||
|
||||
Assert.Equal(64, token1.Length);
|
||||
Assert.Equal(64, token2.Length);
|
||||
Assert.NotEqual(token1, token2);
|
||||
}
|
||||
}
|
||||
127
tests/GsDChat.Tests/DatabaseTests.cs
Normal file
127
tests/GsDChat.Tests/DatabaseTests.cs
Normal file
|
|
@ -0,0 +1,127 @@
|
|||
using System;
|
||||
using System.IO;
|
||||
using System.Threading.Tasks;
|
||||
using GsDChat.Core.Models;
|
||||
using GsDChat.Server.Data;
|
||||
using Xunit;
|
||||
|
||||
namespace GsDChat.Tests;
|
||||
|
||||
public class DatabaseTests : IDisposable
|
||||
{
|
||||
private readonly string _testDir;
|
||||
private readonly ChatDatabase _db;
|
||||
|
||||
public DatabaseTests()
|
||||
{
|
||||
_testDir = Path.Combine(Path.GetTempPath(), "gsdchat_test_" + Guid.NewGuid().ToString("N"));
|
||||
_db = new ChatDatabase(_testDir);
|
||||
_db.InitializeAsync().GetAwaiter().GetResult();
|
||||
}
|
||||
|
||||
public void Dispose()
|
||||
{
|
||||
_db.Dispose();
|
||||
try
|
||||
{
|
||||
if (Directory.Exists(_testDir))
|
||||
{
|
||||
Directory.Delete(_testDir, true);
|
||||
}
|
||||
}
|
||||
catch { }
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task InitializeAsync_ShouldSeedDefaultChannels()
|
||||
{
|
||||
var channels = await _db.GetChannelsAsync();
|
||||
Assert.NotNull(channels);
|
||||
Assert.True(channels.Count >= 2);
|
||||
Assert.Contains(channels, c => c.Name == "general");
|
||||
Assert.Contains(channels, c => c.Name == "announcements");
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task CreateUser_AndGetUserByUsername_ShouldPersistCorrectly()
|
||||
{
|
||||
var user = new User
|
||||
{
|
||||
Username = "Alice",
|
||||
PasswordHash = "hash123",
|
||||
PasswordSalt = "salt123",
|
||||
Role = UserRoles.Owner
|
||||
};
|
||||
|
||||
bool created = await _db.CreateUserAsync(user);
|
||||
Assert.True(created);
|
||||
|
||||
var retrieved = await _db.GetUserByUsernameAsync("Alice");
|
||||
Assert.NotNull(retrieved);
|
||||
Assert.Equal("Alice", retrieved.Username);
|
||||
Assert.Equal(UserRoles.Owner, retrieved.Role);
|
||||
|
||||
// Case insensitivity
|
||||
var retrievedLower = await _db.GetUserByUsernameAsync("alice");
|
||||
Assert.NotNull(retrievedLower);
|
||||
Assert.Equal(retrieved.Id, retrievedLower.Id);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task SaveMessage_AndGetRecentMessages_ShouldPreserveOrder()
|
||||
{
|
||||
var channels = await _db.GetChannelsAsync();
|
||||
var general = channels.First(c => c.Name == "general");
|
||||
|
||||
var msg1 = new ChatMessage
|
||||
{
|
||||
ChannelId = general.Id,
|
||||
SenderId = "u1",
|
||||
SenderUsername = "Alice",
|
||||
Content = "First message",
|
||||
CreatedAt = DateTime.UtcNow.AddSeconds(-10)
|
||||
};
|
||||
var msg2 = new ChatMessage
|
||||
{
|
||||
ChannelId = general.Id,
|
||||
SenderId = "u2",
|
||||
SenderUsername = "Bob",
|
||||
Content = "Second message",
|
||||
CreatedAt = DateTime.UtcNow
|
||||
};
|
||||
|
||||
await _db.SaveMessageAsync(msg1);
|
||||
await _db.SaveMessageAsync(msg2);
|
||||
|
||||
var messages = await _db.GetRecentMessagesAsync(general.Id, 10);
|
||||
Assert.True(messages.Count >= 2);
|
||||
Assert.Equal("First message", messages[^2].Content);
|
||||
Assert.Equal("Second message", messages[^1].Content);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ChannelOperations_CreateAndDuplicateAndGet()
|
||||
{
|
||||
var channel = new Channel
|
||||
{
|
||||
Name = "gaming",
|
||||
Topic = "Gaming discussion"
|
||||
};
|
||||
|
||||
bool created = await _db.CreateChannelAsync(channel);
|
||||
Assert.True(created);
|
||||
|
||||
// Duplicate name should fail
|
||||
var dup = new Channel
|
||||
{
|
||||
Name = "gaming",
|
||||
Topic = "Duplicate"
|
||||
};
|
||||
bool dupCreated = await _db.CreateChannelAsync(dup);
|
||||
Assert.False(dupCreated);
|
||||
|
||||
var found = await _db.GetChannelByNameAsync("gaming");
|
||||
Assert.NotNull(found);
|
||||
Assert.Equal("Gaming discussion", found.Topic);
|
||||
}
|
||||
}
|
||||
272
tests/GsDChat.Tests/EndToEndChatTests.cs
Normal file
272
tests/GsDChat.Tests/EndToEndChatTests.cs
Normal file
|
|
@ -0,0 +1,272 @@
|
|||
using System;
|
||||
using System.IO;
|
||||
using System.Net.Http;
|
||||
using System.Net.Http.Headers;
|
||||
using System.Net.WebSockets;
|
||||
using System.Text;
|
||||
using System.Text.Json;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
using Microsoft.AspNetCore.Builder;
|
||||
using Microsoft.AspNetCore.Hosting;
|
||||
using Microsoft.AspNetCore.Http;
|
||||
using Microsoft.Extensions.DependencyInjection;
|
||||
using Microsoft.Extensions.Logging;
|
||||
using GsDChat.Client.Network;
|
||||
using GsDChat.Client.State;
|
||||
using GsDChat.Core.Models;
|
||||
using GsDChat.Core.Protocol;
|
||||
using GsDChat.Server.Configuration;
|
||||
using GsDChat.Server.Data;
|
||||
using GsDChat.Server.Services;
|
||||
using GsDChat.Server.WebSockets;
|
||||
using Xunit;
|
||||
|
||||
namespace GsDChat.Tests;
|
||||
|
||||
public class EndToEndChatTests : IAsyncLifetime
|
||||
{
|
||||
private readonly string _testDir;
|
||||
private WebApplication? _app;
|
||||
private int _port;
|
||||
private string _serverUrl = string.Empty;
|
||||
|
||||
public EndToEndChatTests()
|
||||
{
|
||||
_testDir = Path.Combine(Path.GetTempPath(), "gsdchat_e2e_" + Guid.NewGuid().ToString("N"));
|
||||
}
|
||||
|
||||
public async Task InitializeAsync()
|
||||
{
|
||||
// Pick an unused local port
|
||||
using var listener = new System.Net.Sockets.TcpListener(System.Net.IPAddress.Loopback, 0);
|
||||
listener.Start();
|
||||
_port = ((System.Net.IPEndPoint)listener.LocalEndpoint).Port;
|
||||
listener.Stop();
|
||||
|
||||
_serverUrl = $"http://127.0.0.1:{_port}";
|
||||
|
||||
var builder = WebApplication.CreateBuilder();
|
||||
builder.WebHost.UseUrls(_serverUrl);
|
||||
builder.Logging.ClearProviders(); // Keep test output clean
|
||||
|
||||
var serverOptions = new ServerOptions
|
||||
{
|
||||
Host = "127.0.0.1",
|
||||
Port = _port,
|
||||
UseTls = false,
|
||||
DataDirectory = _testDir,
|
||||
ServerName = "E2E Test Server",
|
||||
Motd = "Testing GsDChat E2E"
|
||||
};
|
||||
|
||||
builder.Services.AddSingleton(serverOptions);
|
||||
builder.Services.AddSingleton(sp => new ChatDatabase(serverOptions.DataDirectory));
|
||||
builder.Services.AddSingleton<IAuthService, AuthService>();
|
||||
builder.Services.AddSingleton<FileStorageService>();
|
||||
builder.Services.AddSingleton<ChatWebSocketManager>();
|
||||
|
||||
_app = builder.Build();
|
||||
|
||||
var db = _app.Services.GetRequiredService<ChatDatabase>();
|
||||
await db.InitializeAsync();
|
||||
|
||||
_app.UseWebSockets();
|
||||
|
||||
string? ExtractToken(HttpRequest req)
|
||||
{
|
||||
if (req.Headers.TryGetValue("Authorization", out var h) && h.ToString().StartsWith("Bearer "))
|
||||
return h.ToString().Substring(7).Trim();
|
||||
if (req.Query.TryGetValue("token", out var q))
|
||||
return q.ToString();
|
||||
return null;
|
||||
}
|
||||
|
||||
_app.MapGet("/api/info", (ServerOptions opt) => Results.Ok(new ServerInfoResponse
|
||||
{
|
||||
ServerName = opt.ServerName,
|
||||
Version = "1.0.0",
|
||||
RegistrationMode = opt.RegistrationMode,
|
||||
RequiresServerPassword = !string.IsNullOrWhiteSpace(opt.ServerWidePassword),
|
||||
Motd = opt.Motd,
|
||||
MaxFileSizeMb = opt.MaxFileSizeMb
|
||||
}));
|
||||
|
||||
_app.MapPost("/api/auth/register", async (RegisterRequest req, IAuthService auth) =>
|
||||
{
|
||||
var res = await auth.RegisterAsync(req);
|
||||
return res.Success ? Results.Ok(res) : Results.BadRequest(res);
|
||||
});
|
||||
|
||||
_app.MapPost("/api/auth/login", async (LoginRequest req, IAuthService auth) =>
|
||||
{
|
||||
var res = await auth.LoginAsync(req);
|
||||
return res.Success ? Results.Ok(res) : Results.BadRequest(res);
|
||||
});
|
||||
|
||||
_app.MapPost("/api/files/upload", async (HttpRequest req, IAuthService auth, FileStorageService fileSvc, ChatWebSocketManager ws) =>
|
||||
{
|
||||
string? token = ExtractToken(req);
|
||||
var user = await auth.ValidateSessionTokenAsync(token ?? "");
|
||||
if (user == null) return Results.Unauthorized();
|
||||
|
||||
var form = await req.ReadFormAsync();
|
||||
var file = form.Files.GetFile("file");
|
||||
if (file == null) return Results.BadRequest();
|
||||
string chId = form["channelId"].ToString();
|
||||
|
||||
using var stream = file.OpenReadStream();
|
||||
var record = await fileSvc.StoreFileAsync(chId, user.Id, user.Username, file.FileName, file.ContentType, stream, file.Length);
|
||||
await ws.BroadcastFileUploadedAsync(record);
|
||||
|
||||
return Results.Ok(new UploadFileResponse
|
||||
{
|
||||
Success = true,
|
||||
FileId = record.Id,
|
||||
FileName = record.OriginalFileName,
|
||||
FileSizeBytes = record.FileSizeBytes,
|
||||
ChannelId = record.ChannelId
|
||||
});
|
||||
});
|
||||
|
||||
_app.MapGet("/api/files/{id}", async (string id, HttpRequest req, IAuthService auth, FileStorageService fileSvc) =>
|
||||
{
|
||||
string? token = ExtractToken(req);
|
||||
var user = await auth.ValidateSessionTokenAsync(token ?? "");
|
||||
if (user == null) return Results.Unauthorized();
|
||||
|
||||
var record = await fileSvc.GetFileRecordAsync(id);
|
||||
if (record == null) return Results.NotFound();
|
||||
|
||||
var stream = fileSvc.OpenFileStream(record);
|
||||
if (stream == null) return Results.NotFound();
|
||||
|
||||
return Results.File(stream, record.ContentType, record.OriginalFileName);
|
||||
});
|
||||
|
||||
_app.MapGet("/ws", async (HttpContext context, IAuthService auth, ChatWebSocketManager ws) =>
|
||||
{
|
||||
if (!context.WebSockets.IsWebSocketRequest)
|
||||
{
|
||||
context.Response.StatusCode = 400;
|
||||
return;
|
||||
}
|
||||
string? token = ExtractToken(context.Request);
|
||||
var user = await auth.ValidateSessionTokenAsync(token ?? "");
|
||||
if (user == null)
|
||||
{
|
||||
context.Response.StatusCode = 401;
|
||||
return;
|
||||
}
|
||||
var socket = await context.WebSockets.AcceptWebSocketAsync();
|
||||
await ws.HandleClientAsync(socket, user, context.RequestAborted);
|
||||
});
|
||||
|
||||
await _app.StartAsync();
|
||||
}
|
||||
|
||||
public async Task DisposeAsync()
|
||||
{
|
||||
if (_app != null)
|
||||
{
|
||||
await _app.StopAsync();
|
||||
await _app.DisposeAsync();
|
||||
}
|
||||
|
||||
try
|
||||
{
|
||||
if (Directory.Exists(_testDir))
|
||||
{
|
||||
Directory.Delete(_testDir, true);
|
||||
}
|
||||
}
|
||||
catch { }
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task FullChatAndFileTransferFlow_ShouldSucceed()
|
||||
{
|
||||
// 1. Client 1 (Alice): Register
|
||||
var stateAlice = new ClientState { ServerUrl = _serverUrl };
|
||||
using var connAlice = new ChatClientConnection(stateAlice);
|
||||
|
||||
var regAlice = await connAlice.RegisterAsync("Alice", "AliceSecretPassword123");
|
||||
Assert.True(regAlice.Success);
|
||||
Assert.Equal(UserRoles.Owner, regAlice.Role);
|
||||
stateAlice.Token = regAlice.Token!;
|
||||
stateAlice.CurrentUserId = regAlice.UserId!;
|
||||
stateAlice.CurrentUsername = regAlice.Username!;
|
||||
stateAlice.CurrentUserRole = regAlice.Role!;
|
||||
|
||||
// 2. Client 2 (Bob): Register
|
||||
var stateBob = new ClientState { ServerUrl = _serverUrl };
|
||||
using var connBob = new ChatClientConnection(stateBob);
|
||||
|
||||
var regBob = await connBob.RegisterAsync("Bob", "BobSecretPassword123");
|
||||
Assert.True(regBob.Success);
|
||||
Assert.Equal(UserRoles.Member, regBob.Role);
|
||||
stateBob.Token = regBob.Token!;
|
||||
stateBob.CurrentUserId = regBob.UserId!;
|
||||
stateBob.CurrentUsername = regBob.Username!;
|
||||
stateBob.CurrentUserRole = regBob.Role!;
|
||||
|
||||
// 3. Connect both clients to WebSockets
|
||||
await connAlice.StartWebSocketAsync();
|
||||
await connBob.StartWebSocketAsync();
|
||||
|
||||
// Allow initial sync to complete
|
||||
await Task.Delay(300);
|
||||
|
||||
Assert.True(stateAlice.Channels.Count > 0);
|
||||
Assert.True(stateBob.Channels.Count > 0);
|
||||
Assert.False(string.IsNullOrEmpty(stateAlice.ActiveChannelId));
|
||||
string generalChannelId = stateAlice.ActiveChannelId;
|
||||
|
||||
// 4. Alice sends a chat message
|
||||
await connAlice.SendChatMessageAsync(generalChannelId, "Hello Bob, welcome to GsDChat!");
|
||||
|
||||
// Wait for broadcast to reach Bob
|
||||
for (int i = 0; i < 20; i++)
|
||||
{
|
||||
if (stateBob.ChannelMessages.TryGetValue(generalChannelId, out var msgs) && msgs.Exists(m => m.Content.Contains("Hello Bob")))
|
||||
{
|
||||
break;
|
||||
}
|
||||
await Task.Delay(100);
|
||||
}
|
||||
|
||||
Assert.True(stateBob.ChannelMessages.TryGetValue(generalChannelId, out var bobMsgs));
|
||||
Assert.Contains(bobMsgs, m => m.Content == "Hello Bob, welcome to GsDChat!" && m.SenderUsername == "Alice");
|
||||
|
||||
// 5. Alice uploads a test file
|
||||
string localFilePath = Path.Combine(_testDir, "shared_document.txt");
|
||||
string fileContent = "This is a confidential community file uploaded over secure HTTPS.";
|
||||
await File.WriteAllTextAsync(localFilePath, fileContent);
|
||||
|
||||
bool uploadSuccess = await connAlice.UploadFileAsync(localFilePath, generalChannelId);
|
||||
Assert.True(uploadSuccess);
|
||||
|
||||
// Wait for file list sync to reach Bob
|
||||
for (int i = 0; i < 20; i++)
|
||||
{
|
||||
if (stateBob.Files.Exists(f => f.OriginalFileName == "shared_document.txt"))
|
||||
{
|
||||
break;
|
||||
}
|
||||
await Task.Delay(100);
|
||||
}
|
||||
|
||||
var sharedFile = stateBob.Files.Find(f => f.OriginalFileName == "shared_document.txt");
|
||||
Assert.NotNull(sharedFile);
|
||||
|
||||
// 6. Bob downloads the file
|
||||
string bobDownloadsDir = Path.Combine(_testDir, "bob_downloads");
|
||||
bool downloadSuccess = await connBob.DownloadFileAsync(sharedFile.Id, bobDownloadsDir);
|
||||
Assert.True(downloadSuccess);
|
||||
|
||||
string downloadedFilePath = Path.Combine(bobDownloadsDir, "shared_document.txt");
|
||||
Assert.True(File.Exists(downloadedFilePath));
|
||||
string downloadedText = await File.ReadAllTextAsync(downloadedFilePath);
|
||||
Assert.Equal(fileContent, downloadedText);
|
||||
}
|
||||
}
|
||||
81
tests/GsDChat.Tests/FileStorageServiceTests.cs
Normal file
81
tests/GsDChat.Tests/FileStorageServiceTests.cs
Normal file
|
|
@ -0,0 +1,81 @@
|
|||
using System;
|
||||
using System.IO;
|
||||
using System.Text;
|
||||
using System.Threading.Tasks;
|
||||
using GsDChat.Server.Configuration;
|
||||
using GsDChat.Server.Data;
|
||||
using GsDChat.Server.Services;
|
||||
using Xunit;
|
||||
|
||||
namespace GsDChat.Tests;
|
||||
|
||||
public class FileStorageServiceTests : IDisposable
|
||||
{
|
||||
private readonly string _testDir;
|
||||
private readonly ChatDatabase _db;
|
||||
private readonly ServerOptions _options;
|
||||
private readonly FileStorageService _fileService;
|
||||
|
||||
public FileStorageServiceTests()
|
||||
{
|
||||
_testDir = Path.Combine(Path.GetTempPath(), "gsdchat_file_test_" + Guid.NewGuid().ToString("N"));
|
||||
_db = new ChatDatabase(_testDir);
|
||||
_db.InitializeAsync().GetAwaiter().GetResult();
|
||||
_options = new ServerOptions
|
||||
{
|
||||
DataDirectory = _testDir,
|
||||
MaxFileSizeMb = 5
|
||||
};
|
||||
_fileService = new FileStorageService(_db, _options);
|
||||
}
|
||||
|
||||
public void Dispose()
|
||||
{
|
||||
_db.Dispose();
|
||||
try
|
||||
{
|
||||
if (Directory.Exists(_testDir))
|
||||
{
|
||||
Directory.Delete(_testDir, true);
|
||||
}
|
||||
}
|
||||
catch { }
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task StoreAndReadFile_ShouldPreserveExactContentAndComputeSha256()
|
||||
{
|
||||
var channels = await _db.GetChannelsAsync();
|
||||
var general = channels[0];
|
||||
|
||||
string fileContent = "Hello from GsDChat test file storage! Secure and modular.";
|
||||
byte[] fileBytes = Encoding.UTF8.GetBytes(fileContent);
|
||||
|
||||
using var memoryStream = new MemoryStream(fileBytes);
|
||||
var record = await _fileService.StoreFileAsync(
|
||||
general.Id,
|
||||
"uploader-1",
|
||||
"Tester",
|
||||
"test_note.txt",
|
||||
"text/plain",
|
||||
memoryStream,
|
||||
fileBytes.Length
|
||||
);
|
||||
|
||||
Assert.NotNull(record);
|
||||
Assert.Equal("test_note.txt", record.OriginalFileName);
|
||||
Assert.Equal(fileBytes.Length, record.FileSizeBytes);
|
||||
Assert.False(string.IsNullOrWhiteSpace(record.Sha256Checksum));
|
||||
|
||||
// Read file back
|
||||
var fetchedRecord = await _fileService.GetFileRecordAsync(record.Id);
|
||||
Assert.NotNull(fetchedRecord);
|
||||
Assert.Equal(record.Sha256Checksum, fetchedRecord.Sha256Checksum);
|
||||
|
||||
using var stream = _fileService.OpenFileStream(fetchedRecord);
|
||||
Assert.NotNull(stream);
|
||||
using var reader = new StreamReader(stream, Encoding.UTF8);
|
||||
string readBack = await reader.ReadToEndAsync();
|
||||
Assert.Equal(fileContent, readBack);
|
||||
}
|
||||
}
|
||||
29
tests/GsDChat.Tests/GsDChat.Tests.csproj
Normal file
29
tests/GsDChat.Tests/GsDChat.Tests.csproj
Normal file
|
|
@ -0,0 +1,29 @@
|
|||
<Project Sdk="Microsoft.NET.Sdk">
|
||||
|
||||
<PropertyGroup>
|
||||
<TargetFramework>net10.0</TargetFramework>
|
||||
<ImplicitUsings>enable</ImplicitUsings>
|
||||
<Nullable>enable</Nullable>
|
||||
<IsPackable>false</IsPackable>
|
||||
</PropertyGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<PackageReference Include="coverlet.collector" Version="6.0.4" />
|
||||
<PackageReference Include="Microsoft.NET.Test.Sdk" Version="17.14.1" />
|
||||
<PackageReference Include="xunit" Version="2.9.3" />
|
||||
<PackageReference Include="xunit.runner.visualstudio" Version="3.1.4" />
|
||||
</ItemGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<Using Include="Xunit" />
|
||||
</ItemGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<ProjectReference Include="..\..\src\GsDChat.Core\GsDChat.Core.csproj" />
|
||||
<ProjectReference Include="..\..\src\GsDChat.Server\GsDChat.Server.csproj" />
|
||||
<ProjectReference Include="..\..\src\GsDChat.Client\GsDChat.Client.csproj" />
|
||||
<ProjectReference Include="..\..\src\GsDChat.Modding\GsDChat.Modding.csproj" />
|
||||
<ProjectReference Include="..\..\src\GsDChat.Mods.SampleBot\GsDChat.Mods.SampleBot.csproj" />
|
||||
</ItemGroup>
|
||||
|
||||
</Project>
|
||||
199
tests/GsDChat.Tests/ModSystemTests.cs
Normal file
199
tests/GsDChat.Tests/ModSystemTests.cs
Normal 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);
|
||||
}
|
||||
}
|
||||
42
tests/GsDChat.Tests/NetworkProtocolTests.cs
Normal file
42
tests/GsDChat.Tests/NetworkProtocolTests.cs
Normal file
|
|
@ -0,0 +1,42 @@
|
|||
using GsDChat.Core.Protocol;
|
||||
using Xunit;
|
||||
|
||||
namespace GsDChat.Tests;
|
||||
|
||||
public class NetworkProtocolTests
|
||||
{
|
||||
[Fact]
|
||||
public void NetworkEnvelope_PackingAndUnpacking_ShouldPreserveData()
|
||||
{
|
||||
var authPacket = new AuthPacket
|
||||
{
|
||||
Token = "test_token_12345",
|
||||
ServerPassword = "server_secret"
|
||||
};
|
||||
|
||||
var envelope = NetworkEnvelope.Create(MessageTypes.Auth, authPacket);
|
||||
Assert.Equal(MessageTypes.Auth, envelope.Type);
|
||||
Assert.Contains("test_token_12345", envelope.Payload);
|
||||
|
||||
var unpacked = envelope.Unpack<AuthPacket>();
|
||||
Assert.NotNull(unpacked);
|
||||
Assert.Equal("test_token_12345", unpacked.Token);
|
||||
Assert.Equal("server_secret", unpacked.ServerPassword);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void ServerUiSync_DefaultSchema_ContainsAllStandardScreens()
|
||||
{
|
||||
var sync = ServerUiSync.CreateDefault("TestServer", "Welcome MOTD");
|
||||
|
||||
Assert.Equal("TestServer", sync.ServerName);
|
||||
Assert.Equal("Welcome MOTD", sync.Motd);
|
||||
Assert.NotNull(sync.Screens);
|
||||
Assert.Equal(4, sync.Screens.Count);
|
||||
|
||||
Assert.Contains(sync.Screens, s => s.ScreenId == "F1_Chat");
|
||||
Assert.Contains(sync.Screens, s => s.ScreenId == "F2_Channels");
|
||||
Assert.Contains(sync.Screens, s => s.ScreenId == "F3_Users");
|
||||
Assert.Contains(sync.Screens, s => s.ScreenId == "F4_Files");
|
||||
}
|
||||
}
|
||||
Loading…
Add table
Add a link
Reference in a new issue