From 27e1360ffe4b2f5aa7d240e1de88c5459587b489 Mon Sep 17 00:00:00 2001 From: crupest Date: Fri, 8 Apr 2022 17:39:07 +0800 Subject: ... --- .../IntegratedTests2/HttpClientTestExtensions.cs | 52 ++++++++++++++++++++++ 1 file changed, 52 insertions(+) create mode 100644 BackEnd/Timeline.Tests/IntegratedTests2/HttpClientTestExtensions.cs (limited to 'BackEnd/Timeline.Tests/IntegratedTests2/HttpClientTestExtensions.cs') diff --git a/BackEnd/Timeline.Tests/IntegratedTests2/HttpClientTestExtensions.cs b/BackEnd/Timeline.Tests/IntegratedTests2/HttpClientTestExtensions.cs new file mode 100644 index 00000000..0124b72a --- /dev/null +++ b/BackEnd/Timeline.Tests/IntegratedTests2/HttpClientTestExtensions.cs @@ -0,0 +1,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 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 AssertJsonBodyAsync(HttpResponseMessage response) + { + var body = await response.Content.ReadFromJsonAsync(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 TestJsonSendAsync(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(res); + return resBody; + } + } +} -- cgit v1.2.3