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]
|
||||
|
||||
Reference in new issue
Block a user