GsDChat/tests/GsDChat.Tests/DatabaseTests.cs

382 lines
14 KiB
C#

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);
}
[Fact]
public void ServerSettingsManager_ShouldLoadAndPersistLocalJsonFile()
{
string settingsPath = Path.Combine(_testDir, "serversettings.json");
var manager = new GsDChat.Server.Configuration.ServerSettingsManager(settingsPath);
var options = manager.LoadOrCreate();
Assert.True(File.Exists(settingsPath));
Assert.True(options.AllowDmE2ee);
Assert.Equal(10, options.MaxGroupChatUsers);
Assert.False(string.IsNullOrWhiteSpace(options.VapidPublicKey));
Assert.False(string.IsNullOrWhiteSpace(options.VapidPrivateKey));
options.ServerName = "Custom JSON Server";
options.AllowDmE2ee = false;
options.MaxGroupChatUsers = 25;
manager.Save(options);
var reloaded = manager.LoadOrCreate();
Assert.Equal("Custom JSON Server", reloaded.ServerName);
Assert.False(reloaded.AllowDmE2ee);
Assert.Equal(25, reloaded.MaxGroupChatUsers);
}
[Fact]
public async Task DirectMessage_And_GroupChat_DatabaseOperations_ShouldSucceed()
{
var alice = new User { Username = "Alice", PasswordHash = "h", PasswordSalt = "s", PublicKey = "pubA" };
var bob = new User { Username = "Bob", PasswordHash = "h", PasswordSalt = "s", PublicKey = "pubB" };
var charlie = new User { Username = "Charlie", PasswordHash = "h", PasswordSalt = "s", PublicKey = "pubC" };
await _db.CreateUserAsync(alice);
await _db.CreateUserAsync(bob);
await _db.CreateUserAsync(charlie);
// DM creation and reuse
var dm1 = await _db.GetOrCreateDirectMessageAsync(alice.Id, bob.Id, allowDmE2ee: true);
var dm2 = await _db.GetOrCreateDirectMessageAsync(bob.Id, alice.Id, allowDmE2ee: true);
Assert.Equal(dm1.Id, dm2.Id);
Assert.Equal(ChannelTypes.DirectMessage, dm1.Type);
Assert.True(dm1.IsE2ee);
Assert.Equal(2, dm1.MemberIds.Count);
var aliceDms = await _db.GetDirectMessagesForUserAsync(alice.Id, allowDmE2ee: true);
Assert.Single(aliceDms);
Assert.Equal("Bob", aliceDms[0].Name);
// Group chat creation and membership
var group = await _db.CreateGroupChatAsync("Devs", "Dev Group", alice.Id, new[] { bob.Id }, maxUsers: 5);
Assert.Equal(ChannelTypes.Group, group.Type);
Assert.Equal(2, group.MemberIds.Count);
Assert.Equal(5, group.MaxUsers);
await _db.AddGroupMemberAsync(group.Id, charlie.Id);
var updatedGroup = await _db.GetChannelByIdAsync(group.Id);
Assert.NotNull(updatedGroup);
Assert.Equal(3, updatedGroup.MemberIds.Count);
await _db.RemoveGroupMemberAsync(group.Id, charlie.Id);
updatedGroup = await _db.GetChannelByIdAsync(group.Id);
Assert.Equal(2, updatedGroup!.MemberIds.Count);
// Save a message and a physical file in the group, then remove remaining members -> group, message, and physical file should be cleaned up
string tempFilePath = Path.Combine(_testDir, "group_file_test.bin");
await File.WriteAllTextAsync(tempFilePath, "temporary group file");
await _db.SaveFileRecordAsync(new FileRecord
{
Id = "file_grp_1",
ChannelId = group.Id,
UploaderId = alice.Id,
UploaderUsername = alice.Username,
OriginalFileName = "group_file_test.bin",
StoragePath = tempFilePath,
FileSizeBytes = 20,
CreatedAt = DateTime.UtcNow
});
await _db.SaveMessageAsync(new ChatMessage
{
ChannelId = group.Id,
SenderId = alice.Id,
SenderUsername = alice.Username,
Content = "Group message before deletion"
});
await _db.RemoveGroupMemberAsync(group.Id, bob.Id);
await _db.RemoveGroupMemberAsync(group.Id, alice.Id);
Assert.Null(await _db.GetChannelByIdAsync(group.Id));
Assert.Equal(0, await _db.GetMessageCountAsync(group.Id));
Assert.Null(await _db.GetFileRecordAsync("file_grp_1"));
Assert.False(File.Exists(tempFilePath));
}
[Fact]
public async Task InboxAndWebPushSubscriptions_DatabaseCrudOperations_ShouldSucceed()
{
var bob = new User { Username = "BobInbox", PasswordHash = "h", PasswordSalt = "s" };
await _db.CreateUserAsync(bob);
// 1. Default preferences & channel follow overrides
var prefs = await _db.GetInboxPreferencesAsync(bob.Id);
Assert.True(prefs.MentionsEnabled);
Assert.True(prefs.AnnouncementsEnabled);
Assert.True(prefs.DirectMessagesEnabled);
Assert.True(prefs.FollowedChannelsEnabled);
Assert.True(prefs.PushNotificationsEnabled);
Assert.Empty(prefs.FollowedChannelIds);
Assert.Empty(prefs.MutedChannelIds);
var channels = await _db.GetChannelsAsync();
var general = channels.First(c => c.Name == "general");
var announcements = channels.First(c => c.Name == "announcements");
await _db.SetChannelFollowModeAsync(bob.Id, general.Id, ConversationFollowModes.Followed);
await _db.SetChannelFollowModeAsync(bob.Id, announcements.Id, ConversationFollowModes.Muted);
prefs.MentionsEnabled = false;
await _db.SaveInboxPreferencesAsync(prefs);
var reloadedPrefs = await _db.GetInboxPreferencesAsync(bob.Id);
Assert.False(reloadedPrefs.MentionsEnabled);
Assert.Contains(general.Id, reloadedPrefs.FollowedChannelIds);
Assert.Contains(announcements.Id, reloadedPrefs.MutedChannelIds);
// 2. Inbox Items CRUD
var item1 = new InboxItem
{
UserId = bob.Id,
MessageId = "msg_1",
ChannelId = general.Id,
ChannelName = "general",
ChannelType = ChannelTypes.Channel,
SenderId = "u_alice",
SenderUsername = "Alice",
Category = InboxCategories.Mention,
ContentPreview = "Hey @BobInbox!",
IsRead = false,
CreatedAt = DateTime.UtcNow.AddMinutes(-2)
};
var item2 = new InboxItem
{
UserId = bob.Id,
MessageId = "msg_2",
ChannelId = announcements.Id,
ChannelName = "announcements",
ChannelType = ChannelTypes.Channel,
SenderId = "u_alice",
SenderUsername = "Alice",
Category = InboxCategories.Announcement,
ContentPreview = "Server maintenance tonight",
IsRead = false,
CreatedAt = DateTime.UtcNow
};
await _db.CreateInboxItemAsync(item1);
await _db.CreateInboxItemAsync(item2);
Assert.Equal(2, await _db.GetUnreadInboxCountAsync(bob.Id));
var items = await _db.GetInboxItemsForUserAsync(bob.Id);
Assert.Equal(2, items.Count);
Assert.Equal(item2.Id, items[0].Id); // Ordered newest first
// Mark channel read
await _db.MarkChannelInboxItemsReadAsync(bob.Id, general.Id);
Assert.Equal(1, await _db.GetUnreadInboxCountAsync(bob.Id));
// Clear read items
await _db.ClearInboxItemsAsync(bob.Id, onlyRead: true);
items = await _db.GetInboxItemsForUserAsync(bob.Id);
Assert.Single(items);
Assert.Equal(item2.Id, items[0].Id);
// Mark all read & clear all
await _db.MarkAllInboxItemsReadAsync(bob.Id);
Assert.Equal(0, await _db.GetUnreadInboxCountAsync(bob.Id));
await _db.ClearInboxItemsAsync(bob.Id, onlyRead: false);
Assert.Empty(await _db.GetInboxItemsForUserAsync(bob.Id));
// 3. Web Push Subscriptions CRUD
var sub = new PushSubscriptionRecord
{
UserId = bob.Id,
Endpoint = "https://push.example.org/send/sub_1",
P256dh = "p256dh_key_value",
Auth = "auth_secret_value",
UserAgent = "Mozilla/5.0 Test"
};
await _db.SavePushSubscriptionAsync(sub);
var subs = await _db.GetPushSubscriptionsForUserAsync(bob.Id);
Assert.Single(subs);
Assert.Equal("https://push.example.org/send/sub_1", subs[0].Endpoint);
await _db.RemovePushSubscriptionByEndpointAsync("https://push.example.org/send/sub_1");
Assert.Empty(await _db.GetPushSubscriptionsForUserAsync(bob.Id));
}
[Fact]
public async Task DeleteFileRecord_ShouldDeleteRecordAndAssociatedAttachmentMessages()
{
var channels = await _db.GetChannelsAsync();
var general = channels[0];
var file = new FileRecord
{
Id = "file_delete_test_1",
ChannelId = general.Id,
UploaderId = "user_uploader_1",
UploaderUsername = "uploader_user",
OriginalFileName = "document_to_delete.pdf",
ContentType = "application/pdf",
FileSizeBytes = 1234,
StoragePath = "/tmp/dummy.pdf",
Sha256Checksum = "dummy_sha256",
CreatedAt = DateTime.UtcNow
};
await _db.SaveFileRecordAsync(file);
var msg = new ChatMessage
{
ChannelId = general.Id,
SenderId = "user_uploader_1",
SenderUsername = "uploader_user",
Content = "Shared file: document_to_delete.pdf",
AttachmentId = file.Id,
AttachmentName = file.OriginalFileName,
AttachmentSizeBytes = file.FileSizeBytes
};
await _db.SaveMessageAsync(msg);
// Verify file is returned in recent files and includes UploaderId
var recent = await _db.GetRecentFilesAsync();
var summary = recent.Find(f => f.Id == file.Id);
Assert.NotNull(summary);
Assert.Equal("user_uploader_1", summary.UploaderId);
Assert.Equal("uploader_user", summary.UploaderUsername);
// Verify message exists
var msgs = await _db.GetRecentMessagesAsync(general.Id);
Assert.Contains(msgs, m => m.AttachmentId == file.Id);
// Delete file record
bool deleted = await _db.DeleteFileRecordAsync(file.Id);
Assert.True(deleted);
// Verify file record is gone
Assert.Null(await _db.GetFileRecordAsync(file.Id));
recent = await _db.GetRecentFilesAsync();
Assert.DoesNotContain(recent, f => f.Id == file.Id);
// Verify message with attachment_id is gone
msgs = await _db.GetRecentMessagesAsync(general.Id);
Assert.DoesNotContain(msgs, m => m.AttachmentId == file.Id);
}
}