using System.Buffers.Binary;
using System.Collections;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Text.RegularExpressions;
using System.Xml.Linq;
using Anubis.Platform;
using Anubis.Server;
using Anubis.Supervision;
namespace Anubis.Tests;
/// What is delivered: the Unraid template, the image and how it is published (issues #70 and #71, SPEC 15.2, 15.3, 15.5).
[TestClass]
public sealed partial class DeliveryTests
{
private const string Image = "gitea.encke-hake.ts.net/balbosoft/anubis";
private static string Text(string path) => File.ReadAllText(Path.Combine(Repo.Root.FullName, path.Replace('/', Path.DirectorySeparatorChar))).ReplaceLineEndings("\n");
private static string Section(string from, string to)
{
var spec = Text("docs/SPEC.md");
var start = spec.IndexOf("\n" + from, StringComparison.Ordinal);
Assert.IsGreaterThan(0, start, from);
var end = spec.IndexOf("\n" + to, start + 1, StringComparison.Ordinal);
return end < 0 ? spec[start..] : spec[start..end];
}
private static XElement Template() => XDocument.Parse(Text("deploy/unraid/anubis.xml")).Root!;
private static Dictionary Fields(XElement template)
{
var fields = new Dictionary(StringComparer.Ordinal);
foreach (var config in template.Elements("Config"))
{
Assert.IsTrue(fields.TryAdd(config.Attribute("Target")!.Value, config), "Twice: " + config);
}
return fields;
}
private static HashSet VariablesOf151() => VariableName().Matches(string.Join('\n',
Section("### 15.1", "### 15.2").Split('\n').Where(l => l.StartsWith("| `", StringComparison.Ordinal)).Select(l => l.Split('|')[1])))
.Select(m => m.Groups[1].Value).ToHashSet(StringComparer.Ordinal);
// ---- the Unraid template ----
[TestMethod]
[TestCategory(Category.Unit)]
public void TheTemplateHasTheFieldsOfAppendixE()
{
var template = Template();
Assert.AreEqual("Container", template.Name.LocalName);
Assert.AreEqual("2", template.Attribute("version")!.Value);
var appendix = Section("## Appendice E", "## Appendice F");
var draft = appendix[(appendix.IndexOf("```xml\n", StringComparison.Ordinal) + 7)..];
var expected = Fields(XDocument.Parse(draft[..draft.IndexOf("\n```", StringComparison.Ordinal)]).Root!);
var actual = Fields(template);
CollectionAssert.AreEquivalent(expected.Keys.ToList(), actual.Keys.ToList());
foreach (var (target, field) in expected)
{
foreach (var name in new[] { "Type", "Mode", "Display", "Required", "Default", "Mask" })
{
// The address of the heartbeat is a secret of its service: masked, unlike the draft (ADR 0020).
var want = (target, name) == ("ANUBIS_HEARTBEAT_URL", "Mask") ? "true" : field.Attribute(name)!.Value;
Assert.AreEqual(want, actual[target].Attribute(name)!.Value, target + " " + name);
}
Assert.AreEqual(field.Value, actual[target].Value, target);
Assert.IsFalse(string.IsNullOrWhiteSpace(actual[target].Attribute("Description")!.Value), target);
}
}
[TestMethod]
[TestCategory(Category.Unit)]
public void EveryVariableOfTheTemplateIsIn151AndTheAccountKeysAreNot()
{
var known = VariablesOf151();
Assert.IsGreaterThan(20, known.Count);
var targets = Fields(Template()).Where(f => f.Value.Attribute("Type")!.Value == "Variable").Select(f => f.Key).ToList();
Assert.HasCount(16, targets);
CollectionAssert.IsSubsetOf(targets, known.ToList());
Assert.IsEmpty(targets.Where(t => t.StartsWith("ALPACA", StringComparison.Ordinal) || t.StartsWith("OKX", StringComparison.Ordinal) || t.EndsWith("_API_KEY", StringComparison.Ordinal)));
}
[TestMethod]
[TestCategory(Category.Unit)]
public void TheTemplateMasksSecretsAndHidesRareFields()
{
var fields = Fields(Template());
foreach (var secret in new[] { "ANUBIS_DB_PASSWORD", "ANUBIS_SECRET_KEY", "ANUBIS_ADMIN_PASSWORD", "TELEGRAM_BOT_TOKEN", "ANUBIS_DB_URL", "ANUBIS_HEARTBEAT_URL" })
{
Assert.AreEqual("true", fields[secret].Attribute("Mask")!.Value, secret);
Assert.AreEqual("", fields[secret].Value, secret);
}
foreach (var rare in new[] { "ANUBIS_ALLOW_LIVE", "TELEGRAM_BOT_TOKEN", "TELEGRAM_CHAT_ID", "ANUBIS_HEARTBEAT_URL", "PUID", "PGID", "ANUBIS_DB_URL" })
{
Assert.AreEqual("advanced", fields[rare].Attribute("Display")!.Value, rare);
}
Assert.AreEqual("0", fields["ANUBIS_ALLOW_LIVE"].Value);
Assert.AreEqual("postgres|sqlite", fields["ANUBIS_DB_ENGINE"].Attribute("Default")!.Value);
}
[TestMethod]
[TestCategory(Category.Unit)]
public void TheTemplatePointsToTheRealImage()
{
var template = Template();
var text = Text("deploy/unraid/anubis.xml");
Assert.DoesNotContain("example", text);
Assert.DoesNotContain("UTENTE", text);
Assert.DoesNotContain("bozza", text);
Assert.AreEqual(Image + ":latest", template.Element("Repository")!.Value);
StringAssert.Contains(Text("tools/Anubis.Tasks/Program.cs"), Image + ":");
StringAssert.Contains(Text("deploy/docker/publish.sh"), "$REGISTRY/balbosoft/anubis");
var fields = Fields(template);
Assert.AreEqual("8787", fields["8787"].Value);
Assert.AreEqual("/mnt/user/appdata/anubis", fields["/data"].Value);
var extra = template.Element("ExtraParams")!.Value;
StringAssert.Contains(extra, "--memory=4g");
var stop = int.Parse(StopTimeout().Match(extra).Groups[1].Value, System.Globalization.CultureInfo.InvariantCulture);
Assert.AreEqual(60, stop);
Assert.IsGreaterThan(new GuardOptions().GracefulStop, TimeSpan.FromSeconds(stop));
}
[TestMethod]
[TestCategory(Category.Unit)]
public void TheIconIsASquarePngWithTransparency()
{
var url = Template().Element("Icon")!.Value;
StringAssert.EndsWith(url, "/deploy/unraid/anubis-icon.png");
var png = File.ReadAllBytes(Path.Combine(Repo.Root.FullName, "deploy", "unraid", "anubis-icon.png"));
CollectionAssert.AreEqual(new byte[] { 0x89, 0x50, 0x4E, 0x47, 0x0D, 0x0A, 0x1A, 0x0A }, png[..8]);
var width = BinaryPrimitives.ReadInt32BigEndian(png.AsSpan(16));
Assert.AreEqual(width, BinaryPrimitives.ReadInt32BigEndian(png.AsSpan(20)));
Assert.IsGreaterThanOrEqualTo(128, width);
Assert.AreEqual(6, (int)png[25], "Colour type 6: red, green, blue and transparency.");
}
// ---- what the loader reads ----
[TestMethod]
[TestCategory(Category.Unit)]
public void TheLoaderReadsEveryVariableOf151AndNoOther()
{
var read = new HashSet(StringComparer.Ordinal);
Dictionary Base(string engine) => new() { ["ANUBIS_DB_ENGINE"] = engine, ["ANUBIS_SECRET_KEY"] = new string('k', 40), ["ANUBIS_ADMIN_PASSWORD"] = "initial-pass-1" };
var withUrl = Base("postgres");
withUrl["ANUBIS_DB_URL"] = "postgresql://anubis:a-database-pass@db.example:5432/anubis";
var withHost = Base("postgres");
(withHost["ANUBIS_DB_HOST"], withHost["ANUBIS_DB_PASSWORD"]) = ("db.example", "a-database-pass");
foreach (var env in new[] { withHost, Base("sqlite"), withUrl })
{
DockerPlatform.Load(new Recorded(env, read), Path.GetTempPath());
}
var expected = VariablesOf151();
foreach (var key in DockerPlatform.OptionalKeys)
{
Assert.Contains(key, expected);
expected.Add(key + "_DEMO");
}
CollectionAssert.AreEquivalent(expected.Order(StringComparer.Ordinal).ToList(), read.Order(StringComparer.Ordinal).ToList());
}
[TestMethod]
[TestCategory(Category.Unit)]
public void AFieldLeftBlankInTheTemplateIsAsIfItWereNotThere()
{
var env = Fields(Template()).Where(f => f.Value.Attribute("Type")!.Value == "Variable").ToDictionary(f => f.Key, f => (string?)f.Value.Value, StringComparer.Ordinal);
var blank = DockerPlatform.Load(env, Path.GetTempPath());
CollectionAssert.AreEquivalent(new[] { "ANUBIS_DB_HOST", "ANUBIS_DB_PASSWORD", "ANUBIS_SECRET_KEY", "ANUBIS_ADMIN_PASSWORD" }, blank.Problems.Select(p => p.Setting).ToList());
env["ANUBIS_DB_ENGINE"] = "sqlite";
env["ANUBIS_SECRET_KEY"] = new string('k', 40);
env["ANUBIS_ADMIN_PASSWORD"] = "initial-pass-1";
var filled = DockerPlatform.Load(env, Path.GetTempPath());
Assert.IsEmpty(filled.Problems);
Assert.IsFalse(filled.AllowLive);
Assert.IsNull(filled.HeartbeatUrl);
env["PUID"] = "0";
Assert.AreEqual("PUID", DockerPlatform.Load(env, Path.GetTempPath()).Problems.Single().Setting);
}
// ---- the health of the container (SPEC 15.2) ----
[TestMethod]
[TestCategory(Category.Unit)]
public void HealthCoversTheLoopAndThePrices()
{
var now = new DateTimeOffset(2026, 12, 1, 9, 0, 0, TimeSpan.Zero);
DateTimeOffset? Ago(double minutes) => now.AddMinutes(-minutes);
Assert.IsTrue(HealthRules.Loop(now, false, Ago(60)).Ok, "Not started, as on the error page or without keys.");
Assert.IsTrue(HealthRules.Loop(now, true, null).Ok);
Assert.IsTrue(HealthRules.Loop(now, true, Ago(1.9)).Ok);
Assert.AreEqual(("fermo", false), HealthRules.Loop(now, true, Ago(2.1)));
Assert.AreEqual(new GuardOptions().Silence, HealthRules.LoopLimit);
Assert.IsTrue(HealthRules.Feed(now, null, null).Ok, "No instrument to follow yet.");
Assert.IsTrue(HealthRules.Feed(now, Ago(4), null).Ok);
Assert.IsFalse(HealthRules.Feed(now, Ago(6), null).Ok, "Open and silent from the start.");
Assert.IsTrue(HealthRules.Feed(now, Ago(600), Ago(4)).Ok);
Assert.AreEqual(("fermi", false), HealthRules.Feed(now, Ago(600), Ago(6)));
}
// ---- the image ----
[TestMethod]
[TestCategory(Category.Unit)]
public void TheImageSaysWhatItIs()
{
var docker = Text("deploy/docker/Dockerfile");
var project = Template().Element("Project")!.Value;
StringAssert.Contains(docker, $"org.opencontainers.image.source=\"{project}\"");
StringAssert.Contains(docker, "org.opencontainers.image.version=\"$ANUBIS_VERSION\"");
StringAssert.Contains(docker, "org.opencontainers.image.revision=\"$ANUBIS_COMMIT\"");
var publish = docker.Split('\n').Where(l => l.StartsWith("RUN dotnet publish", StringComparison.Ordinal)).ToList();
Assert.HasCount(2, publish);
Assert.IsTrue(publish.All(l => l.EndsWith("${ANUBIS_COMMIT:+-p:SourceRevisionId=$ANUBIS_COMMIT}", StringComparison.Ordinal)));
CollectionAssert.AreEquivalent(new[] { "mcr.microsoft.com/dotnet/sdk:10.0", "mcr.microsoft.com/dotnet/aspnet:10.0" },
docker.Split('\n').Where(l => l.StartsWith("FROM ", StringComparison.Ordinal)).Select(l => l.Split(' ')[1]).ToList());
StringAssert.Contains(docker, "${PORT:-8787}");
StringAssert.Contains(docker, "EXPOSE 8787\n");
StringAssert.Contains(docker, "--timeout=10s", "Longer than the 5 seconds the page waits for the database, so its answer arrives.");
var entry = Text("deploy/docker/entrypoint.sh");
StringAssert.Contains(entry, "PUID=0");
StringAssert.Contains(entry, "--no-new-privs");
}
// ---- the workflow ----
private static Dictionary Workflow() => MiniYaml.Read(Text(".gitea/workflows/ci.yml"));
private static Dictionary At(object map, string key) => (Dictionary)((Dictionary)map)[key];
private static List> Steps(string job) => ((List