test(app): Library logic tests, capture scenes and smoke tests

Timeline bands and month mapping, saved views (validation and a round trip
through the settings table), the mass actions bar's targets and reasons, remote
cards and their place among the pages, the CSV list and the delete dry run's
confirmation. --capture writes library-timeline, library-mass, library-delete
and library-remote in both themes (LibraryScenes), the sample data saves two
views, and a Windows smoke test renders each scene and checks the bar, the
typed confirmation and the saved views.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_012iLMBNwBE2GnphAsu4cjaC
This commit is contained in:
Claude committed 2026-10-03 16:44:10 +00:00
1 parent 743418d944
commit 7f94c9a839
10 files changed
+729

No files matched your search

+11
View File
@@ -4,6 +4,7 @@ using Titano.App.About;
using Titano.App.Editor;
using Titano.App.Import;
using Titano.App.Infrastructure;
using Titano.App.Library;
using Titano.App.Server;
using Titano.App.Settings;
using Titano.Core.Advice;
@@ -96,6 +97,7 @@ public sealed class SampleData
foreach (var job in Jobs(sequences.Select(s => s.Sequence).ToList(), archive.Id)) await db.Jobs.EnqueueAsync(job);
await FillServerAsync(db, sequences.Select(s => s.Sequence).ToList());
await SampleCards.InsertAsync(db, (SampleDeviceMonitor)_services.Devices, _services.Environment.DataDirectory);
await FillViewsAsync(db);
settings.LastArchivePath = @"D:\TitanoArchive";
settings.ServerUrl = "https://nas.local:8443";
@@ -107,6 +109,15 @@ public sealed class SampleData
settings.FirstRunCompleted = true;
}
/// <summary>Two saved views of the Library ("Not analysed, largest" and one camera), BRIEF §12.2.</summary>
private static async Task FillViewsAsync(TitanoDatabase db)
{
var views = new SavedViewStore(db.Settings);
await views.SaveAsync(SavedView.Of(Guid.CreateVersion7(), "Not analysed, largest",
new LibraryFilter { Status = StatusFilter.NotAnalysed, Sort = Data.Repositories.SequenceSort.Size }));
await views.SaveAsync(SavedView.Of(Guid.CreateVersion7(), "Nikon Z 8", new LibraryFilter { Camera = "NIKON Z 8" }));
}
/// <summary>
/// Transfers for the sync table: an upload at 46 % (Comet over the ridge), an upload waiting (Fog lifting, Asti), a
/// download of originals running (Sunrise over Superga) and one paused (Lake Como storm).
+60
View File
@@ -0,0 +1,60 @@
using Titano.App.Archiving;
using Titano.App.Infrastructure;
using Titano.App.Shell;
namespace Titano.App.Library;
/// <summary>
/// The Library states that <c>--capture</c> renders (<c>library-&lt;scene&gt;-&lt;theme&gt;.png</c>) and the screen smoke
/// tests check, on the sample index while signed in to the sample server: the timeline with a month chosen, a selection
/// with the whole mass actions bar, and the server's sequences without a copy here as remote cards.
/// </summary>
public static class LibraryScenes
{
public static readonly IReadOnlyList<string> Scenes = ["timeline", "mass", "remote"];
/// <summary>Sequences selected for the mass actions bar.</summary>
public const int MassSelection = 3;
public static async Task ShowAsync(ShellViewModel shell, string scene)
{
var library = shell.Library;
shell.Navigate(SectionKey.Library);
library.ClearSelectionCommand.Execute(null);
library.ClearFiltersCommand.Execute(null);
library.LayoutIndex = 0;
await library.RefreshAsync();
switch (scene)
{
case "timeline":
library.LayoutIndex = 2;
// A month further down the list: the year becomes the filter and the grid scrolls to the month.
if (library.Items.Count > 0 && library.Items[Math.Min(12, library.Items.Count - 1)].Sequence.FirstCapture is { } month)
{
library.ShowMonth(month.Year, month.Month);
await library.RefreshAsync();
}
break;
case "mass":
foreach (var item in library.Items.Where(i => !i.IsRemote).Take(MassSelection)) item.IsSelected = true;
break;
case "remote":
library.SelectedOrigin = library.Origins.First(o => o.Value == OriginFilter.Server);
await library.RefreshAsync();
if (library.Items.FirstOrDefault() is { } remote) remote.IsSelected = true;
// Remote thumbnails come through the sync engine's connection, not the local thumbnail service.
for (var i = 0; i < 60 && library.Items.Any(item => item.Thumbnail is null); i++) await Task.Delay(50);
break;
default:
throw new ArgumentOutOfRangeException(nameof(scene), scene, "Unknown Library scene.");
}
}
/// <summary>The confirmation Delete shows for the selection: the archive engine's dry run (nothing moves).</summary>
public static async Task<ConfirmRequest?> DeleteRequestAsync(ShellViewModel shell)
{
var archives = shell.Services.Archives ?? throw new InvalidOperationException("The sample index is not open.");
var ids = shell.Library.SelectedItems().Where(i => !i.IsRemote).Select(i => i.Id).ToList();
return DeletePlans.Request(await Task.Run(() => archives.PlanDeleteAsync(ids)));
}
}
+27
View File
@@ -7,6 +7,7 @@ using Titano.App.Archiving;
using Titano.App.DesignTime;
using Titano.App.Editor;
using Titano.App.Import;
using Titano.App.Library;
using Titano.App.Server;
using Titano.App.Settings;
using Titano.Core.Diagnostics;
@@ -61,6 +62,8 @@ public static class ScreenCapture
await shell.Services.Server.RestoreAsync();
await shell.Services.Sync.RefreshAsync();
await shell.Server.Sync.ReloadAsync();
// The server's sequences without a copy here join the Library as remote cards.
await shell.Library.RefreshAsync();
shell.About.SetResult(null);
await shell.Settings.DetectEncodersAsync();
await shell.Settings.SelfTestAsync();
@@ -79,6 +82,7 @@ public static class ScreenCapture
written += await SaveAsync(window, directory, "library-list", theme, waitForThumbnails: shell);
shell.Library.LayoutIndex = 0;
shell.Library.ClearSelectionCommand.Execute(null);
written += await CaptureLibraryScenesAsync(window, shell, directory, theme);
shell.Navigate(SectionKey.Jobs);
if (shell.Jobs.Rows.Count > 0) shell.Jobs.Rows[0].IsExpanded = true;
@@ -148,6 +152,29 @@ public static class ScreenCapture
}
}
/// <summary>
/// <c>library-timeline</c>, <c>library-mass</c> (the selection with the whole bar), <c>library-delete</c> (the dry run
/// of deleting that selection, behind its typed confirmation) and <c>library-remote</c> (the server's sequences as
/// remote cards), then the Library as it was.
/// </summary>
private static async Task<int> CaptureLibraryScenesAsync(MainWindow window, ShellViewModel shell, string directory, AppTheme theme)
{
var written = 0;
foreach (var scene in LibraryScenes.Scenes)
{
DismissToasts(window);
await LibraryScenes.ShowAsync(shell, scene);
written += await SaveAsync(window, directory, "library-" + scene, theme, waitForThumbnails: shell);
if (scene == "mass" && await LibraryScenes.DeleteRequestAsync(shell) is { } request)
written += await SaveDialogAsync(new ConfirmDialog(request), directory, "library-delete", theme);
}
shell.Library.ClearSelectionCommand.Execute(null);
shell.Library.ClearFiltersCommand.Execute(null);
shell.Library.LayoutIndex = 0;
await shell.Library.RefreshAsync();
return written;
}
private static void SelectSyncFilter(ShellViewModel shell, SyncFilter filter) =>
shell.Server.Sync.Chips.First(c => c.Filter == filter).SelectCommand.Execute(null);
@@ -0,0 +1,65 @@
using System.Globalization;
using Titano.App.Archiving;
using Titano.App.Infrastructure;
using Titano.Core.Localization;
using Titano.Core.Model;
using Titano.Data.Archiving;
using Titano.Testing;
namespace Titano.App.Tests.Library;
/// <summary>The confirmation of Delete in the Library and the Archive manager: the engine's dry run behind a typed confirmation (DESIGN §4).</summary>
public sealed class DeletePlansTests
{
private static Sequence Sequence(string title, int frames) => new()
{
Id = Guid.CreateVersion7(),
ArchiveId = Guid.CreateVersion7(),
Title = title,
Folder = "2026/" + title,
FrameCount = frames,
};
private static DeleteStep Step(string title, int frames, int files, long bytes) =>
new(Sequence(title, frames), $".titano/trash/{Guid.CreateVersion7():N}", files, bytes);
[Test]
public void ThePlanAsksToTypeHowManySequencesMove()
{
var plan = new DeletePlan(
[Step("Harbour sunset", 3_600, 3_640, 96_200_000_000), Step("Comet over the ridge", 1_005, 1_020, 21_000_000_000)],
[new BlockedDelete(Sequence("Fog lifting", 980), DeleteBlock.Busy)]);
var request = Assert.NotNull(DeletePlans.Request(plan));
Assert.True(request.IsDestructive, "the action is outlined, never primary");
Assert.Equal("2", request.TypedConfirmation);
Assert.Equal(Loc.L("Archive.Delete.Type", "2"), request.TypedPrompt);
Assert.Equal(Loc.Plural("Archive.Delete.Heading", 2), request.Heading);
Assert.Equal(Loc.L("Archive.Delete.Message", Loc.Plural("Shell.Status.Photos", 4_605), Loc.Plural("Archive.Delete.Files", 4_660),
Formatting.Bytes(117_200_000_000)), request.Message);
var lines = request.Detail!.Split(Environment.NewLine);
Assert.Equal(3, lines.Length);
Assert.Equal(Loc.L("Archive.Delete.Line", "Harbour sunset", Loc.Plural("Shell.Status.Photos", 3_600), Formatting.Bytes(96_200_000_000)), lines[0]);
Assert.Equal(Loc.L("Archive.Delete.Blocked", "Fog lifting", Loc.L("Archive.Delete.Reason.Busy")), lines[2]);
Assert.Equal(Loc.L("Archive.Delete.Keep"), request.SafeText);
Assert.Equal(Loc.Plural("Tooltips.Archive.DeleteAction", 2), request.ActionToolTip);
}
[Test]
public void LongPlansAreCountedAndEmptyOnesAskNothing()
{
var many = Enumerable.Range(1, DeletePlans.ListedLines + 3).Select(i => Step("Sequence " + i.ToString(CultureInfo.InvariantCulture), 10, 10, 1_000)).ToList();
var request = Assert.NotNull(DeletePlans.Request(new DeletePlan(many, [])));
var lines = request.Detail!.Split(Environment.NewLine);
Assert.Equal(DeletePlans.ListedLines + 1, lines.Length);
Assert.Equal(Loc.Plural("Archive.Delete.More", 3), lines[^1]);
Assert.Equal((DeletePlans.ListedLines + 3).ToString(CultureInfo.InvariantCulture), request.TypedConfirmation);
var blocked = new DeletePlan([], [new BlockedDelete(Sequence("Root", 2), DeleteBlock.ArchiveRoot)]);
Assert.Null(DeletePlans.Request(blocked), "nothing can move: no confirmation");
Assert.SequenceEqual([Loc.L("Archive.Delete.Blocked", "Root", Loc.L("Archive.Delete.Reason.ArchiveRoot"))], DeletePlans.Blocked(blocked, 8));
foreach (var reason in Enum.GetValues<DeleteBlock>())
Assert.NotEqual("Archive.Delete.Reason." + reason, Loc.L("Archive.Delete.Reason." + reason), "every reason has words");
}
}
@@ -0,0 +1,45 @@
using Titano.App.Library;
using Titano.Core.Model;
using Titano.Testing;
namespace Titano.App.Tests.Library;
/// <summary>"Export list as CSV" (BRIEF §12.2): RFC 4180 rows that spreadsheets read as data, never as formulas.</summary>
public sealed class LibraryCsvTests
{
[Test]
public void RowsAreQuotedInvariantAndSafe()
{
var harbour = new Sequence
{
Id = Guid.CreateVersion7(),
ArchiveId = Guid.CreateVersion7(),
Title = "Harbour, \"golden\" hour",
Folder = "2026/2026-09-28 Canon EOS R5",
CameraMake = "Canon",
CameraModel = "Canon EOS R5",
FirstCapture = new DateTime(2026, 9, 28, 18, 2, 11),
LastCapture = new DateTime(2026, 9, 28, 20, 2, 9),
FrameCount = 3_600,
TotalBytes = 96_200_000_000,
Tags = ["sunset", "harbour"],
};
var formula = new Sequence
{
Id = Guid.CreateVersion7(),
ArchiveId = Guid.Empty,
Folder = string.Empty,
Title = "=HYPERLINK(\"x\")",
Origin = SequenceOrigin.Server,
SyncState = SyncState.RemoteOnly,
};
var lines = LibraryCsv.Write([harbour, formula]).Split("\r\n");
Assert.Equal("title,first_capture,last_capture,camera_make,camera_model,frames,bytes,folder,tags,origin", lines[0]);
Assert.Equal("\"Harbour, \"\"golden\"\" hour\",2026-09-28 18:02:11,2026-09-28 20:02:09,Canon,Canon EOS R5,3600,96200000000,"
+ "2026/2026-09-28 Canon EOS R5,sunset;harbour,local", lines[1]);
Assert.Equal("\"'=HYPERLINK(\"\"x\"\")\",,,,,0,0,,,server", lines[2]);
Assert.Equal(string.Empty, lines[3], "every row ends with CRLF");
}
}
@@ -0,0 +1,106 @@
using System.Windows;
using System.Windows.Controls;
using System.Windows.Input;
using System.Windows.Media;
using Titano.App.Archiving;
using Titano.App.Library;
using Titano.App.Sections;
using Titano.App.Shell;
using Titano.App.Tests.Windows;
using Titano.Testing;
using Titano.Ui.Visuals;
namespace Titano.App.Tests.Library;
/// <summary>
/// The Library's new states of <c>--capture</c> (<see cref="LibraryScenes"/>) on the sample index while signed in to the
/// sample server, rendered in both themes in the real main window: the timeline, a selection with the whole mass actions
/// bar and its delete dry run, the server's sequences as remote cards, and saved views.
/// </summary>
[WindowsOnly]
[Serial]
[Timeout(300_000)]
public sealed class LibraryScreenSmokeTests
{
[Test]
public Task EveryLibrarySceneRendersInBothThemes() => ScreenHost.RunAsync(async () =>
{
await using var app = await ScreenSmokeTests.SampleApp.StartAsync();
await app.Sample.FillAsync();
await app.Shell.Services.Server.RestoreAsync();
await app.Shell.Services.Sync.RefreshAsync();
var library = app.Shell.Library;
await LibraryScenes.ShowAsync(app.Shell, "timeline");
Assert.True(library.IsTimeline, "the timeline shows its bands");
Assert.True(library.IsGrid, "the cards stay under the bands");
Assert.Equal(2, library.TimelineBands.Count, "one band per year, 2026 and 2025");
Assert.True(library.TimelineBand >= 0 && library.TimelineSlot >= 0, "the chosen month is outlined");
Assert.True(library.IsYearFiltered, "a month narrows the Library to its year");
await app.ExpectAsync<LibraryView>("library-timeline", waitForThumbnails: true);
Assert.True(app.FindAll<TimelineBands>().Any(t => t.IsVisible && t.ActualHeight > 0), "the bands are drawn");
await LibraryScenes.ShowAsync(app.Shell, "mass");
Assert.Equal(LibraryScenes.MassSelection, library.SelectionCount);
await app.ExpectAsync<LibraryView>("library-mass", waitForThumbnails: true);
foreach (var command in new[] { library.AnalyseCommand, library.ProxiesCommand, library.VerifyCommand, library.TagCommand, library.MoveCommand,
library.ExportListCommand, library.DeleteCommand })
Assert.True(ButtonFor(app, command).IsEnabled, "the bar's archive actions work on sequences of this PC");
Assert.True(library.CanRate);
var request = Assert.NotNull(await LibraryScenes.DeleteRequestAsync(app.Shell), "the dry run moves something");
Assert.True(request.IsDestructive);
Assert.NotNull(request.TypedConfirmation);
var dialog = new ConfirmDialog(request) { WindowStartupLocation = WindowStartupLocation.Manual, Left = -20000, Top = -20000, ShowActivated = false };
dialog.Show();
try
{
dialog.UpdateLayout();
var action = Find<Button>(dialog).Single(b => Equals(b.Content, request.ActionText));
Assert.False(action.IsEnabled, "Delete waits for the typed confirmation");
Find<TextBox>(dialog).Single(t => t.IsVisible).Text = request.TypedConfirmation;
Assert.True(action.IsEnabled, "typing the count enables Delete");
}
finally
{
dialog.Close();
}
// The sample dialogs cancel every confirmation: nothing moves.
var selected = library.SelectedItems().Select(i => i.Id).ToList();
Assert.False(await SequenceDeletion.RunAsync(app.Shell, selected));
foreach (var id in selected) Assert.NotNull(await app.Services.Database!.Sequences.GetAsync(id));
await LibraryScenes.ShowAsync(app.Shell, "remote");
Assert.True(library.ShowsOrigin, "signed in, the origin filter shows");
Assert.Equal(2, library.Items.Count, "the two sequences only on the sample server");
Assert.True(library.Items.All(i => i.IsRemote));
Assert.True(library.IsSingleSelection);
Assert.False(library.DeleteCommand.CanExecute(null), "a remote card has nothing here to delete");
Assert.True(library.DownloadCommand.CanExecute(null), "its originals can come here");
await app.ExpectAsync<LibraryView>("library-remote");
library.ClearFiltersCommand.Execute(null);
await library.RefreshAsync();
Assert.True(library.HasViews, "the sample saved two views");
library.ViewChoices.Single(v => v.Label == "Nikon Z 8").Command.Execute(null);
await library.RefreshAsync();
Assert.True(library.IsViewActive);
Assert.True(library.Items.Count > 0 && library.Items.All(i => i.Sequence.CameraModel == "NIKON Z 8"));
});
private static Button ButtonFor(ScreenSmokeTests.SampleApp app, ICommand command) =>
Assert.NotNull(app.FindAll<Button>().FirstOrDefault(b => ReferenceEquals(b.Command, command) && b.IsVisible), "a visible button bound to the command");
private static List<T> Find<T>(DependencyObject root)
where T : DependencyObject
{
var found = new List<T>();
for (var i = 0; i < VisualTreeHelper.GetChildrenCount(root); i++)
{
var child = VisualTreeHelper.GetChild(root, i);
if (child is T match) found.Add(match);
found.AddRange(Find<T>(child));
}
return found;
}
}
@@ -0,0 +1,71 @@
using Titano.App.Library;
using Titano.Core.Model;
using Titano.Data.Repositories;
using Titano.Testing;
namespace Titano.App.Tests.Library;
/// <summary>The Library's timeline: year bands of photos per month and the way from a month to the grid (BRIEF §12.2).</summary>
public sealed class LibraryTimelineTests
{
private static ArchiveStats Stats(params MonthBucket[] months) => new(0, 0, 0, [], months, [], [], new ArchiveHealth(0, 0, 0, 0, 0, 0, 0));
[Test]
public void BandsRunFromTheNewestYearWithEveryYearBetween()
{
var timeline = LibraryTimeline.From(Stats(new MonthBucket(2023, 3, 1, 400), new MonthBucket(2026, 9, 2, 5_000), new MonthBucket(2026, 1, 1, 120)),
new DateTime(2026, 10, 3));
Assert.SequenceEqual([2026, 2025, 2024, 2023], timeline.Years);
Assert.SequenceEqual(["2026", "2025", "2024", "2023"], timeline.Bands.Select(b => b.Label));
var newest = timeline.Bands[0].Values;
Assert.Equal(120.0, newest[0]);
Assert.Equal(5_000.0, newest[8]);
Assert.Equal(0.0, newest[9], "October has passed its first days: an empty month, not a future one");
Assert.True(double.IsNaN(newest[10]), "months to come carry no density");
Assert.Equal(400.0, timeline.Bands[3].Values[2]);
Assert.True(timeline.Bands[1].Values.All(v => v == 0), "a year without photos still has its band");
}
[Test]
public void AnEmptyLibraryHasNoBands()
{
var timeline = LibraryTimeline.From(Stats(), new DateTime(2026, 10, 3));
Assert.Empty(timeline.Bands);
Assert.Null(timeline.MonthAt(0, 0));
Assert.Equal((-1, -1), timeline.SlotOf(2026, 1));
}
[Test]
public void SlotsAndMonthsMapBothWays()
{
var timeline = LibraryTimeline.From(Stats(new MonthBucket(2025, 6, 1, 10), new MonthBucket(2026, 2, 1, 10)), new DateTime(2026, 10, 3));
Assert.Equal((2026, 1), timeline.MonthAt(0, 0));
Assert.Equal((2025, 12), timeline.MonthAt(1, 11));
Assert.Null(timeline.MonthAt(2, 0));
Assert.Null(timeline.MonthAt(0, 12));
Assert.Null(timeline.MonthAt(-1, 3));
Assert.Equal((1, 5), timeline.SlotOf(2025, 6));
Assert.Equal((-1, -1), timeline.SlotOf(2024, 6));
Assert.Equal((-1, -1), timeline.SlotOf(2026, 13));
}
[Test]
public void TheFirstSequenceOfAMonthIsFoundInListOrder()
{
Sequence At(int year, int month, int day) => new()
{
Id = Guid.CreateVersion7(),
ArchiveId = Guid.Empty,
Folder = "f",
FirstCapture = new DateTime(year, month, day, 18, 0, 0),
};
List<Sequence> newestFirst = [At(2026, 9, 28), At(2026, 9, 2), At(2026, 7, 14), new() { Id = Guid.CreateVersion7(), ArchiveId = Guid.Empty, Folder = "g" }];
Assert.Equal(0, LibraryTimeline.FirstOfMonth(newestFirst, 2026, 9));
Assert.Equal(2, LibraryTimeline.FirstOfMonth(newestFirst, 2026, 7));
Assert.Equal(-1, LibraryTimeline.FirstOfMonth(newestFirst, 2026, 8));
Assert.Equal(-1, LibraryTimeline.FirstOfMonth([], 2026, 9));
}
}
@@ -0,0 +1,148 @@
using Titano.App.Library;
using Titano.App.Server;
using Titano.Core.Localization;
using Titano.Core.Model;
using Titano.Data.Sync;
using Titano.Testing;
namespace Titano.App.Tests.Library;
/// <summary>Which selected sequences each button of the mass actions bar works on, and why a button is off (BRIEF §12.2, DESIGN §4).</summary>
public sealed class MassActionsTests
{
private const string Server = "https://nas.local:8443";
private static readonly SyncRights Editor = SyncRights.Of((long)RolePermissions.Default(UserRole.Editor));
private static readonly SyncRights Viewer = SyncRights.Of((long)RolePermissions.Default(UserRole.Viewer));
private static readonly Guid MainArchive = Guid.CreateVersion7();
private static readonly SelectionContext Offline = new(HasEngine: true, IsSignedIn: false, default);
private static readonly SelectionContext SignedIn = new(HasEngine: true, IsSignedIn: true, Editor);
private static Sequence Local(string title, Guid? archive = null) => new()
{
Id = Guid.CreateVersion7(),
ArchiveId = archive ?? MainArchive,
Title = title,
Folder = "2026/" + title,
FrameCount = 120,
};
private static SyncLink Link(Sequence sequence) => new() { Server = Server, RemoteId = Guid.CreateVersion7(), Title = sequence.DisplayTitle };
private static SelectedSequence Remote(string title)
{
var link = new SyncLink { Server = Server, RemoteId = Guid.CreateVersion7(), Title = title, FrameCount = 300 };
var card = RemoteCards.FromLink(link);
return new SelectedSequence(card, new SyncEntry(null, link, SyncStatus.RemoteOnly));
}
private static SelectedSequence Linked(string title, SyncStatus status, Func<SyncLink, SyncLink>? change = null)
{
var local = Local(title);
var link = Link(local);
return new SelectedSequence(local, new SyncEntry(local, change?.Invoke(link) ?? link, status));
}
private static SelectedSequence Only(string title) => new(Local(title), null);
[Test]
public void NothingRunsWithoutASelectionOrAnIndexButTheListExport()
{
foreach (var action in Enum.GetValues<MassAction>())
Assert.Equal(Loc.L("Library.Blocked.NoSelection"), MassActions.Blocker(action, [], SignedIn));
SelectedSequence[] one = [Only("Harbour sunset")];
var noIndex = new SelectionContext(HasEngine: false, IsSignedIn: false, default);
Assert.Equal(Loc.L("Library.Blocked.NoIndex"), MassActions.Blocker(MassAction.Analyse, one, noIndex));
Assert.Equal(Loc.L("Library.Blocked.NoIndex"), MassActions.Blocker(MassAction.Delete, one, noIndex));
Assert.Null(MassActions.Blocker(MassAction.ExportList, one, noIndex), "a CSV needs only the rows on screen");
}
[Test]
public void ArchiveActionsWorkOnTheSequencesOfThisPc()
{
var harbour = Only("Harbour sunset");
var remote = Remote("Sunrise over Superga");
SelectedSequence[] mixed = [harbour, remote];
foreach (var action in new[] { MassAction.Analyse, MassAction.Proxies, MassAction.Verify, MassAction.Tag, MassAction.Rate, MassAction.Move, MassAction.Delete })
{
Assert.Null(MassActions.Blocker(action, mixed, SignedIn), action.ToString());
Assert.SequenceEqual([harbour], MassActions.Targets(action, mixed, SignedIn), action.ToString());
Assert.Equal(Loc.L("Library.Blocked.ServerOnly"), MassActions.Blocker(action, [remote], SignedIn));
}
Assert.SequenceEqual(mixed, MassActions.Targets(MassAction.ExportList, mixed, SignedIn), "the CSV lists remote cards too");
Assert.Equal(Loc.Plural("Tooltips.Library.Mass.Delete", 1), MassActions.ToolTip(MassAction.Delete, 1));
}
[Test]
public void MoveStaysInsideOneArchive()
{
SelectedSequence[] two = [Only("Harbour sunset"), new(Local("Aurora", Guid.CreateVersion7()), null)];
Assert.Equal(Loc.L("Library.Blocked.Archives"), MassActions.Blocker(MassAction.Move, two, Offline));
Assert.Null(MassActions.Blocker(MassAction.Delete, two, Offline), "the trash of each archive takes its own sequences");
}
[Test]
public void TransfersNeedASessionAndTheRight()
{
SelectedSequence[] one = [Only("Harbour sunset")];
Assert.Equal(Loc.L("Library.Blocked.NotConnected"), MassActions.Blocker(MassAction.Upload, one, Offline));
Assert.Equal(Loc.L("Library.Blocked.NotConnected"), MassActions.Blocker(MassAction.Download, one, Offline));
Assert.Equal(Loc.L("Library.Blocked.NoUploadRight"), MassActions.Blocker(MassAction.Upload, one, SignedIn with { Rights = Viewer }));
Assert.Equal(Loc.L("Library.Blocked.NoDownloadRight"), MassActions.Blocker(MassAction.Download, one, SignedIn with { Rights = Viewer }));
Assert.Null(MassActions.Blocker(MassAction.Upload, one, SignedIn), "a sequence only here uploads before the table compares it");
Assert.Equal(Loc.L("Library.Blocked.NothingToDownload"), MassActions.Blocker(MassAction.Download, one, SignedIn));
}
[Test]
public void EachTransferTakesWhatItsSyncRowOffers()
{
var only = Only("Harbour sunset");
var ahead = Linked("Comet over the ridge", SyncStatus.LocalAhead, l => l with { MissingRemote = 4 });
var renders = Linked("Star trails", SyncStatus.InSync, l => l with { ExportsToSend = 1, ExportsToGet = 2 });
var same = Linked("Aurora, Tromsø", SyncStatus.InSync);
var behind = Linked("Fog lifting", SyncStatus.ServerAhead, l => l with { MissingLocal = 12 });
var remote = Remote("Sunrise over Superga");
SelectedSequence[] all = [only, ahead, renders, same, behind, remote];
Assert.SequenceEqual([only, ahead, renders], MassActions.Targets(MassAction.Upload, all, SignedIn));
Assert.Equal(SyncAction.Upload, MassActions.UploadStep(only, Editor));
Assert.Equal(SyncAction.Upload, MassActions.UploadStep(ahead, Editor));
Assert.Equal(SyncAction.SendExports, MassActions.UploadStep(renders, Editor));
Assert.Null(MassActions.UploadStep(same, Editor));
Assert.Null(MassActions.UploadStep(remote, Editor), "a remote card has nothing here to send");
Assert.SequenceEqual([renders, behind, remote], MassActions.Targets(MassAction.Download, all, SignedIn));
Assert.Equal(SyncAction.GetExports, MassActions.DownloadStep(renders, Editor));
Assert.Equal(SyncAction.DownloadOriginals, MassActions.DownloadStep(behind, Editor));
Assert.Equal(SyncAction.DownloadOriginals, MassActions.DownloadStep(remote, Editor));
Assert.Null(MassActions.DownloadStep(only, Editor));
Assert.Equal(Loc.L("Library.Blocked.NothingToUpload"), MassActions.Blocker(MassAction.Upload, [same, remote], SignedIn));
}
[Test]
public void TheCardsSyncDoesTheFirstThingItsRowOffers()
{
Assert.Null(MassActions.QuickSync(Only("Harbour sunset"), Offline, out var why));
Assert.Equal(Loc.L("Library.Blocked.NotConnected"), why);
Assert.Equal(SyncAction.Upload, MassActions.QuickSync(Only("Harbour sunset"), SignedIn, out why));
Assert.Null(why);
Assert.Null(MassActions.QuickSync(Only("Harbour sunset"), SignedIn with { Rights = Viewer }, out why));
Assert.Equal(Loc.L("Library.Blocked.NoUploadRight"), why);
Assert.Equal(SyncAction.DownloadOriginals, MassActions.QuickSync(Remote("Sunrise over Superga"), SignedIn, out _));
Assert.Equal(SyncAction.SyncSettings, MassActions.QuickSync(Linked("Holy grail", SyncStatus.ServerAhead), SignedIn, out _));
Assert.Equal(SyncAction.KeepMine, MassActions.QuickSync(Linked("Holy grail", SyncStatus.Conflict), SignedIn, out _), "a conflict goes to the Server screen");
Assert.Null(MassActions.QuickSync(Linked("Aurora, Tromsø", SyncStatus.InSync), SignedIn, out why));
Assert.Equal(Loc.L("Library.Blocked.InSync"), why);
var moving = Linked("Comet over the ridge", SyncStatus.LocalAhead);
var transferring = moving with { Sync = moving.Sync! with { Transfer = new Job { Id = Guid.CreateVersion7(), Kind = JobKind.UploadCommit, State = JobState.Running } } };
Assert.Null(MassActions.QuickSync(transferring, SignedIn, out why));
Assert.Equal(Loc.L("Library.Blocked.Transferring"), why);
}
}
@@ -0,0 +1,114 @@
using Titano.App.Library;
using Titano.Core.Model;
using Titano.Data.Repositories;
using Titano.Data.Sync;
using Titano.Protocol;
using Titano.Testing;
namespace Titano.App.Tests.Library;
/// <summary>Server sequences without a copy here as Library cards, and their place among the index's pages (BRIEF §4.4).</summary>
public sealed class RemoteCardsTests
{
private const string Server = "https://nas.local:8443";
private static SyncLink Link(string title, int frames = 100) => new() { Server = Server, RemoteId = Guid.CreateVersion7(), Title = title, FrameCount = frames };
private static Sequence Card(string title, DateTime? first, string? camera = null, params string[] tags) =>
RemoteCards.FromLink(Link(title)) with { FirstCapture = first, CameraModel = camera, Tags = tags };
private static Sequence Local(string title, DateTime? first) => new()
{
Id = Guid.CreateVersion7(),
ArchiveId = Guid.CreateVersion7(),
Title = title,
Folder = title,
FirstCapture = first,
};
[Test]
public void OnlyServerSequencesWithoutALocalCopyBecomeCards()
{
var harbour = new Sequence { Id = Guid.CreateVersion7(), ArchiveId = Guid.CreateVersion7(), Folder = "harbour", Title = "Harbour sunset" };
var sunrise = Link("Sunrise over Superga", 2_880) with { TotalBytes = 60_000_000_000, RemoteStatus = SequenceStatus.ProxiesBuilt, RenderCount = 1 };
var lake = Link("Lake Como storm");
SyncEntry[] table =
[
new(harbour, Link("Harbour sunset"), SyncStatus.InSync),
new(harbour with { Id = Guid.CreateVersion7() }, null, SyncStatus.LocalOnly),
new(null, sunrise, SyncStatus.RemoteOnly),
new(null, lake, SyncStatus.ProxiesOnly),
];
var cards = RemoteCards.Build(table, null);
Assert.SequenceEqual([sunrise.RemoteId, lake.RemoteId], cards.Select(c => c.Id));
var card = cards[0];
Assert.Equal("Sunrise over Superga", card.DisplayTitle);
Assert.Equal(2_880, card.FrameCount);
Assert.Equal(60_000_000_000, card.TotalBytes);
Assert.Equal(SequenceStatus.ProxiesBuilt, card.Status);
Assert.Equal(1, card.RenderedCount);
Assert.Equal(SequenceOrigin.Server, card.Origin);
Assert.Equal(SyncState.RemoteOnly, card.SyncState);
Assert.Equal(Guid.Empty, card.ArchiveId, "a remote card belongs to no archive of this PC");
}
[Test]
public void TheServersListingFillsInTheDetails()
{
var link = Link("Sunrise");
var dto = new SequenceDto(link.RemoteId, "Sunrise over Superga", "Sunrise over Superga", "2026/2026-07-02 Sony ILCE-7M4", "Sony", "ILCE-7M4", null,
new DateTime(2026, 7, 2, 5, 40, 0), new DateTime(2026, 7, 2, 7, 16, 0), 2_880, 2.0, 60_000_000_000, (int)SequenceStatus.ProxiesBuilt, 1, null,
["sunrise"], 4, null, 3, 2, 0, null, DateTimeOffset.UtcNow);
var card = RemoteCards.Build([new SyncEntry(null, link, SyncStatus.RemoteOnly)], new Dictionary<Guid, SequenceDto> { [dto.Id] = dto }).Single();
Assert.Equal("Sunrise over Superga", card.DisplayTitle);
Assert.Equal("ILCE-7M4", card.CameraModel);
Assert.Equal(new DateTime(2026, 7, 2, 5, 40, 0), card.FirstCapture);
Assert.SequenceEqual(["sunrise"], card.Tags);
Assert.Equal(4, card.Rating);
Assert.Equal(SyncState.RemoteOnly, card.SyncState);
}
[Test]
public void CardsSortAmongThePagesAndFollowTheFilter()
{
var merge = new RemoteMerge();
var september = Card("Comet", new DateTime(2026, 9, 20), "ILCE-7M4", "stars");
var july = Card("Sunrise", new DateTime(2026, 7, 2), "ILCE-7M4");
var undated = Card("Unknown", null);
var otherYear = Card("Old", new DateTime(2024, 5, 1));
merge.Reset(new LibraryFilter(), [july, undated, september, otherYear]);
Assert.Equal(4, merge.Pending);
// Newest first: each page takes the cards that sort before its last row, the last page the rest.
var first = merge.Merge([Local("A", new DateTime(2026, 9, 28)), Local("B", new DateTime(2026, 8, 1))], last: false);
Assert.SequenceEqual(["A", "Comet", "B"], first.Select(s => s.DisplayTitle));
var second = merge.Merge([Local("C", new DateTime(2025, 1, 1))], last: false);
Assert.SequenceEqual(["Sunrise", "C"], second.Select(s => s.DisplayTitle));
var last = merge.Merge([Local("D", new DateTime(2023, 1, 1))], last: true);
Assert.SequenceEqual(["Old", "D", "Unknown"], last.Select(s => s.DisplayTitle), "undated cards come last");
Assert.Equal(0, merge.Pending);
merge.Reset(new LibraryFilter { Year = 2026, Text = "sun" }, [july, september, otherYear]);
Assert.SequenceEqual(["Sunrise"], merge.Merge([], last: true).Select(s => s.DisplayTitle));
merge.Reset(new LibraryFilter { Tag = "stars" }, [july, september]);
Assert.SequenceEqual(["Comet"], merge.Merge([], last: true).Select(s => s.DisplayTitle));
merge.Reset(new LibraryFilter { Origin = OriginFilter.Local }, [july, september]);
Assert.Equal(0, merge.Pending, "on this PC only: no remote card");
merge.Reset(new LibraryFilter { Status = StatusFilter.Analysed }, [july]);
Assert.Equal(0, merge.Pending, "a remote card not analysed does not pass the status filter");
}
[Test]
public void FiltersCompareLikeTheIndex()
{
var byTitle = new LibraryFilter { Sort = SequenceSort.Title };
Assert.True(byTitle.Compare(Local("aurora", null), Local("Comet", null)) < 0, "titles ignore case");
var bySize = new LibraryFilter { Sort = SequenceSort.Size };
Assert.True(bySize.Compare(Local("big", null) with { TotalBytes = 10 }, Local("small", null) with { TotalBytes = 1 }) < 0, "largest first");
var oldest = new LibraryFilter { Sort = SequenceSort.Oldest };
Assert.True(oldest.Compare(Local("a", new DateTime(2020, 1, 1)), Local("b", new DateTime(2021, 1, 1))) < 0);
Assert.True(oldest.Compare(Local("a", null), Local("b", new DateTime(2021, 1, 1))) > 0, "undated last");
}
}
@@ -0,0 +1,82 @@
using System.IO;
using Titano.App.Library;
using Titano.Core.Localization;
using Titano.Data;
using Titano.Data.Repositories;
using Titano.Testing;
namespace Titano.App.Tests.Library;
/// <summary>Saved views of the Library (BRIEF §12.2): a name for filters and sort, kept as app-scope settings rows.</summary>
public sealed class SavedViewTests(TestContext context)
{
private static readonly LibraryFilter Night = new()
{
Text = " night ",
Year = 2026,
Camera = "ILCE-7M4",
Status = StatusFilter.NotAnalysed,
Tag = "stars",
Origin = OriginFilter.Local,
Sort = SequenceSort.Size,
};
[Test]
public void AViewKeepsFiltersAndSortAndRecognisesThem()
{
var view = SavedView.Of(Guid.CreateVersion7(), " Night, 4K, not analysed ", Night);
Assert.Equal("Night, 4K, not analysed", view.Name);
Assert.Equal("night", view.Text);
Assert.Equal(Night with { Text = "night" }, view.ToFilter());
Assert.True(view.Matches(Night));
Assert.True(view.Matches(Night with { Text = "NIGHT" }), "the search compares trimmed and ignoring case");
Assert.False(view.Matches(Night with { Sort = SequenceSort.Newest }), "the sort is part of the view");
Assert.False(view.Matches(Night with { Origin = OriginFilter.Any }));
Assert.False(view.Matches(Night with { Tag = null }));
var blank = SavedView.Of(Guid.CreateVersion7(), "All", new LibraryFilter { Text = " " });
Assert.Null(blank.Text);
Assert.True(blank.Matches(new LibraryFilter()));
}
[Test]
public void NamesAreShortUniqueAndPrintable()
{
string[] others = ["Night", "Holy grail"];
Assert.Equal(Loc.L("Library.Views.Error.Empty"), SavedView.Validate(" ", others));
Assert.Equal(Loc.L("Library.Views.Error.Long", SavedView.MaxName), SavedView.Validate(new string('a', SavedView.MaxName + 1), others));
Assert.Equal(Loc.L("Library.Views.Error.Long", SavedView.MaxName), SavedView.Validate("Night\tsky", others));
Assert.Equal(Loc.L("Library.Views.Error.Taken"), SavedView.Validate(" night ", others));
Assert.Null(SavedView.Validate("Night, 4K", others));
Assert.Null(SavedView.Validate(new string('a', SavedView.MaxName), others));
}
[Test]
public async Task ViewsRoundTripThroughTheSettingsTable()
{
await using var db = await TitanoDatabase.OpenAsync(DatabaseOptions.Sqlite(Path.Combine(context.CreateTempDirectory("db"), "titano.db")), context.Cancellation);
var store = new SavedViewStore(db.Settings);
Assert.Empty(await store.ListAsync());
var night = SavedView.Of(Guid.CreateVersion7(), "Night", Night);
var grail = SavedView.Of(Guid.CreateVersion7(), "holy grail", new LibraryFilter { Tag = "holy grail", Sort = SequenceSort.Oldest });
await store.SaveAsync(night);
await store.SaveAsync(grail);
// Other app settings and a damaged row live next to the views and are not views.
await db.Settings.SetJsonAsync(SettingScope.App, null, "library.layout", "2");
await db.Settings.SetJsonAsync(SettingScope.App, null, "library.view.broken", "\"not a view\"");
var listed = await store.ListAsync();
Assert.SequenceEqual(["holy grail", "Night"], listed.Select(v => v.Name), "by name, ignoring case");
Assert.Equal(night, listed[1]);
Assert.Equal(grail, listed[0]);
await store.SaveAsync(night with { Name = "Night sky" });
Assert.SequenceEqual(["holy grail", "Night sky"], (await store.ListAsync()).Select(v => v.Name), "a rename keeps one row");
Assert.True(await store.DeleteAsync(grail.Id));
Assert.False(await store.DeleteAsync(grail.Id));
Assert.Equal(night.Id, (await store.ListAsync()).Single().Id);
}
}