Українська
Тестування повідомлень
Крок 1. Останні допоміжні засоби
Що зробити. Завершіть BusinessTestBase (нові рядки зеленим). Тепер клас остаточний:
cs
using System.Globalization;
using Chatex.Core.Abstractions;
using Chatex.Core.Attachments;
using Chatex.Core.Auth;
using Chatex.Core.Chats;
using Chatex.Core.Common;
using Chatex.Core.Messages;
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;
/// <summary>
/// The full business layer on a clean database, with a controllable clock, in-memory files and a recording notifier.
/// Every service call runs in its own scope, like separate HTTP requests.
/// </summary>
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";
public const long MaxAttachmentBytes = 1024;
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,
["Attachments:MaxBytes"] = MaxAttachmentBytes.ToString(CultureInfo.InvariantCulture),
})
.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);
protected Task<T> Messages<T>(Func<IMessageService, Task<T>> call) => Use(call);
protected Task<T> Attachments<T>(Func<IAttachmentService, 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 async Task<MessageDto> SendAsync(Guid userId, Guid chatId, string body, params Guid[] attachmentIds)
{
var result = await Messages(s => s.SendAsync(userId, chatId, new SendMessageCommand(body, null, attachmentIds), Ct));
return result.ShouldSucceed();
}
protected async Task<AttachmentDto> UploadAsync(Guid userId, int size = 100, string contentType = "image/png")
{
var result = await Attachments(s => s.UploadAsync(userId, Upload(size, contentType), 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;
}
}MaxAttachmentBytes = 1024задає через конфігурацію крихітне обмеження завантаження, тож тестам розміру потрібен кілобайт замість 20 МБ.ToString(CultureInfo.InvariantCulture)записує число без роздільників, що залежать від культури, – цього наполегливо вимагають аналізатори з теми 2.SendAsync(userId, chatId, body, params Guid[] attachmentIds)іUploadAsync(userId, size, contentType)– останні допоміжні засоби для наповнення даними.
Крок 2. Тести вкладень
Що зробити.
cs
using Chatex.Core.Common;
using Chatex.Data.Entities;
namespace Chatex.Core.Tests;
public sealed class AttachmentServiceTests(PostgresFixture fixture) : BusinessTestBase(fixture)
{
[Fact]
public async Task UploadAsync_enforces_size_even_when_the_client_understates_it()
{
var alice = await RegisterUserAsync("alice");
var declaredTooBig = await Attachments(s => s.UploadAsync(alice, Upload(10, "image/png", claimedLength: MaxAttachmentBytes + 1), Ct));
var actuallyTooBig = await Attachments(s => s.UploadAsync(alice, Upload((int)MaxAttachmentBytes + 1, "image/png", claimedLength: 10), Ct));
var empty = await Attachments(s => s.UploadAsync(alice, Upload(0, "image/png"), Ct));
declaredTooBig.ShouldFail(ErrorKind.Validation, "attachment_too_large");
actuallyTooBig.ShouldFail(ErrorKind.Validation, "attachment_too_large");
empty.ShouldFail(ErrorKind.Validation, "attachment_empty");
Files.Count.ShouldBe(0);
}
[Fact]
public async Task UploadAsync_accepts_allowed_types_only_and_cleans_the_file_name()
{
var alice = await RegisterUserAsync("alice");
var html = await Attachments(s => s.UploadAsync(alice, Upload(10, "text/html"), Ct));
var text = await Attachments(s => s.UploadAsync(
alice, new FileUpload(new MemoryStream([1, 2, 3]), @"C:\fakepath\..\notes.txt", "text/plain; charset=utf-8", 3), Ct));
html.ShouldFail(ErrorKind.Validation, "attachment_invalid_type");
var saved = text.ShouldSucceed();
saved.FileName.ShouldBe("notes.txt");
saved.ContentType.ShouldBe("text/plain");
saved.SizeBytes.ShouldBe(3);
}
[Fact]
public async Task Sent_files_can_be_downloaded_by_chat_members_only()
{
var alice = await RegisterUserAsync("alice");
var bob = await RegisterUserAsync("bob");
var carol = await RegisterUserAsync("carol");
var group = await CreateChatAsync(alice, ChatType.Group, null, bob);
var file = await UploadAsync(bob, size: 42);
(await Attachments(s => s.GetDownloadAsync(bob, file.Id, Ct))).ShouldSucceed();
(await Attachments(s => s.GetDownloadAsync(alice, file.Id, Ct))).ShouldFail(ErrorKind.NotFound, "attachment_not_found");
await SendAsync(bob, group.Id, "file", file.Id);
var download = (await Attachments(s => s.GetDownloadAsync(alice, file.Id, Ct))).ShouldSucceed();
await using (var content = await Attachments(s => s.OpenReadAsync(download, Ct)))
{
content.Length.ShouldBe(42);
}
(await Attachments(s => s.GetDownloadAsync(carol, file.Id, Ct))).ShouldFail(ErrorKind.NotFound, "attachment_not_found");
}
[Fact]
public async Task CleanupStaleAsync_removes_uploads_that_were_never_sent()
{
var alice = await RegisterUserAsync("alice");
var group = await CreateChatAsync(alice, ChatType.Group);
await UploadAsync(alice);
var sent = await UploadAsync(alice);
await SendAsync(alice, group.Id, "keep", sent.Id);
Time.Advance(TimeSpan.FromDays(2));
var removed = await Attachments(s => s.CleanupStaleAsync(TimeSpan.FromDays(1), Ct));
removed.ShouldBe(1);
Files.Count.ShouldBe(1);
}
}- Розмір: файл, що заявляє забагато, файл, що завеликий, заявляючи 10 байтів, і порожній файл – усі відхиляються, і у підробленому сховищі не лишається жодного файлу.
- Тип та ім’я: HTML відхиляється; текстовий файл із параметром кодування й шляхом Windows замість імені зберігається як
notes.txtіз типомtext/plainі справжнім розміром. - Отримання: той, хто завантажив, може отримати файл одразу, Аліса – ні; після того як Боб надсилає файл у їхню групу, Аліса може, а Керол (не учасниця) – усе ще ні.
- Очищення: через два дні ненадіслане завантаження вилучено, а надіслане лишається.
Крок 3. Тести повідомлень
Що зробити.
cs
using Chatex.Core.Common;
using Chatex.Core.Messages;
using Chatex.Data.Entities;
namespace Chatex.Core.Tests;
public sealed class MessageServiceTests(PostgresFixture fixture) : BusinessTestBase(fixture)
{
[Fact]
public async Task Sending_moves_the_chat_to_the_top_and_counts_as_unread_for_others()
{
var alice = await RegisterUserAsync("alice");
var bob = await RegisterUserAsync("bob");
var older = await CreateChatAsync(alice, ChatType.Group, null, bob);
Time.Advance(TimeSpan.FromMinutes(1));
var newer = await CreateChatAsync(alice, ChatType.Group, null, bob);
Time.Advance(TimeSpan.FromMinutes(1));
var message = await SendAsync(bob, older.Id, " hello ");
var list = (await Chats(s => s.GetMyChatsAsync(alice, null, null, Ct))).ShouldSucceed();
list.Items.Select(c => c.Id).ShouldBe([older.Id, newer.Id]);
list.Items[0].UnreadCount.ShouldBe(1);
list.Items[0].LastMessage.ShouldNotBeNull().Body.ShouldBe("hello");
message.Sender.UserName.ShouldBe("bob");
Notifier.Events.ShouldContain($"MessageCreated:{older.Id}");
}
[Fact]
public async Task Only_the_sender_can_edit()
{
var alice = await RegisterUserAsync("alice");
var bob = await RegisterUserAsync("bob");
var group = await CreateChatAsync(alice, ChatType.Group, null, bob);
var message = await SendAsync(bob, group.Id, "typo");
(await Messages(s => s.EditAsync(alice, message.Id, new EditMessageCommand("fixed"), Ct)))
.ShouldFail(ErrorKind.Forbidden, "not_sender");
var edited = (await Messages(s => s.EditAsync(bob, message.Id, new EditMessageCommand("fixed"), Ct))).ShouldSucceed();
edited.Body.ShouldBe("fixed");
// Postgres keeps microseconds; the fake clock has 100 ns ticks.
edited.EditedAt.ShouldNotBeNull().ShouldBe(Time.GetUtcNow(), TimeSpan.FromMilliseconds(1));
}
[Fact]
public async Task An_admin_can_delete_a_message_and_its_files()
{
var alice = await RegisterUserAsync("alice");
var bob = await RegisterUserAsync("bob");
var group = await CreateChatAsync(alice, ChatType.Group, null, bob);
var file = await UploadAsync(bob);
var message = await SendAsync(bob, group.Id, "see attached", file.Id);
message.Attachments.Select(a => a.Id).ShouldBe([file.Id]);
(await Messages(s => s.DeleteAsync(alice, message.Id, Ct))).ShouldSucceed();
var history = (await Messages(s => s.GetHistoryAsync(bob, group.Id, null, null, null, Ct))).ShouldSucceed();
var deleted = history.Items.ShouldHaveSingleItem();
deleted.IsDeleted.ShouldBeTrue();
deleted.Body.ShouldBeNull();
deleted.Attachments.ShouldBeEmpty();
Files.Count.ShouldBe(0);
(await Attachments(s => s.GetDownloadAsync(bob, file.Id, Ct))).ShouldFail(ErrorKind.NotFound, "attachment_not_found");
}
[Fact]
public async Task A_reply_must_point_to_the_same_chat()
{
var alice = await RegisterUserAsync("alice");
var first = await CreateChatAsync(alice, ChatType.Group);
var second = await CreateChatAsync(alice, ChatType.Group);
var elsewhere = await SendAsync(alice, second.Id, "elsewhere");
var result = await Messages(s => s.SendAsync(alice, first.Id, new SendMessageCommand("re", elsewhere.Id), Ct));
result.ShouldFail(ErrorKind.Validation, "reply_not_found");
}
[Fact]
public async Task Attachments_of_another_user_cannot_be_sent()
{
var alice = await RegisterUserAsync("alice");
var bob = await RegisterUserAsync("bob");
var group = await CreateChatAsync(alice, ChatType.Group, null, bob);
var bobsFile = await UploadAsync(bob);
var result = await Messages(s => s.SendAsync(alice, group.Id, new SendMessageCommand(null, null, [bobsFile.Id]), Ct));
result.ShouldFail(ErrorKind.Validation, "invalid_attachments");
}
[Fact]
public async Task An_empty_message_without_attachments_is_rejected()
{
var alice = await RegisterUserAsync("alice");
var group = await CreateChatAsync(alice, ChatType.Group);
var result = await Messages(s => s.SendAsync(alice, group.Id, new SendMessageCommand(" "), Ct));
result.ShouldFail(ErrorKind.Validation, "validation_failed").Details.ShouldNotBeNull().ShouldContainKey("body");
}
[Fact]
public async Task GetHistoryAsync_pages_with_opaque_cursors()
{
var alice = await RegisterUserAsync("alice");
var group = await CreateChatAsync(alice, ChatType.Group);
for (var i = 0; i < 5; i++)
{
await SendAsync(alice, group.Id, $"m{i}");
}
var page1 = (await Messages(s => s.GetHistoryAsync(alice, group.Id, null, null, 2, Ct))).ShouldSucceed();
var page2 = (await Messages(s => s.GetHistoryAsync(alice, group.Id, page1.NextCursor, null, 2, Ct))).ShouldSucceed();
var page3 = (await Messages(s => s.GetHistoryAsync(alice, group.Id, page2.NextCursor, null, 2, Ct))).ShouldSucceed();
var newer = (await Messages(s => s.GetHistoryAsync(alice, group.Id, null, page2.NextCursor, 10, Ct))).ShouldSucceed();
page1.Items.Concat(page2.Items).Concat(page3.Items).Select(m => m.Body).ShouldBe(["m4", "m3", "m2", "m1", "m0"]);
page3.NextCursor.ShouldBeNull();
newer.Items.Select(m => m.Body).ShouldBe(["m2", "m3", "m4"]);
}
}- Чат піднімається нагору: дві групи створено з різницею в хвилину; повідомлення в старішій робить її першою в списку Аліси з одним непрочитаним повідомленням і обрізаним попереднім переглядом
hello. Підроблений годинник робить порядок певним. - Редагування будь-ким, крім відправника, дає
not_sender; час редагування дорівнює підробленому «зараз» з точністю до мілісекунди – коментар пояснює чому: PostgreSQL зберігає мікросекунди, а годинник має такти по 100 наносекунд. - Видалення адміністратором лишає в історії заглушку (без тексту, без вкладень), вилучає файл зі сховища, і вкладення більше не можна отримати.
- Відповідь на повідомлення іншого чату та чуже завантаження відхиляються; порожнє повідомлення без вкладень завершується помилкою в полі
body. - Сторінки історії по два повідомлення повертають п’ять повідомлень, найновіші першими;
afterповертає новіші, найстаріші першими – наздоганяння з теми 20.
Крок 4. Решта тестів чатів
Навіщо. Чотири правила чатів потребують повідомлень, щоб їх довести; тепер їх можна написати.
Що зробити. Завершіть ChatServiceTests (нові рядки зеленим):
cs
using Chatex.Core.Chats;
using Chatex.Core.Common;
using Chatex.Core.Messages;
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 Subscribers_cannot_post_in_a_channel()
{
var alice = await RegisterUserAsync("alice");
var bob = await RegisterUserAsync("bob");
var channel = await CreateChatAsync(alice, ChatType.Channel, null, bob);
var fromBob = await Messages(s => s.SendAsync(bob, channel.Id, new SendMessageCommand("hi"), Ct));
var fromAlice = await Messages(s => s.SendAsync(alice, channel.Id, new SendMessageCommand("hello"), Ct));
fromBob.ShouldFail(ErrorKind.Forbidden, "cannot_post");
fromAlice.ShouldSucceed();
}
[Fact]
public async Task Private_chats_are_invisible_to_non_members()
{
var alice = await RegisterUserAsync("alice");
var carol = await RegisterUserAsync("carol");
var group = await CreateChatAsync(alice, ChatType.Group);
(await Chats(s => s.GetAsync(carol, group.Id, Ct))).ShouldFail(ErrorKind.NotFound, "chat_not_found");
(await Messages(s => s.GetHistoryAsync(carol, group.Id, null, null, null, Ct))).ShouldFail(ErrorKind.NotFound, "chat_not_found");
(await Chats(s => s.JoinAsync(carol, group.Id, Ct))).ShouldFail(ErrorKind.NotFound, "chat_not_found");
}
[Fact]
public async Task Anyone_can_read_and_join_a_public_channel()
{
var alice = await RegisterUserAsync("alice");
var carol = await RegisterUserAsync("carol");
var channel = await CreateChatAsync(alice, ChatType.Channel, "public_news");
await SendAsync(alice, channel.Id, "first post");
var preview = await Messages(s => s.GetHistoryAsync(carol, channel.Id, null, null, null, Ct));
var joined = await Chats(s => s.JoinAsync(carol, channel.Id, Ct));
var joinedAgain = await Chats(s => s.JoinAsync(carol, channel.Id, Ct));
preview.ShouldSucceed().Items.Count.ShouldBe(1);
joined.ShouldSucceed().MyRole.ShouldBe(ChatMemberRole.Subscriber);
joinedAgain.ShouldSucceed().MemberCount.ShouldBe(2);
(await Chats(s => s.SearchPublicAsync("NEWS", null, Ct))).ShouldSucceed().Select(c => c.Id).ShouldBe([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 MarkReadAsync_requires_a_message_of_that_chat()
{
var alice = await RegisterUserAsync("alice");
var bob = await RegisterUserAsync("bob");
var group = await CreateChatAsync(alice, ChatType.Group, null, bob);
var message = await SendAsync(alice, group.Id, "hi");
(await Chats(s => s.MarkReadAsync(bob, group.Id, Guid.NewGuid(), Ct))).ShouldFail(ErrorKind.NotFound, "message_not_found");
(await Chats(s => s.MarkReadAsync(bob, group.Id, message.Id, Ct))).ShouldSucceed();
Notifier.Events.ShouldContain($"MessagesRead:{group.Id}");
}
[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");
}
}- Підписники не можуть писати в канал; власник може.
- Приватні чати невидимі для не-учасників: читання, читання історії та приєднання – усе відповідає
chat_not_found. - Публічні канали можна читати до приєднання; приєднання робить підписником; подвійне приєднання нічого не змінює; пошук знаходить канал у будь-якому разі.
- Позначення прочитаним потребує повідомлення цього чату й створює
MessagesRead.
Перевірка
powershell
dotnet test --solution Chatex.slnxПроходить 60 тестів: 19 тестів даних і 41 бізнес-тест.