using System; using System.Collections.Generic; using System.Net; using System.Net.Http.Json; using System.Text; using System.Text.Json; namespace LoadTest { internal sealed record TestUser(Guid Id, string Username); internal class Helpers { public static StringContent Json(string raw) => new(raw, Encoding.UTF8, "application/json"); public static HttpRequestMessage Request(HttpMethod method, string url, Guid? userId = null, HttpContent? content = null) { var request = new HttpRequestMessage(method, url) { Content = content }; if (userId is not null) { request.Headers.Add("X-User-Id", userId.Value.ToString()); } return request; } public static async Task ReadJsonAsync(HttpResponseMessage response) { var body = await response.Content.ReadAsStringAsync(); return JsonDocument.Parse(body).RootElement.Clone(); } public static async Task 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 = "Тест" }); var json = await ReadJsonAsync(response); response.EnsureSuccessStatusCode(); return new TestUser(json.GetProperty("id").GetGuid(), username); } public static async Task 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.Id, JsonContent.Create(new { title = "Чат", member_ids = members })); var response = await client.SendAsync(request); response.EnsureSuccessStatusCode(); return (await ReadJsonAsync(response)).GetProperty("id").GetGuid(); } public static async Task SendMessageAsync(HttpClient client, TestUser sender, Guid chatId, string text) { using var request = Request(HttpMethod.Post, $"/api/v1/chats/{chatId}/messages", sender.Id, JsonContent.Create(new { text })); var response = await client.SendAsync(request); response.EnsureSuccessStatusCode(); return response; } } }