English
Testing chats
Step 1. A notifier that records
Why. Tests must prove that the service raises the right events, not only that it saves the right data. A fake notifier that writes every event into a list as "Name:chatId" lets a test check Notifier.Events.ShouldContain($"MembersAdded:{chat.Id}").
Do. Extend Fakes.cs (new lines in green):
cs
using System.Collections.Concurrent;
using Chatex.Core.Abstractions;
using Chatex.Core.Messages;
using Chatex.Data.Abstractions;
namespace Chatex.Core.Tests;
public sealed class InMemoryFileStorage : IFileStorage
{
private readonly ConcurrentDictionary<string, byte[]> _files = new();
public int Count => _files.Count;
public async Task<string> SaveAsync(Stream content, CancellationToken cancellationToken = default)
{
var copy = new MemoryStream();
await content.CopyToAsync(copy, cancellationToken);
var path = $"test/{Guid.NewGuid():N}";
_files[path] = copy.ToArray();
return path;
}
public Task<Stream> OpenReadAsync(string storagePath, CancellationToken cancellationToken = default) =>
_files.TryGetValue(storagePath, out var bytes)
? Task.FromResult<Stream>(new MemoryStream(bytes))
: throw new FileNotFoundException(storagePath);
public Task DeleteAsync(string storagePath, CancellationToken cancellationToken = default)
{
_files.TryRemove(storagePath, out _);
return Task.CompletedTask;
}
}
/// <summary>Records every event as "Name:chatId".</summary>
public sealed class RecordingNotifier : IChatNotifier
{
private readonly ConcurrentQueue<string> _events = new();
public IReadOnlyList<string> Events => [.. _events];
public Task MessageCreatedAsync(MessageDto message, CancellationToken cancellationToken = default) =>
Record("MessageCreated", message.ChatId);
public Task MessageUpdatedAsync(MessageDto message, CancellationToken cancellationToken = default) =>
Record("MessageUpdated", message.ChatId);
public Task MessageDeletedAsync(Guid chatId, Guid messageId, CancellationToken cancellationToken = default) =>
Record("MessageDeleted", chatId);
public Task MessagesReadAsync(Guid chatId, Guid userId, Guid lastReadMessageId, CancellationToken cancellationToken = default) =>
Record("MessagesRead", chatId);
public Task MembersAddedAsync(Guid chatId, IReadOnlyCollection<Guid> userIds, CancellationToken cancellationToken = default) =>
Record("MembersAdded", chatId);
public Task MemberRemovedAsync(Guid chatId, Guid userId, CancellationToken cancellationToken = default) =>
Record("MemberRemoved", chatId);
public Task ChatUpdatedAsync(Guid chatId, CancellationToken cancellationToken = default) => Record("ChatUpdated", chatId);
public Task ChatDeletedAsync(Guid chatId, CancellationToken cancellationToken = default) => Record("ChatDeleted", chatId);
private Task Record(string name, Guid chatId)
{
_events.Enqueue($"{name}:{chatId}");
return Task.CompletedTask;
}
} ConcurrentQueue keeps the order of the events; Events returns a snapshot of them with a collection expression and the spread operator [.. _events].
Step 2. New helpers
Do. Extend BusinessTestBase (new lines in green):
cs
using Chatex.Core.Abstractions;
using Chatex.Core.Auth;
using Chatex.Core.Chats;
using Chatex.Core.Common;
using Chatex.Core.Users;
using Chatex.Data.Abstractions;
using Chatex.Data.Entities;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.DependencyInjection.Extensions;
using Microsoft.Extensions.Time.Testing;
// Tests share one database that is wiped before each test; xunit.runner.json turns off parallel runs.
[assembly: AssemblyFixture(typeof(PostgresFixture))]
namespace Chatex.Core.Tests;
public abstract class BusinessTestBase(PostgresFixture fixture) : DatabaseTest(fixture)
{
public const string Password = "Passw0rd!";
public const string Issuer = "chatex-tests";
public const string SigningKey = "test-signing-key-that-is-long-enough-for-hmac";
protected FakeTimeProvider Time { get; } = new(DateTimeOffset.UtcNow);
protected InMemoryFileStorage Files { get; } = new();
protected RecordingNotifier Notifier { get; } = new();
protected override void ConfigureServices(IServiceCollection services, string connectionString)
{
var configuration = new ConfigurationBuilder()
.AddInMemoryCollection(new Dictionary<string, string?>
{
["ConnectionStrings:Chatex"] = connectionString,
["Storage:RootPath"] = StorageRoot,
["Jwt:Issuer"] = Issuer,
["Jwt:Audience"] = Issuer,
["Jwt:SigningKey"] = SigningKey,
})
.Build();
services.AddSingleton<TimeProvider>(Time);
services.AddSingleton<IChatNotifier>(Notifier);
services.AddCore(configuration);
services.Replace(ServiceDescriptor.Singleton<IFileStorage>(Files));
}
protected Task<T> Auth<T>(Func<IAuthService, Task<T>> call) => Use(call);
protected Task<T> Profiles<T>(Func<IProfileService, Task<T>> call) => Use(call);
protected Task<T> Chats<T>(Func<IChatService, Task<T>> call) => Use(call);
/// <summary>Registers <paramref name="userName"/> and returns the signed-in session.</summary>
protected async Task<AuthResult> RegisterAsync(string userName)
{
var result = await Auth(s => s.RegisterAsync(
new RegisterCommand(userName, $"{userName}@example.test", Password, $"{userName} display"), ClientInfo.Unknown, Ct));
return result.ShouldSucceed();
}
protected async Task<Guid> RegisterUserAsync(string userName) => (await RegisterAsync(userName)).User.Id;
protected async Task<ChatDto> CreateChatAsync(
Guid ownerId, ChatType type, string? handle = null, params Guid[] memberIds)
{
var result = await Chats(s => s.CreateAsync(ownerId, new CreateChatCommand(type, $"{type} chat", null, handle, memberIds), Ct));
return result.ShouldSucceed();
}
protected static FileUpload Upload(int size, string contentType, long? claimedLength = null) =>
new(new MemoryStream(new byte[size]), "photo.png", contentType, claimedLength ?? size);
private async Task<T> Use<TService, T>(Func<TService, Task<T>> call) where TService : notnull
{
await using var scope = NewScope();
return await call(Get<TService>(scope));
}
}
internal static class ResultAssertions
{
public static T ShouldSucceed<T>(this Result<T> result)
{
result.IsSuccess.ShouldBeTrue($"Expected success but got {result.Error}");
return result.Value;
}
public static void ShouldSucceed(this Result result) =>
result.IsSuccess.ShouldBeTrue($"Expected success but got {result.Error}");
public static Error ShouldFail<T>(this Result<T> result, ErrorKind kind, string code)
{
result.IsSuccess.ShouldBeFalse("Expected a failure but the operation succeeded.");
result.Error.Kind.ShouldBe(kind);
result.Error.Code.ShouldBe(code);
return result.Error;
}
public static Error ShouldFail(this Result result, ErrorKind kind, string code)
{
result.IsSuccess.ShouldBeFalse("Expected a failure but the operation succeeded.");
result.Error.Kind.ShouldBe(kind);
result.Error.Code.ShouldBe(code);
return result.Error;
}
}services.AddSingleton<IChatNotifier>(Notifier)comes beforeAddCore, soTryAddSingletoninAddCorekeeps the fake.CreateChatAsync(ownerId, type, handle, memberIds)creates a group or channel with a title made from its type;params Guid[] memberIdslets a test writeCreateChatAsync(alice, ChatType.Group, null, bob, carol).
Step 3. The chat tests
Do.
cs
using Chatex.Core.Chats;
using Chatex.Core.Common;
using Chatex.Data.Entities;
namespace Chatex.Core.Tests;
public sealed class ChatServiceTests(PostgresFixture fixture) : BusinessTestBase(fixture)
{
[Fact]
public async Task OpenDirectAsync_returns_the_same_chat_from_both_sides()
{
var alice = await RegisterUserAsync("alice");
var bob = await RegisterUserAsync("bob");
var first = (await Chats(s => s.OpenDirectAsync(alice, bob, Ct))).ShouldSucceed();
var second = (await Chats(s => s.OpenDirectAsync(bob, alice, Ct))).ShouldSucceed();
second.Id.ShouldBe(first.Id);
first.Type.ShouldBe(ChatType.Direct);
first.Peer.ShouldNotBeNull().UserName.ShouldBe("bob");
second.Peer.ShouldNotBeNull().UserName.ShouldBe("alice");
first.MemberCount.ShouldBe(2);
}
[Fact]
public async Task OpenDirectAsync_rejects_yourself_and_unknown_users()
{
var alice = await RegisterUserAsync("alice");
(await Chats(s => s.OpenDirectAsync(alice, alice, Ct))).ShouldFail(ErrorKind.Validation, "direct_with_self");
(await Chats(s => s.OpenDirectAsync(alice, Guid.NewGuid(), Ct))).ShouldFail(ErrorKind.NotFound, "user_not_found");
}
[Fact]
public async Task CreateAsync_makes_the_caller_owner_and_keeps_handles_unique()
{
var alice = await RegisterUserAsync("alice");
var bob = await RegisterUserAsync("bob");
var channel = await CreateChatAsync(alice, ChatType.Channel, "News_Room", bob);
var duplicate = await Chats(s => s.CreateAsync(bob, new CreateChatCommand(ChatType.Group, "Copy", PublicHandle: "news_ROOM"), Ct));
channel.MyRole.ShouldBe(ChatMemberRole.Owner);
channel.PublicHandle.ShouldBe("news_room");
channel.MemberCount.ShouldBe(2);
duplicate.ShouldFail(ErrorKind.Conflict, "handle_taken");
Notifier.Events.ShouldContain($"MembersAdded:{channel.Id}");
}
[Fact]
public async Task The_owner_must_hand_over_ownership_before_leaving()
{
var alice = await RegisterUserAsync("alice");
var bob = await RegisterUserAsync("bob");
var group = await CreateChatAsync(alice, ChatType.Group, null, bob);
(await Chats(s => s.LeaveAsync(alice, group.Id, Ct))).ShouldFail(ErrorKind.Conflict, "owner_must_transfer");
(await Chats(s => s.ChangeRoleAsync(alice, group.Id, bob, ChatMemberRole.Owner, Ct))).ShouldSucceed();
(await Chats(s => s.GetAsync(alice, group.Id, Ct))).ShouldSucceed().MyRole.ShouldBe(ChatMemberRole.Admin);
(await Chats(s => s.LeaveAsync(alice, group.Id, Ct))).ShouldSucceed();
(await Chats(s => s.GetAsync(bob, group.Id, Ct))).ShouldSucceed().MyRole.ShouldBe(ChatMemberRole.Owner);
}
[Fact]
public async Task Admins_remove_members_but_not_the_owner()
{
var alice = await RegisterUserAsync("alice");
var bob = await RegisterUserAsync("bob");
var carol = await RegisterUserAsync("carol");
var group = await CreateChatAsync(alice, ChatType.Group, null, bob, carol);
(await Chats(s => s.ChangeRoleAsync(alice, group.Id, bob, ChatMemberRole.Admin, Ct))).ShouldSucceed();
(await Chats(s => s.RemoveMemberAsync(bob, group.Id, alice, Ct))).ShouldFail(ErrorKind.Forbidden, "not_allowed");
(await Chats(s => s.RemoveMemberAsync(bob, group.Id, carol, Ct))).ShouldSucceed();
(await Chats(s => s.RemoveMemberAsync(carol, group.Id, bob, Ct))).ShouldFail(ErrorKind.NotFound, "chat_not_found");
}
[Fact]
public async Task Channel_roles_and_member_lists_follow_channel_rules()
{
var alice = await RegisterUserAsync("alice");
var bob = await RegisterUserAsync("bob");
var channel = await CreateChatAsync(alice, ChatType.Channel, null, bob);
(await Chats(s => s.ChangeRoleAsync(alice, channel.Id, bob, ChatMemberRole.Member, Ct)))
.ShouldFail(ErrorKind.Validation, "invalid_role");
(await Chats(s => s.GetMembersAsync(bob, channel.Id, null, null, Ct))).ShouldFail(ErrorKind.Forbidden, "not_allowed");
(await Chats(s => s.GetMembersAsync(alice, channel.Id, null, null, Ct))).ShouldSucceed().Items.Count.ShouldBe(2);
}
[Fact]
public async Task AddMembersAsync_skips_existing_members_and_rejects_unknown_users()
{
var alice = await RegisterUserAsync("alice");
var bob = await RegisterUserAsync("bob");
var carol = await RegisterUserAsync("carol");
var group = await CreateChatAsync(alice, ChatType.Group, null, bob);
(await Chats(s => s.AddMembersAsync(alice, group.Id, [bob, carol], Ct))).ShouldSucceed().ShouldBe(1);
(await Chats(s => s.AddMembersAsync(alice, group.Id, [Guid.NewGuid()], Ct))).ShouldFail(ErrorKind.Validation, "unknown_users");
(await Chats(s => s.AddMembersAsync(bob, group.Id, [carol], Ct))).ShouldFail(ErrorKind.Forbidden, "not_allowed");
}
[Fact]
public async Task Deleted_chats_disappear_for_everyone()
{
var alice = await RegisterUserAsync("alice");
var bob = await RegisterUserAsync("bob");
var group = await CreateChatAsync(alice, ChatType.Group, null, bob);
(await Chats(s => s.DeleteAsync(bob, group.Id, Ct))).ShouldFail(ErrorKind.Forbidden, "not_allowed");
(await Chats(s => s.DeleteAsync(alice, group.Id, Ct))).ShouldSucceed();
(await Chats(s => s.GetAsync(bob, group.Id, Ct))).ShouldFail(ErrorKind.NotFound, "chat_not_found");
(await Chats(s => s.GetMyChatsAsync(bob, null, null, Ct))).ShouldSucceed().Items.ShouldBeEmpty();
}
[Fact]
public async Task GetMyChatsAsync_rejects_a_tampered_cursor()
{
var alice = await RegisterUserAsync("alice");
var result = await Chats(s => s.GetMyChatsAsync(alice, "not-a-cursor", null, Ct));
result.ShouldFail(ErrorKind.Validation, "invalid_cursor");
}
}Each test is one rule of Docs/ChatRules.md:
- Direct chats: both sides get the same chat, each sees the other as the peer; a chat with yourself and with an unknown user is refused.
- Creation: the creator is the owner, the handle is lower-cased, a handle in another case is taken, and
MembersAddedwas raised. - Ownership: the owner cannot leave; after transferring ownership to Bob, Alice is an admin and may leave, and Bob is the owner.
- Removing: an admin cannot remove the owner but can remove a member; a removed member no longer sees the private group at all (
chat_not_found, notnot_allowed). - Channels:
Memberis not a channel role; subscribers cannot list members, the owner can. - Adding skips existing members (returns 1 for
[bob, carol]when Bob is already in), rejects unknown users and refuses a plain member. - Deleting: only the owner; afterwards the chat is gone for everyone, including from their chat lists.
- Cursors: a tampered cursor is
invalid_cursor.
Four more tests of this class need sending messages; they are added in topic 11.
Check
powershell
dotnet test --solution Chatex.slnx45 tests pass: 19 data tests and 26 business tests.