-
Notifications
You must be signed in to change notification settings - Fork 8
Expand file tree
/
Copy pathIntegrationTestBase.cs
More file actions
66 lines (55 loc) · 2.39 KB
/
IntegrationTestBase.cs
File metadata and controls
66 lines (55 loc) · 2.39 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
using System.Net;
using Microsoft.Extensions.DependencyInjection;
using TUnit.AspNetCore;
namespace EssentialCSharp.Web.Tests;
public abstract class IntegrationTestBase : WebApplicationTest<WebApplicationFactory, Program>
{
/// <summary>
/// Executes a GET request and follows redirect responses while preserving
/// TUnit trace correlation by using <see cref="TracedWebApplicationFactory{T}.CreateClient()"/>.
/// </summary>
protected async Task<HttpResponseMessage> GetWithRedirectsAsync(string relativeUrl, int maxRedirects = 10)
{
HttpClient client = Factory.CreateClient();
HttpResponseMessage response = await client.GetAsync(relativeUrl);
for (int redirectCount = 0;
redirectCount < maxRedirects && IsRedirectStatusCode(response.StatusCode);
redirectCount++)
{
Uri? location = response.Headers.Location;
if (location is null)
{
return response;
}
response.Dispose();
response = await client.GetAsync(location);
}
return response;
}
private static bool IsRedirectStatusCode(HttpStatusCode statusCode) =>
statusCode == HttpStatusCode.Moved ||
statusCode == HttpStatusCode.Found ||
statusCode == HttpStatusCode.RedirectMethod ||
statusCode == HttpStatusCode.TemporaryRedirect ||
statusCode == HttpStatusCode.PermanentRedirect;
public T InServiceScope<T>(Func<IServiceProvider, T> action)
{
using IServiceScope scope = Factory.Services.GetRequiredService<IServiceScopeFactory>().CreateScope();
return action(scope.ServiceProvider);
}
public void InServiceScope(Action<IServiceProvider> action)
{
using IServiceScope scope = Factory.Services.GetRequiredService<IServiceScopeFactory>().CreateScope();
action(scope.ServiceProvider);
}
public async Task<T> InServiceScopeAsync<T>(Func<IServiceProvider, Task<T>> action)
{
using IServiceScope scope = Factory.Services.GetRequiredService<IServiceScopeFactory>().CreateScope();
return await action(scope.ServiceProvider);
}
public async Task InServiceScopeAsync(Func<IServiceProvider, Task> action)
{
using IServiceScope scope = Factory.Services.GetRequiredService<IServiceScopeFactory>().CreateScope();
await action(scope.ServiceProvider);
}
}