Українська
Тестування реального часу
Крок 1. Пакет клієнта SignalR
Навіщо. Тести хаба підключаються так, як справжній клієнт, – через клієнт SignalR для .NET і тестовий сервер у пам’яті з теми 12.
Що зробити.
powershell
dotnet add Tests/Chatex.Api.Tests package Microsoft.AspNetCore.SignalR.Clientxml
<Project Sdk="Microsoft.NET.Sdk">
<ItemGroup>
<FrameworkReference Include="Microsoft.AspNetCore.App" />
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\..\Source\Chatex.Api\Chatex.Api.csproj" />
</ItemGroup>
<ItemGroup>
<PackageReference Include="Microsoft.AspNetCore.Mvc.Testing" />
<PackageReference Include="Microsoft.AspNetCore.SignalR.Client" />
</ItemGroup>
</Project>Крок 2. Клієнт, що записує події
Навіщо. Події надходять асинхронно. Тесту потрібно сказати «почекай наступного MessageCreated» із тайм-аутом, а іноді – «переконайся, що X не надійшло». Друге неможливо довести очікуванням (скільки чекати?), але SignalR зберігає порядок подій в одному з’єднанні: якщо пізніша подія надійшла, а X перед нею не було, X ніколи не надсилалося. Коментар тестового класу пояснює цей прийом.
Що зробити.
cs
using System.Threading.Channels;
using Chatex.Core.Messages;
using Microsoft.AspNetCore.SignalR.Client;
namespace Chatex.Api.Tests;
/// <summary>A hub event as the client received it.</summary>
public sealed record HubEvent(string Name, object?[] Args)
{
public T Arg<T>(int index) => (T)Args[index]!;
}
/// <summary>
/// A <see cref="HubConnection"/> that records every server event in arrival order, so tests can wait for one
/// and check what came before it. Events on one connection arrive in the order the server sent them.
/// </summary>
public sealed class HubClient : IAsyncDisposable
{
private static readonly TimeSpan Timeout = TimeSpan.FromSeconds(10);
private static readonly Dictionary<string, Type[]> Events = new()
{
["MessageCreated"] = [typeof(MessageDto)],
["MessageUpdated"] = [typeof(MessageDto)],
["MessageDeleted"] = [typeof(Guid), typeof(Guid)],
["MessagesRead"] = [typeof(Guid), typeof(Guid), typeof(Guid)],
["MembersAdded"] = [typeof(Guid), typeof(Guid[])],
["MemberRemoved"] = [typeof(Guid), typeof(Guid)],
["ChatUpdated"] = [typeof(Guid)],
["ChatDeleted"] = [typeof(Guid)],
["Typing"] = [typeof(Guid), typeof(Guid)],
["UserOnline"] = [typeof(Guid)],
["UserOffline"] = [typeof(Guid), typeof(DateTimeOffset)],
};
private readonly Channel<HubEvent> _received = Channel.CreateUnbounded<HubEvent>();
public HubClient(HubConnection connection)
{
Connection = connection;
foreach (var (name, types) in Events)
{
connection.On(name, types, (args, _) => _received.Writer.WriteAsync(new HubEvent(name, args)).AsTask(), null!);
}
}
public HubConnection Connection { get; }
/// <summary>Waits for the next <paramref name="name"/> event that matches, skipping everything before it.</summary>
public async Task<HubEvent> WaitForAsync(string name, Func<HubEvent, bool>? match = null) =>
(await ReadUntilAsync(name, match))[^1];
/// <summary>Reads events up to and including the next <paramref name="name"/> event that matches.</summary>
public async Task<IReadOnlyList<HubEvent>> ReadUntilAsync(string name, Func<HubEvent, bool>? match = null)
{
using var timeout = CancellationTokenSource.CreateLinkedTokenSource(TestContext.Current.CancellationToken);
timeout.CancelAfter(Timeout);
var read = new List<HubEvent>();
try
{
while (true)
{
var next = await _received.Reader.ReadAsync(timeout.Token);
read.Add(next);
if (next.Name == name && (match is null || match(next)))
{
return read;
}
}
}
catch (OperationCanceledException) when (!TestContext.Current.CancellationToken.IsCancellationRequested)
{
throw new TimeoutException(
$"No matching {name} within {Timeout.TotalSeconds}s. Received: {string.Join(", ", read.Select(e => e.Name))}");
}
}
public ValueTask DisposeAsync() => Connection.DisposeAsync();
}Channel<HubEvent>– асинхронна черга: обробники пишуть, тест читає.- Один обробник на кожне ім’я події з типами аргументів, тож аргументи десеріалізуються в DTO з Chatex.Core.
ReadUntilAsyncповертає всі події аж до тієї, на яку чекав, тож тест може перевірити, що було перед нею; через 10 секунд він завершується помилкою зі списком подій, які таки надійшли.
Крок 3. Підключення в тестах
Що зробити. Завершіть ApiTestBase (нові рядки позначено зеленим). Тепер він остаточний:
cs
using System.Globalization;
using System.Net;
using System.Net.Http.Headers;
using System.Net.Http.Json;
using System.Text.Json;
using System.Text.Json.Serialization;
using Chatex.Api.Contracts;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http.Connections;
using Microsoft.AspNetCore.Mvc.Testing;
using Microsoft.AspNetCore.SignalR.Client;
using Microsoft.Extensions.DependencyInjection;
// Tests share one database that is wiped before each test; xunit.runner.json turns off parallel runs.
[assembly: AssemblyFixture(typeof(PostgresFixture))]
namespace Chatex.Api.Tests;
/// <summary>
/// The real Api in memory (TestServer) on a clean database and a temporary upload folder.
/// Clients talk to https://localhost so the Secure refresh cookie round-trips.
/// </summary>
public abstract class ApiTestBase(PostgresFixture fixture) : IAsyncLifetime
{
public const string Password = "Passw0rd!";
public const long MaxAttachmentBytes = 1024;
protected static readonly JsonSerializerOptions Json = new(JsonSerializerDefaults.Web)
{
Converters = { new JsonStringEnumConverter(JsonNamingPolicy.CamelCase) },
};
/// <summary>The first bytes of a PNG file, enough for the avatar type sniffing.</summary>
protected static readonly byte[] PngBytes = [0x89, 0x50, 0x4E, 0x47, 0x0D, 0x0A, 0x1A, 0x0A, 0, 0, 0, 13, 1, 2, 3, 4];
private readonly string _storageRoot = Path.Combine(Path.GetTempPath(), "chatex-api-tests", Guid.NewGuid().ToString("N"));
private readonly List<HubClient> _hubs = [];
private WebApplicationFactory<Program> _factory = null!;
protected static CancellationToken Ct => TestContext.Current.CancellationToken;
public async ValueTask InitializeAsync()
{
await fixture.ResetAsync();
_factory = new WebApplicationFactory<Program>().WithWebHostBuilder(builder =>
{
builder
.UseEnvironment("Testing")
.UseSetting("ConnectionStrings:Chatex", fixture.ConnectionString)
.UseSetting("Jwt:Issuer", "chatex-api-tests")
.UseSetting("Jwt:Audience", "chatex-api-tests")
.UseSetting("Jwt:SigningKey", "api-test-signing-key-that-is-long-enough-for-hmac")
.UseSetting("Storage:RootPath", _storageRoot)
.UseSetting("Attachments:MaxBytes", MaxAttachmentBytes.ToString(CultureInfo.InvariantCulture))
.UseSetting("Presence:OfflineGraceSeconds", "0")
.UseSetting("Maintenance:Enabled", "false")
// Every test client shares one (unknown) IP, so the auth throttle would trip across tests.
.UseSetting("RateLimiting:AuthPermitLimit", "1000000");
ConfigureHost(builder);
});
}
/// <summary>Overrides settings for one test class; runs after the defaults above.</summary>
protected virtual void ConfigureHost(IWebHostBuilder builder)
{
}
public async ValueTask DisposeAsync()
{
// Close hub connections while the server is still up.
foreach (var hub in _hubs)
{
await hub.DisposeAsync();
}
await _factory.DisposeAsync();
if (Directory.Exists(_storageRoot))
{
Directory.Delete(_storageRoot, recursive: true);
}
GC.SuppressFinalize(this);
}
/// <summary>A client with its own cookie jar, like a separate browser.</summary>
protected HttpClient CreateClient() =>
_factory.CreateClient(new WebApplicationFactoryClientOptions { BaseAddress = new Uri("https://localhost") });
/// <summary>Registers <paramref name="userName"/> and returns a client that sends its access token.</summary>
protected async Task<Session> RegisterAsync(string userName)
{
var client = CreateClient();
var response = await client.PostAsJsonAsync("/api/auth/register", RegisterBody(userName), Json, Ct);
var auth = await response.ShouldHaveAsync<AuthResponse>(HttpStatusCode.OK);
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", auth.AccessToken);
return new Session(client, auth);
}
/// <summary>
/// Opens a hub connection as <paramref name="session"/> (or anonymously) through the in-memory server.
/// Returns once the server has joined the user's chat groups.
/// </summary>
protected async Task<HubClient> ConnectHubAsync(Session? session)
{
var hub = new HubClient(CreateHubConnection(session?.Auth.AccessToken));
_hubs.Add(hub);
await hub.Connection.StartAsync(Ct);
// The handshake completes before OnConnectedAsync, but invocations wait for it, so this one marks the point
// where the connection is in its groups.
await hub.Connection.InvokeAsync<Guid[]>("GetOnlineUsers", Array.Empty<Guid>(), Ct);
return hub;
}
protected HubConnection CreateHubConnection(string? accessToken) =>
new HubConnectionBuilder()
.WithUrl(new Uri("https://localhost/hubs/chat"), o =>
{
o.HttpMessageHandlerFactory = _ => _factory.Server.CreateHandler();
o.Transports = HttpTransportType.LongPolling;
o.AccessTokenProvider = () => Task.FromResult(accessToken);
})
.AddJsonProtocol(o => o.PayloadSerializerOptions.Converters.Add(new JsonStringEnumConverter(JsonNamingPolicy.CamelCase)))
.Build();
protected static object RegisterBody(string userName) => new
{
userName,
email = $"{userName}@example.test",
password = Password,
displayName = $"{userName} display",
};
protected static MultipartFormDataContent FileContent(byte[] bytes, string fileName, string contentType)
{
var file = new ByteArrayContent(bytes);
file.Headers.ContentType = new MediaTypeHeaderValue(contentType);
return new MultipartFormDataContent { { file, "file", fileName } };
}
}
public sealed record Session(HttpClient Client, AuthResponse Auth)
{
public Guid UserId => Auth.User.Id;
}Presence:OfflineGraceSeconds = 0робить «офлайн» миттєвим у тестах.CreateHubConnectionспрямовує клієнта через тестовий сервер (HttpMessageHandlerFactory) з довгим опитуванням (long polling): сервер у пам’яті не має справжніх сокетів. Токен іде черезAccessTokenProvider, який клієнт надсилає в рядку запиту, – саме той шлях, що його обробляє подія Bearer з попереднього розділу.ConnectHubAsyncзапускає з’єднання, а потім один раз викликаєGetOnlineUsers. Рукостискання завершується до того, якOnConnectedAsyncвступить до груп, але виклик методу хаба чекає на це, – тож після цього виклику з’єднання перебуває у своїх групах і тест може діяти.DisposeAsyncзакриває з’єднання з хабом, поки сервер іще працює.
Крок 4. Тести хаба
Що зробити.
cs
using System.Net;
using System.Net.Http.Json;
using Chatex.Api.Contracts;
using Chatex.Core.Chats;
using Chatex.Core.Messages;
using Chatex.Core.Users;
using Microsoft.AspNetCore.SignalR;
using Microsoft.AspNetCore.SignalR.Client;
namespace Chatex.Api.Tests;
/// <summary>
/// The SignalR hub at /hubs/chat over long polling against the in-memory server. To prove that an event did
/// not arrive, a test sends a later event the same client does receive: events on one connection keep their order.
/// </summary>
public sealed class ChatHubTests(PostgresFixture fixture) : ApiTestBase(fixture)
{
[Fact]
public async Task A_connection_without_a_token_is_rejected()
{
var ex = await Should.ThrowAsync<HttpRequestException>(() => ConnectHubAsync(null));
ex.StatusCode.ShouldBe(HttpStatusCode.Unauthorized);
}
[Fact]
public async Task The_access_token_is_accepted_from_the_query_string_on_hub_paths_only()
{
var alice = await RegisterAsync("alice");
var anonymous = CreateClient();
var token = Uri.EscapeDataString(alice.Auth.AccessToken);
var negotiate = await anonymous.PostAsync($"/hubs/chat/negotiate?negotiateVersion=1&access_token={token}", null, Ct);
await negotiate.ShouldHaveStatusAsync(HttpStatusCode.OK);
var api = await anonymous.GetAsync($"/api/me?access_token={token}", Ct);
await api.ShouldHaveStatusAsync(HttpStatusCode.Unauthorized);
}
[Fact]
public async Task Message_events_reach_members_but_not_outsiders()
{
var alice = await RegisterAsync("alice");
var bob = await RegisterAsync("bob");
var eve = await RegisterAsync("eve");
var group = await CreateGroupAsync(alice, bob.UserId);
var aliceAndEve = await OpenDirectAsync(alice, eve.UserId);
var bobHub = await ConnectHubAsync(bob);
var eveHub = await ConnectHubAsync(eve);
var sent = await SendAsync(alice, group.Id, "hello");
var created = (await bobHub.WaitForAsync("MessageCreated")).Arg<MessageDto>(0);
created.Id.ShouldBe(sent.Id);
created.ChatId.ShouldBe(group.Id);
created.Body.ShouldBe("hello");
created.Sender.Id.ShouldBe(alice.UserId);
await (await alice.Client.PutAsJsonAsync($"/api/messages/{sent.Id}", new { body = "hello all" }, Json, Ct))
.ShouldHaveStatusAsync(HttpStatusCode.OK);
var updated = (await bobHub.WaitForAsync("MessageUpdated")).Arg<MessageDto>(0);
updated.Body.ShouldBe("hello all");
updated.EditedAt.ShouldNotBeNull();
await (await alice.Client.DeleteAsync($"/api/messages/{sent.Id}", Ct)).ShouldHaveStatusAsync(HttpStatusCode.NoContent);
var deleted = await bobHub.WaitForAsync("MessageDeleted");
deleted.Arg<Guid>(0).ShouldBe(group.Id);
deleted.Arg<Guid>(1).ShouldBe(sent.Id);
var barrier = await SendAsync(alice, aliceAndEve.Id, "only for eve");
var eveEvents = await eveHub.ReadUntilAsync("MessageCreated", e => e.Arg<MessageDto>(0).Id == barrier.Id);
eveEvents.Where(e => e.Name.StartsWith("Message", StringComparison.Ordinal)).ShouldHaveSingleItem();
}
[Fact]
public async Task Typing_reaches_the_others_but_not_the_sender_and_outsiders_get_an_error()
{
var alice = await RegisterAsync("alice");
var bob = await RegisterAsync("bob");
var eve = await RegisterAsync("eve");
var group = await CreateGroupAsync(alice, bob.UserId);
var aliceHub = await ConnectHubAsync(alice);
var bobHub = await ConnectHubAsync(bob);
var eveHub = await ConnectHubAsync(eve);
await aliceHub.Connection.InvokeAsync("Typing", group.Id, Ct);
var typing = await bobHub.WaitForAsync("Typing");
typing.Arg<Guid>(0).ShouldBe(group.Id);
typing.Arg<Guid>(1).ShouldBe(alice.UserId);
// Alice's first Typing event is Bob's, so her own never came back to her.
await bobHub.Connection.InvokeAsync("Typing", group.Id, Ct);
(await aliceHub.WaitForAsync("Typing")).Arg<Guid>(1).ShouldBe(bob.UserId);
await Should.ThrowAsync<HubException>(() => eveHub.Connection.InvokeAsync("Typing", group.Id, Ct));
}
[Fact]
public async Task An_added_member_gets_later_messages_without_reconnecting_and_a_removed_one_stops()
{
var alice = await RegisterAsync("alice");
var bob = await RegisterAsync("bob");
var carol = await RegisterAsync("carol");
var group = await CreateGroupAsync(alice, bob.UserId);
var bobHub = await ConnectHubAsync(bob);
var carolHub = await ConnectHubAsync(carol);
await (await alice.Client.PostAsJsonAsync($"/api/chats/{group.Id}/members", new AddMembersRequest([carol.UserId]), Json, Ct))
.ShouldHaveStatusAsync(HttpStatusCode.OK);
var added = await carolHub.WaitForAsync("MembersAdded");
added.Arg<Guid>(0).ShouldBe(group.Id);
added.Arg<Guid[]>(1).ShouldBe([carol.UserId]);
var welcome = await SendAsync(alice, group.Id, "welcome carol");
(await carolHub.WaitForAsync("MessageCreated")).Arg<MessageDto>(0).Id.ShouldBe(welcome.Id);
await (await alice.Client.DeleteAsync($"/api/chats/{group.Id}/members/{bob.UserId}", Ct))
.ShouldHaveStatusAsync(HttpStatusCode.NoContent);
var removed = await bobHub.WaitForAsync("MemberRemoved");
removed.Arg<Guid>(0).ShouldBe(group.Id);
removed.Arg<Guid>(1).ShouldBe(bob.UserId);
var afterRemoval = await SendAsync(alice, group.Id, "bob is gone");
(await carolHub.WaitForAsync("MessageCreated")).Arg<MessageDto>(0).Id.ShouldBe(afterRemoval.Id);
var aliceAndBob = await OpenDirectAsync(alice, bob.UserId);
var barrier = await SendAsync(alice, aliceAndBob.Id, "still friends");
var bobEvents = await bobHub.ReadUntilAsync("MessageCreated", e => e.Arg<MessageDto>(0).Id == barrier.Id);
bobEvents.ShouldNotContain(e => e.Name == "MessageCreated" && e.Arg<MessageDto>(0).Id == afterRemoval.Id);
}
[Fact]
public async Task Online_and_offline_reach_a_chat_partner_and_last_seen_is_saved()
{
var alice = await RegisterAsync("alice");
var bob = await RegisterAsync("bob");
await OpenDirectAsync(alice, bob.UserId);
var bobHub = await ConnectHubAsync(bob);
var aliceHub = await ConnectHubAsync(alice);
// Bob's own UserOnline came first: his group includes him.
await bobHub.WaitForAsync("UserOnline", e => e.Arg<Guid>(0) == alice.UserId);
await aliceHub.Connection.StopAsync(Ct);
var offline = await bobHub.WaitForAsync("UserOffline");
offline.Arg<Guid>(0).ShouldBe(alice.UserId);
var lastSeenAt = offline.Arg<DateTimeOffset>(1);
var user = await (await bob.Client.GetAsync($"/api/users/{alice.UserId}", Ct)).ShouldHaveAsync<UserDto>(HttpStatusCode.OK);
// PostgreSQL keeps microseconds, .NET ticks are 100 ns.
(user.LastSeenAt.ShouldNotBeNull() - lastSeenAt).Duration().ShouldBeLessThan(TimeSpan.FromMilliseconds(1));
}
[Fact]
public async Task GetOnlineUsers_returns_the_connected_users()
{
var alice = await RegisterAsync("alice");
var bob = await RegisterAsync("bob");
var carol = await RegisterAsync("carol");
await OpenDirectAsync(alice, bob.UserId);
var aliceHub = await ConnectHubAsync(alice);
var bobHub = await ConnectHubAsync(bob);
Guid[] everyone = [alice.UserId, bob.UserId, carol.UserId, bob.UserId];
var online = await aliceHub.Connection.InvokeAsync<Guid[]>("GetOnlineUsers", everyone, Ct);
online.ShouldBe([alice.UserId, bob.UserId], ignoreOrder: true);
await bobHub.Connection.StopAsync(Ct);
await aliceHub.WaitForAsync("UserOffline", e => e.Arg<Guid>(0) == bob.UserId);
(await aliceHub.Connection.InvokeAsync<Guid[]>("GetOnlineUsers", everyone, Ct)).ShouldBe([alice.UserId]);
}
[Fact]
public async Task Read_receipts_chat_updates_and_chat_deletion_are_forwarded()
{
var alice = await RegisterAsync("alice");
var bob = await RegisterAsync("bob");
var group = await CreateGroupAsync(alice, bob.UserId);
var bobHub = await ConnectHubAsync(bob);
var message = await SendAsync(bob, group.Id, "read me");
await (await alice.Client.PostAsJsonAsync($"/api/chats/{group.Id}/read", new MarkReadRequest(message.Id), Json, Ct))
.ShouldHaveStatusAsync(HttpStatusCode.NoContent);
var read = await bobHub.WaitForAsync("MessagesRead");
read.Arg<Guid>(0).ShouldBe(group.Id);
read.Arg<Guid>(1).ShouldBe(alice.UserId);
read.Arg<Guid>(2).ShouldBe(message.Id);
await (await alice.Client.PutAsJsonAsync($"/api/chats/{group.Id}", new { title = "Renamed" }, Json, Ct))
.ShouldHaveStatusAsync(HttpStatusCode.OK);
(await bobHub.WaitForAsync("ChatUpdated")).Arg<Guid>(0).ShouldBe(group.Id);
await (await alice.Client.DeleteAsync($"/api/chats/{group.Id}", Ct)).ShouldHaveStatusAsync(HttpStatusCode.NoContent);
(await bobHub.WaitForAsync("ChatDeleted")).Arg<Guid>(0).ShouldBe(group.Id);
}
private static async Task<ChatDto> CreateGroupAsync(Session owner, params Guid[] memberIds)
{
var response = await owner.Client.PostAsJsonAsync("/api/chats", new { type = "group", title = "Team", memberIds }, Json, Ct);
return await response.ShouldHaveAsync<ChatDto>(HttpStatusCode.Created);
}
private static async Task<ChatDto> OpenDirectAsync(Session user, Guid otherUserId)
{
var response = await user.Client.PostAsJsonAsync("/api/chats/direct", new OpenDirectRequest(otherUserId), Json, Ct);
return await response.ShouldHaveAsync<ChatDto>(HttpStatusCode.OK);
}
private static async Task<MessageDto> SendAsync(Session sender, Guid chatId, string body)
{
var response = await sender.Client.PostAsJsonAsync($"/api/chats/{chatId}/messages", new { body }, Json, Ct);
return await response.ShouldHaveAsync<MessageDto>(HttpStatusCode.Created);
}
}- Автентифікація: немає токена – немає з’єднання (
401); токен у рядку запиту працює на/hubs/chat/negotiateі ігнорується на/api/me. - Розсилання: Bob отримує створені, оновлені й видалені повідомлення своєї групи; Eve, яка ділить з Alice лише особистий чат, отримує подію цього чату – і нічого з групи перед ним.
- Набір тексту доходить до інших, а не до відправника; той, хто не є учасником, отримує помилку.
- Членство: доданий учасник отримує пізніші повідомлення без перепідключення; вилучений отримує
MemberRemoved, а далі нічого. - Присутність: Bob бачить, як Alice з’являється в мережі й виходить із неї, а її «востаннє в мережі» зберігається;
GetOnlineUsersвідповідає, хто підключений, із відфільтрованими дублікатами й невідомими користувачами. - Підтвердження прочитання, оновлення й видалення чатів пересилаються учасникам.
Перевірка
powershell
dotnet test --solution Chatex.slnxПроходить 93 тести: 19 тестів даних, 41 бізнес-тест і 33 тести API. Серверна частина завершена – кожен файл Source/ і Tests/, крім застосунку Angular, ідентичний еталону:
powershell
git diff --no-index --stat Source/Chatex.Api D:\Work\Chatex-Reference\Source\Chatex.Api