using System.Net; using System.Net.Http.Json; using System.Text.Json.Serialization.Metadata; using Chronos.Protocol; using Chronos.Testing; namespace Chronos.Server.Tests; /// Assertions and JSON helpers for API calls. internal static class Http { /// The body of a successful response (an error response fails the test with its body). public static async Task ReadAsync(this HttpResponseMessage response, JsonTypeInfo type) where T : class { if (!response.IsSuccessStatusCode) Assert.Fail($"Expected success, got {(int)response.StatusCode}: {await response.Content.ReadAsStringAsync()}"); return Assert.NotNull(await response.Content.ReadFromJsonAsync(type)); } /// Asserts the status, the { code, message, details } body with , and the API header. public static async Task ExpectErrorAsync(this HttpResponseMessage response, HttpStatusCode status, string code) { var body = await response.Content.ReadAsStringAsync(); Assert.Equal(status, response.StatusCode, body); Assert.Equal("1", response.Headers.GetValues(ApiVersion.Header).Single()); var error = Assert.NotNull(System.Text.Json.JsonSerializer.Deserialize(body, ProtocolJson.Default.ApiError)); Assert.Equal(code, error.Code, body); Assert.False(string.IsNullOrWhiteSpace(error.Message), "message is empty"); return error; } public static async Task BytesEqualAsync(byte[] expected, Task actual) { var bytes = await actual; Assert.BytesEqual(expected, bytes); } public static async Task ExpectAsync(this HttpResponseMessage response, HttpStatusCode status) { if (response.StatusCode != status) Assert.Fail($"Expected {(int)status}, got {(int)response.StatusCode}: {await response.Content.ReadAsStringAsync()}"); } }