English
Testing profiles
Step 1. A file storage in memory
Why. The avatar tests write and replace files. With LocalFileStorage they would write to disk and need cleaning up; worse, a test could not easily ask "how many files are stored now?". A fake — a simple implementation of IFileStorage that keeps the files in a dictionary — makes the files visible to the test and is fast. This is where the interface of topic 5 pays off: the services cannot tell the difference.
Do. Create Fakes.cs in the test project:
cs
using System.Collections.Concurrent;
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;
}
}ConcurrentDictionarykeeps it safe if two calls ever overlap.Countis the number the tests check: after replacing an avatar there must be exactly one file.OpenReadAsyncthrowsFileNotFoundExceptionfor an unknown path, as the interface of topic 5 documents — the fake must keep the contract of the real thing.
Step 2. Use the fake in the base class
Why. The test base registers the fake and gets helpers for the profile service and for building uploads.
Do. Extend BusinessTestBase (new lines in green):
cs
using Chatex.Core.Auth;
using Chatex.Core.Common;
using Chatex.Core.Users;
using Chatex.Data.Abstractions;
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 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.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);
/// <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 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.Replace(ServiceDescriptor.Singleton<IFileStorage>(Files))runs afterAddCore:Replaceremoves theLocalFileStorageregistration thatAddDatamade and puts the fake in its place. (For the clock we registered first and relied onTryAddSingleton; for the storage,AddDatauses a plainAddSingleton, so it must be replaced afterwards.)Profiles<T>is the one-line helper for the new service.Upload(size, contentType, claimedLength)builds aFileUploadfrom aMemoryStreamofsizezero bytes;claimedLengthlets a test lie about the length, as a hostile client would.
Step 3. The profile tests
Do.
cs
using Chatex.Core.Auth;
using Chatex.Core.Common;
using Chatex.Core.Users;
namespace Chatex.Core.Tests;
public sealed class ProfileServiceTests(PostgresFixture fixture) : BusinessTestBase(fixture)
{
[Fact]
public async Task UpdateProfileAsync_changes_display_name_and_bio()
{
var alice = await RegisterUserAsync("alice");
var updated = await Profiles(s => s.UpdateProfileAsync(alice, new UpdateProfileCommand(" Alice A. ", " "), Ct));
var seenByOthers = await Profiles(s => s.GetUserAsync(alice, Ct));
updated.ShouldSucceed().DisplayName.ShouldBe("Alice A.");
seenByOthers.ShouldSucceed().DisplayName.ShouldBe("Alice A.");
seenByOthers.Value.Bio.ShouldBeNull();
}
[Fact]
public async Task ChangePasswordAsync_ends_all_sessions()
{
var session = await RegisterAsync("alice");
(await Profiles(s => s.ChangePasswordAsync(session.User.Id, new ChangePasswordCommand(Password, "NewPassw0rd"), Ct)))
.ShouldSucceed();
(await Auth(s => s.RefreshAsync(new RefreshCommand(session.RefreshToken), ClientInfo.Unknown, Ct)))
.ShouldFail(ErrorKind.Unauthorized, "invalid_refresh_token");
(await Auth(s => s.LoginAsync(new LoginCommand("alice", "NewPassw0rd"), ClientInfo.Unknown, Ct))).ShouldSucceed();
}
[Fact]
public async Task ChangePasswordAsync_requires_the_current_password()
{
var alice = await RegisterUserAsync("alice");
var result = await Profiles(s => s.ChangePasswordAsync(alice, new ChangePasswordCommand("Wrong1234", "NewPassw0rd"), Ct));
result.ShouldFail(ErrorKind.Validation, "wrong_password");
}
[Fact]
public async Task SetAvatarAsync_accepts_images_only_and_replaces_the_old_file()
{
var alice = await RegisterUserAsync("alice");
(await Profiles(s => s.SetAvatarAsync(alice, Upload(10, "text/html"), Ct)))
.ShouldFail(ErrorKind.Validation, "avatar_invalid_type");
(await Profiles(s => s.SetAvatarAsync(alice, Upload(10, "image/png"), Ct))).ShouldSucceed().HasAvatar.ShouldBeTrue();
(await Profiles(s => s.SetAvatarAsync(alice, Upload(20, "image/webp"), Ct))).ShouldSucceed();
Files.Count.ShouldBe(1);
await using var avatar = (await Profiles(s => s.OpenAvatarAsync(alice, Ct))).ShouldSucceed();
avatar.Length.ShouldBe(20);
}
[Fact]
public async Task SearchUsersAsync_needs_two_characters_and_finds_by_display_name()
{
await RegisterUserAsync("alice");
await RegisterUserAsync("bob");
(await Profiles(s => s.SearchUsersAsync("a", null, Ct))).ShouldFail(ErrorKind.Validation, "query_too_short");
(await Profiles(s => s.SearchUsersAsync("BOB DISP", null, Ct))).ShouldSucceed().Select(u => u.UserName).ShouldBe(["bob"]);
}
}- Updating trims the name and turns a blank bio into
null; another user sees the new name. - Changing the password ends every session — the old refresh token is refused — and the new password works for signing in.
- A wrong current password gives
wrong_passwordas a validation error. - Avatars: an HTML file is refused; a PNG is stored; a WebP replaces it, and afterwards exactly one file remains — the old one was deleted. The stored avatar has the size of the second upload.
- Search needs two characters and finds users by display name in any case (
"BOB DISP"findsbob display).
Check
powershell
dotnet test --solution Chatex.slnx36 tests pass: 19 data tests and 17 business tests.