CI / Build and test (push) Successful in 11m36s
CI / Windows tests and installer (push) Skipped
CI / YAML check (push) Successful in 12s
Release / Build, test and publish (push) Successful in 14m56s
CI / PostgreSQL 16 integration (push) Successful in 10m11s
CI / PostgreSQL 17 integration (push) Successful in 10m15s
CI / Docker image (push) Successful in 45s
Release / Server image (push) Successful in 4m55s
Co-authored-by: Alberto Balbo <alberto.balbo.96@gmail.com>
241 lines
10 KiB
C#
241 lines
10 KiB
C#
using System.Globalization;
|
|
using System.IO;
|
|
using Chronos.App.Archiving;
|
|
using Chronos.App.Editor;
|
|
using Chronos.App.Infrastructure;
|
|
using Chronos.App.Tests.Editor;
|
|
using Chronos.App.Workspace;
|
|
using Chronos.Core.Archiving;
|
|
using Chronos.Core.Codecs.Jpeg;
|
|
using Chronos.Core.Imaging.Decoders;
|
|
using Chronos.Core.Localization;
|
|
using Chronos.Core.Metadata;
|
|
using Chronos.Core.Model;
|
|
using Chronos.Core.Windows.Shell;
|
|
using Chronos.Data;
|
|
using Chronos.Data.Archiving;
|
|
using Chronos.Data.Jobs;
|
|
using Chronos.Data.Workspaces;
|
|
using Chronos.Testing;
|
|
|
|
namespace Chronos.App.Tests.Workspace;
|
|
|
|
/// <summary>
|
|
/// This PC's archive with one sequence of synthetic photos as the projects' home, its job engine (the workspace copy
|
|
/// registered), and workspaces of the desktop that edit it (owner review 2, R8). No window: the view models run on the
|
|
/// test's thread.
|
|
/// </summary>
|
|
internal sealed class WorkspaceTestBed : IAsyncDisposable
|
|
{
|
|
private readonly TestContext _context;
|
|
|
|
private WorkspaceTestBed(TestContext context, string directory, ChronosDatabase db, ArchiveService archives, JobEngine engine, Guid sequenceId,
|
|
AppEnvironment environment)
|
|
{
|
|
_context = context;
|
|
Directory = directory;
|
|
Db = db;
|
|
Archives = archives;
|
|
Engine = engine;
|
|
SequenceId = sequenceId;
|
|
Environment = environment;
|
|
}
|
|
|
|
static WorkspaceTestBed() => Loc.SetCulture(CultureInfo.GetCultureInfo("en"));
|
|
|
|
public string Directory { get; }
|
|
public ChronosDatabase Db { get; }
|
|
public ArchiveService Archives { get; }
|
|
public JobEngine Engine { get; }
|
|
public Guid SequenceId { get; }
|
|
|
|
/// <summary>An installed copy's environment (not a capture): its data folder under the test's own local app data.</summary>
|
|
public AppEnvironment Environment { get; }
|
|
|
|
public CancellationToken Ct => _context.Cancellation;
|
|
|
|
public static async Task<WorkspaceTestBed> CreateAsync(TestContext context, int frames = 8)
|
|
{
|
|
var directory = context.CreateTempDirectory("workspace-app");
|
|
var root = Path.Combine(directory, "archive");
|
|
var db = await ChronosDatabase.OpenAsync(DatabaseOptions.Sqlite(Path.Combine(directory, "index.db")));
|
|
var archives = new ArchiveService(db, new ArchiveServiceOptions { Owner = "test", LeaseWait = TimeSpan.FromSeconds(TestTiming.Budget(20)) });
|
|
var archive = await archives.CreateAsync(root, "Test");
|
|
var sequence = EditorFixture.Sequence(frames);
|
|
var folder = Path.Combine(root, "Synthetic");
|
|
System.IO.Directory.CreateDirectory(folder);
|
|
for (var i = 0; i < sequence.Count; i++)
|
|
{
|
|
using var image = sequence.Render(i);
|
|
var exif = ExifWriter.BuildJpegApp1(sequence.Metadata[i]);
|
|
File.WriteAllBytes(Path.Combine(folder, $"IMG_{i + 1:0000}.JPG"), JpegEncoder.Encode(image, new JpegEncodeOptions { Quality = 90, App1Segments = [exif[4..]] }));
|
|
}
|
|
await archives.Indexer.ScanAsync(archive, ScanMode.Full, null, _ => ValueTask.CompletedTask, context.Cancellation);
|
|
var sequenceId = (await db.Sequences.ListLocationsAsync(archive.Id, context.Cancellation)).Single().Id;
|
|
var engine = new JobEngine(db, [.. archives.CreateJobHandlers(), .. WorkspaceJobs.CreateHandlers(db, archives)],
|
|
new JobEngineOptions { Workers = 1, WorkerId = "test", PollInterval = TimeSpan.FromMilliseconds(50), CheckpointInterval = TimeSpan.FromMilliseconds(50) });
|
|
await engine.StartAsync(context.Cancellation);
|
|
var app = System.IO.Directory.CreateDirectory(Path.Combine(directory, "app")).FullName;
|
|
var local = System.IO.Directory.CreateDirectory(Path.Combine(directory, "local")).FullName;
|
|
var environment = AppEnvironment.From(AppPaths.Resolve(app, local, []));
|
|
return new WorkspaceTestBed(context, directory, db, archives, engine, sequenceId, environment);
|
|
}
|
|
|
|
/// <summary>A workspace of this PC (in its own folder when <paramref name="name"/> is given: another PC's, for conflicts).</summary>
|
|
public WorkspaceHost Host(AppSettings? settings = null, string? name = null)
|
|
{
|
|
settings ??= new AppSettings();
|
|
if (name is not null) settings.WorkspaceFolder = Path.Combine(Directory, name);
|
|
return new WorkspaceHost(Environment, settings, () => { }, () => Db, () => Archives, () => Engine) { LockWait = TimeSpan.FromSeconds(TestTiming.Budget(10)) };
|
|
}
|
|
|
|
/// <summary>The sequence's row in the index now.</summary>
|
|
public async Task<Sequence> RowAsync() => (await Db.Sequences.GetAsync(SequenceId))!;
|
|
|
|
/// <summary>A photo taken before the others added to the sequence at its home (as an import of earlier photos does): every frame moves one place.</summary>
|
|
public async Task InsertEarlierFrameAsync()
|
|
{
|
|
var row = await RowAsync();
|
|
var archive = (await Db.Archives.GetAsync(row.ArchiveId))!;
|
|
var synthetic = EditorFixture.Sequence(1);
|
|
using var image = synthetic.Render(0);
|
|
var metadata = synthetic.Metadata[0] with { CapturedAt = row.FirstCapture!.Value.AddSeconds(-30) };
|
|
var bytes = JpegEncoder.Encode(image, new JpegEncodeOptions { Quality = 80, App1Segments = [ExifWriter.BuildJpegApp1(metadata)[4..]] });
|
|
var staging = Path.Combine(new ArchivePaths(archive.RootPath).StagingDirectory, "uploads");
|
|
System.IO.Directory.CreateDirectory(staging);
|
|
var path = Path.Combine(staging, Guid.NewGuid().ToString("N") + ".part");
|
|
await File.WriteAllBytesAsync(path, bytes, Ct);
|
|
await Archives.Ingest.CommitAsync(new IngestRequest(archive.Id, SequenceId, null, null, path, "IMG_0000.JPG", bytes.Length,
|
|
Convert.ToHexStringLower(System.Security.Cryptography.SHA256.HashData(bytes)), null, null), Ct);
|
|
}
|
|
|
|
/// <summary>A project of the sequence checked out into <paramref name="host"/>'s workspace and its media copied (Main by default).</summary>
|
|
public async Task<Guid> CheckoutAsync(WorkspaceHost host, Guid? projectId = null, string? newName = null)
|
|
{
|
|
var checkout = await host.CheckoutAsync(SequenceId, projectId, newName, cancellationToken: Ct);
|
|
await WaitForJobAsync(checkout.Copy.Id);
|
|
return checkout.Project.Id;
|
|
}
|
|
|
|
/// <summary>The project open in an editor session over the workspace (saves 20 ms after each edit).</summary>
|
|
public async Task<(WorkspaceSequenceSource Source, EditorSession Session)> OpenAsync(WorkspaceHost host, Guid projectId)
|
|
{
|
|
var source = new WorkspaceSequenceSource(host.SyncOf(projectId), projectId, Db, DecoderFactory.CreateClient(null), Engine);
|
|
var content = await source.LoadAsync(Ct);
|
|
return (source, new EditorSession(source, content, [], TimeSpan.FromMilliseconds(20)));
|
|
}
|
|
|
|
/// <summary>Waits until the job ends; it must end as <paramref name="expected"/>.</summary>
|
|
public async Task<Job> WaitForJobAsync(Guid jobId, JobState expected = JobState.Done)
|
|
{
|
|
var deadline = DateTime.UtcNow + TimeSpan.FromSeconds(TestTiming.Budget(60));
|
|
while (true)
|
|
{
|
|
var job = await Db.Jobs.GetAsync(jobId, Ct);
|
|
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, Ct);
|
|
}
|
|
}
|
|
|
|
/// <summary>Polls <paramref name="condition"/> until it holds, within the time budget.</summary>
|
|
public static async Task UntilAsync(Func<bool> condition, string what, double seconds = 60)
|
|
{
|
|
var deadline = DateTime.UtcNow + TimeSpan.FromSeconds(TestTiming.Budget(seconds));
|
|
while (!condition())
|
|
{
|
|
if (DateTime.UtcNow > deadline) Assert.Fail($"Not reached in time: {what}");
|
|
await Task.Delay(50);
|
|
}
|
|
}
|
|
|
|
public async ValueTask DisposeAsync()
|
|
{
|
|
await Engine.DisposeAsync();
|
|
await Db.DisposeAsync();
|
|
}
|
|
}
|
|
|
|
/// <summary>The window a project menu lives in, as the tests see it: dialogs opened, toasts said, projects opened and closed.</summary>
|
|
internal sealed class RecordingUi : IWorkspaceUi
|
|
{
|
|
public List<ArchiveDialogViewModel> Dialogs { get; } = [];
|
|
|
|
public ArchiveDialogViewModel? Open { get; private set; }
|
|
|
|
public List<(string Title, string? Message, bool IsError, Action? Action)> Toasts { get; } = [];
|
|
|
|
public List<ConfirmRequest> Confirmations { get; } = [];
|
|
|
|
/// <summary>What every confirmation answers.</summary>
|
|
public bool ConfirmAnswer { get; set; } = true;
|
|
|
|
public List<(Guid SequenceId, Guid ProjectId)> Opened { get; } = [];
|
|
|
|
public int Closed { get; private set; }
|
|
|
|
public List<Guid> SequencesChanged { get; } = [];
|
|
|
|
/// <summary>Dialogs waiting for the open one to close (<see cref="ShowDialogWhenFree"/>).</summary>
|
|
public Queue<ArchiveDialogViewModel> Waiting { get; } = new();
|
|
|
|
public ArchiveDialogViewModel? Dialog => Open;
|
|
|
|
public void ShowDialog(ArchiveDialogViewModel dialog)
|
|
{
|
|
Open?.Dispose();
|
|
Dialogs.Add(dialog);
|
|
Open = dialog;
|
|
}
|
|
|
|
public void ShowDialogWhenFree(ArchiveDialogViewModel dialog)
|
|
{
|
|
if (Open is null) ShowDialog(dialog);
|
|
else Waiting.Enqueue(dialog);
|
|
}
|
|
|
|
public void CloseDialog(ArchiveDialogViewModel dialog)
|
|
{
|
|
if (!ReferenceEquals(Open, dialog)) return;
|
|
dialog.Dispose();
|
|
Open = null;
|
|
while (Waiting.TryDequeue(out var next))
|
|
{
|
|
if (next.IsClosed) continue;
|
|
ShowDialog(next);
|
|
break;
|
|
}
|
|
}
|
|
|
|
public bool Confirm(ConfirmRequest request)
|
|
{
|
|
Confirmations.Add(request);
|
|
return ConfirmAnswer;
|
|
}
|
|
|
|
public void Notify(string title, string? message = null, string? actionText = null, string? actionToolTip = null, Action? action = null, bool isError = false) =>
|
|
Toasts.Add((title, message, isError, action));
|
|
|
|
public Task OpenProjectAsync(Guid sequenceId, Guid projectId)
|
|
{
|
|
Opened.Add((sequenceId, projectId));
|
|
return Task.CompletedTask;
|
|
}
|
|
|
|
public Task<bool> CloseProjectAsync()
|
|
{
|
|
Closed++;
|
|
return Task.FromResult(true);
|
|
}
|
|
|
|
public Task SequenceChangedAsync(Guid sequenceId)
|
|
{
|
|
SequencesChanged.Add(sequenceId);
|
|
return Task.CompletedTask;
|
|
}
|
|
}
|