-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathApiTestBase.cs
More file actions
73 lines (61 loc) · 2.47 KB
/
ApiTestBase.cs
File metadata and controls
73 lines (61 loc) · 2.47 KB
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
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
using System;
using System.Net.Http;
using System.Threading.Tasks;
using ArmaForces.Boderator.BotService.Tests.TestUtilities.Collections;
using ArmaForces.Boderator.BotService.Tests.TestUtilities.TestFixtures;
using CSharpFunctionalExtensions;
using Microsoft.Extensions.DependencyInjection;
using Newtonsoft.Json;
using Xunit;
namespace ArmaForces.Boderator.BotService.Tests.TestUtilities.TestBases
{
/// <summary>
/// Base class for integration tests involving API.
/// Provider test server and methods to invoke endpoints.
/// </summary>
[Collection(CollectionsNames.ApiTest)]
public abstract class ApiTestBase
{
private readonly HttpClient _httpClient;
protected IServiceProvider Provider { get; }
protected ApiTestBase(TestApiServiceFixture testApi)
{
_httpClient = testApi.HttpClient;
Provider = new ServiceCollection()
.BuildServiceProvider();
}
protected async Task<Result<T>> HttpGetAsync<T>(string path)
{
return await HttpGetAsync(path)
.Bind(DeserializeContent<T>);
}
protected async Task<Result<string>> HttpGetAsync(string path)
{
var httpResponseMessage = await _httpClient.GetAsync(path);
if (httpResponseMessage.IsSuccessStatusCode)
{
return await httpResponseMessage.Content.ReadAsStringAsync();
}
var responseBody = await httpResponseMessage.Content.ReadAsStringAsync();
var error = string.IsNullOrWhiteSpace(responseBody)
? httpResponseMessage.ReasonPhrase
: responseBody;
return Result.Failure<string>(error);
}
protected async Task<Result> HttpPostAsync<T>(string path, T body)
{
var httpResponseMessage = await _httpClient.PostAsync(path, new StringContent(JsonConvert.SerializeObject(body)));
if (httpResponseMessage.IsSuccessStatusCode)
{
return Result.Success();
}
var responseBody = await httpResponseMessage.Content.ReadAsStringAsync();
var error = string.IsNullOrWhiteSpace(responseBody)
? httpResponseMessage.ReasonPhrase
: responseBody;
return Result.Failure<T>(error);
}
private static Result<T> DeserializeContent<T>(string content)
=> JsonConvert.DeserializeObject<T>(content);
}
}