using System.Text.RegularExpressions;
using Febe.Tests.Desktop.Support;
namespace Febe.Tests.Packaging;
///
/// What the Docker image installs (spec §11, Alberto's decision of 18 November 2026): only Chromium with the Debian
/// packages it needs, Xvfb and what the .NET runtime needs, each with its reason next to the list and in docs/docker.md;
/// Febe itself is process 1, without tini.
///
[TestClass]
public sealed partial class ImageContentsTests
{
/// Every package the runtime stage may name, and why (the same reasons the Dockerfile gives).
private static readonly Dictionary Allowed = new(StringComparer.Ordinal)
{
["chromium"] = "the browser",
["chromium-l10n"] = "Chromium's languages: with LANG=it_IT.UTF-8 menus and Accept-Language are Italian",
["xvfb"] = "the virtual display: Chromium is never headless",
["libicu76"] = ".NET globalization (InvariantGlobalization is false)",
["libssl3t64"] = ".NET TLS and AES-GCM",
["libstdc++6"] = "loaded by libcoreclr, libclrjit and libhostfxr",
["libgcc-s1"] = ".NET and Chromium",
["zlib1g"] = "a direct dependency of Chromium",
["fonts-dejavu-core"] = "the first font fontconfig asks for: without a font Chromium draws no text",
["ca-certificates"] = "certificate authorities for .NET TLS",
["tzdata"] = "time zones for the engine and Chromium",
["locales"] = "generates it_IT.UTF-8 for the C library Chromium runs with",
};
///
/// Still installed on this line of work and removed by stages C2–C3 (branch funzione/decoder-h264), which also
/// remove its lines from the Dockerfile. Tolerated, never required: drop it from here once that branch is merged.
///
private static readonly HashSet PendingRemoval = ["ffmpeg"];
/// Without these the image does not work: the browser, its display, and what .NET loads.
private static readonly string[] Required = ["chromium", "chromium-l10n", "xvfb", "libicu76", "libssl3t64", "ca-certificates", "tzdata", "locales"];
/// Programs that must not come back: an init of others, privilege tools, downloaders, other runtimes.
private static readonly string[] Forbidden =
["tini", "dumb-init", "gosu", "su-exec", "sudo", "curl", "wget", "nodejs", "npm", "python3", "jq",
// Fonts for looks only: Chromium does not ask for them (Liberation is a Recommends, the emoji font nothing).
"fonts-liberation", "fonts-liberation2", "fonts-noto-color-emoji", "fonts-noto-core", "fonts-noto"];
[TestMethod]
public void TheImageInstallsOnlyChromiumWhatItNeedsXvfbAndWhatTheDotNetRuntimeNeeds()
{
var installed = InstalledPackages(RuntimeStage());
Assert.HasCount(installed.Distinct(StringComparer.Ordinal).Count(), installed, "every package once");
foreach (var package in installed)
{
Assert.IsTrue(Allowed.ContainsKey(package) || PendingRemoval.Contains(package), $"pacchetto fuori dall'elenco ammesso: {package}");
}
foreach (var package in Required)
{
CollectionAssert.Contains(installed, package);
}
foreach (var package in Forbidden)
{
CollectionAssert.DoesNotContain(installed, package);
}
// Only the runtime stage installs anything with apt: the build stages use the SDK image as it is.
var dockerfile = Dockerfile();
Assert.AreEqual(1, Regex.Matches(Code(dockerfile), @"apt-get install").Count, "a single apt-get install, in the runtime stage");
}
[TestMethod]
public void TheTestsOfTheCiDrawWithTheSameFontsAsTheImage()
{
var environment = Repository.PathOf(".gitea", "scripts", "ambiente-prove.sh");
if (!File.Exists(environment))
{
Assert.Inconclusive("Questa copia del repository non ha .gitea/ (costruzione dell'immagine Docker).");
}
static string[] Fonts(string text) => [.. Regex.Matches(text, @"\bfonts-[a-z0-9-]+").Select(m => m.Value).Distinct().Order(StringComparer.Ordinal)];
var image = Fonts(string.Join('\n', InstalledPackages(RuntimeStage())));
CollectionAssert.AreEqual(new[] { "fonts-dejavu-core" }, image, "one font, the one fontconfig asks for");
CollectionAssert.AreEqual(image, Fonts(Code(File.ReadAllText(environment))), "ambiente-prove.sh installs the fonts of the image, no more");
}
[TestMethod]
public void EveryInstalledPackageHasItsReasonNextToTheList()
{
var stage = RuntimeStage();
var installed = InstalledPackages(stage).Where(p => !PendingRemoval.Contains(p)).ToHashSet(StringComparer.Ordinal);
var reasons = new HashSet(StringComparer.Ordinal);
foreach (Match match in ReasonLine().Matches(stage))
{
foreach (var name in match.Groups["names"].Value.Split(' ', StringSplitOptions.RemoveEmptyEntries))
{
Assert.IsTrue(reasons.Add(name), $"motivo ripetuto per {name}");
}
}
foreach (var package in installed)
{
Assert.Contains(package, reasons, $"manca il motivo di {package} accanto alla lista");
}
foreach (var name in reasons)
{
Assert.Contains(name, installed, $"motivo di un pacchetto che non si installa: {name}");
}
}
[TestMethod]
public void TheGuideGivesTheSameReasonsForTheSamePackages()
{
var path = Repository.PathOf("docs", "docker.md");
if (!File.Exists(path))
{
Assert.Inconclusive("Questa copia del repository non ha docs/ (costruzione dell'immagine Docker).");
}
var guide = File.ReadAllText(path).Replace("\r\n", "\n", StringComparison.Ordinal);
var start = guide.IndexOf("### Perché c'è ogni pacchetto", StringComparison.Ordinal);
Assert.IsGreaterThanOrEqualTo(0, start, "docs/docker.md has the table of the packages");
var end = guide.IndexOf("\n## ", start, StringComparison.Ordinal);
var section = end < 0 ? guide[start..] : guide[start..end];
var listed = new HashSet(StringComparer.Ordinal);
foreach (Match row in GuideRow().Matches(section))
{
foreach (Match name in BacktickedName().Matches(row.Groups["names"].Value))
{
Assert.IsTrue(listed.Add(name.Groups["name"].Value), name.Value);
}
}
var installed = InstalledPackages(RuntimeStage()).Where(p => !PendingRemoval.Contains(p)).ToHashSet(StringComparer.Ordinal);
Assert.IsTrue(installed.SetEquals(listed), $"Dockerfile: {string.Join(' ', installed.Order())}; guida: {string.Join(' ', listed.Order())}");
}
[TestMethod]
public void FebeIsProcessOneWithoutTini()
{
var dockerfile = Dockerfile();
var code = Code(dockerfile);
StringAssert.Contains(code, "ENTRYPOINT [\"/usr/local/bin/febe-avvio\"]");
StringAssert.Contains(code, "CMD [\"/app/febe\"]");
StringAssert.Contains(code, "STOPSIGNAL SIGTERM");
foreach (var program in Forbidden)
{
Assert.IsFalse(Regex.IsMatch(code, $@"(? line.Contains("\"$@\"", StringComparison.Ordinal)).Select(line => line.Trim()).ToList();
CollectionAssert.AreEqual(
new[] { "exec \"$@\"", "exec setpriv --reuid=\"${PUID}\" --regid=\"${PGID}\" --init-groups \"$@\"" },
handovers);
}
[TestMethod]
public void TheToolsTheStartUsesComeWithTheBaseImageAndTheBuildChecksThem()
{
var code = Code(Dockerfile());
StringAssert.Contains(code, "for comando in setpriv groupadd useradd getent; do");
var entrypoint = Code(File.ReadAllText(Repository.PathOf("docker", "entrypoint.sh")));
foreach (var tool in new[] { "setpriv", "groupadd", "useradd", "getent" })
{
StringAssert.Contains(entrypoint, tool + " ");
}
}
[TestMethod]
public void TheReasonsOfThePackagesStillHold()
{
// ICU: the server keeps the culture-aware globalization (dates and sorting in Italian).
var server = File.ReadAllText(Repository.PathOf("src", "Febe.Server", "Febe.Server.csproj"));
StringAssert.Contains(server, "false");
// chromium-l10n and locales: the browser takes its language from LANG, never from a command-line switch.
var code = Code(Dockerfile());
StringAssert.Contains(code, "LANG=it_IT.UTF-8");
StringAssert.Contains(code, "it_IT.UTF-8 UTF-8");
StringAssert.Contains(code, "FEBE_CHROMIUM=/usr/bin/chromium");
}
private static string Dockerfile() =>
File.ReadAllText(Repository.PathOf("docker", "Dockerfile")).Replace("\r\n", "\n", StringComparison.Ordinal);
/// From the FROM of the runtime stage to the end.
private static string RuntimeStage()
{
var dockerfile = Dockerfile();
var start = dockerfile.IndexOf("\nFROM debian:", StringComparison.Ordinal);
Assert.IsGreaterThanOrEqualTo(0, start, "the runtime stage starts from Debian");
StringAssert.Contains(dockerfile[start..dockerfile.IndexOf('\n', start + 1)], " AS runtime");
return dockerfile[start..];
}
/// The packages of the apt-get install of , in order, without options and comments.
private static List InstalledPackages(string stage)
{
var start = stage.IndexOf("apt-get install", StringComparison.Ordinal);
Assert.IsGreaterThanOrEqualTo(0, start, "the runtime stage installs with apt-get install");
var end = stage.IndexOf("&&", start, StringComparison.Ordinal);
Assert.IsGreaterThan(start, end);
var packages = new List();
foreach (var line in Code(stage[start..end]).Split('\n'))
{
foreach (var word in line.Replace('\\', ' ').Split(' ', StringSplitOptions.RemoveEmptyEntries))
{
if (word is not ("apt-get" or "install") && !word.StartsWith('-'))
{
packages.Add(word);
}
}
}
Assert.IsNotEmpty(packages);
return packages;
}
/// The text without comment lines (a Dockerfile drops them even inside a continued RUN).
private static string Code(string text) =>
string.Join('\n', text.Split('\n').Where(line => !line.TrimStart().StartsWith('#')));
/// «# name [name] reason»: a line of the list of reasons (continuation lines start further right).
[GeneratedRegex(@"^# (?[a-z0-9][a-z0-9.+-]*(?: [a-z0-9][a-z0-9.+-]*)*) {2,}\S", RegexOptions.Multiline)]
private static partial Regex ReasonLine();
/// A row of the table in docs/docker.md: «| `name`, `name` | reason |».
[GeneratedRegex(@"^\| (?`[^|]+) \| [^|]+\|$", RegexOptions.Multiline)]
private static partial Regex GuideRow();
[GeneratedRegex(@"`(?[^`]+)`")]
private static partial Regex BacktickedName();
}