2024-04-08 23:34:32 -05:00
|
|
|
namespace Blog.Tests.EndToEnd;
|
|
|
|
|
|
|
|
|
|
public class BlogHostFactory<TProgram> : WebApplicationFactory<TProgram> where TProgram : class
|
|
|
|
|
{
|
|
|
|
|
private IHost? _host;
|
|
|
|
|
|
|
|
|
|
private void EnsureServer()
|
|
|
|
|
{
|
|
|
|
|
if (_host is null)
|
|
|
|
|
{
|
|
|
|
|
using var _ = CreateDefaultClient();
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
protected override void Dispose(bool disposing)
|
|
|
|
|
{
|
|
|
|
|
_host?.Dispose();
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
public string ServerAddress
|
|
|
|
|
{
|
|
|
|
|
get
|
|
|
|
|
{
|
|
|
|
|
EnsureServer();
|
|
|
|
|
return ClientOptions.BaseAddress.ToString();
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
protected override IHost CreateHost(IHostBuilder builder)
|
2024-04-10 01:28:38 -05:00
|
|
|
{
|
2024-04-08 23:34:32 -05:00
|
|
|
var testHost = builder
|
2024-04-10 01:28:38 -05:00
|
|
|
.ConfigureWebHost(webHostBuilder =>
|
|
|
|
|
{
|
|
|
|
|
webHostBuilder.ConfigureLogging(config => config.ClearProviders());
|
|
|
|
|
webHostBuilder.ConfigureTestServices(services =>
|
|
|
|
|
{
|
|
|
|
|
var postsDirectory = Path.Combine(Directory.GetCurrentDirectory(), "TestPosts");
|
|
|
|
|
var postServiceOptions = new FilePostServiceOptions() { PostsDirectory = postsDirectory };
|
|
|
|
|
services.AddSingleton(Options.Create(postServiceOptions));
|
|
|
|
|
});
|
|
|
|
|
})
|
2024-04-08 23:34:32 -05:00
|
|
|
.Build();
|
|
|
|
|
|
|
|
|
|
builder.ConfigureWebHost(
|
|
|
|
|
webHostBuilder => webHostBuilder.UseKestrel(
|
|
|
|
|
o => o.Listen(IPAddress.Loopback, 0)
|
|
|
|
|
)
|
|
|
|
|
);
|
|
|
|
|
|
2024-04-10 01:28:38 -05:00
|
|
|
_host = builder.Build();
|
|
|
|
|
_host.Start();
|
2024-04-08 23:34:32 -05:00
|
|
|
|
2024-04-10 01:28:38 -05:00
|
|
|
var server = _host.Services.GetRequiredService<IServer>();
|
|
|
|
|
var addresses = server.Features.GetRequiredFeature<IServerAddressesFeature>();
|
2024-04-08 23:34:32 -05:00
|
|
|
|
2024-04-10 01:28:38 -05:00
|
|
|
ClientOptions.BaseAddress = addresses.Addresses
|
|
|
|
|
.Select(x => new Uri(x))
|
2024-04-08 23:34:32 -05:00
|
|
|
.Last();
|
|
|
|
|
|
2024-04-10 01:28:38 -05:00
|
|
|
testHost.Start();
|
|
|
|
|
return testHost;
|
2024-04-08 23:34:32 -05:00
|
|
|
}
|
|
|
|
|
}
|