English
Testing real time
Step 1. The SignalR client package
Why. The hub tests connect like a real client does, with the .NET SignalR client, through the in-memory test server of topic 12.
Do.
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>Step 2. A client that records events
Why. Events arrive asynchronously. A test needs to say "wait for the next MessageCreated" with a timeout, and sometimes "make sure X did not arrive". The second is impossible to prove by waiting (how long?), but SignalR keeps the order of events on one connection: if a later event arrives and X did not come before it, X was never sent. The comment of the test class explains this trick.
Do.
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>is an asynchronous queue: the handlers write, the test reads.- One handler per event name, with the argument types, so arguments are deserialized into the DTOs of Chatex.Core.
ReadUntilAsyncreturns every event up to the one it waited for, so a test can check what came before; after 10 seconds it fails with the list of events it did receive.
Step 3. Connecting in tests
Do. Complete ApiTestBase (new lines in green). It is now final:
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 = 0makes "offline" immediate in tests.CreateHubConnectionroutes the client through the test server (HttpMessageHandlerFactory) with long polling: the in-memory server has no real sockets. The token goes throughAccessTokenProvider, which the client sends in the query string — exactly the path the bearer event of the previous chapter handles.ConnectHubAsyncstarts the connection and then callsGetOnlineUsersonce. The handshake completes beforeOnConnectedAsynchas joined the groups, but a hub invocation waits for it — so after this call, the connection is in its groups, and the test can act.DisposeAsynccloses the hub connections while the server is still running.
Step 4. The hub tests
Do.
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);
}
}- Authentication: no token, no connection (
401); a token in the query string works on/hubs/chat/negotiateand is ignored on/api/me. - Fan-out: Bob receives created, updated and deleted messages of his group; Eve, who shares only a direct chat with Alice, gets the event of that chat — and nothing from the group before it.
- Typing reaches the others, not the sender; a non-member gets an error.
- Membership: an added member gets later messages without reconnecting; a removed one gets
MemberRemovedand then no more. - Presence: Bob sees Alice come online and go offline, and her "last seen" is stored;
GetOnlineUsersanswers who is connected, with duplicates and unknown users filtered out. - Read receipts, chat updates and deletion are forwarded to the members.
Check
powershell
dotnet test --solution Chatex.slnx93 tests pass: 19 data, 41 business and 33 API tests. The backend is complete — every file of Source/ and Tests/ except the Angular app is identical to the reference:
powershell
git diff --no-index --stat Source/Chatex.Api D:\Work\Chatex-Reference\Source\Chatex.Api