init
This commit is contained in:
commit
f25ba8adcd
64 changed files with 5959 additions and 0 deletions
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);
|
||||
}
|
||||
}
|
||||
Loading…
Add table
Add a link
Reference in a new issue