Українська
Тестування файлів, обмежень і стану
Крок 1. Тестові налаштування й допоміжні засоби
Навіщо. Нові можливості потребують у тестах нових налаштувань, а два тестові класи – власних: тесту обмеження частоти потрібен низький ліміт, тесту стану – база даних, якої не існує. Віртуальний метод дозволяє тестовому класу перевизначити типові значення.
Що зробити. Розширте 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.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 = 1024робить тести розміру малими, як і в бізнес-тестах.Maintenance:Enabled = false: щогодинне прибирання інакше запускалося б на початку кожного тестового застосунку.RateLimiting:AuthPermitLimit = 1000000: усі тестові клієнти мають одну (невідому) IP-адресу, тож справжній ліміт 20 на хвилину провалював би непов’язані тести.ConfigureHostвиконується після типових значень, тож тестовий клас може перевизначити будь-яке з них.PngBytes– перші 16 байтів PNG, цього досить для розпізнавача;FileContentбудує тіло multipart з однією частиною-файлом на ім’яfile– так називається параметрIFormFile.
Крок 2. Тести файлів
Що зробити.
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);
}
}- Увесь потік вкладення через HTTP: завантаження (
201,Location), надсилання з повідомленням, завантаження іншим учасником із правильним типом, розташуванняinlineіnosniff; сторонній отримує404. - Текстовий файл завантажується як
attachmentпід своєю назвою. - Обмеження: завеликий файл і
text/htmlдають400із бізнес-кодами. - Аватари: встановлення, віддача як
image/png(за розпізнаванням), вилучення, потім404 avatar_not_found. - Запит multipart без файлу дає
400– зв’язування зазнає невдачі ще до виконання кінцевої точки, аThrowOnBadRequest = falseразом зUseStatusCodePagesперетворюють це на Problem Details.
Крок 3. Тести обмеження частоти й стану
Що зробити.
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);
}
}
}З лімітом 3 три хибні входи отримують 401, четвертий – 429 із too_many_requests і заголовком Retry-After; кінцева точка профілю не стримується взагалі.
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);
}
}Другий клас спрямовує застосунок на порт 1, де ніхто не слухає, тож кожне з’єднання одразу завершується невдачею: /health має відповісти 503 – це сигнал, за яким розгортання виконує відкат.
Перевірка
powershell
dotnet test --solution Chatex.slnxПроходить 85 тестів: 19 тестів даних, 41 бізнес-тест і 25 тестів API.