A position left out together with its stop kept the account prudent for good: the stop was still asked for shares that no longer exist. The cover required now stops at what the account holds, the stops are compared again after the choice, and where one is still missing Align takes the excluded position up again. After the choice the account waits for the stop with its own reason, so it returns to normal by itself also past the 15 minutes; a new difference still gets its own 15 minutes. A right password alone no longer clears the wrong second-factor codes: it takes back only its own attempt. Capital and shares are planned and written in one transaction, so overlapping changes cannot apply twice and an interruption leaves nothing halfway; sending the same figures again completes what an old one left. The cash that purchases under way still hold is no longer given away, counted as the risk engine counts it. /health said healthy when the trading engine had failed to start. It now says so at once, or after ten minutes of a stalled start, and the host tries the start again every minute; the guard still sees a start that does not move. The image of the manual publication says its version and its commit, marked when the tree is dirty, and publish.sh refuses before any login an image that does not come from the commit of the tag. refs #75 Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
544 lines
27 KiB
C#
544 lines
27 KiB
C#
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;
|
|
|
|
/// <summary>What is delivered: the Unraid template, the image and how it is published (issues #70 and #71, SPEC 15.2, 15.3, 15.5).</summary>
|
|
[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<string, XElement> Fields(XElement template)
|
|
{
|
|
var fields = new Dictionary<string, XElement>(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<string> 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<string>(StringComparer.Ordinal);
|
|
Dictionary<string, string?> 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.AreEqual(("non avviato", true), HealthRules.Loop(now, null, false, false, null), "No engine to start, as in the demo. Without keys the simulators start as the others.");
|
|
Assert.AreEqual(("in avvio", true), HealthRules.Loop(now, Ago(9.9), false, false, null));
|
|
Assert.AreEqual(("non avviato", false), HealthRules.Loop(now, Ago(10.1), false, false, null), "Stalled.");
|
|
Assert.AreEqual(("non avviato", false), HealthRules.Loop(now, Ago(0.1), false, true, null), "Failed: known at once.");
|
|
Assert.AreEqual(new GuardOptions().StalledStart, HealthRules.StartLimit);
|
|
Assert.AreEqual(("in avvio", true), HealthRules.Loop(now, Ago(60), true, false, null));
|
|
Assert.AreEqual(("ok", true), HealthRules.Loop(now, Ago(60), true, false, Ago(1.9)));
|
|
Assert.AreEqual(("fermo", false), HealthRules.Loop(now, Ago(60), true, false, 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<string, object> Workflow() => MiniYaml.Read(Text(".gitea/workflows/ci.yml"));
|
|
|
|
private static Dictionary<string, object> At(object map, string key) => (Dictionary<string, object>)((Dictionary<string, object>)map)[key];
|
|
|
|
private static List<Dictionary<string, object>> Steps(string job) => ((List<object>)At(At(Workflow(), "jobs"), job)["steps"]).Cast<Dictionary<string, object>>().ToList();
|
|
|
|
[TestMethod]
|
|
[TestCategory(Category.Unit)]
|
|
public void TheWorkflowUsesNoExternalAction()
|
|
{
|
|
foreach (var job in At(Workflow(), "jobs").Keys)
|
|
{
|
|
Assert.IsNotEmpty(Steps(job));
|
|
foreach (var step in Steps(job))
|
|
{
|
|
Assert.IsTrue(step.ContainsKey("run"), $"{job}: {step["name"]}");
|
|
Assert.IsFalse(step.ContainsKey("uses"), $"{job}: {step["name"]}");
|
|
}
|
|
}
|
|
}
|
|
|
|
[TestMethod]
|
|
[TestCategory(Category.Unit)]
|
|
public void TheImageIsPublishedOnlyOnVersionTagsAndAfterTheTests()
|
|
{
|
|
var workflow = Workflow();
|
|
CollectionAssert.AreEqual(new[] { "**" }, ((List<object>)At(At(workflow, "on"), "push")["branches"]).Cast<string>().ToList());
|
|
CollectionAssert.AreEqual(new[] { "v*" }, ((List<object>)At(At(workflow, "on"), "push")["tags"]).Cast<string>().ToList());
|
|
Assert.AreEqual("test", At(At(workflow, "jobs"), "image")["needs"]);
|
|
var matrix = (List<object>)At(At(At(At(workflow, "jobs"), "test"), "strategy"), "matrix")["db"];
|
|
CollectionAssert.AreEquivalent(new[] { "sqlite", "postgres" }, matrix.Cast<string>().ToList());
|
|
|
|
var steps = Steps("image");
|
|
var publishing = Enumerable.Range(0, steps.Count).Where(i => PublishCommand().IsMatch((string)steps[i]["run"])).ToList();
|
|
Assert.HasCount(1, publishing);
|
|
Assert.AreEqual("github.event_name == 'push' && startsWith(github.ref, 'refs/tags/v')", steps[publishing[0]]["if"]);
|
|
Assert.IsGreaterThan(steps.FindIndex(s => ((string)s["run"]).Contains(" drill", StringComparison.Ordinal)), publishing[0]);
|
|
Assert.IsEmpty(Steps("test").Where(s => PublishCommand().IsMatch((string)s["run"])));
|
|
}
|
|
|
|
[TestMethod]
|
|
[TestCategory(Category.Unit)]
|
|
public void TheTokensStayInTheStepsThatNeedThem()
|
|
{
|
|
var text = Text(".gitea/workflows/ci.yml");
|
|
Assert.AreEqual(1, Regex.Count(text, @"secrets\."));
|
|
Assert.DoesNotContain("set -x", text);
|
|
foreach (var job in At(Workflow(), "jobs").Keys)
|
|
{
|
|
var definition = At(At(Workflow(), "jobs"), job);
|
|
if (definition.TryGetValue("env", out var env))
|
|
{
|
|
Assert.IsEmpty(((Dictionary<string, object>)env).Values.OfType<string>().Where(v => v.Contains("token", StringComparison.OrdinalIgnoreCase) || v.Contains("secrets.", StringComparison.Ordinal)));
|
|
}
|
|
|
|
foreach (var step in Steps(job))
|
|
{
|
|
var run = (string)step["run"];
|
|
Assert.DoesNotContain("github.token", run);
|
|
Assert.DoesNotContain("secrets.", run);
|
|
Assert.DoesNotContain("github.ref", run, "A name chosen by who pushes reaches the shell only as a variable.");
|
|
}
|
|
}
|
|
|
|
var publish = Steps("image").Single(s => PublishCommand().IsMatch((string)s["run"]));
|
|
Assert.AreEqual("${{ secrets.REGISTRY_TOKEN }}", At(publish, "env")["REGISTRY_TOKEN"]);
|
|
}
|
|
|
|
[TestMethod]
|
|
[TestCategory(Category.Unit)]
|
|
public void WhatIsPublishedIsTheImageThatWasTried()
|
|
{
|
|
var name = (string)At(At(At(Workflow(), "jobs"), "image"), "env")["IMAGE"];
|
|
StringAssert.Contains(name, "github.run_id");
|
|
var docker = Steps("image").Select(s => (string)s["run"]).Where(r => r.Contains("docker", StringComparison.Ordinal)).ToList();
|
|
Assert.HasCount(4, docker, "Build, drill, publish, remove.");
|
|
Assert.IsTrue(docker.All(r => r.Contains("\"$IMAGE\"", StringComparison.Ordinal)));
|
|
}
|
|
|
|
[TestMethod]
|
|
[TestCategory(Category.Unit)]
|
|
public void TheImageSaysTheVersionAndTheCommitItIsMadeFrom()
|
|
{
|
|
// The image of the manual publication comes from the tasks, that of a tag from the workflow: both say what they are.
|
|
var tasks = Text("tools/Anubis.Tasks/Program.cs");
|
|
StringAssert.Contains(tasks, "$\"ANUBIS_VERSION={Version()}\"");
|
|
StringAssert.Contains(tasks, "$\"ANUBIS_COMMIT={Commit()}\"");
|
|
StringAssert.Contains(tasks, "\"-dirty\"");
|
|
var build = (string)Steps("image").Single(s => ((string)s["run"]).Contains("docker build", StringComparison.Ordinal))["run"];
|
|
StringAssert.Contains(build, "version=${REF_NAME#v}");
|
|
StringAssert.Contains(build, "\"ANUBIS_VERSION=$version\"");
|
|
StringAssert.Contains(build, "\"ANUBIS_COMMIT=$(git rev-parse HEAD)\"");
|
|
var publish = Text("deploy/docker/publish.sh");
|
|
Assert.IsLessThan(publish.IndexOf("docker login", StringComparison.Ordinal), publish.IndexOf("docker image inspect", StringComparison.Ordinal), "Checked before anything leaves the house.");
|
|
}
|
|
|
|
[TestMethod]
|
|
[TestCategory(Category.Unit)]
|
|
public void TheYamlReaderRefusesWhatItDoesNotKnow()
|
|
{
|
|
var read = MiniYaml.Read("# c\na: 1 # c\nb:\n - x\n - k: 'v: w'\n run: |\n one\n two\n\n three\nlist: [\"**\", z]\nfold: >-\n p\n q\n");
|
|
Assert.AreEqual("1", read["a"]);
|
|
Assert.AreEqual("x", ((List<object>)read["b"])[0]);
|
|
Assert.AreEqual("v: w", ((Dictionary<string, object>)((List<object>)read["b"])[1])["k"]);
|
|
Assert.AreEqual("one\n two\nthree", ((Dictionary<string, object>)((List<object>)read["b"])[1])["run"]);
|
|
CollectionAssert.AreEqual(new[] { "**", "z" }, ((List<object>)read["list"]).Cast<string>().ToList());
|
|
Assert.AreEqual("p q", read["fold"]);
|
|
foreach (var wrong in new[] { "a: 1\n\tb: 2", "a: 1\na: 2", "a: &x 1", "a: *x", "a:\n b: 1\n c: 2", "a: 1\n b: 2", "just text", "a: {b: 1}", "a: [1" })
|
|
{
|
|
StringAssert.Contains(Assert.ThrowsExactly<FormatException>(() => MiniYaml.Read(wrong), wrong).Message, "line ");
|
|
}
|
|
}
|
|
|
|
// ---- the script that publishes, with a docker and a git that only take note ----
|
|
|
|
[TestMethod]
|
|
[TestCategory(Category.Integration)]
|
|
[OSCondition(OperatingSystems.Linux)]
|
|
[DataRow("v0.9.0", "v0.7.0", 0, "0.9.0,latest")]
|
|
[DataRow("v0.9.0", "", 0, "0.9.0,latest")]
|
|
[DataRow("v0.9.0-rc.1", "v0.7.0", 0, "0.9.0-rc.1")]
|
|
[DataRow("v0.9.0", "v0.10.0", 0, "0.9.0")]
|
|
[DataRow("v0.9.0", "v0.10.0-rc.1", 0, "0.9.0,latest")]
|
|
[DataRow("v0.9.1", "v0.7.0", 1, "")]
|
|
[DataRow("fase-9", "v0.7.0", 1, "")]
|
|
[DataRow("v9", "v0.7.0", 1, "")]
|
|
[DataRow("v0.9.0;id", "v0.7.0", 1, "")]
|
|
public async Task TheScriptPublishesTheVersionAndMovesLatestOnlyForward(string tag, string others, int exit, string pushed)
|
|
{
|
|
using var run = new PublishRun(others);
|
|
var (code, output) = await run.RunAsync(tag, PublishRun.Token);
|
|
Assert.AreEqual(exit, code, output);
|
|
CollectionAssert.AreEqual(pushed.Split(',', StringSplitOptions.RemoveEmptyEntries), run.Pushed(), output);
|
|
if (exit != 0)
|
|
{
|
|
StringAssert.Contains(output, "Pubblicazione non riuscita");
|
|
}
|
|
}
|
|
|
|
[TestMethod]
|
|
[TestCategory(Category.Integration)]
|
|
[OSCondition(OperatingSystems.Linux)]
|
|
public async Task TheScriptGivesTheTokenToDockerOnlyOnItsInputAndLeavesNothing()
|
|
{
|
|
using var run = new PublishRun("v0.7.0");
|
|
var (code, output) = await run.RunAsync("v0.9.0", PublishRun.Token);
|
|
Assert.AreEqual(0, code, output);
|
|
Assert.DoesNotContain(PublishRun.Token, output);
|
|
Assert.DoesNotContain(PublishRun.Token, run.Calls);
|
|
Assert.AreEqual(PublishRun.Token, run.Input);
|
|
var config = run.Config;
|
|
Assert.IsNotEmpty(config);
|
|
Assert.IsFalse(Directory.Exists(config), "The folder with the credentials is gone.");
|
|
|
|
using var without = new PublishRun("v0.7.0");
|
|
(code, output) = await without.RunAsync("v0.9.0", "");
|
|
Assert.AreEqual(1, code);
|
|
StringAssert.Contains(output, "REGISTRY_TOKEN");
|
|
Assert.AreEqual("", without.Calls);
|
|
|
|
using var offline = new PublishRun("v0.7.0", gitFails: true);
|
|
(code, output) = await offline.RunAsync("v0.9.0", PublishRun.Token);
|
|
Assert.AreEqual(1, code, output);
|
|
Assert.IsEmpty(offline.Pushed());
|
|
}
|
|
|
|
[TestMethod]
|
|
[TestCategory(Category.Integration)]
|
|
[OSCondition(OperatingSystems.Linux)]
|
|
[DataRow("v0.9.0", "ci", PublishRun.Commit, false)]
|
|
[DataRow("v0.9.0", "0.8.0", PublishRun.Commit, false)]
|
|
[DataRow("v0.9.0", "0.9.0-rc.1", PublishRun.Commit, false)]
|
|
[DataRow("v0.9.0", "0.9.0", PublishRun.Commit + "-dirty", false)]
|
|
[DataRow("v0.9.0", "0.9.0", "fedcba9876543210fedcba9876543210fedcba98", false)]
|
|
[DataRow("v0.9.0", "0.9.0", "", false)]
|
|
[DataRow("v0.9.0", "0.9.0", PublishRun.Commit, true)]
|
|
public async Task TheScriptRefusesAnImageThatIsNotTheOneOfTheTag(string tag, string version, string revision, bool tagged)
|
|
{
|
|
using var run = new PublishRun("v0.7.0", version: version, revision: revision, tagged: tagged);
|
|
var (code, output) = await run.RunAsync(tag, PublishRun.Token);
|
|
Assert.AreEqual(1, code, output);
|
|
StringAssert.Contains(output, "Pubblicazione non riuscita: l'immagine");
|
|
Assert.IsEmpty(run.Pushed());
|
|
Assert.AreEqual("", run.Input, "Not even the login.");
|
|
}
|
|
|
|
[TestMethod]
|
|
[TestCategory(Category.Integration)]
|
|
[OSCondition(OperatingSystems.Linux)]
|
|
[DataRow("v0.9.0", PublishRun.TagCommit, true)]
|
|
[DataRow("v0.9.0-rc.1", PublishRun.TagCommit, true)]
|
|
[DataRow("v0.9.0-rc.1", PublishRun.Commit, false)]
|
|
public async Task TheScriptTakesTheImageOfTheTasksAtTheCommitOfTheTag(string tag, string revision, bool tagged)
|
|
{
|
|
// The commit of the tag when the tag is here, otherwise the one checked out: in the workflow they are the same.
|
|
using var run = new PublishRun("v0.7.0", version: "0.9.0", revision: revision, tagged: tagged);
|
|
var (code, output) = await run.RunAsync(tag, PublishRun.Token);
|
|
Assert.AreEqual(0, code, output);
|
|
Assert.IsNotEmpty(run.Pushed());
|
|
}
|
|
|
|
private sealed class PublishRun : IDisposable
|
|
{
|
|
public const string Token = "a-token-only-for-the-test";
|
|
public const string Commit = "0123456789abcdef0123456789abcdef01234567";
|
|
public const string TagCommit = "89abcdef0123456789abcdef0123456789abcdef";
|
|
|
|
private readonly string _root = Path.Combine(Path.GetTempPath(), "anubis-publish-" + Guid.NewGuid().ToString("N"));
|
|
|
|
public PublishRun(string others, bool gitFails = false, string? version = null, string revision = Commit, bool tagged = false)
|
|
{
|
|
Directory.CreateDirectory(Path.Combine(_root, "deploy", "docker"));
|
|
Directory.CreateDirectory(Path.Combine(_root, "bin"));
|
|
File.WriteAllText(Path.Combine(_root, "deploy", "docker", "publish.sh"), Text("deploy/docker/publish.sh"));
|
|
File.WriteAllText(Path.Combine(_root, "Directory.Build.props"), "<Project>\n <Version>0.9.0</Version>\n</Project>\n");
|
|
_version = version;
|
|
Tool("docker", "printf '%s\\n' \"$*\" >> \"$RECORD/calls\"\nif [ \"$1\" = login ]; then cat > \"$RECORD/input\"; printf '%s' \"$DOCKER_CONFIG\" > \"$RECORD/config\"; fi\n" +
|
|
$"case \"$*\" in *image.version*) printf '%s\\n' \"$VERSION\" ;; *image.revision*) printf '%s\\n' '{revision}' ;; esac\n");
|
|
var tagCommit = tagged ? $"printf '%s\\n' {TagCommit}; exit 0" : "exit 1";
|
|
Tool("git", $"case \"$*\" in *rev-parse*refs/tags/*) {tagCommit} ;; *rev-parse*HEAD*) printf '%s\\n' {Commit}; exit 0 ;; esac\n" +
|
|
(gitFails ? "exit 128\n" : string.Concat(others.Split(',', StringSplitOptions.RemoveEmptyEntries).Select(o => $"printf 'abc\\trefs/tags/{o}\\n'\n"))));
|
|
}
|
|
|
|
// What the image says of itself when the test says nothing: the version of the tag.
|
|
private readonly string? _version;
|
|
|
|
public string Calls => Recorded("calls");
|
|
|
|
public string Input => Recorded("input");
|
|
|
|
public string Config => Recorded("config");
|
|
|
|
public List<string> Pushed() => Calls.Split('\n').Where(l => l.StartsWith("push registry.test/balbosoft/anubis:", StringComparison.Ordinal)).Select(l => l[(l.LastIndexOf(':') + 1)..]).ToList();
|
|
|
|
public async Task<(int Code, string Output)> RunAsync(string tag, string token)
|
|
{
|
|
var info = new ProcessStartInfo("sh") { RedirectStandardError = true, RedirectStandardOutput = true, UseShellExecute = false };
|
|
info.ArgumentList.Add(Path.Combine(_root, "deploy", "docker", "publish.sh"));
|
|
info.ArgumentList.Add("anubis:ci-1-1");
|
|
info.ArgumentList.Add(tag);
|
|
info.Environment["PATH"] = Path.Combine(_root, "bin") + ":" + Environment.GetEnvironmentVariable("PATH");
|
|
info.Environment["RECORD"] = _root;
|
|
info.Environment["VERSION"] = _version ?? tag[1..];
|
|
info.Environment["REGISTRY"] = "registry.test";
|
|
info.Environment["REGISTRY_USER"] = "someone";
|
|
info.Environment["REGISTRY_TOKEN"] = token;
|
|
using var process = Process.Start(info)!;
|
|
var output = process.StandardOutput.ReadToEndAsync();
|
|
var error = process.StandardError.ReadToEndAsync();
|
|
await process.WaitForExitAsync();
|
|
return (process.ExitCode, await output + await error);
|
|
}
|
|
|
|
public void Dispose() => Directory.Delete(_root, recursive: true);
|
|
|
|
private string Recorded(string name) => File.Exists(Path.Combine(_root, name)) ? File.ReadAllText(Path.Combine(_root, name)) : "";
|
|
|
|
private void Tool(string name, string body)
|
|
{
|
|
var path = Path.Combine(_root, "bin", name);
|
|
File.WriteAllText(path, "#!/bin/sh\n" + body);
|
|
if (!OperatingSystem.IsWindows())
|
|
{
|
|
File.SetUnixFileMode(path, UnixFileMode.UserRead | UnixFileMode.UserWrite | UnixFileMode.UserExecute);
|
|
}
|
|
}
|
|
}
|
|
|
|
/// <summary>An environment that takes note of the names asked for.</summary>
|
|
private sealed class Recorded(Dictionary<string, string?> values, HashSet<string> read) : IReadOnlyDictionary<string, string?>
|
|
{
|
|
public IEnumerable<string> Keys => values.Keys;
|
|
|
|
public IEnumerable<string?> Values => values.Values;
|
|
|
|
public int Count => values.Count;
|
|
|
|
public string? this[string key] => TryGetValue(key, out var value) ? value : throw new KeyNotFoundException(key);
|
|
|
|
public bool ContainsKey(string key)
|
|
{
|
|
read.Add(key);
|
|
return values.ContainsKey(key);
|
|
}
|
|
|
|
public bool TryGetValue(string key, [MaybeNullWhen(false)] out string? value)
|
|
{
|
|
read.Add(key);
|
|
return values.TryGetValue(key, out value);
|
|
}
|
|
|
|
public IEnumerator<KeyValuePair<string, string?>> GetEnumerator() => values.GetEnumerator();
|
|
|
|
IEnumerator IEnumerable.GetEnumerator() => GetEnumerator();
|
|
}
|
|
|
|
[GeneratedRegex("`([A-Z][A-Z0-9_]+)`")]
|
|
private static partial Regex VariableName();
|
|
|
|
[GeneratedRegex(@"--stop-timeout (\d+)")]
|
|
private static partial Regex StopTimeout();
|
|
|
|
[GeneratedRegex(@"publish\.sh|docker (push|login)")]
|
|
private static partial Regex PublishCommand();
|
|
}
|