English
Testing files, limits and health
Step 1. Test settings and helpers
Why. The new features need new settings in the tests, and two test classes need settings of their own: the rate limit test wants a low limit, the health test a database that does not exist. A virtual method lets a test class override the defaults.
Do. Extend ApiTestBase (new lines in green):
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.Mvc.Testing;
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 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("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()
{
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);
}
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;
}MaxAttachmentBytes = 1024keeps the size tests small, as in the business tests.Maintenance:Enabled = false: the hourly cleanup would otherwise run at the start of every test application.RateLimiting:AuthPermitLimit = 1000000: all test clients share one (unknown) IP, so the real limit of 20 per minute would fail unrelated tests.ConfigureHostruns after the defaults, so a test class can override any of them.PngBytesare the first 16 bytes of a PNG — enough for the sniffer;FileContentbuilds a multipart body with one file part namedfile, the name of theIFormFileparameter.
Step 2. File tests
Do.
cs
using System.Net;
using System.Net.Http.Json;
using Chatex.Core.Attachments;
using Chatex.Core.Chats;
using Chatex.Core.Users;
namespace Chatex.Api.Tests;
public sealed class FileEndpointsTests(PostgresFixture fixture) : ApiTestBase(fixture)
{
[Fact]
public async Task Attachments_are_uploaded_sent_and_downloaded_by_chat_members()
{
var alice = await RegisterAsync("alice");
var bob = await RegisterAsync("bob");
var eve = await RegisterAsync("eve");
var chat = await (await alice.Client.PostAsJsonAsync(
"/api/chats", new { type = "group", title = "Team", memberIds = new[] { bob.UserId } }, Json, Ct))
.ShouldHaveAsync<ChatDto>(HttpStatusCode.Created);
var upload = await alice.Client.PostAsync("/api/attachments", FileContent(PngBytes, "photo.png", "image/png"), Ct);
var attachment = await upload.ShouldHaveAsync<AttachmentDto>(HttpStatusCode.Created);
attachment.SizeBytes.ShouldBe(PngBytes.Length);
upload.Headers.Location.ShouldBe(new Uri($"/api/attachments/{attachment.Id}", UriKind.Relative));
await (await alice.Client.PostAsJsonAsync(
$"/api/chats/{chat.Id}/messages", new { attachmentIds = new[] { attachment.Id } }, Json, Ct))
.ShouldHaveStatusAsync(HttpStatusCode.Created);
var download = await bob.Client.GetAsync($"/api/attachments/{attachment.Id}", Ct);
await download.ShouldHaveStatusAsync(HttpStatusCode.OK);
(await download.Content.ReadAsByteArrayAsync(Ct)).ShouldBe(PngBytes);
download.Content.Headers.ContentType?.MediaType.ShouldBe("image/png");
download.Content.Headers.ContentDisposition?.DispositionType.ShouldBe("inline");
download.Headers.GetValues("X-Content-Type-Options").ShouldBe(["nosniff"]);
var outsider = await eve.Client.GetAsync($"/api/attachments/{attachment.Id}", Ct);
await outsider.ShouldBeProblemAsync(HttpStatusCode.NotFound, "attachment_not_found");
}
[Fact]
public async Task Non_image_attachments_download_under_their_file_name()
{
var alice = await RegisterAsync("alice");
var bytes = "plain text"u8.ToArray();
var attachment = await (await alice.Client.PostAsync("/api/attachments", FileContent(bytes, "notes.txt", "text/plain"), Ct))
.ShouldHaveAsync<AttachmentDto>(HttpStatusCode.Created);
var download = await alice.Client.GetAsync($"/api/attachments/{attachment.Id}", Ct);
await download.ShouldHaveStatusAsync(HttpStatusCode.OK);
var disposition = download.Content.Headers.ContentDisposition.ShouldNotBeNull();
disposition.DispositionType.ShouldBe("attachment");
(disposition.FileNameStar ?? disposition.FileName).ShouldBe("notes.txt");
}
[Fact]
public async Task Too_large_and_disallowed_uploads_are_400()
{
var alice = await RegisterAsync("alice");
var tooLarge = await alice.Client.PostAsync(
"/api/attachments", FileContent(new byte[MaxAttachmentBytes + 1], "big.png", "image/png"), Ct);
var html = await alice.Client.PostAsync(
"/api/attachments", FileContent("<script></script>"u8.ToArray(), "x.html", "text/html"), Ct);
await tooLarge.ShouldBeProblemAsync(HttpStatusCode.BadRequest, "attachment_too_large");
await html.ShouldBeProblemAsync(HttpStatusCode.BadRequest, "attachment_invalid_type");
}
[Fact]
public async Task Avatars_are_set_served_with_their_image_type_and_removed()
{
var alice = await RegisterAsync("alice");
var bob = await RegisterAsync("bob");
var profile = await (await alice.Client.PutAsync("/api/me/avatar", FileContent(PngBytes, "me.png", "image/png"), Ct))
.ShouldHaveAsync<MyProfileDto>(HttpStatusCode.OK);
profile.HasAvatar.ShouldBeTrue();
var avatar = await bob.Client.GetAsync($"/api/users/{alice.UserId}/avatar", Ct);
await avatar.ShouldHaveStatusAsync(HttpStatusCode.OK);
avatar.Content.Headers.ContentType?.MediaType.ShouldBe("image/png");
(await avatar.Content.ReadAsByteArrayAsync(Ct)).ShouldBe(PngBytes);
var removed = await (await alice.Client.DeleteAsync("/api/me/avatar", Ct)).ShouldHaveAsync<MyProfileDto>(HttpStatusCode.OK);
removed.HasAvatar.ShouldBeFalse();
await (await bob.Client.GetAsync($"/api/users/{alice.UserId}/avatar", Ct))
.ShouldBeProblemAsync(HttpStatusCode.NotFound, "avatar_not_found");
}
[Fact]
public async Task Upload_without_a_file_is_400()
{
var alice = await RegisterAsync("alice");
var response = await alice.Client.PostAsync("/api/attachments", new MultipartFormDataContent(), Ct);
await response.ShouldBeProblemAsync(HttpStatusCode.BadRequest);
}
}- The whole attachment flow over HTTP: upload (
201,Location), send with the message, download by another member with the right type,inlinedisposition andnosniff; an outsider gets404. - A text file downloads as an
attachmentunder its name. - Limits: too large and
text/htmlare400with the business codes. - Avatars: set, served as
image/png(sniffed), removed, then404 avatar_not_found. - A multipart request without a file is
400— the binding fails before the endpoint runs, andThrowOnBadRequest = falseplusUseStatusCodePagesturn it into Problem Details.
Step 3. Rate limiting and health tests
Do.
cs
using System.Globalization;
using System.Net;
using System.Net.Http.Json;
using Microsoft.AspNetCore.Hosting;
namespace Chatex.Api.Tests;
public sealed class RateLimitingTests(PostgresFixture fixture) : ApiTestBase(fixture)
{
private const int Limit = 3;
protected override void ConfigureHost(IWebHostBuilder builder) =>
builder.UseSetting("RateLimiting:AuthPermitLimit", Limit.ToString(CultureInfo.InvariantCulture));
[Fact]
public async Task Auth_endpoints_answer_429_problem_with_retry_after_once_the_limit_is_used_up()
{
var client = CreateClient();
for (var i = 0; i < Limit; i++)
{
var allowed = await client.PostAsJsonAsync("/api/auth/login", new { login = "nobody", password = Password }, Json, Ct);
allowed.StatusCode.ShouldBe(HttpStatusCode.Unauthorized);
}
var throttled = await client.PostAsJsonAsync("/api/auth/login", new { login = "nobody", password = Password }, Json, Ct);
await throttled.ShouldBeProblemAsync(HttpStatusCode.TooManyRequests, "too_many_requests");
throttled.Headers.RetryAfter.ShouldNotBeNull();
}
[Fact]
public async Task Other_endpoints_are_not_throttled()
{
var alice = await RegisterAsync("alice");
for (var i = 0; i < Limit + 2; i++)
{
(await alice.Client.GetAsync("/api/me", Ct)).StatusCode.ShouldBe(HttpStatusCode.OK);
}
}
}With a limit of 3, three wrong logins answer 401, the fourth 429 with too_many_requests and a Retry-After header; the profile endpoint is not throttled at all.
cs
using System.Net;
using Microsoft.AspNetCore.Hosting;
namespace Chatex.Api.Tests;
public sealed class HealthTests(PostgresFixture fixture) : ApiTestBase(fixture)
{
[Fact]
public async Task Health_answers_200_without_a_token_when_the_database_is_reachable()
{
var response = await CreateClient().GetAsync("/health", Ct);
response.StatusCode.ShouldBe(HttpStatusCode.OK);
(await response.Content.ReadAsStringAsync(Ct)).ShouldBe("Healthy");
}
}
public sealed class HealthWithoutDatabaseTests(PostgresFixture fixture) : ApiTestBase(fixture)
{
// Nothing listens on port 1, so every connection attempt fails at once.
protected override void ConfigureHost(IWebHostBuilder builder) =>
builder.UseSetting("ConnectionStrings:Chatex", "Host=127.0.0.1;Port=1;Database=chatex;Username=x;Password=x;Timeout=2");
[Fact]
public async Task Health_answers_503_when_the_database_is_unreachable()
{
var response = await CreateClient().GetAsync("/health", Ct);
response.StatusCode.ShouldBe(HttpStatusCode.ServiceUnavailable);
}
}The second class points the application to port 1, where nothing listens, so every connection fails immediately: /health must answer 503 — the signal the deployment uses for its rollback.
Check
powershell
dotnet test --solution Chatex.slnx85 tests pass: 19 data, 41 business and 25 API tests.