using GameList.Data; using Microsoft.AspNetCore.Hosting; using Microsoft.AspNetCore.Mvc.Testing; using Microsoft.Data.Sqlite; using Microsoft.EntityFrameworkCore; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Hosting; namespace GameList.Tests.Support; internal class TestWebApplicationFactory : WebApplicationFactory { private SqliteConnection? _connection; protected override void ConfigureWebHost(IWebHostBuilder builder) { builder.UseEnvironment("Development"); builder.ConfigureAppConfiguration((_, config) => { config.AddInMemoryCollection(new Dictionary { ["ADMIN_PASSWORD"] = "admin-key" }); }); builder.ConfigureServices(services => { var descriptor = services.SingleOrDefault(d => d.ServiceType == typeof(DbContextOptions)); if (descriptor != null) { services.Remove(descriptor); } _connection = new SqliteConnection($"Data Source=file:tests-{Guid.NewGuid():N}?mode=memory&cache=shared"); _connection.Open(); services.AddDbContext(options => { options.UseSqlite(_connection); }); services.AddSingleton(); services.AddSingleton(); }); builder.UseSetting("https_port", "0"); } protected override IHost CreateHost(IHostBuilder builder) { var host = base.CreateHost(builder); using var scope = host.Services.CreateScope(); var db = scope.ServiceProvider.GetRequiredService(); db.Database.Migrate(); return host; } protected override void Dispose(bool disposing) { base.Dispose(disposing); if (disposing) { _connection?.Dispose(); } } public StubHttpMessageHandler HttpHandler => Services.GetRequiredService(); public Task WithDbContextAsync(Func action) { using var scope = Services.CreateScope(); var db = scope.ServiceProvider.GetRequiredService(); return action(db); } public Task WithDbContextAsync(Func> action) { using var scope = Services.CreateScope(); var db = scope.ServiceProvider.GetRequiredService(); return action(db); } public HttpClient CreateClientWithCookies() { var client = CreateClient(new WebApplicationFactoryClientOptions { HandleCookies = true, AllowAutoRedirect = false }); if (client.BaseAddress is { } baseAddress) { var origin = $"{baseAddress.Scheme}://{baseAddress.Authority}"; client.DefaultRequestHeaders.TryAddWithoutValidation("Origin", origin); } return client; } }