refactor!: rename Titano to Chronos and move CI and releases to Gitea (#6)
CI / Build and test (push) Successful in 8m14s
CI / Windows tests and installer (push) Skipped
CI / YAML check (push) Successful in 7s
Release / Build, test and publish (push) Successful in 13m19s
CI / PostgreSQL 16 integration (push) Successful in 4m49s
CI / PostgreSQL 17 integration (push) Successful in 5m28s
CI / Docker image (push) Successful in 53s
Release / Server image (push) Failing after 10s
CI / Build and test (push) Successful in 8m14s
CI / Windows tests and installer (push) Skipped
CI / YAML check (push) Successful in 7s
Release / Build, test and publish (push) Successful in 13m19s
CI / PostgreSQL 16 integration (push) Successful in 4m49s
CI / PostgreSQL 17 integration (push) Successful in 5m28s
CI / Docker image (push) Successful in 53s
Release / Server image (push) Failing after 10s
The owner renamed the product and moved the repository to the self-hosted Gitea (https://gitea.encke-hake.ts.net/BalboSoft/Chronos) for more control, and asked for Actions and a first automatic release with the server package and the Windows exe (docs/requests/2026-10-23-chronos-gitea.md). - Chronos everywhere: a byte-exact rename of contents and paths, then a per-language review of the forms the old name's ending had dictated. - Gitea instead of GitHub: the update check, licence, issue and support links read ChronosReleasesUrl; the update check takes the highest stable version, offers a pre-release build its final release and reports a repository it cannot see as a failed check. EULA, security policy and Gitea issue forms live at the repository root. - Gitea Actions for the Linux act_runner (.gitea/workflows): CI, release, nightly image and performance gates in the .NET SDK container with git checkout and the system SQLite. The release cross-compiles the Windows programs, checks their icon, version and DPI manifest, packs installers and zips, publishes the Gitea release and pushes the server image (REGISTRY_TOKEN). Windows-only tests run in an opt-in job on a Windows runner (WINDOWS_RUNNER). - New Chronos.Tools commands: zip, gitea-release, postgres-ci (replaces the docker-exec script, which Gitea's service containers do not allow; the throw-away server runs without durability) and pe-check. - Timed tests take their budget from TestTiming (CHRONOS_TEST_TIME_FACTOR, 3 on the shared runner; the weekly performance gates keep theirs). BREAKING CHANGE: programs, settings, data folders, file types, environment variables and the Docker image use the new name; nothing is migrated from Titano, which never had a release. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Co-authored-by: Alberto Balbo <alberto.balbo.96@gmail.com>
This commit was merged in pull request #6.
This commit is contained in:
1 parent
c99842cc86
commit
f2b58522b9
1801 files changed
+11804
-10676
No files matched your search
@@ -0,0 +1,33 @@
|
||||
using Chronos.Testing;
|
||||
using Chronos.Tools.Commands;
|
||||
|
||||
namespace Chronos.Tools.Tests;
|
||||
|
||||
/// <summary>Release notes from Conventional Commits (BRIEF §19.3), as release.yml renders them with a title.</summary>
|
||||
public sealed class ChangelogCommandTests
|
||||
{
|
||||
[Test]
|
||||
public void EntriesAreGroupedByTypeUnderTheTitle()
|
||||
{
|
||||
var notes = ChangelogCommand.Render(["abc1234\tfeat(editor): save the project as a .chronos file", "def5678\tfix: keep user data", "0a1b2c3\tchore: bump"], "Chronos 1.2.0");
|
||||
Assert.Equal(
|
||||
"# Chronos 1.2.0\n\n### Added\n- **editor**: save the project as a .chronos file (abc1234)\n\n### Fixed\n- keep user data (def5678)\n\n",
|
||||
notes.ReplaceLineEndings("\n"));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void ATitledReleaseWithoutListedChangesSaysItIsAMaintenanceRelease()
|
||||
{
|
||||
string[] lines = ["abc1234\tchore: bump", "def5678\tci: cache", "0a1b2c3\ttest(setup): cover uninstall", "not a conventional subject"];
|
||||
Assert.Equal("# Chronos 1.2.1\n\nMaintenance release.\n", ChangelogCommand.Render(lines, "Chronos 1.2.1").ReplaceLineEndings("\n"));
|
||||
Assert.Equal("Maintenance release.\n", ChangelogCommand.Render(lines, null).ReplaceLineEndings("\n"));
|
||||
Assert.Equal("Maintenance release.\n", ChangelogCommand.Render([], null).ReplaceLineEndings("\n"));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void ABreakingChangeOfAnUnlistedTypeIsStillWritten()
|
||||
{
|
||||
var notes = ChangelogCommand.Render(["abc1234\trefactor(core)!: rename the archive layout"], "Chronos 2.0.0").ReplaceLineEndings("\n");
|
||||
Assert.Equal("# Chronos 2.0.0\n\n### Breaking changes\n- **core**: rename the archive layout (abc1234)\n\n", notes);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,11 @@
|
||||
<Project Sdk="Microsoft.NET.Sdk">
|
||||
<PropertyGroup>
|
||||
<OutputType>Exe</OutputType>
|
||||
<TargetFramework>net10.0</TargetFramework>
|
||||
<RootNamespace>Chronos.Tools.Tests</RootNamespace>
|
||||
</PropertyGroup>
|
||||
<ItemGroup>
|
||||
<ProjectReference Include="..\Chronos.Testing\Chronos.Testing.csproj" />
|
||||
<ProjectReference Include="..\..\src\Chronos.Tools\Chronos.Tools.csproj" />
|
||||
</ItemGroup>
|
||||
</Project>
|
||||
@@ -0,0 +1,37 @@
|
||||
using Chronos.Testing;
|
||||
using Chronos.Tools.Commands;
|
||||
|
||||
namespace Chronos.Tools.Tests;
|
||||
|
||||
/// <summary>The fixtures command reports a sample it cannot fetch instead of passing silently (BRIEF §20.2).</summary>
|
||||
public sealed class FixturesCommandTests(TestContext context)
|
||||
{
|
||||
[Test]
|
||||
public void TheWarningAnnotationNamesTheFixtureAndEscapesWorkflowCommandCharacters()
|
||||
{
|
||||
var entry = new FixturesCommand.Entry("canon-eos-r5.cr3", new Uri("https://raw.pixls.us/data/Canon/EOS%20R5/IMG_0001.CR3"), null, null, "Cr3");
|
||||
var line = FixturesCommand.Annotation("tests/fixtures/manifest.json", entry, "Response status code 404, 100% missing\r\nretry later.");
|
||||
Assert.Equal(
|
||||
"::warning file=tests/fixtures/manifest.json,title=RAW fixture missing::canon-eos-r5.cr3 (Cr3) could not be fetched from " +
|
||||
"https://raw.pixls.us/data/Canon/EOS%2520R5/IMG_0001.CR3: Response status code 404, 100%25 missing%0D%0Aretry later. " +
|
||||
"Its decode tests are skipped. Replace the url in the manifest (see its 'instructions').",
|
||||
line);
|
||||
Assert.True(FixturesCommand.Annotation("a:b,c.json", entry, "x").StartsWith("::warning file=a%3Ab%2Cc.json,title=", StringComparison.Ordinal));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task AMissingFixtureFailsTheCommandUnlessMissingFilesAreAllowed()
|
||||
{
|
||||
var folder = context.CreateTempDirectory();
|
||||
var manifest = Path.Combine(folder, "manifest.json");
|
||||
// Port 1 refuses the connection at once (or the proxy answers with an error): the fixture stays missing.
|
||||
await File.WriteAllTextAsync(manifest, """
|
||||
{ "files": [ { "name": "missing.dng", "url": "https://127.0.0.1:1/missing.dng", "sha256": null, "size": null, "format": "Dng" } ] }
|
||||
""");
|
||||
var output = Path.Combine(folder, "external");
|
||||
|
||||
Assert.Equal(1, await new FixturesCommand().RunAsync(["--manifest", manifest, "--out", output]));
|
||||
Assert.Equal(0, await new FixturesCommand().RunAsync(["--manifest", manifest, "--out", output, "--allow-missing"]));
|
||||
Assert.FileMissing(Path.Combine(output, "missing.dng"));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,218 @@
|
||||
using System.Net;
|
||||
using System.Text.Json.Nodes;
|
||||
using System.Text.RegularExpressions;
|
||||
using Chronos.Testing;
|
||||
using Chronos.Tools.Commands;
|
||||
|
||||
namespace Chronos.Tools.Tests;
|
||||
|
||||
/// <summary>gitea-release publishes a release only once its files are uploaded (BRIEF §19.3, amended 2026-10-23, R3).</summary>
|
||||
public sealed partial class GiteaReleaseCommandTests(TestContext context)
|
||||
{
|
||||
private const string Server = "http://gitea.test:3000/";
|
||||
private const string Token = "token-value";
|
||||
|
||||
[Test]
|
||||
public async Task ANewTagBecomesADraftThatIsPublishedAfterItsFilesAreUploaded()
|
||||
{
|
||||
var files = Files(("SHA256SUMS", 120), ("Chronos-Setup-1.2.0.exe", 3000));
|
||||
var gitea = new FakeGitea();
|
||||
using var http = new HttpClient(gitea);
|
||||
var log = new StringWriter();
|
||||
|
||||
var url = await GiteaReleaseCommand.PublishAsync(http,
|
||||
new ReleaseRequest(Server, "BalboSoft/Chronos", "v1.2.0", "Chronos 1.2.0", "# Chronos 1.2.0\n", files, Prerelease: false), Token, log, CancellationToken.None);
|
||||
|
||||
Assert.Equal("https://gitea.example/BalboSoft/Chronos/releases/tag/v1.2.0", url);
|
||||
var release = Assert.Contains(gitea.Releases, r => r.Tag == "v1.2.0");
|
||||
Assert.False(release.Draft);
|
||||
Assert.False(release.Prerelease);
|
||||
Assert.Equal("Chronos 1.2.0", release.Name);
|
||||
Assert.Equal("# Chronos 1.2.0\n", release.Body);
|
||||
Assert.SequenceEqual(["Chronos-Setup-1.2.0.exe", "SHA256SUMS"], release.Assets.Select(a => a.Name));
|
||||
Assert.Equal(3000L, release.Assets[0].Size);
|
||||
// The release is created as a draft and published only after the last upload.
|
||||
Assert.True(gitea.DraftAtCreation, "created as a draft");
|
||||
var lastUpload = gitea.Requests.FindLastIndex(r => r.StartsWith("POST /api/v1/repos/BalboSoft/Chronos/releases/1/assets", StringComparison.Ordinal));
|
||||
var publish = gitea.Requests.FindIndex(r => r == "PATCH /api/v1/repos/BalboSoft/Chronos/releases/1");
|
||||
Assert.True(lastUpload >= 0 && publish > lastUpload, string.Join("\n", gitea.Requests));
|
||||
Assert.True(gitea.Authorized, "every request carries the token");
|
||||
Assert.False(log.ToString().Contains(Token, StringComparison.Ordinal), "the token is never logged");
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task PublishingAnExistingReleaseAgainReplacesItsFilesOfTheSameName()
|
||||
{
|
||||
var gitea = new FakeGitea();
|
||||
var existing = gitea.Add("v1.2.0-rc.1", draft: false, prerelease: true);
|
||||
existing.Assets.Add(new FakeAsset(40, "SHA256SUMS", 10));
|
||||
existing.Assets.Add(new FakeAsset(41, "old-notes.txt", 5));
|
||||
var files = Files(("SHA256SUMS", 64));
|
||||
using var http = new HttpClient(gitea);
|
||||
|
||||
await GiteaReleaseCommand.PublishAsync(http,
|
||||
new ReleaseRequest(Server, "BalboSoft/Chronos", "v1.2.0-rc.1", "Chronos 1.2.0-rc.1", "notes", files, Prerelease: true), Token, TextWriter.Null, CancellationToken.None);
|
||||
|
||||
// The published release loses its old checksums before any other file changes.
|
||||
var firstChange = gitea.Requests.FindIndex(r => r.StartsWith("DELETE ", StringComparison.Ordinal) || r.StartsWith("POST /api/v1/repos/BalboSoft/Chronos/releases/1/assets", StringComparison.Ordinal));
|
||||
Assert.Equal("DELETE /api/v1/repos/BalboSoft/Chronos/releases/1/assets/40", gitea.Requests[firstChange]);
|
||||
Assert.DoesNotContain("DELETE /api/v1/repos/BalboSoft/Chronos/releases/1/assets/41", gitea.Requests);
|
||||
Assert.False(gitea.Requests.Any(r => r == "POST /api/v1/repos/BalboSoft/Chronos/releases"), "no second release");
|
||||
Assert.Equal(64L, existing.Assets.Single(a => a.Name == "SHA256SUMS").Size);
|
||||
Assert.True(existing.Prerelease);
|
||||
Assert.Equal("Chronos 1.2.0-rc.1", existing.Name);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task AFileTheServerListsWithAnotherSizeFailsThePublication()
|
||||
{
|
||||
var gitea = new FakeGitea { TruncateUploads = true };
|
||||
using var http = new HttpClient(gitea);
|
||||
|
||||
var error = await Assert.ThrowsAsync<ToolException>(() => GiteaReleaseCommand.PublishAsync(http,
|
||||
new ReleaseRequest(Server, "BalboSoft/Chronos", "v1.0.0", "Chronos 1.0.0", "", Files(("Chronos-Setup-1.0.0.exe", 500)), false), Token, TextWriter.Null, CancellationToken.None));
|
||||
Assert.Contains("Chronos-Setup-1.0.0.exe", error.Message);
|
||||
// Checked before publishing: the broken release stays a draft nobody downloads from.
|
||||
Assert.True(Assert.Contains(gitea.Releases, r => r.Tag == "v1.0.0").Draft);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task AnUnexpectedReplyNamesTheRequestAndTheStatus()
|
||||
{
|
||||
var gitea = new FakeGitea { Forbidden = true };
|
||||
using var http = new HttpClient(gitea);
|
||||
|
||||
var error = await Assert.ThrowsAsync<ToolException>(() => GiteaReleaseCommand.PublishAsync(http,
|
||||
new ReleaseRequest(Server, "BalboSoft/Chronos", "v1.0.0", "Chronos 1.0.0", "", [], false), Token, TextWriter.Null, CancellationToken.None));
|
||||
Assert.Contains("403", error.Message);
|
||||
Assert.Contains("/releases/tags/v1.0.0", error.Message);
|
||||
Assert.False(error.Message.Contains(Token, StringComparison.Ordinal));
|
||||
await Assert.ThrowsAsync<ToolException>(() => GiteaReleaseCommand.PublishAsync(http,
|
||||
new ReleaseRequest(Server, "Chronos", "v1.0.0", "Chronos 1.0.0", "", [], false), Token, TextWriter.Null, CancellationToken.None));
|
||||
}
|
||||
|
||||
private List<string> Files(params (string Name, int Size)[] files)
|
||||
{
|
||||
var folder = context.CreateTempDirectory("assets");
|
||||
var paths = new List<string>();
|
||||
foreach (var (name, size) in files)
|
||||
{
|
||||
var path = Path.Combine(folder, name);
|
||||
File.WriteAllBytes(path, new byte[size]);
|
||||
paths.Add(path);
|
||||
}
|
||||
return paths;
|
||||
}
|
||||
|
||||
private sealed record FakeAsset(long Id, string Name, long Size);
|
||||
|
||||
private sealed class FakeRelease(long id, string tag)
|
||||
{
|
||||
public long Id { get; } = id;
|
||||
public string Tag { get; } = tag;
|
||||
public string Name { get; set; } = string.Empty;
|
||||
public string Body { get; set; } = string.Empty;
|
||||
public bool Draft { get; set; }
|
||||
public bool Prerelease { get; set; }
|
||||
public List<FakeAsset> Assets { get; } = [];
|
||||
|
||||
public JsonObject ToJson() => new()
|
||||
{
|
||||
["id"] = Id,
|
||||
["tag_name"] = Tag,
|
||||
["name"] = Name,
|
||||
["body"] = Body,
|
||||
["draft"] = Draft,
|
||||
["prerelease"] = Prerelease,
|
||||
["html_url"] = $"https://gitea.example/BalboSoft/Chronos/releases/tag/{Tag}",
|
||||
["assets"] = new JsonArray(Assets.Select(a => (JsonNode)new JsonObject { ["id"] = a.Id, ["name"] = a.Name, ["size"] = a.Size }).ToArray()),
|
||||
};
|
||||
}
|
||||
|
||||
/// <summary>The release endpoints of the Gitea API v1, in memory.</summary>
|
||||
private sealed partial class FakeGitea : HttpMessageHandler
|
||||
{
|
||||
private long _nextAsset = 100;
|
||||
|
||||
public List<FakeRelease> Releases { get; } = [];
|
||||
public List<string> Requests { get; } = [];
|
||||
public bool Authorized { get; private set; } = true;
|
||||
public bool DraftAtCreation { get; private set; }
|
||||
public bool TruncateUploads { get; init; }
|
||||
public bool Forbidden { get; init; }
|
||||
|
||||
public FakeRelease Add(string tag, bool draft, bool prerelease)
|
||||
{
|
||||
var release = new FakeRelease(Releases.Count + 1, tag) { Draft = draft, Prerelease = prerelease };
|
||||
Releases.Add(release);
|
||||
return release;
|
||||
}
|
||||
|
||||
protected override async Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
|
||||
{
|
||||
var path = request.RequestUri!.AbsolutePath;
|
||||
Requests.Add($"{request.Method} {path}");
|
||||
if (request.Headers.Authorization?.ToString() != "token " + Token) Authorized = false;
|
||||
if (Forbidden) return Reply(HttpStatusCode.Forbidden, new JsonObject { ["message"] = "forbidden" });
|
||||
|
||||
if (ByTag().Match(path) is { Success: true } byTag)
|
||||
{
|
||||
var release = Releases.FirstOrDefault(r => r.Tag == Uri.UnescapeDataString(byTag.Groups[1].Value));
|
||||
return release is null ? Reply(HttpStatusCode.NotFound, new JsonObject { ["message"] = "not found" }) : Reply(HttpStatusCode.OK, release.ToJson());
|
||||
}
|
||||
if (request.Method == HttpMethod.Post && path == "/api/v1/repos/BalboSoft/Chronos/releases")
|
||||
{
|
||||
var body = JsonNode.Parse(await request.Content!.ReadAsStringAsync(cancellationToken))!;
|
||||
DraftAtCreation = body["draft"]!.GetValue<bool>();
|
||||
var release = Add(body["tag_name"]!.GetValue<string>(), DraftAtCreation, body["prerelease"]!.GetValue<bool>());
|
||||
release.Name = body["name"]!.GetValue<string>();
|
||||
release.Body = body["body"]!.GetValue<string>();
|
||||
return Reply(HttpStatusCode.Created, release.ToJson());
|
||||
}
|
||||
if (Assets().Match(path) is { Success: true } assets)
|
||||
{
|
||||
var release = Releases.Single(r => r.Id == long.Parse(assets.Groups[1].Value, System.Globalization.CultureInfo.InvariantCulture));
|
||||
if (request.Method == HttpMethod.Get) return Reply(HttpStatusCode.OK, new JsonArray(release.Assets.Select(a => (JsonNode)new JsonObject { ["id"] = a.Id, ["name"] = a.Name, ["size"] = a.Size }).ToArray()));
|
||||
if (request.Method == HttpMethod.Delete)
|
||||
{
|
||||
var removed = release.Assets.RemoveAll(a => a.Id == long.Parse(assets.Groups[2].Value, System.Globalization.CultureInfo.InvariantCulture));
|
||||
return new HttpResponseMessage(removed > 0 ? HttpStatusCode.NoContent : HttpStatusCode.NotFound);
|
||||
}
|
||||
var form = (MultipartFormDataContent)request.Content!;
|
||||
var part = form.Single();
|
||||
Assert.Equal("attachment", part.Headers.ContentDisposition!.Name!.Trim('"'));
|
||||
var bytes = await part.ReadAsByteArrayAsync(cancellationToken);
|
||||
var name = Uri.UnescapeDataString(request.RequestUri.Query.Replace("?name=", "", StringComparison.Ordinal));
|
||||
var asset = new FakeAsset(_nextAsset++, name, TruncateUploads ? bytes.Length / 2 : bytes.Length);
|
||||
release.Assets.Add(asset);
|
||||
return Reply(HttpStatusCode.Created, new JsonObject { ["id"] = asset.Id, ["name"] = asset.Name, ["size"] = asset.Size });
|
||||
}
|
||||
if (Release().Match(path) is { Success: true } one)
|
||||
{
|
||||
var release = Releases.Single(r => r.Id == long.Parse(one.Groups[1].Value, System.Globalization.CultureInfo.InvariantCulture));
|
||||
if (request.Method.Method == "PATCH")
|
||||
{
|
||||
var body = JsonNode.Parse(await request.Content!.ReadAsStringAsync(cancellationToken))!;
|
||||
release.Name = body["name"]!.GetValue<string>();
|
||||
release.Body = body["body"]!.GetValue<string>();
|
||||
release.Draft = body["draft"]!.GetValue<bool>();
|
||||
release.Prerelease = body["prerelease"]!.GetValue<bool>();
|
||||
}
|
||||
return Reply(HttpStatusCode.OK, release.ToJson());
|
||||
}
|
||||
return Reply(HttpStatusCode.NotFound, new JsonObject { ["message"] = "no route" });
|
||||
}
|
||||
|
||||
private static HttpResponseMessage Reply(HttpStatusCode status, JsonNode body) =>
|
||||
new(status) { Content = new StringContent(body.ToJsonString(), System.Text.Encoding.UTF8, "application/json") };
|
||||
|
||||
[GeneratedRegex(@"^/api/v1/repos/BalboSoft/Chronos/releases/tags/(.+)$")]
|
||||
private static partial Regex ByTag();
|
||||
|
||||
[GeneratedRegex(@"^/api/v1/repos/BalboSoft/Chronos/releases/(\d+)/assets(?:/(\d+))?$")]
|
||||
private static partial Regex Assets();
|
||||
|
||||
[GeneratedRegex(@"^/api/v1/repos/BalboSoft/Chronos/releases/(\d+)$")]
|
||||
private static partial Regex Release();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,131 @@
|
||||
using System.Xml.Linq;
|
||||
using Chronos.Testing;
|
||||
using Chronos.Tools.Commands;
|
||||
|
||||
namespace Chronos.Tools.Tests;
|
||||
|
||||
/// <summary><c>i18n check</c>: English texts that count something need plural forms (BRIEF §16), and every error code
|
||||
/// of the server has its message, whose key is built at run time.</summary>
|
||||
public sealed class I18nCommandTests(TestContext context)
|
||||
{
|
||||
[Test]
|
||||
public void ANumberInFrontOfACountedNounNeedsPluralForms()
|
||||
{
|
||||
Assert.Equal("frames", I18nCommand.CountedNoun("Advisor.Finding.BlackFrames", "{0} frames are black (lens cap or missed exposure)."));
|
||||
Assert.Equal("gaps", I18nCommand.CountedNoun("Advisor.Reason.Timing.SparseGaps", "{0} short gaps, but motion is unmeasured or fast."));
|
||||
Assert.Equal("changes", I18nCommand.CountedNoun("Advisor.Finding.StepsNotReceived", "{0} logged exposure changes never reached the pixels."));
|
||||
Assert.Equal("times", I18nCommand.CountedNoun("Advisor.Finding.LensChanged", "The lens changes {0} times."));
|
||||
Assert.Equal("sequences", I18nCommand.CountedNoun("Errors.Analysis.Failed", "{0} of {1} sequences could not be analysed; see the job log."));
|
||||
Assert.Equal("jobs", I18nCommand.CountedNoun("Shell.JobBar.Ready", "Ready · {0:N0} jobs queued"));
|
||||
Assert.Equal("cores", I18nCommand.CountedNoun("Settings.Rendering.Cores", "of {0} logical cores"));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void PluralFormsBoundsLabelsAndUnitsCountNothing()
|
||||
{
|
||||
Assert.Null(I18nCommand.CountedNoun("Advisor.Finding.BlackFrames.other", "{0} frames are black (lens cap or missed exposure)."));
|
||||
Assert.Null(I18nCommand.CountedNoun("Advisor.Finding.BlackFrames.one", "{0} frame is black (lens cap or missed exposure)."));
|
||||
Assert.Null(I18nCommand.CountedNoun("Server.Error.WeakPassword", "Use at least {0} characters."));
|
||||
Assert.Null(I18nCommand.CountedNoun("Library.Views.Error.Long", "At most {0} characters, no control characters."));
|
||||
Assert.Null(I18nCommand.CountedNoun("Archive.Retag.Invalid", "Each tag has 1 to {0} characters."));
|
||||
Assert.Null(I18nCommand.CountedNoun("Archive.Log.ScanDone", "Folders: {0}, indexed: {1}, adopted: {2}, removed: {3}"));
|
||||
Assert.Null(I18nCommand.CountedNoun("Advisor.Reason.Window.Period.other", "Flicker repeats every {0} frames: a {1}-frame window averages four cycles."));
|
||||
Assert.Null(I18nCommand.CountedNoun("Advisor.Reason.Timing.Regular", "Steady {0} s interval (jitter {1} s): each photo becomes one video frame."));
|
||||
Assert.Null(I18nCommand.CountedNoun("Tooltips.Editor.Remote", "Changes are saved on {0} and analyses and renders run there"));
|
||||
Assert.Null(I18nCommand.CountedNoun("Advisor.Reason.Transition.Single", "A single exposure step: a {0}-frame transition keeps the change gentle."));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void ATallyOfParticiplesNeedsLabels()
|
||||
{
|
||||
// Italian reads "1 copiate · 1 non riuscite": the participle agrees with the number in front of it.
|
||||
Assert.Equal("copied", I18nCommand.CountedTally("Import.Result.Partial", "{0} copied · {1} failed"));
|
||||
Assert.Equal("missing", I18nCommand.CountedTally("Archive.Health.Damaged", "{0} missing · {1} damaged"));
|
||||
Assert.Equal("made", I18nCommand.CountedTally("Archive.Log.ImagesDone", "{0}: {1} made, {2} reused, {3} unreadable"));
|
||||
Assert.Equal("copied", I18nCommand.CountedTally("Archive.Log.ImportDone", "{0:N0} copied, {1:N0} skipped, {2:N0} failed."));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void LabelsNamesAndSizesAreNoTally()
|
||||
{
|
||||
Assert.Null(I18nCommand.CountedTally("Import.Result.Partial", "Copied: {0} · failed: {1}"));
|
||||
Assert.Null(I18nCommand.CountedTally("Archive.Log.ImagesDone", "{0}: made {1}, reused {2}, unreadable {3}"));
|
||||
Assert.Null(I18nCommand.CountedTally("Archive.Log.ScanDone", "Folders: {0}, indexed: {1}, adopted: {2}, removed: {3}"));
|
||||
// A single participle after a placeholder is as often a name or a size as a count.
|
||||
Assert.Null(I18nCommand.CountedTally("Export.Log.Failed", "{0} failed: {1}"));
|
||||
Assert.Null(I18nCommand.CountedTally("Library.Queued", "{0} queued · {1}"));
|
||||
Assert.Null(I18nCommand.CountedTally("Import.Plan.SpaceMissing", "{0} missing"));
|
||||
Assert.Null(I18nCommand.CountedTally("Settings.Storage.Usage", "{0} used · {1} free"));
|
||||
Assert.Null(I18nCommand.CountedTally("Import.Result.Skipped.other", "{0:N0} copied, {1:N0} skipped"));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void PruneRemovesOnlyTheKeysEnglishNoLongerHas()
|
||||
{
|
||||
var dir = context.CreateTempDirectory();
|
||||
void Write(string culture, string file, params (string Key, string Value)[] entries)
|
||||
{
|
||||
Directory.CreateDirectory(Path.Combine(dir, culture));
|
||||
var data = string.Concat(entries.Select(e => $" <data name=\"{e.Key}\" xml:space=\"preserve\"><value>{e.Value}</value></data>\n"));
|
||||
File.WriteAllText(Path.Combine(dir, culture, file), $"<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<root>\n{data}</root>\n");
|
||||
}
|
||||
Write("en", "Jobs.resx", ("Jobs.Kind.Render", "Render"), ("Jobs.Parallelism.one", "{0} photo at once"), ("Jobs.Parallelism.other", "{0} photos at once"));
|
||||
Write("it", "Jobs.it.resx", ("Jobs.Kind.Render", "Render"), ("Jobs.Workers", "Processi {0} / {1}"), ("Jobs.Parallelism.one", "{0} foto alla volta"));
|
||||
// Polish adds plural forms English has not: they stay.
|
||||
Write("pl", "Jobs.pl.resx", ("Jobs.Parallelism.few", "{0} zdjęcia naraz"), ("Jobs.Parallelism.many", "{0} zdjęć naraz"));
|
||||
var untouched = File.ReadAllText(Path.Combine(dir, "pl", "Jobs.pl.resx"));
|
||||
|
||||
Assert.Equal(1, I18nCommand.PruneOrphans(dir, I18nCommand.Catalog.Load(dir)));
|
||||
|
||||
var italian = I18nCommand.Catalog.Load(dir).Cultures["it"];
|
||||
Assert.SequenceEqual(["Jobs.Kind.Render", "Jobs.Parallelism.one"], italian.Keys.Order(StringComparer.Ordinal));
|
||||
Assert.Equal("{0} foto alla volta", italian["Jobs.Parallelism.one"].Value);
|
||||
Assert.Equal(untouched, File.ReadAllText(Path.Combine(dir, "pl", "Jobs.pl.resx")));
|
||||
Assert.Equal(3, I18nCommand.Catalog.Load(dir).Cultures["en"].Count);
|
||||
Assert.Equal(0, I18nCommand.PruneOrphans(dir, I18nCommand.Catalog.Load(dir)));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void ErrorCodesAreTheLiteralsPassedToTheServerErrorHelpers()
|
||||
{
|
||||
const string source = """
|
||||
if (bad) return ApiErrors.BadRequest(context, "invalid_filter", "status");
|
||||
return known.SequenceId == sequenceId
|
||||
? new StartUploadResponse(null, options.ChunkSizeBytes, [], AlreadyExists: true, null)
|
||||
: Outcome<StartUploadResponse>.Fail(409, "render_exists");
|
||||
return Fail<ChunkReceived>(400, "chunk_size", expected.ToString(CultureInfo.InvariantCulture));
|
||||
DeleteBlock.Offline => ApiErrors.Result(context, StatusCodes.Status503ServiceUnavailable,
|
||||
"archive_offline"),
|
||||
return TooMany(context, "rate_limited", wait);
|
||||
return ApiErrors.NotFound(context, "sequence");
|
||||
return ApiErrors.BadRequest(context, code, setting, setting);
|
||||
await FailAsync(upload, "not_a_code");
|
||||
""";
|
||||
|
||||
Assert.SequenceEqual(["invalid_filter", "render_exists", "chunk_size", "archive_offline", "rate_limited"], I18nCommand.ErrorCodes(source).ToList());
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void AnErrorCodeNamesItsMessageKeyLikeTheServer()
|
||||
{
|
||||
Assert.Equal("Server.Error.RenderExists", I18nCommand.ErrorKey("render_exists"));
|
||||
Assert.Equal("Server.Error.Forbidden", I18nCommand.ErrorKey("forbidden"));
|
||||
Assert.Equal("Server.Error.Http413", I18nCommand.ErrorKey("http_413"));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void EveryErrorCodeOfTheServerHasAnEnglishMessage()
|
||||
{
|
||||
var root = Args.RepoRoot();
|
||||
var keys = XDocument.Load(Path.Combine(root, "i18n", "en", "Server.resx")).Root!.Elements("data")
|
||||
.Select(d => (string)d.Attribute("name")!).ToHashSet(StringComparer.Ordinal);
|
||||
|
||||
var missing = I18nCommand.MissingErrorMessages(root, keys).ToList();
|
||||
|
||||
Assert.Empty(missing.Select(m => $"{m.Code} ({Path.GetFileName(m.File)})"));
|
||||
var withoutOne = keys.Where(k => k != "Server.Error.RenderExists").ToHashSet(StringComparer.Ordinal);
|
||||
var reported = I18nCommand.MissingErrorMessages(root, withoutOne).ToList();
|
||||
Assert.Count(1, reported);
|
||||
Assert.Equal(("render_exists", "Server.Error.RenderExists", "RenderUploads.cs"), (reported[0].Code, reported[0].Key, Path.GetFileName(reported[0].File)));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,44 @@
|
||||
using Chronos.Core.Packaging;
|
||||
using Chronos.Testing;
|
||||
using Chronos.Tools.Commands;
|
||||
|
||||
namespace Chronos.Tools.Tests;
|
||||
|
||||
/// <summary>pack-installer writes the components, shortcuts and file types setup installs (BRIEF §18).</summary>
|
||||
public sealed class PackInstallerCommandTests(TestContext context)
|
||||
{
|
||||
[Test]
|
||||
public async Task TheServerInstallsOnlyForAllUsersAndChronosOwnsTheProjectFileType()
|
||||
{
|
||||
var root = context.CreateTempDirectory("pack");
|
||||
var stub = Path.Combine(root, "Chronos.Setup.exe");
|
||||
var bytes = new byte[4096];
|
||||
new Random(5).NextBytes(bytes);
|
||||
"MZ"u8.CopyTo(bytes);
|
||||
await File.WriteAllBytesAsync(stub, bytes);
|
||||
var app = Program(root, "app", "Chronos.exe");
|
||||
var server = Program(root, "server", "Chronos.Server.exe");
|
||||
var output = Path.Combine(root, "out", "Chronos-Setup.exe");
|
||||
|
||||
Assert.Equal(0, await new PackInstallerCommand().RunAsync(
|
||||
["--setup", stub, "--product", "Chronos", "--version", "1.2.3", "--component", "Chronos=" + app, "--component", "Server=" + server, "--out", output]));
|
||||
|
||||
using var reader = PayloadReader.Open(output);
|
||||
var manifest = reader.Manifest;
|
||||
Assert.False(manifest.FindComponent("Chronos")!.AllUsersOnly);
|
||||
var serverComponent = manifest.FindComponent("Server")!;
|
||||
Assert.True(serverComponent.AllUsersOnly);
|
||||
Assert.False(serverComponent.DefaultSelected);
|
||||
var association = Assert.Contains(manifest.Associations, a => a.Extension == ".chronos");
|
||||
Assert.Equal("Chronos.Project", association.ProgId);
|
||||
Assert.Equal("Chronos.exe", association.Target);
|
||||
Assert.Equal("Chronos", association.Component);
|
||||
}
|
||||
|
||||
private static string Program(string root, string folder, string name)
|
||||
{
|
||||
var dir = Directory.CreateDirectory(Path.Combine(root, folder)).FullName;
|
||||
File.WriteAllText(Path.Combine(dir, name), "MZ " + name);
|
||||
return dir;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,38 @@
|
||||
using Chronos.Testing;
|
||||
using Chronos.Tools.Commands;
|
||||
|
||||
namespace Chronos.Tools.Tests;
|
||||
|
||||
/// <summary>pe-check stops a release whose cross-compiled programs lost their resources (BRIEF §18, amended 2026-10-23, R3).</summary>
|
||||
public sealed class PeCheckCommandTests(TestContext context)
|
||||
{
|
||||
[Test]
|
||||
public void AFileThatIsNotAWindowsProgramIsReported()
|
||||
{
|
||||
var folder = context.CreateTempDirectory("pe");
|
||||
var text = Path.Combine(folder, "Chronos.exe");
|
||||
File.WriteAllText(text, "not a program");
|
||||
Assert.SequenceEqual(["not a PE image"], PeCheckCommand.Check(text));
|
||||
Assert.SequenceEqual(["file not found"], PeCheckCommand.Check(Path.Combine(folder, "missing.exe")));
|
||||
}
|
||||
|
||||
[Test]
|
||||
[WindowsOnly]
|
||||
public void AWindowsGuiProgramWithItsResourcesPasses()
|
||||
{
|
||||
var notepad = Path.Combine(Environment.SystemDirectory, "notepad.exe");
|
||||
var problems = PeCheckCommand.Check(notepad);
|
||||
Assert.DoesNotContain("no icon", problems);
|
||||
Assert.DoesNotContain("no version information", problems);
|
||||
Assert.DoesNotContain("no application manifest", problems);
|
||||
Assert.False(problems.Any(p => p.StartsWith("subsystem", StringComparison.Ordinal)), string.Join("; ", problems));
|
||||
}
|
||||
|
||||
[Test]
|
||||
[WindowsOnly]
|
||||
public void AConsoleProgramIsNotTakenForADesktopProgram()
|
||||
{
|
||||
var problems = PeCheckCommand.Check(Environment.ProcessPath!);
|
||||
Assert.Contains(problems, p => p.StartsWith("subsystem WindowsCui", StringComparison.Ordinal));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,38 @@
|
||||
using System.Security.Cryptography.X509Certificates;
|
||||
using Chronos.Testing;
|
||||
using Chronos.Tools.Commands;
|
||||
|
||||
namespace Chronos.Tools.Tests;
|
||||
|
||||
/// <summary>postgres-ci prepares the CI server for the wire tests without docker (BRIEF §6.3, amended 2026-10-23, R3).</summary>
|
||||
public sealed class PostgresCiCommandTests
|
||||
{
|
||||
[Test]
|
||||
public void TheTestRolesGoAheadOfTheImagesRulesOnceOnly()
|
||||
{
|
||||
const string image = "local all all trust\nhost all all all scram-sha-256\n";
|
||||
var once = PostgresCiCommand.PrependRules(image);
|
||||
Assert.Equal(
|
||||
"host all chronos_md5 all md5\nhost all chronos_clear all password\nhost all chronos_trust all trust\n" + image,
|
||||
once);
|
||||
Assert.Equal(once, PostgresCiCommand.PrependRules(once));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void TheCertificateNamesTheServiceHostAndLoopback()
|
||||
{
|
||||
var (pem, key) = PostgresCiCommand.CreateCertificate("postgres");
|
||||
using var certificate = X509Certificate2.CreateFromPem(pem, key);
|
||||
Assert.True(certificate.HasPrivateKey);
|
||||
Assert.Equal("CN=postgres", certificate.Subject);
|
||||
Assert.True(certificate.MatchesHostname("postgres"));
|
||||
Assert.True(certificate.MatchesHostname("localhost"));
|
||||
Assert.True(certificate.MatchesHostname("127.0.0.1"));
|
||||
Assert.False(certificate.MatchesHostname("example.org"));
|
||||
Assert.Less((certificate.NotAfter - DateTime.Now).TotalDays, 3);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void LiteralsDoubleTheirQuotes() =>
|
||||
Assert.Equal("'/var/lib/postgresql/data/it''s'", PostgresCiCommand.Literal("/var/lib/postgresql/data/it's"));
|
||||
}
|
||||
@@ -0,0 +1,8 @@
|
||||
using Chronos.Testing;
|
||||
|
||||
namespace Chronos.Tools.Tests;
|
||||
|
||||
internal static class TestMain
|
||||
{
|
||||
public static Task<int> Main(string[] args) => TestRunner.RunAsync(args, typeof(TestMain).Assembly);
|
||||
}
|
||||
@@ -0,0 +1,188 @@
|
||||
using Chronos.Core.Codecs.Png;
|
||||
using Chronos.Testing;
|
||||
using Chronos.Tools.Commands;
|
||||
using static Chronos.Tools.Commands.ScreenshotsCommand;
|
||||
|
||||
namespace Chronos.Tools.Tests;
|
||||
|
||||
/// <summary>
|
||||
/// The screenshot diff fails on changed screens and tolerates noise (BRIEF §20.2); a screen without a baseline fails
|
||||
/// once any baseline exists, and a run before the first baselines says that it compared nothing.
|
||||
/// </summary>
|
||||
public sealed class ScreenshotsCommandTests(TestContext context)
|
||||
{
|
||||
private const int Size = 100;
|
||||
|
||||
/// <summary>A 100×100 RGB screen: a dark background with a light panel, then <paramref name="change"/> applied.</summary>
|
||||
private static void WriteScreen(string folder, string name, Action<byte[]>? change = null, int width = Size, int height = Size)
|
||||
{
|
||||
var pixels = new byte[width * height * 3];
|
||||
for (var y = 0; y < height; y++)
|
||||
{
|
||||
for (var x = 0; x < width; x++)
|
||||
{
|
||||
var v = (byte)(x is >= 20 and < 80 && y is >= 30 and < 60 ? 230 : 32);
|
||||
pixels[(y * width + x) * 3] = pixels[(y * width + x) * 3 + 1] = pixels[(y * width + x) * 3 + 2] = v;
|
||||
}
|
||||
}
|
||||
change?.Invoke(pixels);
|
||||
File.WriteAllBytes(Path.Combine(folder, name), PngEncoder.Encode(pixels, width, height, PngColorType.Rgb));
|
||||
}
|
||||
|
||||
/// <summary>Adds <paramref name="delta"/> to the red channel of the first <paramref name="count"/> pixels.</summary>
|
||||
private static Action<byte[]> Shift(int count, int delta) => pixels =>
|
||||
{
|
||||
for (var i = 0; i < count; i++) pixels[i * 3] = (byte)(pixels[i * 3] + delta);
|
||||
};
|
||||
|
||||
private (string Captured, string Baseline, string Output) Folders()
|
||||
{
|
||||
var root = context.CreateTempDirectory();
|
||||
var folders = (Path.Combine(root, "screenshots"), Path.Combine(root, "baselines"), Path.Combine(root, "diff"));
|
||||
Directory.CreateDirectory(folders.Item1);
|
||||
Directory.CreateDirectory(folders.Item2);
|
||||
return folders;
|
||||
}
|
||||
|
||||
private static DiffReport Run(string captured, string baseline, string output, StringWriter log, int tolerance = DefaultTolerance, double maxDiff = DefaultMaxDiff) =>
|
||||
ScreenshotsCommand.Diff(new DiffOptions(captured, baseline, output, tolerance, maxDiff), log, annotate: true, stepSummary: null);
|
||||
|
||||
[Test]
|
||||
public void ChangedScreensFailAndNoiseWithinTheToleranceDoesNot()
|
||||
{
|
||||
var (captured, baseline, output) = Folders();
|
||||
foreach (var name in new[] { "library-dark.png", "jobs-dark.png", "about-dark.png", "server-dark.png" }) WriteScreen(baseline, name);
|
||||
WriteScreen(captured, "library-dark.png");
|
||||
// Every pixel a little off: anti-aliasing noise below the per-channel tolerance.
|
||||
WriteScreen(captured, "jobs-dark.png", Shift(Size * Size, DefaultTolerance));
|
||||
// Four pixels clearly off: 0.04 % of the screen, under the 0.05 % allowed.
|
||||
WriteScreen(captured, "about-dark.png", Shift(4, 100));
|
||||
// A whole row moved: 1 % of the screen.
|
||||
WriteScreen(captured, "server-dark.png", Shift(Size, 100));
|
||||
|
||||
using var log = new StringWriter();
|
||||
var report = Run(captured, baseline, output, log);
|
||||
|
||||
Assert.True(report.Fails);
|
||||
Assert.SequenceEqual(new[] { Verdict.Within, Verdict.Same, Verdict.Same, Verdict.Changed }, report.Screens.Select(s => s.Verdict));
|
||||
Assert.SequenceEqual(new[] { "about-dark.png", "jobs-dark.png", "library-dark.png", "server-dark.png" }, report.Screens.Select(s => s.Name));
|
||||
Assert.Equal(Size, report.Screens[3].Differing);
|
||||
Assert.FileExists(Path.Combine(output, "server-dark-diff.png"));
|
||||
Assert.FileExists(Path.Combine(output, "about-dark-diff.png"));
|
||||
Assert.FileMissing(Path.Combine(output, "library-dark-diff.png"));
|
||||
Assert.Contains("::error title=Screenshot changed::server-dark.png: 1 %25 of the pixels differ (100; limit 0.05 %25)", log.ToString());
|
||||
Assert.Contains("| server-dark.png | changed | 1 % of the pixels differ (100; limit 0.05 %) |", File.ReadAllText(Path.Combine(output, "summary.md")));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void TheDiffImageShowsTheDifferingPixelsInMagentaOverTheFadedBaseline()
|
||||
{
|
||||
var (captured, baseline, output) = Folders();
|
||||
WriteScreen(baseline, "a.png");
|
||||
WriteScreen(captured, "a.png", Shift(Size, 100));
|
||||
using var log = new StringWriter();
|
||||
Run(captured, baseline, output, log);
|
||||
|
||||
var diff = ScreenshotsCommand.Read(Path.Combine(output, "a-diff.png"));
|
||||
Assert.Equal(Size, diff.Width);
|
||||
Assert.SequenceEqual(new byte[] { 255, 0, 255, 255 }, diff.Pixels[..4], "a differing pixel");
|
||||
var panel = ((40 * Size) + 50) * 4;
|
||||
var background = ((90 * Size) + 50) * 4;
|
||||
Assert.Greater(diff.Pixels[panel], diff.Pixels[background], "the baseline's light panel stays lighter than its background");
|
||||
Assert.InRange(diff.Pixels[background], 112, 207);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void BeforeTheFirstBaselinesTheRunWarnsThatItComparedNothing()
|
||||
{
|
||||
var (captured, baseline, output) = Folders();
|
||||
WriteScreen(captured, "welcome-dark.png");
|
||||
WriteScreen(captured, "about-dark.png");
|
||||
// A README is not a baseline: the folder as committed before the first screens are accepted.
|
||||
File.WriteAllText(Path.Combine(baseline, "README.md"), "# Screenshot baselines");
|
||||
foreach (var folder in new[] { baseline, Path.Combine(baseline, "not-there") })
|
||||
{
|
||||
using var log = new StringWriter();
|
||||
var report = Run(captured, folder, output, log);
|
||||
|
||||
Assert.False(report.Fails);
|
||||
Assert.False(report.Armed);
|
||||
Assert.True(report.Screens.All(s => s.Verdict == Verdict.New));
|
||||
Assert.Contains("::warning title=No screenshot baselines::The baseline folder holds no PNG: nothing was compared, and no visual change can fail " +
|
||||
"this step until baselines are committed. 2 screenshot(s) without a baseline (about-dark.png, welcome-dark.png);", log.ToString());
|
||||
Assert.False(log.ToString().Contains("::error", StringComparison.Ordinal));
|
||||
Assert.Contains("0 compared", log.ToString());
|
||||
Assert.Contains("**The baseline folder holds no PNG: nothing was compared", File.ReadAllText(Path.Combine(output, "summary.md")));
|
||||
}
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void OnceAnyBaselineExistsAScreenWithoutOneFails()
|
||||
{
|
||||
var (captured, baseline, output) = Folders();
|
||||
WriteScreen(baseline, "library-dark.png");
|
||||
WriteScreen(captured, "library-dark.png");
|
||||
// A screen added after the baselines were committed, whose baseline nobody accepted.
|
||||
WriteScreen(captured, "library-new-dark.png");
|
||||
using var log = new StringWriter();
|
||||
var report = Run(captured, baseline, output, log);
|
||||
|
||||
Assert.True(report.Armed);
|
||||
Assert.True(report.Fails);
|
||||
Assert.SequenceEqual(new[] { Verdict.Same, Verdict.Unbased }, report.Screens.Select(s => s.Verdict));
|
||||
Assert.Contains("::error title=Screenshot without baseline::library-new-dark.png: no baseline, while other screens have one (screenshots accept adds it)", log.ToString());
|
||||
Assert.False(log.ToString().Contains("::warning", StringComparison.Ordinal), "the not-compared warning belongs to a run before the first baselines");
|
||||
Assert.Contains("1 compared: 1 within tolerance, 0 changed; 1 without a baseline; 0 missing.", log.ToString());
|
||||
Assert.False(File.ReadAllText(Path.Combine(output, "summary.md")).Contains("holds no PNG", StringComparison.Ordinal));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void AResizedScreenAndABaselineWithoutItsScreenFail()
|
||||
{
|
||||
var (captured, baseline, output) = Folders();
|
||||
WriteScreen(baseline, "settings-dark.png");
|
||||
WriteScreen(baseline, "setup-failed-dark.png");
|
||||
WriteScreen(captured, "settings-dark.png", width: Size + 1);
|
||||
using var log = new StringWriter();
|
||||
var report = Run(captured, baseline, output, log);
|
||||
|
||||
Assert.SequenceEqual(new[] { Verdict.Resized, Verdict.Missing }, report.Screens.Select(s => s.Verdict));
|
||||
Assert.True(report.Screens.All(s => s.Fails));
|
||||
Assert.Contains("settings-dark.png: 101×100, baseline 100×100", log.ToString());
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void ThePerChannelToleranceIsInclusive()
|
||||
{
|
||||
var expected = new Picture(2, 1, [10, 10, 10, 255, 10, 10, 10, 255]);
|
||||
var actual = new Picture(2, 1, [18, 10, 10, 255, 10, 10, 10, 247]);
|
||||
Assert.Equal(0L, ScreenshotsCommand.Compare(expected, actual, tolerance: 8).Differing);
|
||||
Assert.Equal(2L, ScreenshotsCommand.Compare(expected, actual, tolerance: 7).Differing, "alpha counts like a colour");
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void TheCommandExitsWithOneOnAChangeAndAcceptCopiesTheBaselines()
|
||||
{
|
||||
var (captured, baseline, output) = Folders();
|
||||
WriteScreen(baseline, "a.png");
|
||||
WriteScreen(captured, "a.png", Shift(Size * 2, 120));
|
||||
WriteScreen(captured, "b.png");
|
||||
using var log = new StringWriter();
|
||||
int Run(params string[] args) => ScreenshotsCommand.Run(args, _ => null, log);
|
||||
|
||||
Assert.Equal(1, Run("diff", captured, "--baseline", baseline, "--out", output, "--tolerance", "8", "--max-diff", "0.001"));
|
||||
// a.png is now within the limit, but b.png still has no baseline beside a.png's.
|
||||
Assert.Equal(1, Run("diff", captured, "--baseline", baseline, "--out", output, "--max-diff", "0.05"));
|
||||
Assert.FileExists(Path.Combine(output, "a-diff.png"));
|
||||
File.Copy(Path.Combine(captured, "b.png"), Path.Combine(baseline, "b.png"));
|
||||
Assert.Equal(0, Run("diff", captured, "--baseline", baseline, "--out", output, "--max-diff", "0.05"));
|
||||
Assert.Equal(0, Run("accept", captured, "--baseline", baseline));
|
||||
Assert.FileExists(Path.Combine(baseline, "b.png"));
|
||||
Assert.Equal(0, Run("diff", captured, "--baseline", baseline, "--out", output));
|
||||
// The diff of the earlier run is removed with the change it showed.
|
||||
Assert.FileMissing(Path.Combine(output, "a-diff.png"));
|
||||
Assert.False(log.ToString().Contains("::", StringComparison.Ordinal), "no workflow commands outside a workflow run");
|
||||
Assert.Throws<ToolException>(() => Run("diff", captured, "--baseline", baseline, "--tolerance", "300"));
|
||||
Assert.Throws<ToolException>(() => Run("compare", captured));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,102 @@
|
||||
using Chronos.Testing;
|
||||
|
||||
namespace Chronos.Tools.Tests;
|
||||
|
||||
/// <summary>
|
||||
/// The in-house runner reports what a test class did, not how reflection called it (BRIEF §20.1). The nested classes
|
||||
/// are fixtures: assembly discovery leaves them out, and each test hands one to the runner.
|
||||
/// </summary>
|
||||
public sealed class TestRunnerTests(TestContext context)
|
||||
{
|
||||
public sealed class SkippingConstructor
|
||||
{
|
||||
public SkippingConstructor() => TestContext.Skip("no server configured");
|
||||
|
||||
[Test]
|
||||
public void Body() => Assert.Fail("the body ran after the constructor skipped");
|
||||
}
|
||||
|
||||
public sealed class FailingConstructor
|
||||
{
|
||||
public FailingConstructor(TestContext context) => Assert.Fail($"{context.TestName} could not start its fixture");
|
||||
|
||||
[Test]
|
||||
public void Body() => Assert.Fail("the body ran after the constructor failed");
|
||||
}
|
||||
|
||||
public sealed class ThrowingFieldInitializer
|
||||
{
|
||||
private readonly string _root = Environment.GetEnvironmentVariable("CHRONOS_NO_SUCH_VARIABLE") ?? throw new InvalidOperationException("no root folder");
|
||||
|
||||
[Test]
|
||||
public void Body() => Assert.Fail("the body ran with " + _root);
|
||||
}
|
||||
|
||||
public sealed class BesideOthers
|
||||
{
|
||||
[Test]
|
||||
public async Task SeesItsOwnContext(TestContext context)
|
||||
{
|
||||
Assert.Same(context, TestContext.Current);
|
||||
Assert.False(context.IsSerial);
|
||||
await Task.Yield();
|
||||
Assert.Same(context, await Task.Run(() => TestContext.Current));
|
||||
}
|
||||
}
|
||||
|
||||
[Serial]
|
||||
public sealed class Alone
|
||||
{
|
||||
[Test]
|
||||
public void KnowsItRunsAlone(TestContext context) => Assert.True(context.IsSerial && TestContext.Current == context);
|
||||
}
|
||||
|
||||
private static async Task<TestResult> RunAsync<T>()
|
||||
{
|
||||
var test = TestRunner.Discover(typeof(T)).Single();
|
||||
return await TestRunner.ExecuteAsync(test);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void NestedFixturesAreNotDiscoveredWithTheAssembly()
|
||||
{
|
||||
var names = TestRunner.Discover(typeof(TestRunnerTests).Assembly).Select(t => t.FullName).ToList();
|
||||
Assert.Contains(typeof(TestRunnerTests).FullName + "." + nameof(NestedFixturesAreNotDiscoveredWithTheAssembly), names);
|
||||
Assert.False(names.Any(n => n.Contains('+', StringComparison.Ordinal)), "a nested class would run as a real test");
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task ASkipInTheConstructorSkipsTheTest()
|
||||
{
|
||||
var result = await RunAsync<SkippingConstructor>();
|
||||
Assert.Equal(TestOutcome.Skipped, result.Outcome);
|
||||
Assert.Equal("no server configured", result.Message);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task AFailureInTheConstructorKeepsItsMessage()
|
||||
{
|
||||
var result = await RunAsync<FailingConstructor>();
|
||||
Assert.Equal(TestOutcome.Failed, result.Outcome);
|
||||
Assert.Equal(typeof(FailingConstructor).FullName + ".Body could not start its fixture", result.Message);
|
||||
Assert.Contains(nameof(FailingConstructor), result.StackTrace);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task AnExceptionInAFieldInitializerIsReportedAsItself()
|
||||
{
|
||||
var result = await RunAsync<ThrowingFieldInitializer>();
|
||||
Assert.Equal(TestOutcome.Failed, result.Outcome);
|
||||
Assert.Equal("System.InvalidOperationException: no root folder", result.Message);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task TheCurrentContextFollowsEachTestAndItsTasks()
|
||||
{
|
||||
var parallel = await RunAsync<BesideOthers>();
|
||||
Assert.Equal(TestOutcome.Passed, parallel.Outcome, parallel.Message);
|
||||
var alone = await RunAsync<Alone>();
|
||||
Assert.Equal(TestOutcome.Passed, alone.Outcome, alone.Message);
|
||||
Assert.Same(context, TestContext.Current);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,18 @@
|
||||
using Chronos.Testing;
|
||||
|
||||
namespace Chronos.Tools.Tests;
|
||||
|
||||
/// <summary>Time budgets stretch only by an explicit factor of at least 1 (BRIEF §20.1, amended 2026-10-23, R3).</summary>
|
||||
public sealed class TestTimingTests
|
||||
{
|
||||
[Theory]
|
||||
[Case("3", 3.0)]
|
||||
[Case("1.5", 1.5)]
|
||||
[Case(null, 1.0)]
|
||||
[Case("", 1.0)]
|
||||
[Case("0.5", 1.0)]
|
||||
[Case("fast", 1.0)]
|
||||
[Case("Infinity", 1.0)]
|
||||
public void TheFactorIsReadInvariantlyAndNeverShrinksABudget(string? value, double expected) =>
|
||||
Assert.Equal(expected, TestTiming.Parse(value));
|
||||
}
|
||||
@@ -0,0 +1,36 @@
|
||||
using System.IO.Compression;
|
||||
using Chronos.Testing;
|
||||
using Chronos.Tools.Commands;
|
||||
|
||||
namespace Chronos.Tools.Tests;
|
||||
|
||||
/// <summary>zip writes the release archives without a zip program (BRIEF §19.3, amended 2026-10-23, R3).</summary>
|
||||
public sealed class ZipCommandTests(TestContext context)
|
||||
{
|
||||
[Test]
|
||||
public void TheArchiveHoldsTheFolderContentsWithSortedForwardSlashNames()
|
||||
{
|
||||
var root = context.CreateTempDirectory("zip");
|
||||
var folder = Directory.CreateDirectory(Path.Combine(root, "portable")).FullName;
|
||||
File.WriteAllText(Path.Combine(folder, "portable.txt"), "portable");
|
||||
Directory.CreateDirectory(Path.Combine(folder, "data", "logs"));
|
||||
File.WriteAllBytes(Path.Combine(folder, "data", "logs", "a.log"), [1, 2, 3]);
|
||||
File.WriteAllBytes(Path.Combine(folder, "Chronos.exe"), [0x4D, 0x5A]);
|
||||
var output = Path.Combine(root, "release", "Chronos-portable.zip");
|
||||
|
||||
Assert.Equal(3, ZipCommand.Create(folder, output));
|
||||
|
||||
using var zip = ZipFile.OpenRead(output);
|
||||
Assert.SequenceEqual(["Chronos.exe", "data/logs/a.log", "portable.txt"], zip.Entries.Select(e => e.FullName));
|
||||
using var reader = new StreamReader(zip.GetEntry("portable.txt")!.Open());
|
||||
Assert.Equal("portable", reader.ReadToEnd());
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void AnArchiveInsideTheZippedFolderOrAMissingFolderIsRefused()
|
||||
{
|
||||
var root = context.CreateTempDirectory("zip");
|
||||
Assert.Throws<ToolException>(() => ZipCommand.Create(root, Path.Combine(root, "self.zip")));
|
||||
Assert.Throws<ToolException>(() => ZipCommand.Create(Path.Combine(root, "missing"), Path.Combine(root, "out.zip")));
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user