Publish the image on version tags and test what is delivered
A v* tag now builds, tries and publishes the image: the version must be the one of Directory.Build.props, latest only moves forward and the registry token is in one step, given to docker on its input. The same script works by hand. The image says its version and commit, and its health check also covers the engine loop and the live prices. The Unraid template is final: a test compares it with appendix E and with the variables the loader really reads, and another reads the workflow. refs #70 refs #71 Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
1 parent
4d92a39fef
commit
3cd214ae78
16 files changed
+859
-27
No files matched your search
@@ -0,0 +1,477 @@
|
||||
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.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<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 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());
|
||||
}
|
||||
|
||||
private sealed class PublishRun : IDisposable
|
||||
{
|
||||
public const string Token = "a-token-only-for-the-test";
|
||||
|
||||
private readonly string _root = Path.Combine(Path.GetTempPath(), "anubis-publish-" + Guid.NewGuid().ToString("N"));
|
||||
|
||||
public PublishRun(string others, bool gitFails = 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");
|
||||
Tool("docker", "printf '%s\\n' \"$*\" >> \"$RECORD/calls\"\nif [ \"$1\" = login ]; then cat > \"$RECORD/input\"; printf '%s' \"$DOCKER_CONFIG\" > \"$RECORD/config\"; fi\n");
|
||||
Tool("git", gitFails ? "exit 128\n" : string.Concat(others.Split(',', StringSplitOptions.RemoveEmptyEntries).Select(o => $"printf 'abc\\trefs/tags/{o}\\n'\n")));
|
||||
}
|
||||
|
||||
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["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();
|
||||
}
|
||||
@@ -0,0 +1,177 @@
|
||||
using System.Globalization;
|
||||
|
||||
namespace Anubis.Tests;
|
||||
|
||||
/// <summary>
|
||||
/// The part of YAML the workflow of the CI uses, for the tests only: maps, lists, plain and quoted scalars, lists of
|
||||
/// strings in brackets, block text (| and >-) and comments. Anything else is refused with the line number, so a
|
||||
/// workflow written in a way this reader does not understand fails the test instead of passing unread.
|
||||
/// Values are <see cref="Dictionary{TKey,TValue}"/>, <see cref="List{T}"/> or <see cref="string"/>.
|
||||
/// </summary>
|
||||
internal sealed class MiniYaml
|
||||
{
|
||||
private readonly List<(int Number, int Indent, string Text)> _lines = [];
|
||||
private readonly string[] _raw;
|
||||
private int _at;
|
||||
|
||||
private MiniYaml(string text)
|
||||
{
|
||||
_raw = text.ReplaceLineEndings("\n").Split('\n');
|
||||
for (var i = 0; i < _raw.Length; i++)
|
||||
{
|
||||
var indent = _raw[i].Length - _raw[i].TrimStart(' ').Length;
|
||||
var body = _raw[i].Trim(' ');
|
||||
if (_raw[i][indent..].StartsWith('\t'))
|
||||
{
|
||||
throw Bad(i + 1, "tab");
|
||||
}
|
||||
|
||||
_lines.Add((i + 1, indent, body));
|
||||
}
|
||||
}
|
||||
|
||||
public static Dictionary<string, object> Read(string text)
|
||||
{
|
||||
var yaml = new MiniYaml(text);
|
||||
yaml.SkipBlank();
|
||||
var map = yaml.Map(0);
|
||||
yaml.SkipBlank();
|
||||
return yaml._at == yaml._lines.Count ? map : throw Bad(yaml._lines[yaml._at].Number, "unexpected indentation");
|
||||
}
|
||||
|
||||
private static FormatException Bad(int line, string why) => new($"YAML line {line.ToString(CultureInfo.InvariantCulture)}: {why}.");
|
||||
|
||||
private void SkipBlank()
|
||||
{
|
||||
while (_at < _lines.Count && (_lines[_at].Text.Length == 0 || _lines[_at].Text.StartsWith('#')))
|
||||
{
|
||||
_at++;
|
||||
}
|
||||
}
|
||||
|
||||
private object Node(int indent, int line)
|
||||
{
|
||||
SkipBlank();
|
||||
if (_at >= _lines.Count || _lines[_at].Indent < indent)
|
||||
{
|
||||
return "";
|
||||
}
|
||||
|
||||
var found = _lines[_at];
|
||||
return found.Text.StartsWith("- ", StringComparison.Ordinal) ? List(found.Indent) : found.Indent >= indent ? Map(found.Indent) : throw Bad(line, "indentation");
|
||||
}
|
||||
|
||||
private List<object> List(int indent)
|
||||
{
|
||||
var list = new List<object>();
|
||||
for (SkipBlank(); _at < _lines.Count && _lines[_at].Indent == indent && _lines[_at].Text.StartsWith("- ", StringComparison.Ordinal); SkipBlank())
|
||||
{
|
||||
var (number, _, text) = _lines[_at];
|
||||
var body = text[2..].TrimStart();
|
||||
if (Key(body) is null)
|
||||
{
|
||||
list.Add(Scalar(body, number));
|
||||
_at++;
|
||||
continue;
|
||||
}
|
||||
|
||||
// "- key: value" is a map whose first line starts after the dash.
|
||||
_lines[_at] = (number, indent + (text.Length - body.Length), body);
|
||||
list.Add(Map(_lines[_at].Indent));
|
||||
}
|
||||
|
||||
return list;
|
||||
}
|
||||
|
||||
private Dictionary<string, object> Map(int indent)
|
||||
{
|
||||
var map = new Dictionary<string, object>(StringComparer.Ordinal);
|
||||
for (SkipBlank(); _at < _lines.Count && _lines[_at].Indent == indent && !_lines[_at].Text.StartsWith("- ", StringComparison.Ordinal); SkipBlank())
|
||||
{
|
||||
var (number, _, text) = _lines[_at];
|
||||
if (Key(text) is not { } key)
|
||||
{
|
||||
throw Bad(number, "not a key");
|
||||
}
|
||||
|
||||
var rest = Uncommented(text[(key.Length + 1)..]).Trim();
|
||||
_at++;
|
||||
object value = rest switch
|
||||
{
|
||||
"" => Node(indent + 1, number),
|
||||
"|" => Block(indent, "\n"),
|
||||
">-" => Block(indent, " "),
|
||||
_ => Scalar(rest, number),
|
||||
};
|
||||
if (!map.TryAdd(key, value))
|
||||
{
|
||||
throw Bad(number, "duplicate key " + key);
|
||||
}
|
||||
}
|
||||
|
||||
return _at < _lines.Count && _lines[_at].Indent > indent ? throw Bad(_lines[_at].Number, "unexpected indentation") : map;
|
||||
}
|
||||
|
||||
private string Block(int indent, string join)
|
||||
{
|
||||
var lines = new List<string>();
|
||||
var margin = -1;
|
||||
while (_at < _lines.Count && (_lines[_at].Text.Length == 0 || _lines[_at].Indent > indent))
|
||||
{
|
||||
if (_lines[_at].Text.Length > 0)
|
||||
{
|
||||
margin = margin < 0 ? _lines[_at].Indent : margin;
|
||||
lines.Add(_raw[_lines[_at].Number - 1][margin..]);
|
||||
}
|
||||
|
||||
_at++;
|
||||
}
|
||||
|
||||
return string.Join(join, lines);
|
||||
}
|
||||
|
||||
// A key is a plain word followed by ": " or by the end of the line.
|
||||
private static string? Key(string text)
|
||||
{
|
||||
var colon = text.IndexOf(':', StringComparison.Ordinal);
|
||||
return colon > 0 && (colon == text.Length - 1 || text[colon + 1] == ' ') && text.Take(colon).All(c => char.IsAsciiLetterOrDigit(c) || c is '_' or '-') ? text[..colon] : null;
|
||||
}
|
||||
|
||||
private static string Uncommented(string text)
|
||||
{
|
||||
var quote = '\0';
|
||||
for (var i = 0; i < text.Length; i++)
|
||||
{
|
||||
if (quote != '\0')
|
||||
{
|
||||
quote = text[i] == quote ? '\0' : quote;
|
||||
}
|
||||
else if (text[i] is '"' or '\'')
|
||||
{
|
||||
quote = text[i];
|
||||
}
|
||||
else if (text[i] == '#' && i > 0 && text[i - 1] == ' ')
|
||||
{
|
||||
return text[..i];
|
||||
}
|
||||
}
|
||||
|
||||
return text;
|
||||
}
|
||||
|
||||
private static object Scalar(string text, int line)
|
||||
{
|
||||
if (text.StartsWith('['))
|
||||
{
|
||||
return text.EndsWith(']') ? text[1..^1].Split(',', StringSplitOptions.TrimEntries | StringSplitOptions.RemoveEmptyEntries).Select(t => Scalar(t, line)).ToList()
|
||||
: throw Bad(line, "open list");
|
||||
}
|
||||
|
||||
if (text[0] is '"' or '\'' && text[^1] == text[0] && text.Length > 1)
|
||||
{
|
||||
return text[1..^1];
|
||||
}
|
||||
|
||||
return text[0] is '&' or '*' or '{' or '!' or '|' or '>' or '"' or '@' or '`' ? throw Bad(line, "not supported: " + text) : text;
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user