aboutsummaryrefslogtreecommitdiff
path: root/BackEnd/Timeline.Tests/IntegratedTests2/HttpClientTestExtensions.cs
blob: 0124b72ae41d72df177566a2c8b3cd7563afe473 (plain)
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
39
40
41
42
43
44
45
46
47
48
49
50
51
52
using FluentAssertions;
using System;
using System.Net;
using System.Net.Http;
using System.Net.Http.Json;
using System.Threading.Tasks;
using Timeline.Models.Http;
using Timeline.Tests.Helpers;

namespace Timeline.Tests.IntegratedTests2
{
    public delegate Task RequestSetupAsync(HttpRequestMessage httpRequest);

    public static class HttpClientTestExtensions
    {
        public static async Task<HttpResponseMessage> TestSendAsync(this HttpClient client, HttpMethod method, string url, HttpContent? body = null, HttpStatusCode expectedStatusCode = HttpStatusCode.OK, RequestSetupAsync? requestSetup = null)
        {
            using var req = new HttpRequestMessage
            {
                Method = method,
                RequestUri = new Uri(url, UriKind.Relative),
                Content = body
            };
            var task = requestSetup?.Invoke(req);
            if (task is not null) await task;
            var res = await client.SendAsync(req);
            res.StatusCode.Should().Be(expectedStatusCode);
            return res;
        }

        public static async Task<T> AssertJsonBodyAsync<T>(HttpResponseMessage response)
        {
            var body = await response.Content.ReadFromJsonAsync<T>(CommonJsonSerializeOptions.Options);
            body.Should().NotBeNull($"Body is not json format of type {typeof(T).FullName}");
            return body!;
        }

        public static async Task TestJsonSendAsync(this HttpClient client, HttpMethod method, string url, object? jsonBody = null, HttpStatusCode expectedStatusCode = HttpStatusCode.OK, RequestSetupAsync? requestSetup = null)
        {
            using JsonContent? reqContent = jsonBody is null ? null : JsonContent.Create(jsonBody, options: CommonJsonSerializeOptions.Options);
            await client.TestSendAsync(method, url, reqContent, expectedStatusCode, requestSetup);
        }

        public static async Task<T> TestJsonSendAsync<T>(this HttpClient client, HttpMethod method, string url, object? jsonBody = null, HttpStatusCode expectedStatusCode = HttpStatusCode.OK, RequestSetupAsync? requestSetup = null)
        {
            using JsonContent? reqContent = jsonBody == null ? null : JsonContent.Create(jsonBody, options: CommonJsonSerializeOptions.Options);
            var res = await client.TestSendAsync(method, url, reqContent, expectedStatusCode, requestSetup);
            var resBody = await AssertJsonBodyAsync<T>(res);
            return resBody;
        }
    }
}