Files
Chronos/tests/Chronos.Tools.Tests/GiteaReleaseCommandTests.cs
T
Alby96andClaude Opus 5.5 5f27a86406
CI / Build and test (pull_request) Failing after 2m3s
CI / PostgreSQL 16 integration (pull_request) Skipped
CI / PostgreSQL 17 integration (pull_request) Skipped
CI / Docker image (pull_request) Skipped
CI / Windows tests and installer (pull_request) Skipped
CI / YAML check (pull_request) Successful in 4s
refactor!: rename Titano to Chronos and move CI and releases to Gitea
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. 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) and
  pe-check.

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>
2026-10-23 11:34:48 +02:00

219 lines
12 KiB
C#

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();
}
}