Выполнение работы на 4.
This commit is contained in:
@@ -0,0 +1,104 @@
|
||||
using System.Net;
|
||||
using System.Net.Http.Headers;
|
||||
using System.Net.Http.Json;
|
||||
using System.Text;
|
||||
using System.Text.Json;
|
||||
|
||||
namespace Messenger.Api.Tests;
|
||||
|
||||
internal sealed record TestUser(Guid Id, string Username, string Password, string Token);
|
||||
|
||||
internal static class ApiHelpers
|
||||
{
|
||||
public const string DefaultPassword = "correct horse battery staple";
|
||||
|
||||
public static StringContent Json(string raw) =>
|
||||
new(raw, Encoding.UTF8, "application/json");
|
||||
|
||||
// user != null — запрос с Bearer-токеном этого пользователя.
|
||||
public static HttpRequestMessage Request(HttpMethod method, string url, TestUser? user = null, HttpContent? content = null)
|
||||
{
|
||||
var request = new HttpRequestMessage(method, url) { Content = content };
|
||||
if (user is not null)
|
||||
{
|
||||
request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", user.Token);
|
||||
}
|
||||
|
||||
return request;
|
||||
}
|
||||
|
||||
public static async Task<JsonElement> ReadJsonAsync(HttpResponseMessage response)
|
||||
{
|
||||
var body = await response.Content.ReadAsStringAsync();
|
||||
return JsonDocument.Parse(body).RootElement.Clone();
|
||||
}
|
||||
|
||||
public static async Task<string> ErrorCodeAsync(HttpResponseMessage response)
|
||||
{
|
||||
var json = await ReadJsonAsync(response);
|
||||
return json.GetProperty("error").GetProperty("code").GetString()!;
|
||||
}
|
||||
|
||||
public static string BasicHeader(string username, string password) =>
|
||||
"Basic " + Convert.ToBase64String(Encoding.UTF8.GetBytes($"{username}:{password}"));
|
||||
|
||||
public static async Task<HttpResponseMessage> LoginAsync(HttpClient client, string username, string password)
|
||||
{
|
||||
using var request = new HttpRequestMessage(HttpMethod.Post, "/api/v1/auth/sessions");
|
||||
request.Headers.TryAddWithoutValidation("Authorization", BasicHeader(username, password));
|
||||
return await client.SendAsync(request);
|
||||
}
|
||||
|
||||
// Регистрирует пользователя и входит: возвращает его с рабочим Bearer-токеном.
|
||||
public static async Task<TestUser> CreateUserAsync(HttpClient client, string? username = null)
|
||||
{
|
||||
username ??= "u" + Guid.NewGuid().ToString("N")[..12];
|
||||
var response = await client.PostAsJsonAsync("/api/v1/users",
|
||||
new { username, display_name = "Тест", password = DefaultPassword });
|
||||
Assert.Equal(HttpStatusCode.Created, response.StatusCode);
|
||||
var id = (await ReadJsonAsync(response)).GetProperty("id").GetGuid();
|
||||
|
||||
var login = await LoginAsync(client, username, DefaultPassword);
|
||||
Assert.Equal(HttpStatusCode.Created, login.StatusCode);
|
||||
var token = (await ReadJsonAsync(login)).GetProperty("token").GetString()!;
|
||||
return new TestUser(id, username, DefaultPassword, token);
|
||||
}
|
||||
|
||||
public static async Task<Guid> CreateChatAsync(HttpClient client, TestUser owner, params TestUser[] others)
|
||||
{
|
||||
var members = others.Append(owner).Select(u => u.Id).ToArray();
|
||||
using var request = Request(HttpMethod.Post, "/api/v1/chats", owner,
|
||||
JsonContent.Create(new { title = "Чат", member_ids = members }));
|
||||
var response = await client.SendAsync(request);
|
||||
Assert.Equal(HttpStatusCode.Created, response.StatusCode);
|
||||
return (await ReadJsonAsync(response)).GetProperty("id").GetGuid();
|
||||
}
|
||||
|
||||
// key == null — новый уникальный Idempotency-Key (каждое сообщение независимо); иначе повтор с заданным ключом.
|
||||
public static async Task<HttpResponseMessage> SendMessageAsync(
|
||||
HttpClient client, TestUser sender, Guid chatId, string text, string? key = null)
|
||||
{
|
||||
using var request = Request(HttpMethod.Post, $"/api/v1/chats/{chatId}/messages", sender,
|
||||
JsonContent.Create(new { text }));
|
||||
request.Headers.Add("Idempotency-Key", key ?? Guid.NewGuid().ToString("N"));
|
||||
return await client.SendAsync(request);
|
||||
}
|
||||
|
||||
public static async Task<List<Guid>> ReadAllMessagesAsync(HttpClient client, Guid chatId, TestUser user, int limit)
|
||||
{
|
||||
string? cursor = null;
|
||||
var received = new List<Guid>();
|
||||
do
|
||||
{
|
||||
var url = $"/api/v1/chats/{chatId}/messages?limit={limit}" +
|
||||
(cursor is null ? "" : "&cursor=" + Uri.EscapeDataString(cursor));
|
||||
using var request = Request(HttpMethod.Get, url, user);
|
||||
var page = await ReadJsonAsync(await client.SendAsync(request));
|
||||
received.AddRange(page.GetProperty("items").EnumerateArray().Select(m => m.GetProperty("id").GetGuid()));
|
||||
var next = page.GetProperty("next_cursor");
|
||||
cursor = next.ValueKind == JsonValueKind.Null ? null : next.GetString();
|
||||
}
|
||||
while (cursor is not null);
|
||||
return received;
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user