using System.Diagnostics;
using System.Globalization;
using System.Net.Http.Headers;
using System.Net.Http.Json;
using System.Text;
using System.Text.Json;
using Elternbeirat.PocketBase;
namespace Elternbeirat.Web.Tests;
///
/// Starts a throwaway PocketBase container once per test run, creates the four
/// content collections and seeds them with a small, known data set. The tests run
/// against this instance instead of the live one, so they are hermetic (no network
/// to Unraid), reproducible (fixed data) and safe (isolated from production).
///
/// The container is started from the real compose.yaml + compose.dev.yaml
/// (only the eb-pocketbase service, not the web app) by shelling out to
/// docker compose, so the image version, superuser env and port stay defined
/// in one place -- the compose files -- and the tests always exercise the same
/// PocketBase the stack runs.
///
///
/// The collection schema is not typed out here: it is imported from
/// pb/pb_migrations/collections_schema.json, the same file the dev seed
/// migration uses, so the schema is defined once and cannot drift between the two.
/// The seeded records, by contrast, are fixed in this file on purpose (not
/// the dev seed's data), so tests assert against values this file controls -- e.g.
/// a non-public draft page that must never appear, and an event at a known time.
/// Requires Docker with the Compose plugin.
///
///
public sealed class PocketBaseFixture : IAsyncLifetime
{
// The service name and container port as defined in the compose files. Everything
// else about the container (image version, superuser env, host port) comes from
// compose, so there is nothing to keep in sync with it here.
private const string ServiceName = "eb-pocketbase";
private const int PocketBasePort = 8090;
// The superuser the dev overlay creates (PB_ADMIN_EMAIL/PASSWORD in
// compose.dev.yaml); used only to authenticate for the one-time seed.
private const string AdminEmail = "test@example.com";
private const string AdminPassword = "test-password"; // >= 8 chars (PB rule)
// A fixed compose project name for the tests, sibling to the dev stack
// ("eb-stack"). Fixed (not per-run) so the
// container names are predictable and a leftover from an aborted run can be
// cleaned up before the next start. Because it is its own project, it never
// touches the dev stack -- the container_name is cleared in the test overlay so
// both projects can coexist.
private const string Project = "eb-test-stack";
// One HttpClient shared by all tests through the client; the fixture owns it and
// disposes it in DisposeAsync. Its BaseAddress is set once the container is up.
private readonly HttpClient _http = new();
/// Creates a pointed at this container.
public PocketBaseClient CreateClient() => new(_http);
///
/// The base URL the container's PocketBase is reachable at. Set once the
/// container is up; used to point the web app's client at this instance in the
/// route smoke tests.
///
public Uri BaseUrl => _http.BaseAddress
?? throw new InvalidOperationException("PocketBase is not started yet.");
public async Task InitializeAsync()
{
// Clear any leftover from an earlier run that was aborted before DisposeAsync
// (a hard kill), so the fixed-name project starts from a clean, empty volume.
await ComposeAsync("down", "--volumes", "--remove-orphans");
// `up --wait` blocks until the service is healthy (the compose healthcheck),
// so once this returns PocketBase is ready to answer.
await ComposeAsync("up", "--detach", "--wait", ServiceName);
_http.BaseAddress = await ResolveBaseUrlAsync();
await SeedAsync();
}
public async Task DisposeAsync()
{
_http.Dispose();
// Remove containers, network and the (dev) volume for this project.
await ComposeAsync("down", "--volumes");
}
/// Reads the host address compose bound the service port to.
private static async Task ResolveBaseUrlAsync()
{
// `docker compose port ` prints e.g. "0.0.0.0:49153".
var mapping = (await ComposeAsync(
"port", ServiceName, PocketBasePort.ToString(CultureInfo.InvariantCulture))).Trim();
var host = mapping[..mapping.LastIndexOf(':')];
var port = mapping[(mapping.LastIndexOf(':') + 1)..];
// 0.0.0.0 is a bind address, not something to connect to; use loopback.
if (host is "0.0.0.0" or "::")
host = "localhost";
return new Uri($"http://{host}:{port}");
}
///
/// Runs `docker compose -p <project> -f compose.yaml -f compose.dev.yaml <args>`
/// from the repo root and returns its stdout, throwing on a non-zero exit.
///
private static async Task ComposeAsync(params string[] args)
{
var start = new ProcessStartInfo("docker")
{
WorkingDirectory = RepoRoot(),
RedirectStandardOutput = true,
RedirectStandardError = true,
UseShellExecute = false,
};
// compose -p -f -f -f . The test
// overlay swaps the dev overlay's fixed host port for a random one, so the
// test stack does not fight a running dev stack over port 8090.
start.ArgumentList.Add("compose");
start.ArgumentList.Add("-p");
start.ArgumentList.Add(Project);
start.ArgumentList.Add("-f");
start.ArgumentList.Add("compose.yaml");
start.ArgumentList.Add("-f");
start.ArgumentList.Add("compose.dev.yaml");
start.ArgumentList.Add("-f");
start.ArgumentList.Add("compose.test.yaml");
foreach (var arg in args)
start.ArgumentList.Add(arg);
using var process = Process.Start(start)
?? throw new InvalidOperationException("Could not start the docker process.");
var stdout = await process.StandardOutput.ReadToEndAsync();
var stderr = await process.StandardError.ReadToEndAsync();
await process.WaitForExitAsync();
if (process.ExitCode != 0)
throw new InvalidOperationException(
$"`docker compose {string.Join(' ', args)}` failed ({process.ExitCode}): {stderr}");
return stdout;
}
/// Repo root, resolved by walking up from the test assembly to compose.yaml.
private static string RepoRoot()
{
// The test binary sits under /Elternbeirat.Web.Tests/bin//;
// walk up until the directory that holds the compose files (the repo root).
var dir = new DirectoryInfo(AppContext.BaseDirectory);
while (dir is not null && !File.Exists(Path.Combine(dir.FullName, "compose.yaml")))
dir = dir.Parent;
return dir?.FullName
?? throw new InvalidOperationException("Could not locate the repo root (compose.yaml).");
}
///
/// Authenticates as superuser, then imports the shared collection schema and
/// seeds the fixed test records the tests assert against.
///
private async Task SeedAsync()
{
var token = await AuthenticateAsync(_http);
_http.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue(token);
await ImportCollectionsAsync(_http);
await SeedRecordsAsync(_http);
// Drop the superuser token so the tests read as an anonymous visitor would,
// exercising the public list/view rules rather than a privileged bypass.
_http.DefaultRequestHeaders.Authorization = null;
}
private static async Task AuthenticateAsync(HttpClient http)
{
// The superuser upsert runs before serve, so once /api/health answers the
// account exists; a couple of retries still guard against a race.
for (var attempt = 0; ; attempt++)
{
var response = await http.PostAsJsonAsync(
"/api/collections/_superusers/auth-with-password",
new { identity = AdminEmail, password = AdminPassword });
if (response.IsSuccessStatusCode)
{
var payload = await response.Content.ReadFromJsonAsync();
return payload?.Token ?? throw new InvalidOperationException("No auth token returned.");
}
if (attempt >= 5)
response.EnsureSuccessStatusCode(); // give up: throw with the status.
await Task.Delay(500);
}
}
///
/// Imports the four content collections from the shared schema file, the same
/// one the dev seed migration reads (pb/pb_migrations/collections_schema.json).
/// Uses PocketBase's /api/collections/import so the whole schema is
/// defined in one place instead of being typed out here.
///
private static async Task ImportCollectionsAsync(HttpClient http)
{
// The file maps name -> collection object; the import endpoint wants a
// flat list, so unwrap the values. deleteMissing=false leaves anything
// already present untouched (the import is idempotent).
var path = Path.Combine(RepoRoot(), "pb", "pb_migrations", "collections_schema.json");
using var schema = JsonDocument.Parse(await File.ReadAllTextAsync(path));
var collections = schema.RootElement.EnumerateObject()
.Select(property => property.Value)
.ToArray();
// Serialize the JsonElement list back to JSON for the request body.
var body = JsonSerializer.Serialize(new { collections, deleteMissing = false });
using var content = new StringContent(body, Encoding.UTF8, "application/json");
var response = await http.PutAsync(new Uri("/api/collections/import", UriKind.Relative), content);
response.EnsureSuccessStatusCode();
}
private static async Task SeedRecordsAsync(HttpClient http)
{
// Pages that the route smoke tests reach through the navigation, the
// footer or the FAQ hub. Every page carries a location ("header" or
// "footer") -- the field is required, matching production. All public.
// The home page sits in the header at order 1, like production; the brand
// links home too, but the nav entry is the single source of the home link.
await CreateRecordAsync(http, "pages", new
{
// The body drives the home hero: "# heading" -> h1, the paragraph -> intro,
// the last paragraph of only links -> the button row.
title = "Start",
body = "# Willkommen\n\nSchön, dass Sie da sind.\n\n[Kommende Termine](/events)\n[Kontakt aufnehmen](/contact)",
location = "header",
order = 1, slug = "home", embed = new[] { "posts", "events" }, @public = true,
});
await CreateRecordAsync(http, "pages", new
{
// The body uses the "::: team" block like production: one card with the
// full convention (bold name, role, italic duties, note) in a large block,
// and one item without the convention, which must become a plain card.
title = "Vorstandsteam",
body = "## Vorsitz\n\n::: team gross\n"
+ "- **Jenny Reger-Stilgenbauer** (Vorsitzende) \n *Schulkonferenz, Mensarat* \n Mitglied im Gesamtelternbeirat.\n"
+ ":::\n\n## Beisitz\n\n::: team\n"
+ "- Özlem Ünal, Beisitz\n"
+ ":::",
location = "header",
order = 2, slug = "board", embed = Array.Empty(), @public = true,
});
await CreateRecordAsync(http, "pages", new
{
// The body uses a design block, so the smoke tests can follow a ":::"
// container through PocketBase and the page into the rendered HTML.
title = "Förderverein",
body = "Der Förderverein unterstützt die Schule.\n\n::: kennzahlen\n- **seit 1975** Gründung\n:::",
location = "header",
order = 3, slug = "patrons", embed = Array.Empty(), @public = true,
});
// Page record for the FAQ list. Route /faqs is served by FaqList, which reads
// this record for its heading and intro (title + body) and renders the topic
// cards itself. Slug matches production's "faqs" nav entry. The body carries
// no "# heading": the title already renders as the h1.
await CreateRecordAsync(http, "pages", new
{
title = "FAQs",
body = "Wählen Sie ein Thema, um die passenden Fragen zu sehen.",
location = "header",
order = 4, slug = "faqs", embed = Array.Empty(), @public = true,
});
await CreateRecordAsync(http, "pages", new
{
title = "Downloads", body = "# Downloads", location = "header",
order = 5, slug = "downloads", embed = Array.Empty(), @public = true,
});
// Page records for the posts and events lists. Routes /posts and /events are
// served by PostList and EventList, which read these records for their heading
// and intro (title + body) and render the list themselves, just like FaqList.
// The body carries no "# heading": the title already renders as the h1.
await CreateRecordAsync(http, "pages", new
{
title = "Beiträge", body = "Neuigkeiten aus dem Elternbeirat.",
location = "header",
order = 6, slug = "posts", embed = Array.Empty(), @public = true,
});
await CreateRecordAsync(http, "pages", new
{
title = "Termine", body = "Sitzungen und Veranstaltungen auf einen Blick.",
location = "header",
order = 7, slug = "events", embed = Array.Empty(), @public = true,
});
// A plain content page reached only by its slug (not shown in the header),
// so the catch-all "/{slug}" ContentPage route stays covered. It carries a
// valid location because the field is required; footer keeps it low-key.
await CreateRecordAsync(http, "pages", new
{
title = "FAQ Mensa", body = "# Mensa", location = "footer",
order = 9, slug = "faq-lunch", embed = Array.Empty(), @public = true,
});
await CreateRecordAsync(http, "pages", new
{
title = "Kontakt", body = "Mail an uns", location = "footer",
order = 1, slug = "contact", embed = Array.Empty(), @public = true,
});
await CreateRecordAsync(http, "pages", new
{
title = "Impressum", body = "# Impressum", location = "footer",
order = 2, slug = "imprint", embed = Array.Empty(), @public = true,
});
await CreateRecordAsync(http, "pages", new
{
title = "Datenschutz", body = "# Datenschutz", location = "footer",
order = 3, slug = "privacy", embed = Array.Empty(), @public = true,
});
// A draft page that must never appear (public=false).
await CreateRecordAsync(http, "pages", new
{
title = "Entwurf", body = "geheim", location = "header",
order = 9, slug = "draft", embed = Array.Empty(), @public = false,
});
// Posts: newest first once sorted by -date. The first post is stored as
// 2026-03-01 23:30Z on purpose: that is 2 March 00:30 in Berlin (winter,
// UTC+1). An editor who picked 2 March must get 2 March back -- the date is
// the Berlin day, so it must NOT be read as the raw UTC day (1 March).
await CreateRecordAsync(http, "posts", new
{
date = "2026-03-01 23:30:00.000Z", title = "Neuer Vorstand",
body = "Text", slug = "new-board", @public = true,
});
await CreateRecordAsync(http, "posts", new
{
date = "2026-01-15 00:00:00.000Z", title = "Neue Sporthalle",
body = "Text", slug = "new-hall", @public = true,
});
// Events: PocketBase stores UTC. The meeting is 19:30 Berlin; October is
// summer time (UTC+2), so it is stored as 17:30Z and the timezone test
// expects 19:30 back. The Herbstbasar is 09:00-13:00 Berlin in November
// (winter, UTC+1), stored as 08:00Z-12:00Z.
await CreateRecordAsync(http, "events", new
{
start = "2026-10-08 17:30:00.000Z", title = "Elternbeiratssitzung",
location = "Aula", note = "", @public = true,
});
await CreateRecordAsync(http, "events", new
{
start = "2026-11-22 08:00:00.000Z", end = "2026-11-22 12:00:00.000Z",
title = "Herbstbasar", location = "Schulhof", note = "", @public = true,
});
// Two past events (before the smoke tests' clock of 1 October 2026), so the
// folded-up "Vergangene Termine" section on /events has something to show:
// one with a time (19:00 Berlin, summer time), and one over several days
// without a time. All-day means 00:00 Berlin, i.e. 22:00Z the day before.
await CreateRecordAsync(http, "events", new
{
start = "2026-09-10 17:00:00.000Z", title = "Infoabend Klasse 5",
location = "Aula", note = "", @public = true,
});
await CreateRecordAsync(http, "events", new
{
start = "2026-07-19 22:00:00.000Z", end = "2026-07-21 22:00:00.000Z",
title = "Projekttage", location = "", note = "", @public = true,
});
// Faq topics: two, ordered. The topics own the grouping and the order the FAQ
// page shows the groups in (cafeteria before lockers). Titles stay German for
// visitors; slugs are English, as for every route.
var lunchTopicId = await CreateRecordAsync(http, "faq_topics", new
{
title = "Mensa und Mittagessen", slug = "cafeteria", intro = "",
order = 1, @public = true,
});
var lockerTopicId = await CreateRecordAsync(http, "faq_topics", new
{
title = "Schließfächer", slug = "lockers", intro = "",
order = 2, @public = true,
});
// Faqs: each points at its topic through the "topic" relation (the created
// topic id), and carries its own order within the topic.
await CreateRecordAsync(http, "faqs", new
{
question = "Wann gibt es Mittagessen?", answer = "Um 12 Uhr.",
topic = lunchTopicId, order = 1, @public = true,
});
await CreateRecordAsync(http, "faqs", new
{
question = "Wie viel kostet ein Schließfach?", answer = "20 Euro.",
topic = lockerTopicId, order = 1, @public = true,
});
}
private static async Task CreateRecordAsync(HttpClient http, string collection, object record)
{
var response = await http.PostAsJsonAsync($"/api/collections/{collection}/records", record);
response.EnsureSuccessStatusCode();
// Return the created record's id so a caller can seed a relation to it (e.g. a
// faq pointing at its topic). Callers that do not need it just ignore the value.
var created = await response.Content.ReadFromJsonAsync();
return created?.Id ?? throw new InvalidOperationException(
$"PocketBase returned no id for the created '{collection}' record.");
}
private sealed record CreatedRecord
{
[System.Text.Json.Serialization.JsonPropertyName("id")]
public string Id { get; init; } = string.Empty;
}
private sealed record AuthResponse
{
[System.Text.Json.Serialization.JsonPropertyName("token")]
public string Token { get; init; } = string.Empty;
}
}