Heimdall Gitea / Detect CI scope (push) Successful in 6s
Heimdall Gitea / Build and tests (push) Successful in 19m19s
Heimdall Gitea / Publish versioned release (push) Skipped
Heimdall Gitea / Build and scan server image (push) Successful in 6m13s
Heimdall Gitea / Build and scan agent image (push) Successful in 14m44s
Heimdall Gitea / Publish Docker Hub latest tags (push) Successful in 1m48s
Heimdall Gitea / Build and scan NVIDIA Agent image (push) Successful in 19m9s
Heimdall Gitea / CI policy (push) Successful in 10s
Merge pull request #138 Co-authored-by: Arnaud Dartois <admin@tordais.cc>
215 lines
9.7 KiB
C#
215 lines
9.7 KiB
C#
using System.Net.Http.Json;
|
|
using System.Net.Sockets;
|
|
using Heimdall.TestCommon;
|
|
using Microsoft.AspNetCore.Builder;
|
|
using Microsoft.AspNetCore.Hosting;
|
|
using Microsoft.Extensions.Configuration;
|
|
using Microsoft.Extensions.DependencyInjection;
|
|
using Microsoft.Playwright;
|
|
using Shouldly;
|
|
|
|
namespace Heimdall.E2E.Tests;
|
|
|
|
/// <summary>
|
|
/// Base class for Playwright E2E tests against the Heimdall Blazor Server app.
|
|
/// Starts a real Kestrel HTTP server on a free port so Playwright's Chromium
|
|
/// can connect via HTTP and WebSocket (SignalR).
|
|
/// </summary>
|
|
[Collection("E2E")]
|
|
public abstract class E2ETestBase : IAsyncLifetime
|
|
{
|
|
private readonly string _connectionString;
|
|
private WebApplication? _app;
|
|
private int _port;
|
|
private IPage? _page;
|
|
private IBrowser? _browser;
|
|
private IBrowserContext? _context;
|
|
|
|
protected E2ETestBase(PostgreSqlContainerFixture postgres)
|
|
{
|
|
_connectionString = postgres.ConnectionString;
|
|
}
|
|
|
|
protected IPage Page => _page ?? throw new InvalidOperationException("Playwright not initialized");
|
|
protected string BaseUrl => $"http://127.0.0.1:{_port}";
|
|
protected WebApplication App => _app ?? throw new InvalidOperationException("App not initialized");
|
|
|
|
/// <summary>Seeded admin account (see Seed:AdminLogin/Seed:AdminPassword in-memory config).</summary>
|
|
protected const string AdminEmail = "admin@heimdall.test";
|
|
protected const string AdminPassword = "AdminDev123!";
|
|
|
|
/// <summary>
|
|
/// Waits until the Blazor Server SignalR circuit is established on the
|
|
/// current page. The prerendered HTML is static until then, so form
|
|
/// submissions before the circuit is up are silently dropped.
|
|
/// </summary>
|
|
protected async Task WaitForBlazorCircuitAsync()
|
|
{
|
|
var circuitTask = Page.WaitForWebSocketAsync();
|
|
// If the circuit is already up (page loaded earlier), this returns immediately.
|
|
await circuitTask.WaitAsync(TimeSpan.FromSeconds(15));
|
|
}
|
|
|
|
/// <summary>
|
|
/// Navigates to a page and waits for the Blazor circuit so forms are interactive.
|
|
/// </summary>
|
|
protected async Task GotoWithCircuitAsync(string path)
|
|
{
|
|
var circuitTask = Page.WaitForWebSocketAsync();
|
|
await Page.GotoAsync($"{BaseUrl}{path}");
|
|
await circuitTask.WaitAsync(TimeSpan.FromSeconds(15));
|
|
// The Blazor circuit keeps SignalR activity open, so waiting for network
|
|
// idle can time out even after the page and circuit are ready.
|
|
// Give the circuit a moment to hydrate event handlers before we interact.
|
|
// Increased delay to allow Blazor content to fully render.
|
|
await Task.Delay(2000);
|
|
var pwaDismiss = Page.Locator(".pwa-install-notice .pwa-notice-dismiss");
|
|
if (await pwaDismiss.IsVisibleAsync())
|
|
await pwaDismiss.ClickAsync();
|
|
}
|
|
|
|
/// <summary>
|
|
/// Logs in through the real Blazor UI. Navigates to /login, fills the form,
|
|
/// submits, and waits for the redirect to the dashboard.
|
|
/// </summary>
|
|
protected async Task LoginViaUiAsync(string email = AdminEmail, string password = AdminPassword)
|
|
{
|
|
await GotoWithCircuitAsync("/login");
|
|
|
|
await Page.WaitForSelectorAsync("input[autocomplete='email']", new() { Timeout = 15000 });
|
|
await Page.FillAsync("input[autocomplete='email']", email);
|
|
await Page.FillAsync("input[autocomplete='current-password']", password);
|
|
await Page.ClickAsync("button:has-text('Se connecter')");
|
|
|
|
// After a successful login the app redirects to /dashboard
|
|
await Page.WaitForURLAsync("**/dashboard**", new() { Timeout = 20000 });
|
|
}
|
|
|
|
/// <summary>
|
|
/// Returns a JWT access token by calling the REST API directly (no browser).
|
|
/// Used by tests that need an authenticated HTTP client (e.g. admin setup).
|
|
/// </summary>
|
|
protected async Task<string> LoginViaApiAsync(string email = AdminEmail, string password = AdminPassword)
|
|
{
|
|
using var http = new HttpClient { BaseAddress = new Uri(BaseUrl) };
|
|
var response = await http.PostAsJsonAsync("/api/auth/login", new { email, password });
|
|
response.EnsureSuccessStatusCode();
|
|
var body = await response.Content.ReadFromJsonAsync<AuthResponseJson>();
|
|
return body!.AccessToken;
|
|
}
|
|
|
|
private sealed record AuthResponseJson(string AccessToken, string RefreshToken, bool Requires2fa);
|
|
|
|
public virtual async Task InitializeAsync()
|
|
{
|
|
// Find a free TCP port
|
|
using var socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
|
|
socket.Bind(new System.Net.IPEndPoint(System.Net.IPAddress.Loopback, 0));
|
|
_port = ((System.Net.IPEndPoint)socket.LocalEndPoint!).Port;
|
|
|
|
// Build and start a real Kestrel WebApplication for E2E tests
|
|
_app = Program.CreateTestApplication(configure: builder =>
|
|
{
|
|
builder.Environment.EnvironmentName = "Testing";
|
|
// Must add in-memory config BEFORE ConfigureServices reads it
|
|
builder.Configuration.AddInMemoryCollection(new Dictionary<string, string?>
|
|
{
|
|
["ConnectionStrings:Default"] = _connectionString,
|
|
["Database:MigrateOnStartup"] = "true",
|
|
["Jwt:Key"] = "ThisIsATestKeyThatIsAtLeast32BytesLong!",
|
|
["Jwt:RefreshKey"] = "ThisIsATestRefreshKeyThatIsAlso32Bytes!",
|
|
["Jwt:Issuer"] = "heimdall-test",
|
|
["Jwt:Audience"] = "heimdall-test",
|
|
["Cors:AllowedOrigins"] = "*",
|
|
// Ephemeral Data Protection keys — no filesystem persistence needed.
|
|
// NOTE: appsettings.Testing.json is NOT auto-loaded here because the
|
|
// environment is switched after WebApplication.CreateBuilder, so the
|
|
// Testing JSON file is never picked up — config must be explicit.
|
|
["DataProtection:Mode"] = "Ephemeral",
|
|
// Seed a known admin so login/user-management flows have an account.
|
|
["Seed:DemoOnStartup"] = "true",
|
|
["Seed:AdminLogin"] = AdminEmail,
|
|
["Seed:AdminPassword"] = AdminPassword,
|
|
["Seed:AdminDisplayName"] = "Admin Test",
|
|
});
|
|
builder.WebHost.UseUrls($"http://127.0.0.1:{_port}");
|
|
builder.WebHost.UseKestrel();
|
|
});
|
|
|
|
await _app.StartAsync();
|
|
|
|
// Apply migrations + seed roles/admin — the E2E host boots via
|
|
// CreateTestApplication (no Program.Main), so this must be explicit.
|
|
if (_app.Configuration.GetValue<bool?>("Database:MigrateOnStartup") == true)
|
|
await Program.ApplyMigrationsAsync(_app);
|
|
await Program.SeedAsync(_app, _app.Configuration);
|
|
|
|
// Diagnostic: endpoint inventory AFTER startup (in ConfigureMiddleware the
|
|
// composite datasource may not yet include controller/razor endpoints).
|
|
var ds = _app.Services.GetRequiredService<Microsoft.AspNetCore.Routing.EndpointDataSource>();
|
|
var eps = ds.Endpoints
|
|
.Select(e => e is Microsoft.AspNetCore.Routing.RouteEndpoint re ? re.RoutePattern.RawText : e.ToString())
|
|
.Where(s => !string.IsNullOrEmpty(s))
|
|
.OrderBy(s => s, StringComparer.Ordinal)
|
|
.ToList();
|
|
Console.WriteLine($"[DIAG] POST-START endpoints ({eps.Count}): {string.Join(", ", eps)}");
|
|
|
|
// Give the server a moment to be ready
|
|
await Task.Delay(1500);
|
|
|
|
await StartPlaywrightAsync();
|
|
}
|
|
|
|
private async Task StartPlaywrightAsync()
|
|
{
|
|
// Use system Node.js if bundled one is incompatible
|
|
if (File.Exists("/usr/bin/node"))
|
|
Environment.SetEnvironmentVariable("PLAYWRIGHT_NODEJS_PATH", "/usr/bin/node");
|
|
|
|
var playwright = await Microsoft.Playwright.Playwright.CreateAsync();
|
|
|
|
// Prefer a Playwright-bundled Chromium (works on Proxmox LXC where the CPU
|
|
// lacks SSE3 and the Debian chromium package refuses to start), then system.
|
|
var home = Environment.GetFolderPath(Environment.SpecialFolder.UserProfile);
|
|
var bundledCandidates = Directory.Exists(Path.Combine(home, ".cache", "ms-playwright"))
|
|
? Directory.GetDirectories(Path.Combine(home, ".cache", "ms-playwright"))
|
|
.Where(d => d.Contains("chromium", StringComparison.OrdinalIgnoreCase) && !d.Contains("headless"))
|
|
.Select(d => Path.Combine(d, "chrome-linux64", "chrome"))
|
|
.Where(File.Exists)
|
|
.ToArray()
|
|
: [];
|
|
|
|
var chromePaths = bundledCandidates
|
|
.Concat(new[]
|
|
{
|
|
"/usr/bin/chromium",
|
|
"/usr/bin/chromium-browser",
|
|
"/root/.cache/ms-playwright/chromium-1228/chrome-linux64/chrome",
|
|
}).ToArray();
|
|
|
|
var chromePath = chromePaths.FirstOrDefault(File.Exists)
|
|
?? throw new FileNotFoundException(
|
|
"Chromium not found. Install with: playwright install chromium or apt install chromium");
|
|
|
|
_browser = await playwright.Chromium.LaunchAsync(new BrowserTypeLaunchOptions
|
|
{
|
|
Headless = true,
|
|
ExecutablePath = chromePath,
|
|
Args = ["--no-sandbox", "--disable-setuid-sandbox", "--disable-gpu", "--disable-dev-shm-usage"]
|
|
});
|
|
_context = await _browser.NewContextAsync(new BrowserNewContextOptions { IgnoreHTTPSErrors = true });
|
|
_page = await _context.NewPageAsync();
|
|
}
|
|
|
|
public async Task DisposeAsync()
|
|
{
|
|
if (_page is not null) await _page.CloseAsync();
|
|
if (_context is not null) await _context.CloseAsync();
|
|
if (_browser is not null) await _browser.CloseAsync();
|
|
if (_app is not null) await _app.StopAsync();
|
|
}
|
|
}
|
|
|
|
[CollectionDefinition("E2E")]
|
|
public class E2ETestCollectionFixture : ICollectionFixture<PostgreSqlContainerFixture>;
|