using System.Collections.Concurrent; using System.Diagnostics; using System.Net; using System.Net.Http.Headers; using System.Net.Http.Json; using System.Security.Cryptography; using Helpdesk.Application.Abstractions; using Helpdesk.Application.Auth; using Helpdesk.Application.Users; using Helpdesk.Infrastructure.Persistence; using Microsoft.AspNetCore.Hosting; using Microsoft.AspNetCore.Mvc.Testing; using Microsoft.AspNetCore.TestHost; using Microsoft.AspNetCore.WebUtilities; using Microsoft.EntityFrameworkCore; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.DependencyInjection.Extensions; using Microsoft.Extensions.Hosting; using Testcontainers.MariaDb; namespace Helpdesk.IntegrationTests; public sealed class BackendFixture : IAsyncLifetime { internal const string AdminEmail = "admin@example.test"; internal const string Password = "Integration-test-password"; internal static string MigrationsPath => Path.Combine(AppContext.BaseDirectory, "migrations"); internal static CancellationToken Cancellation => TestContext.Current.CancellationToken; private readonly MariaDbContainer database = new MariaDbBuilder("mariadb:11.4") .WithDatabase("helpdesk") .WithPassword(Convert.ToHexString(RandomNumberGenerator.GetBytes(24))) .WithCommand("--character-set-server=utf8mb4") .Build(); private readonly TestEmailSender email = new(); private ApiFactory? factory; internal TokenSaveGate TokenSaves { get; } = new(); internal IServiceProvider Services => factory!.Services; public async ValueTask InitializeAsync() { await database.StartAsync(Cancellation); await RunMigratorAsync(database.GetConnectionString()); factory = new ApiFactory(database.GetConnectionString(), email, TokenSaves); } public async ValueTask DisposeAsync() { try { if (factory is not null) await factory.DisposeAsync(); } finally { await database.DisposeAsync(); } } internal HttpClient CreateClient(string? accessToken = null) { var client = factory!.CreateClient(); if (accessToken is not null) client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", accessToken); return client; } internal async Task RegisterAsync(HttpClient client) { var address = $"{Guid.NewGuid():N}@student.example.test"; var user = await ReadAsync(client.PostAsJsonAsync("/api/v1/auth/register", new RegisterRequest(address, Password, "Test", "User"), Cancellation), HttpStatusCode.Created); await ExpectAsync(client.PostAsJsonAsync("/api/v1/auth/confirm-email", new EmailTokenRequest(email.TakeConfirmationToken(address)), Cancellation), HttpStatusCode.NoContent); return user; } internal static Task LoginAsync(HttpClient client, string address) => ReadAsync(client.PostAsJsonAsync("/api/v1/auth/login", new LoginRequest(address, Password), Cancellation)); internal static async Task ReadAsync(Task request, HttpStatusCode expected = HttpStatusCode.OK) where T : class { using var response = await request; Assert.Equal(expected, response.StatusCode); return Assert.IsType(await response.Content.ReadFromJsonAsync(Cancellation)); } internal static async Task ExpectAsync(Task request, HttpStatusCode expected) { using var response = await request; Assert.Equal(expected, response.StatusCode); } private static async Task RunMigratorAsync(string connectionString) { var startInfo = new ProcessStartInfo(Environment.GetEnvironmentVariable("DOTNET_HOST_PATH") ?? "dotnet") { RedirectStandardOutput = true, RedirectStandardError = true, }; startInfo.ArgumentList.Add(Path.Combine(AppContext.BaseDirectory, "Helpdesk.Migrator.dll")); startInfo.Environment["ConnectionStrings__Migrator"] = connectionString; startInfo.Environment["MIGRATIONS_PATH"] = MigrationsPath; using var process = Process.Start(startInfo) ?? throw new InvalidOperationException("Could not start the migrator."); var output = process.StandardOutput.ReadToEndAsync(Cancellation); var errors = process.StandardError.ReadToEndAsync(Cancellation); try { await process.WaitForExitAsync(Cancellation); Assert.True(process.ExitCode == 0, $"Migrator failed with exit code {process.ExitCode}.\n{await output}\n{await errors}"); } finally { if (!process.HasExited) { process.Kill(); await process.WaitForExitAsync(); } } } private sealed class ApiFactory(string connectionString, TestEmailSender email, TokenSaveGate tokenSaves) : WebApplicationFactory { private readonly Dictionary settings = new() { ["ConnectionStrings:Helpdesk"] = connectionString, ["Jwt:SigningKey"] = Convert.ToHexString(RandomNumberGenerator.GetBytes(32)), ["Encryption:Key"] = Convert.ToBase64String(RandomNumberGenerator.GetBytes(32)), ["Registration:StudentEmailDomains:0"] = "student.example.test", ["Registration:WebBaseUrl"] = "https://helpdesk.example.test", ["ADMIN_EMAIL"] = AdminEmail, ["ADMIN_PASSWORD"] = Password, ["Firebase:ServiceAccountJson"] = "", ["Smtp:Mailbox"] = "", ["Smtp:Password"] = "", ["ReverseProxy:TrustedIp"] = "", }; protected override IHost CreateHost(IHostBuilder builder) { // Program čte konfiguraci před Build(), proto musí hodnoty dostat už při startu. builder.UseEnvironment(Environments.Development) .ConfigureHostConfiguration(config => config.AddInMemoryCollection(settings)); return base.CreateHost(builder); } protected override void ConfigureWebHost(IWebHostBuilder builder) => builder.ConfigureTestServices(services => { services.RemoveAll(); services.AddSingleton(email); services.AddDbContext((_, options) => options.AddInterceptors(tokenSaves)); }); } private sealed class TestEmailSender : IEmailSender { private readonly ConcurrentDictionary tokens = new(); public Task SendAsync(string to, string subject, string body, CancellationToken cancellationToken = default) { if (Uri.TryCreate(body[(body.LastIndexOf('\n') + 1)..], UriKind.Absolute, out var link) && link.AbsolutePath == "/confirm-email") tokens[to] = QueryHelpers.ParseQuery(link.Query)["token"].ToString(); return Task.CompletedTask; } internal string TakeConfirmationToken(string address) { Assert.True(tokens.TryRemove(address, out var token), "Registration did not send a confirmation link."); return token; } } }