English
Testing the repositories
Each step of this chapter adds a test class (or tests to an existing one) for one area of the data layer. Type the tests, run them, and for at least one test per class break the code it protects and watch the test fail, as in the previous chapter.
Step 1. The message history
Why. Keyset paging (topic 5) is easy to get subtly wrong: an off-by-one at the page boundary, a missing Take(limit + 1), the wrong sort direction for after. The tests use 120 messages with known order and check every boundary.
Do.
cs
using Chatex.Data.Abstractions;
using Chatex.Data.Entities;
namespace Chatex.Data.Tests;
public sealed class MessageRepositoryTests(PostgresFixture fixture) : DbTestBase(fixture)
{
[Fact]
public async Task GetPageAsync_pages_backwards_through_history_newest_first()
{
var alice = await CreateUserAsync("alice");
var chat = await CreateChatAsync(ChatType.Group, alice, []);
var messages = await AddMessagesAsync(chat, alice, 120);
var ids = messages.Select(m => m.Id).ToList();
await using var scope = NewScope();
var repository = Get<IMessageRepository>(scope);
var page1 = await repository.GetPageAsync(chat.Id, before: null, after: null, limit: 50, Ct);
var page2 = await repository.GetPageAsync(chat.Id, before: page1.NextCursor, after: null, limit: 50, Ct);
var page3 = await repository.GetPageAsync(chat.Id, before: page2.NextCursor, after: null, limit: 50, Ct);
page1.Items.Select(m => m.Id).ShouldBe(ids[70..120].AsEnumerable().Reverse());
page2.Items.Select(m => m.Id).ShouldBe(ids[20..70].AsEnumerable().Reverse());
page3.Items.Select(m => m.Id).ShouldBe(ids[0..20].AsEnumerable().Reverse());
page1.NextCursor.ShouldBe(ids[70]);
page3.NextCursor.ShouldBeNull();
page1.Items[0].Sender.Profile.ShouldNotBeNull();
}
[Fact]
public async Task GetPageAsync_after_returns_newer_messages_oldest_first()
{
var alice = await CreateUserAsync("alice");
var chat = await CreateChatAsync(ChatType.Group, alice, []);
var ids = (await AddMessagesAsync(chat, alice, 30)).Select(m => m.Id).ToList();
await using var scope = NewScope();
var repository = Get<IMessageRepository>(scope);
var page1 = await repository.GetPageAsync(chat.Id, before: null, after: ids[9], limit: 15, Ct);
var page2 = await repository.GetPageAsync(chat.Id, before: null, after: page1.NextCursor, limit: 15, Ct);
page1.Items.Select(m => m.Id).ShouldBe(ids[10..25]);
page2.Items.Select(m => m.Id).ShouldBe(ids[25..30]);
page2.NextCursor.ShouldBeNull();
}
[Fact]
public async Task GetPageAsync_only_returns_messages_of_the_chat()
{
var alice = await CreateUserAsync("alice");
var chat = await CreateChatAsync(ChatType.Group, alice, []);
var other = await CreateChatAsync(ChatType.Group, alice, []);
await AddMessagesAsync(chat, alice, 3);
await AddMessagesAsync(other, alice, 5);
await using var scope = NewScope();
var page = await Get<IMessageRepository>(scope).GetPageAsync(chat.Id, null, null, 50, Ct);
page.Items.Count.ShouldBe(3);
page.Items.ShouldAllBe(m => m.ChatId == chat.Id);
}
}- Ranges such as
ids[70..120]take the elements 70 to 119 (the end is exclusive). With 120 messages and pages of 50, the pages are messages 119–70, 69–20 and 19–0, newest first;.AsEnumerable().Reverse()turns the ascending range into that order. ShouldBeon sequences compares the elements in order and, on failure, prints both sequences and the first difference.page1.NextCursor.ShouldBe(ids[70])pins the contract of the cursor: it is the id of the last returned item.- The third test protects against the most dangerous bug of all — a page that leaks messages of another chat.
Step 2. Members and read positions
Do.
cs
using Chatex.Data.Abstractions;
using Chatex.Data.Entities;
namespace Chatex.Data.Tests;
public sealed class ChatMemberRepositoryTests(PostgresFixture fixture) : DbTestBase(fixture)
{
[Fact]
public async Task MarkReadAsync_only_moves_the_read_position_forward()
{
var alice = await CreateUserAsync("alice");
var bob = await CreateUserAsync("bob");
var chat = await CreateChatAsync(ChatType.Group, alice, [bob]);
var messages = await AddMessagesAsync(chat, alice, 10);
await using var scope = NewScope();
var repository = Get<IChatMemberRepository>(scope);
(await repository.MarkReadAsync(chat.Id, bob.Id, messages[5].Id, Ct)).ShouldBeTrue();
(await repository.MarkReadAsync(chat.Id, bob.Id, messages[3].Id, Ct)).ShouldBeFalse();
(await repository.MarkReadAsync(chat.Id, bob.Id, messages[7].Id, Ct)).ShouldBeTrue();
var member = await repository.GetAsync(chat.Id, bob.Id, Ct);
member.ShouldNotBeNull().LastReadMessageId.ShouldBe(messages[7].Id);
}
[Fact]
public async Task GetMembersAsync_pages_through_members_with_profiles()
{
var owner = await CreateUserAsync("owner");
var others = new List<User>();
for (var i = 0; i < 4; i++)
{
others.Add(await CreateUserAsync($"user{i}"));
}
var chat = await CreateChatAsync(ChatType.Channel, owner, others);
await using var scope = NewScope();
var repository = Get<IChatMemberRepository>(scope);
var page1 = await repository.GetMembersAsync(chat.Id, afterUserId: null, limit: 3, Ct);
var page2 = await repository.GetMembersAsync(chat.Id, afterUserId: page1.NextCursor, limit: 3, Ct);
page1.Items.Count.ShouldBe(3);
page2.Items.Count.ShouldBe(2);
page2.NextCursor.ShouldBeNull();
page1.Items.Concat(page2.Items).Select(m => m.UserId).ShouldBeUnique();
page1.Items.ShouldAllBe(m => m.User.Profile != null);
(await repository.CountAsync(chat.Id, Ct)).ShouldBe(5);
}
[Fact]
public async Task GetChatIdsForUserAsync_skips_deleted_chats()
{
var alice = await CreateUserAsync("alice");
var kept = await CreateChatAsync(ChatType.Group, alice, []);
var deleted = await CreateChatAsync(ChatType.Group, alice, []);
await using var scope = NewScope();
var chat = await Get<IChatRepository>(scope).GetByIdAsync(deleted.Id, Ct);
chat.ShouldNotBeNull().DeletedAt = DateTimeOffset.UtcNow;
await Get<IUnitOfWork>(scope).SaveChangesAsync(Ct);
var ids = await Get<IChatMemberRepository>(scope).GetChatIdsForUserAsync(alice.Id, Ct);
ids.ShouldBe([kept.Id]);
}
[Fact]
public void Only_owners_and_admins_post_in_channels()
{
new ChatMember { Role = ChatMemberRole.Subscriber }.CanPost(ChatType.Channel).ShouldBeFalse();
new ChatMember { Role = ChatMemberRole.Admin }.CanPost(ChatType.Channel).ShouldBeTrue();
new ChatMember { Role = ChatMemberRole.Member }.CanPost(ChatType.Group).ShouldBeTrue();
}
}MarkReadAsync_only_moves_the_read_position_forwardreads like its rule: forward to 5 (changed), back to 3 (refused), forward to 7 (changed), and the stored position is 7.ShouldBeUniquechecks that the two pages of members do not overlap.GetChatIdsForUserAsync_skips_deleted_chatssoft-deletes a chat through a tracked entity andSaveChangesAsync— the way a service will do it in topic 10.Only_owners_and_admins_post_in_channelsis a plain unit test ofChatMember.CanPost; it needs no database and is notasync. It lives here becauseCanPostis part of the data layer.
Step 3. The chat list and public search
Why. GetUserChatsAsync is the most complex query of the project: order, paging with a two-part cursor, the last message, the unread counter with its three conditions and the peer. One test builds a small world in which every condition matters.
Do. Add the remaining tests to ChatRepositoryTests (new lines in green):
cs
using Chatex.Data.Abstractions;
using Chatex.Data.Entities;
using Chatex.Data.Exceptions;
using Microsoft.EntityFrameworkCore;
using Npgsql;
namespace Chatex.Data.Tests;
public sealed class ChatRepositoryTests(PostgresFixture fixture) : DbTestBase(fixture)
{
[Fact]
public async Task A_pair_of_users_can_have_only_one_direct_chat()
{
var alice = await CreateUserAsync("alice");
var bob = await CreateUserAsync("bob");
await CreateChatAsync(ChatType.Direct, alice, [bob]);
var error = await Should.ThrowAsync<UniqueConstraintException>(() => CreateChatAsync(ChatType.Direct, bob, [alice]));
error.ConstraintName.ShouldBe("ix_chats_direct_key");
}
[Fact]
public async Task Only_direct_chats_have_a_direct_key()
{
var alice = await CreateUserAsync("alice");
var bob = await CreateUserAsync("bob");
await using var scope = NewScope();
Get<IChatRepository>(scope).Add(new Chat
{
Type = ChatType.Group,
Title = "group",
DirectKey = Chat.MakeDirectKey(alice.Id, bob.Id),
CreatedById = alice.Id,
});
var error = await Should.ThrowAsync<DbUpdateException>(() => Get<IUnitOfWork>(scope).SaveChangesAsync(Ct));
error.InnerException.ShouldBeOfType<PostgresException>().SqlState.ShouldBe(PostgresErrorCodes.CheckViolation);
}
[Fact]
public async Task GetDirectAsync_finds_the_chat_in_either_order()
{
var alice = await CreateUserAsync("alice");
var bob = await CreateUserAsync("bob");
var chat = await CreateChatAsync(ChatType.Direct, alice, [bob]);
await using var scope = NewScope();
var found = await Get<IChatRepository>(scope).GetDirectAsync(bob.Id, alice.Id, Ct);
found.ShouldNotBeNull().Id.ShouldBe(chat.Id);
}
[Fact]
public async Task GetUserChatsAsync_orders_by_activity_and_counts_unread_messages()
{
var alice = await CreateUserAsync("alice");
var bob = await CreateUserAsync("bob");
var now = DateTimeOffset.UtcNow;
var group = await CreateChatAsync(ChatType.Group, alice, [bob], now.AddHours(-3));
var channel = await CreateChatAsync(ChatType.Channel, bob, [alice], now.AddHours(-2));
var direct = await CreateChatAsync(ChatType.Direct, alice, [bob], now.AddHours(-1));
await CreateChatAsync(ChatType.Group, bob, [], now); // alice is not a member
var fromBob = await AddMessagesAsync(direct, bob, 3);
await AddMessagesAsync(direct, alice, 1); // own messages are never unread
await AddMessagesAsync(channel, bob, 4);
await using var scope = NewScope();
(await Get<IChatMemberRepository>(scope).MarkReadAsync(direct.Id, alice.Id, fromBob[0].Id, Ct)).ShouldBeTrue();
var repository = Get<IChatRepository>(scope);
var page1 = await repository.GetUserChatsAsync(alice.Id, after: null, limit: 2, Ct);
var page2 = await repository.GetUserChatsAsync(alice.Id, after: page1.NextCursor, limit: 2, Ct);
page1.Items.Select(i => i.Chat.Id).ShouldBe([direct.Id, channel.Id]);
page2.Items.Select(i => i.Chat.Id).ShouldBe([group.Id]);
page2.NextCursor.ShouldBeNull();
var directItem = page1.Items[0];
directItem.UnreadCount.ShouldBe(2);
directItem.Peer.ShouldNotBeNull().UserName.ShouldBe("bob");
directItem.LastMessage.ShouldNotBeNull().SenderId.ShouldBe(alice.Id);
var channelItem = page1.Items[1];
channelItem.UnreadCount.ShouldBe(4);
channelItem.Role.ShouldBe(ChatMemberRole.Subscriber);
channelItem.Peer.ShouldBeNull();
page2.Items[0].LastMessage.ShouldBeNull();
page2.Items[0].UnreadCount.ShouldBe(0);
}
[Fact]
public async Task SearchPublicAsync_matches_handle_or_title_of_public_chats_only()
{
var alice = await CreateUserAsync("alice");
await using (var seed = NewScope())
{
var chats = Get<IChatRepository>(seed);
chats.Add(new Chat { Type = ChatType.Channel, Title = "Dotnet news", PublicHandle = "dotnet", CreatedById = alice.Id });
chats.Add(new Chat { Type = ChatType.Group, Title = "Private dotnet", CreatedById = alice.Id });
await Get<IUnitOfWork>(seed).SaveChangesAsync(Ct);
}
await using var scope = NewScope();
var results = await Get<IChatRepository>(scope).SearchPublicAsync("DOTNET", 10, Ct);
results.Select(c => c.PublicHandle).ShouldBe(["dotnet"]);
}
}The world of the chat list test:
| Chat | Alice's role | Activity | Messages | Expected |
|---|---|---|---|---|
| direct with Bob | member | 1 hour ago | 3 from Bob, 1 from Alice; Alice has read Bob's first | first; 2 unread; peer bob; last message from Alice |
| channel of Bob | subscriber | 2 hours ago | 4 from Bob | second; 4 unread; no peer |
| group of Alice | owner | 3 hours ago | none | on page 2; no last message; 0 unread |
| group of Bob | not a member | now | — | not in the list at all |
- "Own messages are never unread": Alice's own message in the direct chat is newer than her read position, but must not count.
- The group Alice is not in has the newest activity; if the query started from chats instead of memberships, it would come first.
- Paging with a limit of 2 puts the third chat on page 2, which must be the last page.
SearchPublicAsyncsearches in upper case ("DOTNET") and must find only the public channel, not the private group with the same word in its title.
Step 4. Users, transactions and tokens
Why. These tests prove the Unit of Work: a registration that saves both the user and the profile in one transaction, and a registration that fails halfway and leaves nothing behind. They also prove the timestamps of the interceptor and the escaping of search patterns.
Do.
cs
using Chatex.Data.Abstractions;
using Chatex.Data.Entities;
using Microsoft.AspNetCore.Identity;
namespace Chatex.Data.Tests;
public sealed class UserAndAuthTests(PostgresFixture fixture) : DbTestBase(fixture)
{
[Fact]
public async Task Registration_saves_user_and_profile_in_one_transaction()
{
Guid userId;
await using (var scope = NewScope())
{
userId = await Get<IUnitOfWork>(scope).ExecuteInTransactionAsync(async ct =>
{
var user = new User { UserName = "alice", Email = "[email protected]" };
(await Get<UserManager<User>>(scope).CreateAsync(user, "Passw0rd!")).Succeeded.ShouldBeTrue();
Get<IUserRepository>(scope).AddProfile(new UserProfile { UserId = user.Id, DisplayName = "Alice" });
await Get<IUnitOfWork>(scope).SaveChangesAsync(ct);
return user.Id;
}, Ct);
}
await using var check = NewScope();
var saved = await Get<IUserRepository>(check).GetWithProfileAsync(userId, Ct);
saved.ShouldNotBeNull();
saved.CreatedAt.ShouldNotBe(default);
saved.Profile.ShouldNotBeNull().DisplayName.ShouldBe("Alice");
saved.Profile.UpdatedAt.ShouldNotBe(default);
}
[Fact]
public async Task Registration_rolls_back_the_user_when_a_later_step_fails()
{
await using (var scope = NewScope())
{
await Should.ThrowAsync<InvalidOperationException>(() =>
Get<IUnitOfWork>(scope).ExecuteInTransactionAsync(async _ =>
{
var user = new User { UserName = "alice", Email = "[email protected]" };
(await Get<UserManager<User>>(scope).CreateAsync(user, "Passw0rd!")).Succeeded.ShouldBeTrue();
throw new InvalidOperationException("profile step failed");
}, Ct));
}
await using var check = NewScope();
(await Get<UserManager<User>>(check).FindByNameAsync("alice")).ShouldBeNull();
}
[Fact]
public async Task SearchAsync_treats_like_wildcards_as_plain_text()
{
await CreateUserAsync("alice");
await CreateUserAsync("bob_smith");
await using var scope = NewScope();
var repository = Get<IUserRepository>(scope);
(await repository.SearchAsync("_", 10, Ct)).Select(u => u.UserName).ShouldBe(["bob_smith"]);
(await repository.SearchAsync("ALI", 10, Ct)).Select(u => u.UserName).ShouldBe(["alice"]);
}
[Fact]
public async Task RevokeAllForUserAsync_revokes_only_active_tokens_of_that_user()
{
var alice = await CreateUserAsync("alice");
var bob = await CreateUserAsync("bob");
var now = DateTimeOffset.UtcNow;
await using (var seed = NewScope())
{
var tokens = Get<IRefreshTokenRepository>(seed);
tokens.Add(new RefreshToken { UserId = alice.Id, TokenHash = "a1", ExpiresAt = now.AddDays(7) });
tokens.Add(new RefreshToken { UserId = alice.Id, TokenHash = "a2", ExpiresAt = now.AddDays(7) });
tokens.Add(new RefreshToken { UserId = alice.Id, TokenHash = "a-expired", ExpiresAt = now.AddDays(-1) });
tokens.Add(new RefreshToken { UserId = bob.Id, TokenHash = "b1", ExpiresAt = now.AddDays(7) });
await Get<IUnitOfWork>(seed).SaveChangesAsync(Ct);
}
await using var scope = NewScope();
var repository = Get<IRefreshTokenRepository>(scope);
(await repository.RevokeAllForUserAsync(alice.Id, now, Ct)).ShouldBe(2);
(await repository.GetByHashAsync("a1", Ct)).ShouldNotBeNull().IsActiveAt(now).ShouldBeFalse();
(await repository.GetByHashAsync("b1", Ct)).ShouldNotBeNull().IsActiveAt(now).ShouldBeTrue();
(await repository.DeleteStaleAsync(now.AddSeconds(1), Ct)).ShouldBe(3);
}
}- The rollback test throws inside
ExecuteInTransactionAsyncafterUserManagerhas already saved the user. A new scope then looks foralice— and must not find her. Without the transaction, the user would exist without a profile. saved.CreatedAt.ShouldNotBe(default)andsaved.Profile.UpdatedAt.ShouldNotBe(default)are the tests ofTimestampInterceptorthat topic 4 promised.SearchAsync("_", …)must find onlybob_smith: with an unescaped_, every user would match.RevokeAllForUserAsyncrevokes Alice's two active tokens but neither her expired token nor Bob's; thenDeleteStaleAsyncremoves the three tokens that are expired or revoked.
Step 5. The Unit of Work and file storage
Do.
cs
using Chatex.Data.Abstractions;
using Chatex.Data.Entities;
using Chatex.Data.Exceptions;
namespace Chatex.Data.Tests;
public sealed class StorageAndUnitOfWorkTests(PostgresFixture fixture) : DbTestBase(fixture)
{
[Fact]
public async Task SaveChangesAsync_turns_a_unique_violation_into_UniqueConstraintException()
{
var alice = await CreateUserAsync("alice");
await using var scope = NewScope();
var chats = Get<IChatRepository>(scope);
chats.Add(new Chat { Type = ChatType.Channel, Title = "a", PublicHandle = "taken", CreatedById = alice.Id });
chats.Add(new Chat { Type = ChatType.Channel, Title = "b", PublicHandle = "taken", CreatedById = alice.Id });
var error = await Should.ThrowAsync<UniqueConstraintException>(() => Get<IUnitOfWork>(scope).SaveChangesAsync(Ct));
error.ConstraintName.ShouldBe("ix_chats_public_handle");
}
[Fact]
public async Task LocalFileStorage_saves_reads_and_deletes_a_file()
{
await using var scope = NewScope();
var storage = Get<IFileStorage>(scope);
var path = await storage.SaveAsync(new MemoryStream([1, 2, 3]), Ct);
path.ShouldMatch(@"^\d{4}/\d{2}/[0-9a-f]{32}$");
await using (var read = await storage.OpenReadAsync(path, Ct))
{
var copy = new MemoryStream();
await read.CopyToAsync(copy, Ct);
copy.ToArray().ShouldBe([1, 2, 3]);
}
await storage.DeleteAsync(path, Ct);
await Should.ThrowAsync<FileNotFoundException>(() => storage.OpenReadAsync(path, Ct));
}
[Fact]
public async Task LocalFileStorage_rejects_paths_outside_its_root()
{
await using var scope = NewScope();
await Should.ThrowAsync<ArgumentException>(() => Get<IFileStorage>(scope).OpenReadAsync("../secret.txt", Ct));
}
}- Two chats with the same handle in one save — the second insert violates
ix_chats_public_handle, andUnitOfWorkturns the PostgreSQL error intoUniqueConstraintExceptionwith that name. ShouldMatchchecks the storage path against a regular expression: four digits, two digits, 32 hexadecimal characters — no trace of a client file name."../secret.txt"must be refused with anArgumentExceptionbefore the file system is touched.
Check
powershell
dotnet test --solution Chatex.slnxTest run summary: Passed!
total: 19
failed: 0
succeeded: 19
skipped: 0The whole run, including starting the container and applying the migration, takes about 15 seconds.