Files
Chronos/tests/Chronos.Data.Tests/Archiving/MassRenameTests.cs
T
Alby96andClaude Opus 5.5 f2b58522b9
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
refactor!: rename Titano to Chronos and move CI and releases to Gitea (#6)
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>
2026-10-23 12:45:18 +02:00

256 lines
14 KiB
C#

using Chronos.Core.Archiving;
using Chronos.Data.Archiving;
using Chronos.Testing;
using static Chronos.Data.Tests.Archiving.ArchiveFixture;
namespace Chronos.Data.Tests.Archiving;
[Category("archive")]
public sealed class MassRenameTests(TestContext context)
{
private static async Task<List<Guid>> PopulateAsync(ArchiveFixture fx)
{
Photos.WriteSeries(Path.Combine(fx.Paths.Root, "inbox", "a"), Start, 3);
Photos.WriteSeries(Path.Combine(fx.Paths.Root, "inbox", "b"), Start.AddDays(1), 3, firstSeed: 10);
Photos.WriteSeries(Path.Combine(fx.Paths.Root, "inbox", "c"), Start.AddDays(2), 3, firstSeed: 20);
await fx.ScanAsync();
return (await fx.Db.Sequences.ListLocationsAsync(fx.Archive.Id)).OrderBy(l => l.Folder).Select(l => l.Id).ToList();
}
/// <summary>Folder, title and every frame path of each sequence as the index and the disk see them.</summary>
private static async Task<List<string>> StateAsync(ArchiveFixture fx, IEnumerable<Guid> ids)
{
var state = new List<string>();
foreach (var id in ids)
{
var s = (await fx.Db.Sequences.GetAsync(id))!;
var sidecar = ManifestStore.ReadSequence(fx.Paths.Sequence(s.Folder).ManifestPath);
Assert.Equal(id, sidecar.Id);
Assert.Equal(s.Title, sidecar.Title);
foreach (var f in await fx.Db.Frames.ListBySequenceAsync(id)) Assert.FileExists(fx.Paths.FromRelative(f.RelativePath));
state.Add($"{s.Folder}|{s.Title}|{string.Join(',', (await fx.Db.Frames.ListBySequenceAsync(id)).Select(f => f.RelativePath))}");
}
return state;
}
private static List<string> Expected(RenamePlan plan, IEnumerable<string> before) =>
before.Select(line =>
{
var folder = line.Split('|')[0];
var step = plan.Steps.SingleOrDefault(s => s.FromFolder == folder);
return step is null ? line : $"{step.ToFolder}|{step.ToTitle}|{line.Split('|')[2].Replace(step.FromFolder + "/", step.ToFolder + "/")}";
}).ToList();
[Test]
public async Task ApplyingAPlanDoesExactlyWhatTheDryRunSaid()
{
await using var fx = await CreateAsync(context);
var ids = await PopulateAsync(fx);
var before = await StateAsync(fx, ids);
var plan = await fx.Service.PlanRenameAsync(fx.Archive.Id, ids, "{year}/{date} {title}", "Trip", fx.Ct);
Assert.SequenceEqual(["2026/2026-09-28 Trip", "2026/2026-09-29 Trip", "2026/2026-09-30 Trip"], plan.Steps.Select(s => s.ToFolder));
Assert.SequenceEqual(before, await StateAsync(fx, ids));
await fx.Service.ApplyRenameAsync(plan, null, fx.Ct);
Assert.SequenceEqual(Expected(plan, before), await StateAsync(fx, ids));
Assert.Empty(RenameJournal.ListPending(fx.Paths));
Assert.False(Directory.Exists(Path.Combine(fx.Paths.Root, "inbox", "a")));
Assert.Equal(0, (await fx.ScanAsync()).Indexed);
}
[Test]
public async Task AnInterruptedRenameResumesFromItsJournal()
{
await using var fx = await CreateAsync(context);
var ids = await PopulateAsync(fx);
var before = await StateAsync(fx, ids);
var plan = await fx.Service.PlanRenameAsync(fx.Archive.Id, ids, "renamed/{date}", null, fx.Ct);
using var cts = new CancellationTokenSource();
await Assert.ThrowsAsync<OperationCanceledException>(() => fx.Service.ApplyRenameAsync(plan, new SyncProgress(_ => cts.Cancel()), cts.Token));
var journal = RenameJournal.ListPending(fx.Paths).Single();
Assert.Count(1, journal.Completed);
// Crash in the middle of the next step: its folder moved, the index not yet updated.
var next = plan.Steps[1];
Directory.CreateDirectory(Path.GetDirectoryName(fx.Paths.FromRelative(next.ToFolder))!);
Directory.Move(fx.Paths.FromRelative(next.FromFolder), fx.Paths.FromRelative(next.ToFolder));
await fx.Service.OpenAsync(fx.Archive.RootPath, fx.Ct); // the next start finds the journal
Assert.Empty(RenameJournal.ListPending(fx.Paths));
Assert.SequenceEqual(Expected(plan, before), await StateAsync(fx, ids));
}
[Test]
public async Task AResumedRenameOnTheSameIndexMatchesThePlan()
{
await using var fx = await CreateAsync(context);
var ids = await PopulateAsync(fx);
var before = await StateAsync(fx, ids);
var plan = await fx.Service.PlanRenameAsync(fx.Archive.Id, ids, "renamed/{date}", "{title} 2026", fx.Ct);
using var cts = new CancellationTokenSource();
await Assert.ThrowsAsync<OperationCanceledException>(() => fx.Service.ApplyRenameAsync(plan, new SyncProgress(_ => cts.Cancel()), cts.Token));
Assert.Equal(1, await fx.Service.Renamer.ResumePendingAsync(fx.Archive, fx.Ct));
Assert.SequenceEqual(Expected(plan, before), await StateAsync(fx, ids));
}
[Test]
public async Task AStalePlanIsRefused()
{
await using var fx = await CreateAsync(context);
var ids = await PopulateAsync(fx);
var plan = await fx.Service.PlanRenameAsync(fx.Archive.Id, [ids[0]], "x/{date}", null, fx.Ct);
var other = await fx.Service.PlanRenameAsync(fx.Archive.Id, [ids[0]], "y/{date}", null, fx.Ct);
await fx.Service.ApplyRenameAsync(other, null, fx.Ct);
await Assert.ThrowsAsync<StaleRenamePlanException>(() => fx.Service.ApplyRenameAsync(plan, null, fx.Ct));
Assert.True(Directory.Exists(fx.Paths.FromRelative(other.Steps[0].ToFolder)));
}
[Test]
public async Task ASequenceIndexedInsideAMovingFolderAfterTheDryRunMakesThePlanStale()
{
await using var fx = await CreateAsync(context);
Photos.WriteSeries(Path.Combine(fx.Paths.Root, "trips"), Start, 2);
await fx.ScanAsync();
var trips = (await fx.Db.Sequences.ListLocationsAsync(fx.Archive.Id)).Single();
var plan = await fx.Service.PlanRenameAsync(fx.Archive.Id, [trips.Id], "moved/{date}", null, fx.Ct);
Assert.Count(1, plan.Steps);
// Photos copied into a subfolder and indexed by the next scan, after the dry run was shown.
Photos.WriteSeries(Path.Combine(fx.Paths.Root, "trips", "day2"), Start.AddDays(1), 2, firstSeed: 10);
await fx.ScanAsync();
var day2 = (await fx.Db.Sequences.ListLocationsAsync(fx.Archive.Id)).Single(l => l.Folder == "trips/day2");
var stale = await Assert.ThrowsAsync<StaleRenamePlanException>(() => fx.Service.ApplyRenameAsync(plan, null, fx.Ct));
Assert.Equal(day2.Id, stale.SequenceId);
Assert.Empty(RenameJournal.ListPending(fx.Paths));
Assert.SequenceEqual(["trips|trips|trips/IMG_0001.JPG,trips/IMG_0002.JPG", "trips/day2|day2|trips/day2/IMG_0001.JPG,trips/day2/IMG_0002.JPG"],
await StateAsync(fx, [trips.Id, day2.Id]));
}
[Test]
public async Task AFolderThatGainedASequenceWhileTheRenameRanStaysWhereItIs()
{
await using var fx = await CreateAsync(context);
var ids = await PopulateAsync(fx);
var plan = await fx.Service.PlanRenameAsync(fx.Archive.Id, [ids[0], ids[1]], "renamed/{date}", null, fx.Ct);
Assert.SequenceEqual(["inbox/a", "inbox/b"], plan.Steps.Select(s => s.FromFolder));
// Once the first folder moved, a scan indexes photos copied into the second one.
var late = Path.Combine(fx.Paths.Root, "inbox", "b", "late");
var progress = new SyncProgress(done =>
{
if (done != 1) return;
Photos.WriteSeries(late, Start.AddDays(5), 2, firstSeed: 40);
fx.ScanAsync().GetAwaiter().GetResult();
});
await Assert.ThrowsAsync<StaleRenamePlanException>(() => fx.Service.ApplyRenameAsync(plan, progress, fx.Ct));
var newcomer = (await fx.Db.Sequences.ListLocationsAsync(fx.Archive.Id)).Single(l => l.Folder == "inbox/b/late");
Assert.True(Directory.Exists(late), "the folder did not move");
Assert.Count(1, RenameJournal.ListPending(fx.Paths).Single().Completed);
// Resumed, the rest of the plan runs but that step is dropped: every index row still names its files.
Assert.Equal(1, await fx.Service.Renamer.ResumePendingAsync(fx.Archive, fx.Ct));
Assert.Empty(RenameJournal.ListPending(fx.Paths));
var state = await StateAsync(fx, [ids[0], ids[1], newcomer.Id]);
Assert.SequenceEqual(["renamed/2026-09-28", "inbox/b", "inbox/b/late"], state.Select(s => s.Split('|')[0]));
Assert.Equal(0, (await fx.ScanAsync()).Indexed);
}
/// <summary>"trips" with photos of its own, "trips/day2" inside it and "trips/day2/dawn" inside that: three nested sequences.</summary>
private static async Task<List<Guid>> NestedAsync(ArchiveFixture fx)
{
Photos.WriteSeries(Path.Combine(fx.Paths.Root, "trips"), Start, 2);
Photos.WriteSeries(Path.Combine(fx.Paths.Root, "trips", "day2"), Start.AddDays(1), 2, firstSeed: 10);
Photos.WriteSeries(Path.Combine(fx.Paths.Root, "trips", "day2", "dawn"), Start.AddDays(2), 2, firstSeed: 20);
await fx.ScanAsync();
var locations = (await fx.Db.Sequences.ListLocationsAsync(fx.Archive.Id)).OrderBy(l => l.Folder, StringComparer.Ordinal).ToList();
Assert.SequenceEqual(["trips", "trips/day2", "trips/day2/dawn"], locations.Select(l => l.Folder));
return [.. locations.Select(l => l.Id)];
}
[Test]
public async Task SequencesInsideAMovedFolderAreInTheDryRunAndMoveWithIt()
{
await using var fx = await CreateAsync(context);
var ids = await NestedAsync(fx);
var before = await StateAsync(fx, ids);
var plan = await fx.Service.PlanRenameAsync(fx.Archive.Id, [ids[0]], "moved/{date}", null, fx.Ct);
Assert.SequenceEqual(["moved/2026-09-28", "moved/2026-09-28/day2", "moved/2026-09-28/day2/dawn"], plan.Steps.Select(s => s.ToFolder));
Assert.SequenceEqual([false, true, true], plan.Steps.Select(s => s.Carried));
Assert.SequenceEqual(before, await StateAsync(fx, ids));
await fx.Service.ApplyRenameAsync(plan, null, fx.Ct);
Assert.SequenceEqual(Expected(plan, before), await StateAsync(fx, ids));
Assert.Empty(RenameJournal.ListPending(fx.Paths));
Assert.Equal(0, (await fx.ScanAsync()).Indexed);
Assert.Empty((await fx.Service.FindOrphansAsync(fx.Archive.Id, fx.Ct)).MissingSequences);
}
[Test]
public async Task AFolderMovesOnceTheWritersOfTheSequencesInsideAreDone()
{
await using var fx = await CreateAsync(context);
var ids = await NestedAsync(fx);
var before = await StateAsync(fx, ids);
var plan = await fx.Service.PlanRenameAsync(fx.Archive.Id, [ids[0]], "moved/{date}", null, fx.Ct);
// An ingest into trips/day2 holds that sequence's lease; a thumbnail pass of trips/day2/dawn holds its pack's.
Task apply;
using (await LeaseFile.AcquireAsync(fx.Paths.LocksDirectory, $"seq-{ids[1]:N}", "ingest", TimeSpan.FromSeconds(5), cancellationToken: fx.Ct))
using (await LeaseFile.AcquireAsync(fx.Paths.LocksDirectory, $"thumbs-{ids[2]:N}", "thumbnails", TimeSpan.FromSeconds(5), cancellationToken: fx.Ct))
{
apply = fx.Service.ApplyRenameAsync(plan, null, fx.Ct);
await Task.Delay(500, fx.Ct);
Assert.False(apply.IsCompleted);
Assert.True(Directory.Exists(Path.Combine(fx.Paths.Root, "trips", "day2", "dawn")), "nothing moved while they write");
}
await apply;
Assert.SequenceEqual(Expected(plan, before), await StateAsync(fx, ids));
Assert.Empty(RenameJournal.ListPending(fx.Paths));
}
[Test]
public async Task NestedSequencesMovedTogetherLeaveTheirFolderFirst()
{
await using var fx = await CreateAsync(context);
var ids = await NestedAsync(fx);
var before = await StateAsync(fx, ids);
var plan = await fx.Service.PlanRenameAsync(fx.Archive.Id, ids, "moved/{date}", null, fx.Ct);
Assert.SequenceEqual([ids[2], ids[1], ids[0]], plan.Steps.Select(s => s.SequenceId));
Assert.True(plan.Steps.All(s => !s.Carried));
await fx.Service.ApplyRenameAsync(plan, null, fx.Ct);
Assert.SequenceEqual(["moved/2026-09-28", "moved/2026-09-29", "moved/2026-09-30"], (await fx.Db.Sequences.ListLocationsAsync(fx.Archive.Id))
.Select(l => l.Folder).Order(StringComparer.Ordinal));
Assert.SequenceEqual(Expected(plan, before), await StateAsync(fx, ids));
// The folders a nested sequence moved out of changed after their rows were written, as a folder another process
// changed would: the next scan reads those two again, and finds the index as it is.
Assert.SequenceEqual([ids[0], ids[1]], (await fx.ScanAsync()).Sequences);
Assert.SequenceEqual(Expected(plan, before), await StateAsync(fx, ids));
Assert.Equal(0, (await fx.ScanAsync()).Indexed);
}
[Test]
public async Task AFolderInsideASequenceFolderIsRefused()
{
await using var fx = await CreateAsync(context);
var ids = await PopulateAsync(fx);
var before = await StateAsync(fx, ids);
var into = await Assert.ThrowsAsync<NestedRenameException>(() => fx.Service.PlanRenameAsync(fx.Archive.Id, [ids[1]], "inbox/a/{date}", null, fx.Ct));
Assert.Equal("inbox/a", into.Folder);
var itself = await Assert.ThrowsAsync<NestedRenameException>(() => fx.Service.PlanRenameAsync(fx.Archive.Id, [ids[0]], "inbox/a/{date}", null, fx.Ct));
Assert.Equal("inbox/a/2026-09-28", itself.Target);
Assert.SequenceEqual(before, await StateAsync(fx, ids));
}
/// <summary>Reports synchronously (Progress&lt;T&gt; would post to the thread pool).</summary>
private sealed class SyncProgress(Action<int> report) : IProgress<int>
{
public void Report(int value) => report(value);
}
}