Merge branch 'fix/app-fixes': localized error toasts, plural counts, archive and import view-model fixes
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_012iLMBNwBE2GnphAsu4cjaC
This commit is contained in:
303 files changed
+968
-2234
No files matched your search
@@ -170,6 +170,45 @@ public sealed class ArchiveScreenSmokeTests
|
||||
static DialogFact Fact(RebuildDialogViewModel dialog, string label) => dialog.FactRows.Single(f => f.Label == Loc.L(label));
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Picking another archive while one is being read shows the picked one: the read in progress is followed by one of
|
||||
/// the new archive, and meanwhile nothing of the previous archive's tree can be acted on.
|
||||
/// </summary>
|
||||
[Test]
|
||||
public Task PickingAnotherArchiveDuringAReadShowsThePickedOne() => ScreenHost.RunAsync(async () =>
|
||||
{
|
||||
await using var app = await ScreenSmokeTests.SampleApp.StartAsync();
|
||||
await app.Sample.FillAsync();
|
||||
var archive = app.Shell.Archive;
|
||||
await ArchiveScenes.ShowAsync(app.Shell, "overview");
|
||||
Assert.Contains(archive.TreeRows, r => r.Node.Kind == TreeNodeKind.Sequence);
|
||||
var second = await app.Services.Archives!.CreateAsync(Path.Combine(app.Services.Environment.DataDirectory, "second-archive"), "Second");
|
||||
|
||||
var reading = archive.LoadAsync();
|
||||
archive.SelectedArchive = second;
|
||||
Assert.Empty(archive.TreeRows);
|
||||
Assert.False(archive.AnalyseSetCommand.CanExecute(null), "nothing of the first archive can be acted on while the picked one is read");
|
||||
Assert.False(archive.ScanCommand.CanExecute(null), "the picked archive is not known to be online yet");
|
||||
Assert.Equal(Loc.L("Archive.Blocked.Reading"), archive.ScanToolTip, "not yet read is not offline");
|
||||
Assert.False(archive.RebuildCommand.CanExecute(null), "the rebuild dialog waits for the picked archive's own state and figures");
|
||||
Assert.Null(await archive.OpenRebuildDialogAsync());
|
||||
Assert.Empty(archive.Health);
|
||||
await reading;
|
||||
|
||||
Assert.Equal(second.Id, archive.SelectedArchive!.Id);
|
||||
Assert.Contains(archive.Archives, a => a.Id == second.Id);
|
||||
Assert.True(archive.TreeRows[0].IsArchive);
|
||||
Assert.False(archive.TreeRows.Any(r => r.Node.Kind == TreeNodeKind.Sequence), "the tree is the picked, empty archive's");
|
||||
Assert.True(archive.ScanCommand.CanExecute(null), "the picked archive was probed: it is online");
|
||||
Assert.Equal(Loc.L("Tooltips.Archive.Scan"), archive.ScanToolTip);
|
||||
Assert.True(archive.RebuildCommand.CanExecute(null));
|
||||
var rebuild = Assert.NotNull(await archive.OpenRebuildDialogAsync());
|
||||
Assert.Equal(second.Id, rebuild.Archive.Id);
|
||||
Assert.Equal(ArchiveAvailability.Online, rebuild.Availability, "the dialog shows the picked archive's availability");
|
||||
Assert.Equal(0, rebuild.Indexed, "and its own index, not the first archive's");
|
||||
rebuild.CloseCommand.Execute(null);
|
||||
});
|
||||
|
||||
[Test]
|
||||
public void TheArrowTowardsTheIndentOpensAYearInEitherDirection()
|
||||
{
|
||||
|
||||
@@ -1,4 +1,7 @@
|
||||
using System.Collections.Specialized;
|
||||
using System.Globalization;
|
||||
using System.IO;
|
||||
using System.Net.Http;
|
||||
using System.Windows;
|
||||
using System.Windows.Controls;
|
||||
using System.Windows.Media;
|
||||
@@ -251,6 +254,40 @@ public sealed class EditorSmokeTests
|
||||
Assert.False(viewer.OptimiseAllCommand.CanExecute(null));
|
||||
Assert.False(viewer.AnalyseCommand.CanExecute(null));
|
||||
}
|
||||
|
||||
// A failed save says why in one localized sentence (BRIEF §0.2 rule 6); the exception's own text stays in the log.
|
||||
// The editor's own reasons keep their sentence (they are I/O failures too, which would read "does not answer").
|
||||
var toasts = new List<Toast>();
|
||||
NotifyCollectionChangedEventHandler collect = (_, e) => toasts.AddRange(e.NewItems?.OfType<Toast>() ?? []);
|
||||
shell.PendingToasts.CollectionChanged += collect;
|
||||
try
|
||||
{
|
||||
foreach (var (remote, failure, cause) in new (bool, Exception, string)[]
|
||||
{
|
||||
(true, new HttpRequestException("No such host is known."), "Server.Error.Unreachable"),
|
||||
(false, new UnauthorizedAccessException(@"Access to the path 'D:\Archive\.titano\sequence.json' is denied."), "Archive.Failed.Access"),
|
||||
(true, new ProxiesOutdatedException(Loc.L("Editor.Error.FramesChanged")), "Editor.Error.FramesChanged"),
|
||||
(true, new EditorException(Loc.L("Editor.Error.RemoteReadOnly")), "Editor.Error.RemoteReadOnly"),
|
||||
(false, new EditorException(Loc.L("Editor.Error.SaveConflict")), "Editor.Error.SaveConflict"),
|
||||
(false, new EditorException(Loc.L("Editor.Error.Project"), new InvalidDataException("project.json version 9 is newer")), "Editor.Error.Project"),
|
||||
})
|
||||
{
|
||||
toasts.Clear();
|
||||
var saving = new FakeSequenceSource(EditorFixture.Sunset, content) { IsRemote = remote, FailNextSave = failure };
|
||||
var failing = new EditorViewModel(shell, new EditorSession(saving, content, []), [], EncoderHost.Client);
|
||||
await using (failing)
|
||||
{
|
||||
failing.Session.Edit(p => p with { HeroFrame = 1 });
|
||||
Assert.False(await failing.Session.FlushAsync(), "the save failed");
|
||||
var toast = Assert.Contains(toasts, t => t.Title == Loc.L("Editor.Save.Failed"));
|
||||
Assert.Equal(Loc.L(cause), toast.Message);
|
||||
}
|
||||
}
|
||||
}
|
||||
finally
|
||||
{
|
||||
shell.PendingToasts.CollectionChanged -= collect;
|
||||
}
|
||||
}
|
||||
finally
|
||||
{
|
||||
|
||||
@@ -4,6 +4,7 @@ using Titano.Core.Archiving;
|
||||
using Titano.Core.Codecs.Jpeg;
|
||||
using Titano.Core.Imaging;
|
||||
using Titano.Core.Imaging.Decoders;
|
||||
using Titano.Core.Localization;
|
||||
using Titano.Core.Metadata;
|
||||
using Titano.Core.Model;
|
||||
using Titano.Core.Project;
|
||||
@@ -147,7 +148,8 @@ public sealed class ProjectStoreTests(TestContext context)
|
||||
new ArchiveServiceOptions { Owner = "test", LeaseWait = TimeSpan.FromSeconds(20) });
|
||||
var content = await source.LoadAsync(context.Cancellation);
|
||||
Assert.True(await db.Sequences.DeleteAsync(sequenceId));
|
||||
await Assert.ThrowsAsync<InvalidOperationException>(() => source.SaveProjectAsync(content.Project with { HeroFrame = 1 }, content.Project, context.Cancellation));
|
||||
var gone = await Assert.ThrowsAsync<EditorException>(() => source.SaveProjectAsync(content.Project with { HeroFrame = 1 }, content.Project, context.Cancellation));
|
||||
Assert.Equal(Loc.L("Editor.Error.Missing"), gone.Message, "the toast shows the editor's own sentence");
|
||||
}
|
||||
}
|
||||
|
||||
@@ -178,8 +180,15 @@ public sealed class ProjectStoreTests(TestContext context)
|
||||
var path = Path.Combine(root, "Synthetic", ".titano", "project.json");
|
||||
File.WriteAllText(path, "{ not json");
|
||||
await using var source = new LocalSequenceSource(db, sequenceId, DecoderFactory.CreateClient(null), null);
|
||||
await Assert.ThrowsAsync<InvalidDataException>(() => source.LoadAsync(context.Cancellation));
|
||||
var unreadable = await Assert.ThrowsAsync<EditorException>(() => source.LoadAsync(context.Cancellation));
|
||||
Assert.Equal(Loc.L("Editor.Error.Project"), unreadable.Message);
|
||||
Assert.Equal("{ not json", File.ReadAllText(path));
|
||||
|
||||
// A project written by a newer Titano reads the same, not as the parser's English sentence.
|
||||
var newer = $"{{\"version\":{ProjectSettings.CurrentVersion + 1}}}";
|
||||
File.WriteAllText(path, newer);
|
||||
Assert.Equal(Loc.L("Editor.Error.Project"), (await Assert.ThrowsAsync<EditorException>(() => source.LoadAsync(context.Cancellation))).Message);
|
||||
Assert.Equal(newer, File.ReadAllText(path));
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -5,6 +5,7 @@ using Titano.Core.Codecs.Jpeg;
|
||||
using Titano.Core.Diagnostics.Synthetic;
|
||||
using Titano.Core.Imaging;
|
||||
using Titano.Core.Imaging.Decoders;
|
||||
using Titano.Core.Localization;
|
||||
using Titano.Core.Model;
|
||||
using Titano.Core.Project;
|
||||
using Titano.Data.Processing;
|
||||
@@ -229,7 +230,8 @@ public sealed class RemoteSequenceSourceTests(TestContext context)
|
||||
return (theirs with { Camera = theirs.Camera with { OffsetX = offset } }).ToJson();
|
||||
});
|
||||
}
|
||||
await Assert.ThrowsAsync<IOException>(() => source.SaveProjectAsync(content.Project with { HeroFrame = 2 }, content.Project, context.Cancellation));
|
||||
var conflict = await Assert.ThrowsAsync<EditorException>(() => source.SaveProjectAsync(content.Project with { HeroFrame = 2 }, content.Project, context.Cancellation));
|
||||
Assert.Equal(Loc.L("Editor.Error.SaveConflict"), conflict.Message, "the toast shows the editor's own sentence");
|
||||
Assert.False(api.Edits.Any(e => e.Accepted));
|
||||
}
|
||||
}
|
||||
@@ -268,8 +270,9 @@ public sealed class RemoteSequenceSourceTests(TestContext context)
|
||||
}
|
||||
|
||||
// The source refuses a change as well; the same project is no change.
|
||||
await Assert.ThrowsAsync<InvalidOperationException>(() =>
|
||||
var refused = await Assert.ThrowsAsync<EditorException>(() =>
|
||||
source.SaveProjectAsync(content.Project with { HeroFrame = 1 }, content.Project, context.Cancellation));
|
||||
Assert.Equal(Loc.L("Editor.Error.RemoteReadOnly"), refused.Message);
|
||||
Assert.True(ProjectMerge.SameValues(content.Project, await source.SaveProjectAsync(content.Project, content.Project, context.Cancellation)));
|
||||
Assert.Empty(api.Edits);
|
||||
}
|
||||
@@ -366,8 +369,9 @@ public sealed class RemoteSequenceSourceTests(TestContext context)
|
||||
{
|
||||
var content = await source.LoadAsync(context.Cancellation);
|
||||
api.Gone = true;
|
||||
await Assert.ThrowsAsync<InvalidOperationException>(() => source.LoadAsync(context.Cancellation));
|
||||
await Assert.ThrowsAsync<InvalidOperationException>(() => source.SaveProjectAsync(content.Project with { HeroFrame = 1 }, content.Project, context.Cancellation));
|
||||
Assert.Equal(Loc.L("Editor.Error.Missing"), (await Assert.ThrowsAsync<EditorException>(() => source.LoadAsync(context.Cancellation))).Message);
|
||||
var gone = await Assert.ThrowsAsync<EditorException>(() => source.SaveProjectAsync(content.Project with { HeroFrame = 1 }, content.Project, context.Cancellation));
|
||||
Assert.Equal(Loc.L("Editor.Error.Missing"), gone.Message);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -3,8 +3,10 @@ using System.IO;
|
||||
using System.Net;
|
||||
using System.Net.Http;
|
||||
using Titano.App.Import;
|
||||
using Titano.Core.Archiving;
|
||||
using Titano.Core.Import;
|
||||
using Titano.Core.Localization;
|
||||
using Titano.Data;
|
||||
using Titano.Protocol;
|
||||
using Titano.Protocol.Client;
|
||||
using Titano.Testing;
|
||||
@@ -38,4 +40,31 @@ public sealed class ImportFailuresTests
|
||||
Assert.Equal(@"D:\Shoots could not be read.", ImportFailures.Plan(new IOException("The device is not ready."), Folder));
|
||||
Assert.Equal("The import could not be planned.", ImportFailures.Plan(new InvalidOperationException("Sequence contains no elements"), Folder));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void ACardCheckOrDeleteFailureIsOneSentenceByCause()
|
||||
{
|
||||
const string Card = "EOS R5 · card A";
|
||||
var root = Directory.CreateTempSubdirectory("titano-card-").FullName;
|
||||
try
|
||||
{
|
||||
Assert.Equal("A photo or its archive copy could not be read.", ImportFailures.Check(new IOException("The semaphore timeout period has expired."), Card, root));
|
||||
Assert.Equal("The index could not be read or written.", ImportFailures.Check(new DatabaseConnectionException("database is locked"), Card, root));
|
||||
Assert.Equal("The archive D:\\Shoots is offline.", ImportFailures.Check(new ArchiveOfflineException(@"D:\Shoots", ArchiveAvailability.Offline), Card, root));
|
||||
Assert.Equal("Something went wrong.", ImportFailures.Check(new InvalidOperationException("Collection was modified."), Card, root));
|
||||
Assert.Equal("EOS R5 · card A is write-protected or holds protected photos.",
|
||||
ImportFailures.Erase(new IOException("The media is write protected.", unchecked((int)0x80070013)), Card, root));
|
||||
Assert.Equal("EOS R5 · card A is write-protected or holds protected photos.",
|
||||
ImportFailures.Erase(new UnauthorizedAccessException(@"Access to the path 'E:\DCIM\IMG_0001.CR3' is denied."), Card, root));
|
||||
Assert.Equal("Something went wrong.", ImportFailures.Erase(new IOException("The request could not be performed because of an I/O device error."), Card, root));
|
||||
}
|
||||
finally
|
||||
{
|
||||
Directory.Delete(root);
|
||||
}
|
||||
// A card that left explains whatever failed while it was read or written.
|
||||
var gone = Path.Combine(Path.GetTempPath(), "titano-card-" + Guid.NewGuid().ToString("N"));
|
||||
Assert.Equal("EOS R5 · card A is no longer available.", ImportFailures.Check(new IOException("The device is not ready."), Card, gone));
|
||||
Assert.Equal("EOS R5 · card A is no longer available.", ImportFailures.Erase(new UnauthorizedAccessException("Access denied."), Card, gone));
|
||||
}
|
||||
}
|
||||
@@ -166,6 +166,62 @@ public sealed class ImportScreenSmokeTests
|
||||
}
|
||||
});
|
||||
|
||||
/// <summary>
|
||||
/// An archive import whose job ends before the screen records its id (here cancelled inside the engine's own "queued"
|
||||
/// event, so the screen sees none of its events) still ends the screen's run instead of leaving it copying forever.
|
||||
/// </summary>
|
||||
[Test]
|
||||
public Task AnImportJobThatEndsBeforeItIsRecordedStillEndsTheRun() => ScreenHost.RunAsync(async () =>
|
||||
{
|
||||
await using var app = await ScreenSmokeTests.SampleApp.StartAsync();
|
||||
await app.Sample.FillAsync();
|
||||
var import = app.Shell.Import;
|
||||
await ShowAsync(app, "plan");
|
||||
var engine = Assert.NotNull(app.Services.Engine);
|
||||
void CancelAtOnce(Core.Model.Job job)
|
||||
{
|
||||
if (job is { Kind: Core.Model.JobKind.Import, State: Core.Model.JobState.Queued }) engine.CancelAsync(job.Id).GetAwaiter().GetResult();
|
||||
}
|
||||
engine.JobChanged += CancelAtOnce;
|
||||
try
|
||||
{
|
||||
Assert.True(import.StartCommand.CanExecute(null), "the plan can be imported");
|
||||
import.StartCommand.Execute(null);
|
||||
for (var i = 0; i < 300 && !import.IsFailed; i++) await Task.Delay(50);
|
||||
}
|
||||
finally
|
||||
{
|
||||
engine.JobChanged -= CancelAtOnce;
|
||||
}
|
||||
Assert.True(import.IsFailed, "the screen left Running though no event of the job reached it");
|
||||
Assert.Equal(Loc.L("Import.Status.Cancelled"), import.ErrorText);
|
||||
});
|
||||
|
||||
/// <summary>A result replaced by New import stops following the language: nothing keeps it, or its plan, alive.</summary>
|
||||
[Test]
|
||||
public Task AReplacedResultStopsFollowingTheLanguage() => ScreenHost.RunAsync(async () =>
|
||||
{
|
||||
await using var app = await ScreenSmokeTests.SampleApp.StartAsync();
|
||||
await app.Sample.FillAsync();
|
||||
var import = app.Shell.Import;
|
||||
await ShowAsync(app, "done");
|
||||
var replaced = Assert.NotNull(import.Result);
|
||||
var refreshed = 0;
|
||||
replaced.PropertyChanged += (_, _) => refreshed++;
|
||||
import.NewImportCommand.Execute(null);
|
||||
Assert.Null(import.Result);
|
||||
try
|
||||
{
|
||||
UiLanguage.Apply("it");
|
||||
}
|
||||
finally
|
||||
{
|
||||
UiLanguage.Apply("en");
|
||||
}
|
||||
Assert.Equal(0, refreshed, "the replaced result was disposed");
|
||||
await import.WaitForPlanAsync();
|
||||
});
|
||||
|
||||
/// <summary>As <c>--capture</c> does: toasts of the previous state go, those of an insertion state stay.</summary>
|
||||
private static async Task ShowAsync(ScreenSmokeTests.SampleApp app, string state)
|
||||
{
|
||||
|
||||
@@ -0,0 +1,43 @@
|
||||
using System.Globalization;
|
||||
using System.IO;
|
||||
using System.Net;
|
||||
using System.Net.Http;
|
||||
using Titano.App.Shell;
|
||||
using Titano.Core.Archiving;
|
||||
using Titano.Core.Localization;
|
||||
using Titano.Protocol;
|
||||
using Titano.Protocol.Client;
|
||||
using Titano.Testing;
|
||||
|
||||
namespace Titano.App.Tests.Infrastructure;
|
||||
|
||||
/// <summary>An error toast says what happened in one localized sentence; framework and OS messages stay in the log.</summary>
|
||||
public sealed class ErrorTextTests
|
||||
{
|
||||
public ErrorTextTests() => Loc.SetCulture(CultureInfo.GetCultureInfo("en"));
|
||||
|
||||
[Test]
|
||||
public void AServerFailureIsTheServersSentenceOrThatItDoesNotAnswer()
|
||||
{
|
||||
const string Unreachable = "The server does not answer; check the address and the network.";
|
||||
Assert.Equal("The server is out of disk space.",
|
||||
ErrorText.ForServer(new TitanoApiException(HttpStatusCode.InsufficientStorage, new ApiError("insufficient_storage", "The server is out of disk space.", null))));
|
||||
Assert.Equal(Unreachable, ErrorText.ForServer(new HttpRequestException("No such host is known. (nas.local:8443)")));
|
||||
Assert.Equal(Unreachable, ErrorText.ForServer(new TaskCanceledException("A task was canceled.")));
|
||||
Assert.Equal(Unreachable, ErrorText.ForServer(new IOException("The response ended prematurely.")));
|
||||
Assert.Equal(Unreachable, ErrorText.ForServer(new AggregateException(new HttpRequestException("Connection refused"))));
|
||||
Assert.Equal("The certificate was not trusted, so nothing was sent.", ErrorText.ForServer(new UntrustedCertificateException("AB:CD")));
|
||||
// Failures that already carry a catalog sentence keep it.
|
||||
Assert.Equal(@"The archive D:\Shoots is offline.", ErrorText.ForServer(new ArchiveOfflineException(@"D:\Shoots", ArchiveAvailability.Offline)));
|
||||
Assert.Equal("Something went wrong.", ErrorText.ForServer(new InvalidOperationException("Sequence contains no elements")));
|
||||
Assert.Equal("Something went wrong.", ErrorText.ForServer(new TitanoApiException(HttpStatusCode.BadGateway, new ApiError("bad_gateway", " ", null))));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void AnyOtherFailureNeverShowsTheFrameworkText()
|
||||
{
|
||||
Assert.Equal("Something went wrong.", ErrorText.For(new HttpRequestException("No such host is known.")));
|
||||
Assert.Equal("Something went wrong.", ErrorText.For(new IOException(@"Access to the path 'D:\Archive' is denied.")));
|
||||
Assert.Equal(@"The archive D:\Shoots is read-only.", ErrorText.For(new ArchiveOfflineException(@"D:\Shoots", ArchiveAvailability.ReadOnly)));
|
||||
}
|
||||
}
|
||||
@@ -1,14 +1,18 @@
|
||||
using System.Collections.Specialized;
|
||||
using System.Windows;
|
||||
using System.Windows.Controls;
|
||||
using System.Windows.Input;
|
||||
using System.Windows.Media;
|
||||
using Titano.App.Archiving;
|
||||
using Titano.App.Infrastructure;
|
||||
using Titano.App.Library;
|
||||
using Titano.App.Sections;
|
||||
using Titano.App.Shell;
|
||||
using Titano.App.Tests.Windows;
|
||||
using Titano.Core.Localization;
|
||||
using Titano.Core.Model;
|
||||
using Titano.Testing;
|
||||
using Titano.Ui.Controls;
|
||||
using Titano.Ui.Visuals;
|
||||
|
||||
namespace Titano.App.Tests.Library;
|
||||
@@ -153,6 +157,72 @@ public sealed class LibraryScreenSmokeTests
|
||||
trash.CloseCommand.Execute(null);
|
||||
});
|
||||
|
||||
/// <summary>A language switch makes the timeline's month readouts again, as it does the filters (BRIEF §16).</summary>
|
||||
[Test]
|
||||
public Task TheTimelineReadoutsFollowALanguageSwitch() => 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");
|
||||
var english = Readout(library);
|
||||
try
|
||||
{
|
||||
UiLanguage.Apply("it");
|
||||
var italian = Readout(library);
|
||||
Assert.NotEqual(english, italian, "the month readouts follow the language");
|
||||
}
|
||||
finally
|
||||
{
|
||||
UiLanguage.Apply("en");
|
||||
}
|
||||
Assert.Equal(english, Readout(library), "and come back with it");
|
||||
|
||||
static string Readout(LibraryViewModel library) => library.TimelineBands[0].ToolTips!.First(t => !string.IsNullOrEmpty(t))!;
|
||||
});
|
||||
|
||||
/// <summary>
|
||||
/// A remote card's Analyse posted to a server whose certificate changed since sign-in: the pin refuses it before
|
||||
/// anything is sent, and the error toast says so (it used to escape the action unreported).
|
||||
/// </summary>
|
||||
[Test]
|
||||
public Task APostRefusedByThePinnedCertificateSaysSo() => ScreenHost.RunAsync(async () =>
|
||||
{
|
||||
using var server = new UntrustedTlsEndpoint();
|
||||
await using var app = await ScreenSmokeTests.SampleApp.StartAsync();
|
||||
await app.Sample.FillAsync();
|
||||
app.Services.Settings.ServerUrl = server.Address.ToString();
|
||||
await app.Shell.Services.Server.RestoreAsync();
|
||||
var actions = new LibraryActions(app.Shell);
|
||||
Assert.True(actions.CanPost, "signed in to the endpoint (the sample's own certificate was trusted at sign-in)");
|
||||
|
||||
var toasts = new List<Toast>();
|
||||
NotifyCollectionChangedEventHandler collect = (_, e) => toasts.AddRange(e.NewItems?.OfType<Toast>() ?? []);
|
||||
app.Shell.PendingToasts.CollectionChanged += collect;
|
||||
try
|
||||
{
|
||||
var remote = new Sequence
|
||||
{
|
||||
Id = Guid.CreateVersion7(),
|
||||
ArchiveId = Guid.Empty,
|
||||
Folder = "Harbour",
|
||||
Title = "Harbour sunset",
|
||||
Origin = SequenceOrigin.Server,
|
||||
SyncState = SyncState.RemoteOnly,
|
||||
};
|
||||
await actions.AnalyseAsync([remote]);
|
||||
}
|
||||
finally
|
||||
{
|
||||
app.Shell.PendingToasts.CollectionChanged -= collect;
|
||||
}
|
||||
var toast = Assert.Contains(toasts, t => t.Title == Loc.L("Library.Post.Failed"));
|
||||
Assert.Equal(Loc.L("Server.Error.Untrusted"), toast.Message);
|
||||
Assert.True(toast.IsError);
|
||||
});
|
||||
|
||||
private static void Press(UIElement target, Key key) =>
|
||||
target.RaiseEvent(new KeyEventArgs(Keyboard.PrimaryDevice, PresentationSource.FromVisual(target)!, 0, key) { RoutedEvent = Keyboard.KeyDownEvent });
|
||||
|
||||
|
||||
@@ -0,0 +1,78 @@
|
||||
using System.IO;
|
||||
using System.Net;
|
||||
using System.Net.Security;
|
||||
using System.Net.Sockets;
|
||||
using System.Security.Authentication;
|
||||
using System.Security.Cryptography;
|
||||
using System.Security.Cryptography.X509Certificates;
|
||||
|
||||
namespace Titano.App.Tests.Library;
|
||||
|
||||
/// <summary>
|
||||
/// A TLS endpoint on loopback with a self-signed certificate no client trusted (a server whose certificate changed since
|
||||
/// sign-in): the client's pinning refuses every handshake, so nothing is ever sent.
|
||||
/// </summary>
|
||||
internal sealed class UntrustedTlsEndpoint : IDisposable
|
||||
{
|
||||
private readonly TcpListener _listener = new(IPAddress.Loopback, 0);
|
||||
private readonly X509Certificate2 _certificate;
|
||||
private readonly CancellationTokenSource _stop = new();
|
||||
private readonly Task _accepting;
|
||||
|
||||
public UntrustedTlsEndpoint()
|
||||
{
|
||||
using var key = RSA.Create(2048);
|
||||
var request = new CertificateRequest("CN=127.0.0.1", key, HashAlgorithmName.SHA256, RSASignaturePadding.Pkcs1);
|
||||
using var created = request.CreateSelfSigned(DateTimeOffset.UtcNow.AddDays(-1), DateTimeOffset.UtcNow.AddDays(1));
|
||||
// Schannel serves only a certificate whose key it can open: a PKCS #12 round trip gives it one.
|
||||
_certificate = X509CertificateLoader.LoadPkcs12(created.Export(X509ContentType.Pkcs12), null);
|
||||
_listener.Start();
|
||||
_accepting = Task.Run(AcceptAsync);
|
||||
}
|
||||
|
||||
public Uri Address => new($"https://127.0.0.1:{((IPEndPoint)_listener.LocalEndpoint).Port}/");
|
||||
|
||||
public void Dispose()
|
||||
{
|
||||
_stop.Cancel();
|
||||
_listener.Stop();
|
||||
try
|
||||
{
|
||||
_accepting.Wait(TimeSpan.FromSeconds(5));
|
||||
}
|
||||
catch (AggregateException)
|
||||
{
|
||||
// The loop ends with the listener; how it ended does not matter.
|
||||
}
|
||||
_certificate.Dispose();
|
||||
_stop.Dispose();
|
||||
}
|
||||
|
||||
private async Task AcceptAsync()
|
||||
{
|
||||
while (!_stop.IsCancellationRequested)
|
||||
{
|
||||
TcpClient client;
|
||||
try
|
||||
{
|
||||
client = await _listener.AcceptTcpClientAsync(_stop.Token);
|
||||
}
|
||||
catch (Exception ex) when (ex is OperationCanceledException or SocketException or ObjectDisposedException)
|
||||
{
|
||||
return;
|
||||
}
|
||||
using (client)
|
||||
{
|
||||
try
|
||||
{
|
||||
await using var tls = new SslStream(client.GetStream());
|
||||
await tls.AuthenticateAsServerAsync(new SslServerAuthenticationOptions { ServerCertificate = _certificate }, _stop.Token);
|
||||
}
|
||||
catch (Exception ex) when (ex is AuthenticationException or IOException or OperationCanceledException or SocketException)
|
||||
{
|
||||
// The client refused the certificate: the handshake ends here, as intended.
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -55,7 +55,16 @@ public sealed class UploaderTextTests
|
||||
{
|
||||
Assert.Null(UploaderText.Failed(Mockup, En));
|
||||
Assert.Equal("1,203 failed", UploaderText.Failed(Mockup with { Failed = 1_203 }, En));
|
||||
Assert.Equal("3 non riusciti", UploaderText.Failed(Mockup with { Failed = 3 }, It));
|
||||
// Italian participles agree with the number ("1 non riuscito", "3 non riusciti"): the count follows a label instead.
|
||||
Assert.Equal("Non riusciti: 3", UploaderText.Failed(Mockup with { Failed = 3 }, It));
|
||||
Assert.Equal("Non riusciti: 1", UploaderText.Failed(Mockup with { Failed = 1 }, It));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void ItalianProgressReadsForASingleFileToo()
|
||||
{
|
||||
Assert.Equal("Inviati: 1 di 1 · Verificati dal server: 1 · 0 nuovi tentativi",
|
||||
UploaderText.ProgressLine(Mockup with { Files = 1, Sent = 1, Verified = 1 }, It));
|
||||
}
|
||||
|
||||
[Test]
|
||||
|
||||
@@ -31,14 +31,56 @@ public sealed partial class AdvisorLocalizationTests(TestContext context)
|
||||
var keys = Keys(typeof(AdvisorKeys)).Concat(Keys(typeof(FindingKeys))).Concat(Keys(typeof(DeepFindingKeys)))
|
||||
.Concat(english.Keys.Where(k => k.StartsWith(LogPrefix, StringComparison.Ordinal))).ToList();
|
||||
Assert.Greater(keys.Count, 90);
|
||||
var forms = 0;
|
||||
foreach (var key in keys)
|
||||
{
|
||||
Assert.True(english.TryGetValue(key, out var en), $"English text missing for {key}");
|
||||
Assert.True(italian.TryGetValue(key, out var it), $"Italian text missing for {key}");
|
||||
Assert.SequenceEqual(Placeholders(en!), Placeholders(it!), key);
|
||||
Assert.LessOrEqual(en!.Length, 200);
|
||||
// A key that counts something is a plural stem (BRIEF §16) whose count is its first argument.
|
||||
string[] names = english.ContainsKey(key) ? [key] : [key + ".one", key + ".other"];
|
||||
if (names.Length == 2) Assert.Contains("0", Placeholders(english.GetValueOrDefault(key + ".other") ?? string.Empty), $"{key}.other counts with {{0}}");
|
||||
foreach (var name in names)
|
||||
{
|
||||
Assert.True(english.TryGetValue(name, out var en), $"English text missing for {name}");
|
||||
Assert.True(italian.TryGetValue(name, out var it), $"Italian text missing for {name}");
|
||||
Assert.SequenceEqual(Placeholders(en!), Placeholders(it!), name);
|
||||
Assert.LessOrEqual(en!.Length, 200);
|
||||
forms++;
|
||||
}
|
||||
}
|
||||
Assert.Equal(english.Count, keys.Count);
|
||||
Assert.Equal(english.Count, forms);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void ACountOfOneReadsInTheSingularInBothLanguages()
|
||||
{
|
||||
Assert.Equal("1 frame is black (lens cap or missed exposure).", Loc.Text(DeepFindingKeys.BlackFrames, [1.0], English));
|
||||
Assert.Equal("3 frames are black (lens cap or missed exposure).", Loc.Text(DeepFindingKeys.BlackFrames, [3.0], English));
|
||||
Assert.Equal("1 fotogramma è nero (tappo sull'obiettivo o scatto mancato).", Loc.Text(DeepFindingKeys.BlackFrames, [1.0], Italian));
|
||||
Assert.Equal("The lens changes once.", Loc.Text(FindingKeys.LensChanged, [1], English));
|
||||
Assert.Equal("L'obiettivo cambia 2 volte.", Loc.Text(FindingKeys.LensChanged, [2], Italian));
|
||||
Assert.Equal("2 exposure changes reached the pixels: each is spread over a smooth transition.", Loc.Text(AdvisorKeys.HolyGrailReceived, [2], English));
|
||||
// Advisor windows are measured in tenths of a frame: a fraction takes the plural.
|
||||
Assert.Equal("Flicker stays correlated over 1.5 frames: a 7-frame window spans four times that.", Loc.Text(AdvisorKeys.WindowCorrelation, [1.5, 7], English));
|
||||
Assert.Equal("Flicker stays correlated over 1 frame: a 5-frame window spans four times that.", Loc.Text(AdvisorKeys.WindowCorrelation, [1.0, 5], English));
|
||||
// Keys without a count read as before.
|
||||
Assert.Equal("Clouds cover about 42% of the sky on average.", Loc.Text(DeepFindingKeys.Clouds, [42.0], English));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void ASingleExposureChangeHasNoSpacing()
|
||||
{
|
||||
var frames = Enumerable.Range(0, 20).Select(i => new LightFrame
|
||||
{
|
||||
Index = i,
|
||||
CapturedAt = new DateTime(2026, 6, 1, 20, 0, 0, DateTimeKind.Utc).AddSeconds(10 * i),
|
||||
ExposureTime = i < 12 ? 1.0 / 250 : 1.0 / 125,
|
||||
FNumber = 8,
|
||||
Iso = 100,
|
||||
}).ToList();
|
||||
var single = LightAnalyzer.Analyze(frames).Findings.Single(f => f.Key == FindingKeys.ExposureStep);
|
||||
Assert.SequenceEqual([12], single.Frames);
|
||||
Assert.Equal("One exposure change of -1.0 EV.", Loc.Text(single.Key, single.Arguments, English));
|
||||
Assert.Equal("Un solo cambio di esposizione di -1,0 EV.", Loc.Text(single.Key, single.Arguments, Italian));
|
||||
Assert.DoesNotContain(FindingKeys.ExposureSteps, LightAnalyzer.Analyze(frames).Findings.Select(f => f.Key));
|
||||
}
|
||||
|
||||
[Test]
|
||||
@@ -106,9 +148,8 @@ public sealed partial class AdvisorLocalizationTests(TestContext context)
|
||||
{
|
||||
foreach (var culture in new[] { English, Italian })
|
||||
{
|
||||
var format = Loc.Get(key, culture);
|
||||
Assert.NotNull(format);
|
||||
var text = Format(format!, culture, args);
|
||||
var text = Loc.Text(key, args, culture);
|
||||
Assert.False(text.Contains('⟦'), $"{key} has no {culture.Name} text");
|
||||
Assert.False(text.Contains('{'), $"{key} left a placeholder: {text}");
|
||||
}
|
||||
return 1;
|
||||
|
||||
@@ -34,7 +34,7 @@ public sealed class ArchiveJobTests(TestContext context)
|
||||
|
||||
var full = await engine.EnqueueAsync(ArchiveJobs.Scan(fx.Archive, full: true), cancellationToken: fx.Ct);
|
||||
var done = await fx.WaitForAsync(full.Id, JobState.Done);
|
||||
Assert.Contains("2 folders", done.LogTail);
|
||||
Assert.Contains("Folders: 2", done.LogTail);
|
||||
Assert.SequenceEqual(["a", "b"], (await LocationsAsync(fx)).Select(l => l.Folder));
|
||||
|
||||
var rebuild = await engine.EnqueueAsync(ArchiveJobs.Rebuild(fx.Archive), cancellationToken: fx.Ct);
|
||||
@@ -56,7 +56,7 @@ public sealed class ArchiveJobTests(TestContext context)
|
||||
Assert.NotNull((await fx.Db.Sequences.GetAsync(b.Id))!.VerifiedAt);
|
||||
var hashes = (await fx.Db.Frames.ListBySequenceAsync(b.Id)).Select(f => f.Sha256).ToList();
|
||||
Assert.True(hashes.Take(2).All(h => h is null) && hashes.Skip(2).All(h => h is not null));
|
||||
Assert.Contains("4 photos checked", done.LogTail);
|
||||
Assert.Contains("Photos checked: 4", done.LogTail);
|
||||
}
|
||||
|
||||
[Test]
|
||||
@@ -85,7 +85,7 @@ public sealed class ArchiveJobTests(TestContext context)
|
||||
// A full pass reuses what is current and builds the rest.
|
||||
var all = await engine.EnqueueAsync(ArchiveJobs.Thumbnails([a.Id]), cancellationToken: fx.Ct);
|
||||
var done = await fx.WaitForAsync(all.Id, JobState.Done);
|
||||
Assert.Contains("3 made, 3 reused", done.LogTail);
|
||||
Assert.Contains("made 3, reused 3", done.LogTail);
|
||||
}
|
||||
|
||||
[Test]
|
||||
@@ -125,6 +125,6 @@ public sealed class ArchiveJobTests(TestContext context)
|
||||
var frames = await fx.Db.Frames.ListBySequenceAsync(id);
|
||||
Assert.SequenceEqual(plan.Items.Skip(32).Select(i => i.FileName), frames.Select(f => f.FileName));
|
||||
Assert.Equal(8, (await fx.Db.MediaCards.GetImportedKeysAsync(media.Id)).Count);
|
||||
Assert.Contains("8 copied", done.LogTail);
|
||||
Assert.Contains("Copied: 8,", done.LogTail);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,59 @@
|
||||
using Titano.Testing;
|
||||
using Titano.Tools.Commands;
|
||||
|
||||
namespace Titano.Tools.Tests;
|
||||
|
||||
/// <summary><c>i18n check</c> flags an English text that counts something without plural forms (BRIEF §16).</summary>
|
||||
public sealed class I18nCommandTests
|
||||
{
|
||||
[Test]
|
||||
public void ANumberInFrontOfACountedNounNeedsPluralForms()
|
||||
{
|
||||
Assert.Equal("frames", I18nCommand.CountedNoun("Advisor.Finding.BlackFrames", "{0} frames are black (lens cap or missed exposure)."));
|
||||
Assert.Equal("gaps", I18nCommand.CountedNoun("Advisor.Reason.Timing.SparseGaps", "{0} short gaps, but motion is unmeasured or fast."));
|
||||
Assert.Equal("changes", I18nCommand.CountedNoun("Advisor.Finding.StepsNotReceived", "{0} logged exposure changes never reached the pixels."));
|
||||
Assert.Equal("times", I18nCommand.CountedNoun("Advisor.Finding.LensChanged", "The lens changes {0} times."));
|
||||
Assert.Equal("sequences", I18nCommand.CountedNoun("Errors.Analysis.Failed", "{0} of {1} sequences could not be analysed; see the job log."));
|
||||
Assert.Equal("jobs", I18nCommand.CountedNoun("Shell.JobBar.Ready", "Ready · {0:N0} jobs queued"));
|
||||
Assert.Equal("cores", I18nCommand.CountedNoun("Settings.Rendering.Cores", "of {0} logical cores"));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void PluralFormsBoundsLabelsAndUnitsCountNothing()
|
||||
{
|
||||
Assert.Null(I18nCommand.CountedNoun("Advisor.Finding.BlackFrames.other", "{0} frames are black (lens cap or missed exposure)."));
|
||||
Assert.Null(I18nCommand.CountedNoun("Advisor.Finding.BlackFrames.one", "{0} frame is black (lens cap or missed exposure)."));
|
||||
Assert.Null(I18nCommand.CountedNoun("Server.Error.WeakPassword", "Use at least {0} characters."));
|
||||
Assert.Null(I18nCommand.CountedNoun("Library.Views.Error.Long", "At most {0} characters, no control characters."));
|
||||
Assert.Null(I18nCommand.CountedNoun("Archive.Retag.Invalid", "Each tag has 1 to {0} characters."));
|
||||
Assert.Null(I18nCommand.CountedNoun("Archive.Log.ScanDone", "Folders: {0}, indexed: {1}, adopted: {2}, removed: {3}"));
|
||||
Assert.Null(I18nCommand.CountedNoun("Advisor.Reason.Window.Period.other", "Flicker repeats every {0} frames: a {1}-frame window averages four cycles."));
|
||||
Assert.Null(I18nCommand.CountedNoun("Advisor.Reason.Timing.Regular", "Steady {0} s interval (jitter {1} s): each photo becomes one video frame."));
|
||||
Assert.Null(I18nCommand.CountedNoun("Tooltips.Editor.Remote", "Changes are saved on {0} and analyses and renders run there"));
|
||||
Assert.Null(I18nCommand.CountedNoun("Advisor.Reason.Transition.Single", "A single exposure step: a {0}-frame transition keeps the change gentle."));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void ATallyOfParticiplesNeedsLabels()
|
||||
{
|
||||
// Italian reads "1 copiate · 1 non riuscite": the participle agrees with the number in front of it.
|
||||
Assert.Equal("copied", I18nCommand.CountedTally("Import.Result.Partial", "{0} copied · {1} failed"));
|
||||
Assert.Equal("missing", I18nCommand.CountedTally("Archive.Health.Damaged", "{0} missing · {1} damaged"));
|
||||
Assert.Equal("made", I18nCommand.CountedTally("Archive.Log.ImagesDone", "{0}: {1} made, {2} reused, {3} unreadable"));
|
||||
Assert.Equal("copied", I18nCommand.CountedTally("Archive.Log.ImportDone", "{0:N0} copied, {1:N0} skipped, {2:N0} failed."));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void LabelsNamesAndSizesAreNoTally()
|
||||
{
|
||||
Assert.Null(I18nCommand.CountedTally("Import.Result.Partial", "Copied: {0} · failed: {1}"));
|
||||
Assert.Null(I18nCommand.CountedTally("Archive.Log.ImagesDone", "{0}: made {1}, reused {2}, unreadable {3}"));
|
||||
Assert.Null(I18nCommand.CountedTally("Archive.Log.ScanDone", "Folders: {0}, indexed: {1}, adopted: {2}, removed: {3}"));
|
||||
// A single participle after a placeholder is as often a name or a size as a count.
|
||||
Assert.Null(I18nCommand.CountedTally("Export.Log.Failed", "{0} failed: {1}"));
|
||||
Assert.Null(I18nCommand.CountedTally("Library.Queued", "{0} queued · {1}"));
|
||||
Assert.Null(I18nCommand.CountedTally("Import.Plan.SpaceMissing", "{0} missing"));
|
||||
Assert.Null(I18nCommand.CountedTally("Settings.Storage.Usage", "{0} used · {1} free"));
|
||||
Assert.Null(I18nCommand.CountedTally("Import.Result.Skipped.other", "{0:N0} copied, {1:N0} skipped"));
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user