Files
Chronos/tests/Chronos.App.Tests/Workspace/WorkspaceMoveTests.cs
T
Alby96andClaude Opus 5.5 db389a54f2
CI / Build and test (push) Successful in 9m26s
CI / Windows tests and installer (push) Skipped
CI / YAML check (push) Successful in 8s
Release / Build, test and publish (push) Successful in 14m31s
CI / PostgreSQL 16 integration (push) Successful in 9m53s
CI / PostgreSQL 17 integration (push) Successful in 9m22s
CI / Docker image (push) Successful in 44s
Release / Server image (push) Successful in 1m36s
feat: owner review 2 phase 5c: originals, local render, clean-up and the workspace settings (#18)
Originals in the workspace, local render and send home with provenance, the workspace clean-up, size limit and trash, moving the workspace folder, and the complete Settings › Workspace page (owner review 2, R8, phase 5c). One adversarial review round (35 findings, 32 fixed), a copy-cancel race fixed, 184 strings in all 38 languages.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Co-authored-by: Alberto Balbo <alberto.balbo.96@gmail.com>
2026-11-04 20:03:52 +01:00

225 lines
12 KiB
C#
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
using System.Globalization;
using System.IO;
using Chronos.App.Infrastructure;
using Chronos.App.Workspace;
using Chronos.Core.Localization;
using Chronos.Core.Model;
using Chronos.Data;
using Chronos.Data.Archiving;
using Chronos.Data.Jobs;
using Chronos.Data.Workspaces;
using Chronos.Testing;
namespace Chronos.App.Tests.Workspace;
/// <summary>
/// Settings › Workspace › Move… (phase 5c, P6) as the desktop runs it: the plan and its confirmation, the open project
/// closed first, the workspace held while the move waits or runs, the setting switched only once the move verified
/// everything, a failed move that leaves both as they were, and a move stopped before it ended taken up again.
/// </summary>
[Category("workspace")]
public sealed class WorkspaceMoveTests(TestContext context)
{
static WorkspaceMoveTests() => Loc.SetCulture(CultureInfo.GetCultureInfo("en"));
[Test]
public async Task TheWorkspaceWaitsForTheMoveAndFollowsTheFolderOnlyOnceItEnded()
{
await using var bed = await WorkspaceTestBed.CreateAsync(context, frames: 4);
var settings = new AppSettings();
var mainId = await bed.CheckoutAsync(bed.Host(settings));
await using var moves = await MovesAsync(bed, settings);
var host = moves.Host;
var from = host.Root;
var target = Path.Combine(bed.Directory, "moved workspace");
var plan = await host.PlanMoveAsync(target);
Assert.True(plan.CanMove, plan.Refusal);
Assert.Equal((from, Path.GetFullPath(target), true), (plan.From, plan.To, plan.SameVolume));
var project = Assert.NotNull(plan.Projects.SingleOrDefault());
Assert.Equal(mainId, project.ProjectId);
Assert.True(plan.Files >= project.Files && project.Files > 0 && plan.Bytes > 0);
var failures = new List<string>();
var closes = 0;
var close = true;
Task<bool> CloseProject()
{
closes++;
return Task.FromResult(close);
}
// Declined, or the open project kept open: nothing is queued.
var dialogs = new MoveDialogs { Folder = target, Answer = false };
Assert.False(await WorkspaceFolderChange.MoveAsync(host, dialogs, CloseProject, failures.Add));
var asked = Assert.NotNull(dialogs.Asked.SingleOrDefault());
Assert.Equal(Loc.L("Settings.Workspace.MovePlan.Message", plan.From, plan.To), asked.Message);
Assert.Contains(Loc.L("Settings.Workspace.MovePlan.Projects", Formatting.Count(1)), asked.Detail);
Assert.Contains(Loc.L("Settings.Workspace.MovePlan.SameVolume"), asked.Detail);
Assert.True(asked is { IsDestructive: false, ActionText.Length: > 0, ActionToolTip.Length: > 0, SafeToolTip.Length: > 0 });
Assert.Equal(0, closes, "nothing closed before the plan is confirmed");
dialogs.Answer = true;
close = false;
Assert.False(await WorkspaceFolderChange.MoveAsync(host, dialogs, CloseProject, failures.Add));
Assert.False(host.IsMoving);
// Queued: until it ends the workspace opens, copies, syncs and changes folder no more, and is not moved twice.
close = true;
Assert.True(await WorkspaceFolderChange.MoveAsync(host, dialogs, CloseProject, failures.Add));
Assert.Empty(failures);
Assert.True(host.IsMoving);
var moving = Loc.L("Errors.Workspace.Moving");
Assert.Equal(moving, (await Assert.ThrowsAsync<WorkspaceException>(() => host.FindAsync(mainId))).Message);
Assert.Equal(moving, (await Assert.ThrowsAsync<WorkspaceException>(() => host.ProjectsOfAsync(bed.SequenceId))).Message);
Assert.Equal(moving, (await Assert.ThrowsAsync<WorkspaceException>(() => host.SyncAsync(mainId))).Message);
Assert.Equal(moving, (await Assert.ThrowsAsync<WorkspaceException>(() => host.QueueCopyAsync(mainId))).Message);
Assert.Equal(moving, (await Assert.ThrowsAsync<WorkspaceException>(() => host.CheckoutAsync(bed.SequenceId, mainId, null))).Message);
Assert.Equal(moving, (await Assert.ThrowsAsync<WorkspaceException>(() => host.UseFolderAsync(Path.Combine(bed.Directory, "elsewhere")))).Message);
Assert.False(await WorkspaceFolderChange.MoveAsync(host, dialogs, CloseProject, failures.Add));
Assert.SequenceEqual([moving], failures);
Assert.Equal(((string?)null, 0), (settings.WorkspaceFolder, moves.Saves), "the setting waits for the move");
await moves.Engine.StartAsync(context.Cancellation);
var job = Assert.NotNull((await moves.Db.Jobs.ListAsync(null, JobKind.WorkspaceMove, 5, cancellationToken: context.Cancellation)).Items.SingleOrDefault());
await moves.WaitAsync(job.Id, JobState.Done);
await WorkspaceTestBed.UntilAsync(() => !host.IsMoving, "the workspace is let go");
Assert.Equal((Path.GetFullPath(target), 1), (settings.WorkspaceFolder, moves.Saves));
Assert.Equal(Path.GetFullPath(target), host.Root);
Assert.Equal(mainId, Assert.NotNull(await host.FindAsync(mainId)).ProjectId);
Assert.Equal(mainId, (await host.ListAsync()).Single().ProjectId);
Assert.False(Directory.Exists(Path.Combine(from, mainId.ToString("N"))), "the project left the folder");
}
[Test]
public async Task AMoveThatFailsLeavesTheSettingAndTheWorkspaceWhereTheyWere()
{
await using var bed = await WorkspaceTestBed.CreateAsync(context, frames: 4);
var settings = new AppSettings();
var mainId = await bed.CheckoutAsync(bed.Host(settings));
await using var moves = await MovesAsync(bed, settings);
var host = moves.Host;
var from = host.Root;
var target = Path.Combine(bed.Directory, "target");
// A workspace job waiting refuses the plan.
var copy = await moves.Engine.EnqueueAsync(JobKind.WorkspaceCopy, [bed.SequenceId], "copy", null, cancellationToken: context.Cancellation);
Assert.Equal(Loc.L("Errors.Workspace.JobsRunning"), (await host.PlanMoveAsync(target)).Refusal);
await moves.Engine.CancelAsync(copy.Id, context.Cancellation);
var plan = await host.PlanMoveAsync(target);
await host.QueueMoveAsync(plan);
// Meanwhile the target became a workspace of its own: the job refuses it.
_ = new WorkspaceStore(target);
await moves.Engine.StartAsync(context.Cancellation);
var job = Assert.NotNull((await moves.Db.Jobs.ListAsync(null, JobKind.WorkspaceMove, 5, cancellationToken: context.Cancellation)).Items.SingleOrDefault());
var failed = await moves.WaitAsync(job.Id, JobState.Failed);
Assert.Equal(Loc.L("Errors.Workspace.MoveTargetNotEmpty", Path.GetFullPath(target)), failed.Error);
await WorkspaceTestBed.UntilAsync(() => !host.IsMoving, "the workspace is let go");
Assert.Equal(((string?)null, 0, from), (settings.WorkspaceFolder, moves.Saves, host.Root));
Assert.Equal(mainId, Assert.NotNull(await host.FindAsync(mainId)).ProjectId);
Assert.Empty(new WorkspaceStore(target).List());
}
[Test]
public async Task AMoveStoppedBeforeItEndedIsOfferedAgainAndGoesOn()
{
await using var bed = await WorkspaceTestBed.CreateAsync(context, frames: 4);
var settings = new AppSettings();
var mainId = await bed.CheckoutAsync(bed.Host(settings));
await using var moves = await MovesAsync(bed, settings);
var host = moves.Host;
var from = host.Root;
var target = Path.Combine(bed.Directory, "target");
// The program closed as the move began: its journal is in the folder, and no job waits for it.
var plan = await host.PlanMoveAsync(target);
using (var closed = new CancellationTokenSource())
{
await closed.CancelAsync();
await Assert.ThrowsAsync<OperationCanceledException>(() => new WorkspaceMover(from, target).MoveAsync(plan.Fingerprint, cancellationToken: closed.Token));
}
Assert.True(host.IsMoving, "a journal holds the workspace");
Assert.Equal(Loc.L("Errors.Workspace.Moving"), (await Assert.ThrowsAsync<WorkspaceException>(() => host.FindAsync(mainId))).Message);
var journal = Assert.NotNull(await host.UnfinishedMoveAsync());
Assert.Equal((Path.GetFullPath(target), WorkspaceMoveStage.Moving), (journal.To, journal.Stage));
var job = await host.ResumeMoveAsync(journal);
Assert.Null(await host.UnfinishedMoveAsync());
await moves.Engine.StartAsync(context.Cancellation);
var done = await moves.WaitAsync(job.Id, JobState.Done);
Assert.Contains(Loc.L("Archive.Log.WorkspaceMoveResumed", Path.Combine(from, WorkspaceMover.JournalFile)), done.LogTail);
await WorkspaceTestBed.UntilAsync(() => !host.IsMoving, "the workspace is let go");
Assert.Equal(Path.GetFullPath(target), settings.WorkspaceFolder);
Assert.Equal(mainId, Assert.NotNull(await host.FindAsync(mainId)).ProjectId);
Assert.Null(await host.UnfinishedMoveAsync());
}
/// <summary>
/// A workspace over the bed's folder whose move jobs run on an engine of their own (over an index of their own, so the
/// bed's engine never takes them), which tells the workspace once a move ended; the engine is started by the test.
/// </summary>
private async Task<Moves> MovesAsync(WorkspaceTestBed bed, AppSettings settings)
{
var db = await ChronosDatabase.OpenAsync(DatabaseOptions.Sqlite(Path.Combine(context.CreateTempDirectory("moves"), "index.db")), context.Cancellation);
var moves = new Moves(db);
var options = new WorkspaceJobOptions(WorkspaceJobOptions.For(bed.Archives).Processing, () => false, (f, t) => moves.Host.MovedAsync(f, t));
moves.Engine = new JobEngine(db, WorkspaceJobs.CreateHandlers(db, bed.Archives, null, options),
new JobEngineOptions { Workers = 1, WorkerId = "moves", PollInterval = TimeSpan.FromMilliseconds(50), CheckpointInterval = TimeSpan.FromMilliseconds(50) });
moves.Host = new WorkspaceHost(bed.Environment, settings, () => moves.Saves++, () => db, () => bed.Archives, () => moves.Engine)
{
LockWait = TimeSpan.FromSeconds(TestTiming.Budget(10)),
};
return moves;
}
private sealed class Moves(ChronosDatabase db) : IAsyncDisposable
{
public ChronosDatabase Db { get; } = db;
public JobEngine Engine { get; set; } = null!;
public WorkspaceHost Host { get; set; } = null!;
public int Saves { get; set; }
public async Task<Job> WaitAsync(Guid jobId, JobState expected)
{
var deadline = DateTime.UtcNow + TimeSpan.FromSeconds(TestTiming.Budget(60));
while (true)
{
var job = await Db.Jobs.GetAsync(jobId);
if (job is { State: JobState.Done or JobState.Failed or JobState.Cancelled })
{
Assert.Equal(expected, job.State, job.Error ?? job.LogTail);
return job;
}
if (DateTime.UtcNow > deadline) Assert.Fail($"Job {jobId} still {job?.State} after its time budget");
await Task.Delay(50);
}
}
public async ValueTask DisposeAsync()
{
await Engine.DisposeAsync();
await Db.DisposeAsync();
}
}
/// <summary>Dialogs that pick <see cref="Folder"/> and answer every confirmation with <see cref="Answer"/>, recording what they were asked.</summary>
private sealed class MoveDialogs : IAppDialogs
{
public string? Folder { get; set; }
public bool Answer { get; set; }
public List<ConfirmRequest> Asked { get; } = [];
public string? PickFolder(string title, string? initialFolder = null) => Folder;
public string? PickJsonFile(string title) => null;
public bool Confirm(ConfirmRequest request)
{
Asked.Add(request);
return Answer;
}
public bool SignIn(string server, string? username, Func<string, string, Task<string?>> signIn) => false;
}
}