summary refs log tree commit diff
path: root/extra/admin-api/Tests/Spacebar.Tests/Extensions/AssertHttpExtensions.cs
blob: f5e99dc98c71c2cfa32a43ff2772b24db1bae983 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
using System.Net.Http.Json;
using System.Text.Json.Nodes;

namespace Spacebar.Tests.Extensions;

public static class AssertHttpExtensions {
    private static readonly HttpClient Hc = new();

    public static async Task<string> GetFormattedErrorDetails(HttpResponseMessage res) {
        return res.Content.Headers.ContentType?.MediaType == "application/json"
            ? (await res.Content.ReadFromJsonAsync<JsonObject>())!.ToJsonString(new() {
                WriteIndented = true
            })
            : await res.Content.ReadAsStringAsync();
    }

    extension(Assert) {
        public static async Task<HttpResponseMessage> SuccessfullyHttpGetAsync(string url) {
            var res = await Hc.GetAsync(url);
            Assert.True(res.IsSuccessStatusCode, $"Could not get {url}: {res.StatusCode}\n{await GetFormattedErrorDetails(res)}");
            return res;
        }

        public static async Task<HttpResponseMessage> SuccessfullyHttpPostAsJsonAsync<TValue>(string url, TValue obj) {
            var res = await Hc.PostAsJsonAsync(url, obj);
            if (!res.IsSuccessStatusCode)
                Assert.True(res.IsSuccessStatusCode, $"Could not POST JSON to {url}: {(int)res.StatusCode} {res.StatusCode}\n{await GetFormattedErrorDetails(res)}");
            return res;
        }

        public static async Task<HttpResponseMessage> HttpSuccess(HttpResponseMessage res) {
            if (!res.IsSuccessStatusCode)
                Assert.True(res.IsSuccessStatusCode,
                    $"Could not {res.RequestMessage!.Method.Method.ToUpper()} to {res.RequestMessage!.RequestUri!.ToString()}: {(int)res.StatusCode} {res.StatusCode}\n{await GetFormattedErrorDetails(res)}");
            return res;
        }
    }
}