Українська
Тестування через HTTP
Крок 1. Тестовий проєкт
Навіщо. Бізнес-тести доводять правила. Тести API доводять те, у чому може помилитися лише веб-рівень: маршрути, коди стану, форму JSON (camelCase, перелічення як рядки), Problem Details, токен Bearer, атрибути cookie. Вони запускають справжній застосунок у пам’яті через WebApplicationFactory<Program> із Microsoft.AspNetCore.Mvc.Testing: увесь Program.cs, зокрема проміжне програмне забезпечення, на тестовому сервері без мережевих портів, поверх контейнера PostgreSQL із теми 6.
Що зробити.
powershell
dotnet new classlib -o Tests/Chatex.Api.Testspowershell
Remove-Item Tests/Chatex.Api.Tests/Class1.cspowershell
dotnet sln add Tests/Chatex.Api.Testspowershell
dotnet add Tests/Chatex.Api.Tests reference Source/Chatex.Apipowershell
dotnet add Tests/Chatex.Api.Tests package Microsoft.AspNetCore.Mvc.TestingВидаліть із шаблону <PropertyGroup> і додайте посилання на фреймворк вручну:
xml
<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" />
</ItemGroup>
</Project><FrameworkReference Include="Microsoft.AspNetCore.App" /> дає бібліотеці класів типи ASP.NET Core (IWebHostBuilder, HttpContext), які веб-проєкт отримує зі свого SDK.
Крок 2. Перевірки HTTP-відповідей
Навіщо. Тести HTTP знову й знову перевіряють те саме: код стану (з тілом у повідомленні про збій, інакше 400 – це загадка), тіло JSON заданого типу, тіло Problem Details із заданим code, cookie. Кілька методів розширення роблять кожну перевірку одним рядком.
Що зробити.
cs
using System.Net;
using System.Net.Http.Json;
using System.Text.Json;
using System.Text.Json.Serialization;
namespace Chatex.Api.Tests;
internal static class HttpAssertions
{
private static readonly JsonSerializerOptions Json = new(JsonSerializerDefaults.Web)
{
Converters = { new JsonStringEnumConverter(JsonNamingPolicy.CamelCase) },
};
private static CancellationToken Ct => TestContext.Current.CancellationToken;
public static async Task<T> ShouldHaveAsync<T>(this HttpResponseMessage response, HttpStatusCode status)
where T : class
{
await response.ShouldHaveStatusAsync(status);
var body = await response.Content.ReadFromJsonAsync<T>(Json, Ct);
body.ShouldNotBeNull();
return body;
}
public static async Task ShouldHaveStatusAsync(this HttpResponseMessage response, HttpStatusCode status)
{
if (response.StatusCode != status)
{
var body = await response.Content.ReadAsStringAsync(Ct);
response.StatusCode.ShouldBe(status, $"Body: {body}");
}
}
/// <summary>Checks a problem details response and returns its body.</summary>
public static async Task<JsonElement> ShouldBeProblemAsync(this HttpResponseMessage response, HttpStatusCode status, string? code = null)
{
await response.ShouldHaveStatusAsync(status);
response.Content.Headers.ContentType?.MediaType.ShouldBe("application/problem+json");
var problem = await response.Content.ReadFromJsonAsync<JsonElement>(Ct);
problem.GetProperty("status").GetInt32().ShouldBe((int)status);
if (code is not null)
{
problem.GetProperty("code").GetString().ShouldBe(code);
}
return problem;
}
/// <summary>The value of a cookie the response sets, with its attributes.</summary>
public static string? SetCookie(this HttpResponseMessage response, string name) =>
response.Headers.TryGetValues("Set-Cookie", out var values)
? values.FirstOrDefault(v => v.StartsWith(name + "=", StringComparison.Ordinal))
: null;
public static string CookieValue(string setCookie) => setCookie.Split(';')[0].Split('=', 2)[1];
}Крок 3. Базовий клас
Навіщо. Кожен тестовий клас запускає застосунок на чистій базі даних із тестовими налаштуваннями та пропонує спосіб створювати клієнтів – кожного зі своїм сховищем cookie, як окремий браузер, – а також реєструвати користувача й отримувати клієнта, що надсилає токен цього користувача.
Що зробити.
cs
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!";
protected static readonly JsonSerializerOptions Json = new(JsonSerializerDefaults.Web)
{
Converters = { new JsonStringEnumConverter(JsonNamingPolicy.CamelCase) },
};
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);
});
}
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",
};
}
public sealed record Session(HttpClient Client, AuthResponse Auth)
{
public Guid UserId => Auth.User.Id;
}WithWebHostBuilderналаштовує справжній застосунок для тесту: середовищеTesting(тожappsettings.Development.jsonне завантажується, а Scalar вимкнено), рядок підключення тестового контейнера, тестові налаштування JWT і тимчасову папку завантажень.UseSettingперевизначає значення конфігурації.https://localhostяк базова адреса: cookie оновлення має атрибутSecure, тож іде лише через HTTPS. Тестовий сервер насправді нічого не шифрує, але сховище cookie клієнта дотримується правил схеми.RegisterAsyncреєструє користувача через справжню кінцеву точку й задає заголовокAuthorizationповернутого клієнта.Sessionтримає клієнта й відповідь автентифікації разом.Jsonвикористовує типові параметри для вебу (camelCase) і той самий перетворювач перелічень, що й API, тож тести можуть десеріалізувати відповіді у DTO з Chatex.Core.
Крок 4. Тести кінцевих точок
Що зробити.
cs
using System.Net;
using System.Net.Http.Json;
using System.Text;
using System.Text.Json;
using Chatex.Api.Contracts;
using Chatex.Core.Users;
namespace Chatex.Api.Tests;
public sealed class AuthEndpointsTests(PostgresFixture fixture) : ApiTestBase(fixture)
{
private const string Cookie = "chatex_refresh";
[Fact]
public async Task Register_returns_access_token_and_sets_refresh_cookie()
{
var client = CreateClient();
var response = await client.PostAsJsonAsync("/api/auth/register", RegisterBody("alice"), Json, Ct);
await response.ShouldHaveStatusAsync(HttpStatusCode.OK);
var body = await response.Content.ReadFromJsonAsync<JsonElement>(Ct);
body.GetProperty("accessToken").GetString().ShouldNotBeNullOrEmpty();
body.GetProperty("user").GetProperty("userName").GetString().ShouldBe("alice");
body.TryGetProperty("refreshToken", out _).ShouldBeFalse();
var cookie = response.SetCookie(Cookie).ShouldNotBeNull().ToLowerInvariant();
cookie.ShouldContain("httponly");
cookie.ShouldContain("secure");
cookie.ShouldContain("samesite=strict");
cookie.ShouldContain("path=/api/auth");
}
[Fact]
public async Task Access_token_authenticates_requests()
{
var alice = await RegisterAsync("alice");
var me = await (await alice.Client.GetAsync("/api/me", Ct)).ShouldHaveAsync<MyProfileDto>(HttpStatusCode.OK);
me.Id.ShouldBe(alice.UserId);
me.Email.ShouldBe("[email protected]");
}
[Fact]
public async Task Requests_without_a_token_get_401_problem()
{
var response = await CreateClient().GetAsync("/api/me", Ct);
await response.ShouldBeProblemAsync(HttpStatusCode.Unauthorized);
}
[Fact]
public async Task Login_accepts_user_name_and_rejects_a_wrong_password()
{
await RegisterAsync("alice");
var client = CreateClient();
var ok = await client.PostAsJsonAsync("/api/auth/login", new { login = "alice", password = Password }, Json, Ct);
var wrong = await client.PostAsJsonAsync("/api/auth/login", new { login = "alice", password = "nope12345" }, Json, Ct);
(await ok.ShouldHaveAsync<AuthResponse>(HttpStatusCode.OK)).User.UserName.ShouldBe("alice");
ok.SetCookie(Cookie).ShouldNotBeNull();
await wrong.ShouldBeProblemAsync(HttpStatusCode.Unauthorized, "invalid_credentials");
}
[Fact]
public async Task Refresh_rotates_the_cookie_and_a_reused_token_is_rejected()
{
var client = CreateClient();
var register = await client.PostAsJsonAsync("/api/auth/register", RegisterBody("alice"), Json, Ct);
var firstToken = HttpAssertions.CookieValue(register.SetCookie(Cookie).ShouldNotBeNull());
var refreshed = await client.PostAsync("/api/auth/refresh", null, Ct);
var auth = await refreshed.ShouldHaveAsync<AuthResponse>(HttpStatusCode.OK);
auth.User.UserName.ShouldBe("alice");
HttpAssertions.CookieValue(refreshed.SetCookie(Cookie).ShouldNotBeNull()).ShouldNotBe(firstToken);
var replay = new HttpRequestMessage(HttpMethod.Post, "/api/auth/refresh");
replay.Headers.Add("Cookie", $"{Cookie}={firstToken}");
var reused = await CreateClient().SendAsync(replay, Ct);
await reused.ShouldBeProblemAsync(HttpStatusCode.Unauthorized, "invalid_refresh_token");
// Reuse signs the user out everywhere, so the newest cookie stops working too.
var afterReuse = await client.PostAsync("/api/auth/refresh", null, Ct);
await afterReuse.ShouldBeProblemAsync(HttpStatusCode.Unauthorized, "invalid_refresh_token");
}
[Fact]
public async Task Refresh_without_a_cookie_is_401()
{
var response = await CreateClient().PostAsync("/api/auth/refresh", null, Ct);
await response.ShouldBeProblemAsync(HttpStatusCode.Unauthorized, "invalid_refresh_token");
}
[Fact]
public async Task Logout_clears_the_cookie_and_ends_the_session()
{
var client = CreateClient();
var register = await client.PostAsJsonAsync("/api/auth/register", RegisterBody("alice"), Json, Ct);
var token = HttpAssertions.CookieValue(register.SetCookie(Cookie).ShouldNotBeNull());
var logout = await client.PostAsync("/api/auth/logout", null, Ct);
await logout.ShouldHaveStatusAsync(HttpStatusCode.NoContent);
logout.SetCookie(Cookie).ShouldNotBeNull().ShouldContain("expires=Thu, 01 Jan 1970", Case.Insensitive);
var replay = new HttpRequestMessage(HttpMethod.Post, "/api/auth/refresh");
replay.Headers.Add("Cookie", $"{Cookie}={token}");
await (await CreateClient().SendAsync(replay, Ct)).ShouldBeProblemAsync(HttpStatusCode.Unauthorized);
}
[Fact]
public async Task Duplicate_user_name_is_409()
{
await RegisterAsync("alice");
var response = await CreateClient().PostAsJsonAsync("/api/auth/register", RegisterBody("alice"), Json, Ct);
await response.ShouldBeProblemAsync(HttpStatusCode.Conflict, "user_name_taken");
}
[Fact]
public async Task Invalid_fields_are_400_with_per_field_errors()
{
var body = new { userName = "a", email = "not-an-email", password = Password, displayName = "A" };
var response = await CreateClient().PostAsJsonAsync("/api/auth/register", body, Json, Ct);
var problem = await response.ShouldBeProblemAsync(HttpStatusCode.BadRequest, "validation_failed");
var errors = problem.GetProperty("errors");
errors.TryGetProperty("userName", out _).ShouldBeTrue();
errors.TryGetProperty("email", out _).ShouldBeTrue();
}
[Fact]
public async Task Malformed_json_is_400_problem()
{
var content = new StringContent("{ not json", Encoding.UTF8, "application/json");
var response = await CreateClient().PostAsync("/api/auth/login", content, Ct);
await response.ShouldBeProblemAsync(HttpStatusCode.BadRequest);
}
}Тести автентифікації перевіряють контракт із браузером: токен у тілі, а токена оновлення в тілі немає; cookie має всі чотири атрибути; запит без токена отримує Problem Details 401; оновлення замінює cookie, а повторно використане cookie виводить користувача звідусіль; вихід закінчує строк дії cookie; дублікати дають 409, недійсні поля – 400 з errors для кожного поля, зіпсований JSON – 400 Problem Details.
cs
using System.Net;
using System.Net.Http.Json;
using System.Text.Json;
using Chatex.Api.Contracts;
using Chatex.Core.Chats;
using Chatex.Core.Common;
using Chatex.Core.Messages;
using Chatex.Data.Entities;
namespace Chatex.Api.Tests;
public sealed class ChatAndMessageEndpointsTests(PostgresFixture fixture) : ApiTestBase(fixture)
{
[Fact]
public async Task Creating_a_group_returns_201_with_location_and_camel_case_enums()
{
var alice = await RegisterAsync("alice");
var bob = await RegisterAsync("bob");
var response = await alice.Client.PostAsJsonAsync(
"/api/chats", new { type = "group", title = "Team", memberIds = new[] { bob.UserId } }, Json, Ct);
await response.ShouldHaveStatusAsync(HttpStatusCode.Created);
var raw = await response.Content.ReadFromJsonAsync<JsonElement>(Ct);
raw.GetProperty("type").GetString().ShouldBe("group");
raw.GetProperty("myRole").GetString().ShouldBe("owner");
var chat = raw.Deserialize<ChatDto>(Json).ShouldNotBeNull();
chat.MemberCount.ShouldBe(2);
response.Headers.Location.ShouldBe(new Uri($"/api/chats/{chat.Id}", UriKind.Relative));
var fetched = await (await bob.Client.GetAsync($"/api/chats/{chat.Id}", Ct)).ShouldHaveAsync<ChatDto>(HttpStatusCode.OK);
fetched.MyRole.ShouldBe(ChatMemberRole.Member);
}
[Fact]
public async Task Messages_can_be_sent_read_edited_and_deleted()
{
var alice = await RegisterAsync("alice");
var bob = await RegisterAsync("bob");
var chat = await CreateGroupAsync(alice, bob.UserId);
var sent = await (await bob.Client.PostAsJsonAsync($"/api/chats/{chat.Id}/messages", new { body = "hi all" }, Json, Ct))
.ShouldHaveAsync<MessageDto>(HttpStatusCode.Created);
await SendAsync(alice, chat.Id, "hello bob");
var page = await (await alice.Client.GetAsync($"/api/chats/{chat.Id}/messages?limit=1", Ct))
.ShouldHaveAsync<PageDto<MessageDto>>(HttpStatusCode.OK);
page.Items.Single().Body.ShouldBe("hello bob");
page.NextCursor.ShouldNotBeNull();
var older = await (await alice.Client.GetAsync($"/api/chats/{chat.Id}/messages?before={page.NextCursor}", Ct))
.ShouldHaveAsync<PageDto<MessageDto>>(HttpStatusCode.OK);
older.Items.Single().Id.ShouldBe(sent.Id);
older.NextCursor.ShouldBeNull();
var edited = await (await bob.Client.PutAsJsonAsync($"/api/messages/{sent.Id}", new { body = "hi everyone" }, Json, Ct))
.ShouldHaveAsync<MessageDto>(HttpStatusCode.OK);
edited.Body.ShouldBe("hi everyone");
edited.EditedAt.ShouldNotBeNull();
var notSender = await alice.Client.PutAsJsonAsync($"/api/messages/{sent.Id}", new { body = "hacked" }, Json, Ct);
await notSender.ShouldBeProblemAsync(HttpStatusCode.Forbidden, "not_sender");
await (await bob.Client.DeleteAsync($"/api/messages/{sent.Id}", Ct)).ShouldHaveStatusAsync(HttpStatusCode.NoContent);
var after = await (await alice.Client.GetAsync($"/api/chats/{chat.Id}/messages", Ct))
.ShouldHaveAsync<PageDto<MessageDto>>(HttpStatusCode.OK);
after.Items.Single(m => m.Id == sent.Id).IsDeleted.ShouldBeTrue();
}
[Fact]
public async Task Outsiders_cannot_read_a_private_group()
{
var alice = await RegisterAsync("alice");
var eve = await RegisterAsync("eve");
var chat = await CreateGroupAsync(alice);
var response = await eve.Client.GetAsync($"/api/chats/{chat.Id}/messages", Ct);
await response.ShouldBeProblemAsync(HttpStatusCode.NotFound, "chat_not_found");
}
[Fact]
public async Task Unknown_chat_is_404_problem()
{
var alice = await RegisterAsync("alice");
var response = await alice.Client.GetAsync($"/api/chats/{Guid.NewGuid()}", Ct);
await response.ShouldBeProblemAsync(HttpStatusCode.NotFound, "chat_not_found");
}
[Fact]
public async Task Public_channels_can_be_found_and_joined_but_subscribers_cannot_post()
{
var alice = await RegisterAsync("alice");
var bob = await RegisterAsync("bob");
var created = await alice.Client.PostAsJsonAsync(
"/api/chats", new { type = "channel", title = "News", publicHandle = "news_room" }, Json, Ct);
var channel = await created.ShouldHaveAsync<ChatDto>(HttpStatusCode.Created);
var found = await (await bob.Client.GetAsync("/api/chats/search?query=news", Ct))
.ShouldHaveAsync<ChatSummaryDto[]>(HttpStatusCode.OK);
found.ShouldContain(c => c.Id == channel.Id);
var joined = await (await bob.Client.PostAsync($"/api/chats/{channel.Id}/join", null, Ct))
.ShouldHaveAsync<ChatDto>(HttpStatusCode.OK);
joined.MyRole.ShouldBe(ChatMemberRole.Subscriber);
var post = await bob.Client.PostAsJsonAsync($"/api/chats/{channel.Id}/messages", new { body = "me too" }, Json, Ct);
await post.ShouldBeProblemAsync(HttpStatusCode.Forbidden, "cannot_post");
}
[Fact]
public async Task Direct_chat_members_roles_and_read_state()
{
var alice = await RegisterAsync("alice");
var bob = await RegisterAsync("bob");
var carol = await RegisterAsync("carol");
var direct = await (await alice.Client.PostAsJsonAsync("/api/chats/direct", new OpenDirectRequest(bob.UserId), Json, Ct))
.ShouldHaveAsync<ChatDto>(HttpStatusCode.OK);
direct.Type.ShouldBe(ChatType.Direct);
direct.Peer.ShouldNotBeNull().Id.ShouldBe(bob.UserId);
var group = await CreateGroupAsync(alice);
var added = await (await alice.Client.PostAsJsonAsync(
$"/api/chats/{group.Id}/members", new AddMembersRequest([bob.UserId, carol.UserId]), Json, Ct))
.ShouldHaveAsync<AddMembersResponse>(HttpStatusCode.OK);
added.Added.ShouldBe(2);
await (await alice.Client.PutAsJsonAsync(
$"/api/chats/{group.Id}/members/{bob.UserId}/role", new { role = "admin" }, Json, Ct))
.ShouldHaveStatusAsync(HttpStatusCode.NoContent);
await (await bob.Client.DeleteAsync($"/api/chats/{group.Id}/members/{carol.UserId}", Ct))
.ShouldHaveStatusAsync(HttpStatusCode.NoContent);
var members = await (await alice.Client.GetAsync($"/api/chats/{group.Id}/members", Ct))
.ShouldHaveAsync<PageDto<ChatMemberDto>>(HttpStatusCode.OK);
members.Items.Select(m => (m.User.Id, m.Role)).ShouldBe(
[(alice.UserId, ChatMemberRole.Owner), (bob.UserId, ChatMemberRole.Admin)], ignoreOrder: true);
var message = await SendAsync(alice, group.Id, "unread for bob");
var unread = await BobsChatAsync(bob, group.Id);
unread.UnreadCount.ShouldBe(1);
await (await bob.Client.PostAsJsonAsync($"/api/chats/{group.Id}/read", new MarkReadRequest(message.Id), Json, Ct))
.ShouldHaveStatusAsync(HttpStatusCode.NoContent);
await (await bob.Client.PutAsJsonAsync($"/api/chats/{group.Id}/mute", new SetMutedRequest(true), Json, Ct))
.ShouldHaveStatusAsync(HttpStatusCode.NoContent);
var read = await BobsChatAsync(bob, group.Id);
read.UnreadCount.ShouldBe(0);
read.IsMuted.ShouldBeTrue();
}
private static async Task<ChatListItemDto> BobsChatAsync(Session bob, Guid chatId)
{
var page = await (await bob.Client.GetAsync("/api/chats", Ct)).ShouldHaveAsync<PageDto<ChatListItemDto>>(HttpStatusCode.OK);
return page.Items.Single(c => c.Id == chatId);
}
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<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);
}
}Тести чатів проходять найважливішими сценаріями через HTTP: створення групи (201, Location, перелічення як "group" і "owner"), надсилання, посторінкове читання з непрозорим курсором, редагування, видалення; приватна група для сторонніх – 404; публічний канал можна знайти й вступити до нього, але він відхиляє публікації підписників; особисті чати, учасники, ролі, лічильники непрочитаного, позиції прочитання й вимкнення сповіщень.
Перевірка
powershell
dotnet test --solution Chatex.slnxПроходить 76 тестів: 19 тестів даних, 41 бізнес-тест і 16 тестів API. Три тестові проєкти працюють паралельно, кожен зі своїм контейнером PostgreSQL.