Files
Chronos/tests/Titano.App.Tests/Windows/EditSectionTests.cs
T
Alby96 5aeb6aa787 Add comprehensive tests for EditSection functionality in the Windows application
- Implement tests for picker behavior, including loading sequences, searching, and handling empty libraries.
- Validate sequence opening via Enter key and double-click actions.
- Ensure proper handling of unsaved edits and sequence deletion scenarios.
- Verify accessibility features for picker rows across different languages.
- Introduce a dialog counting mechanism to manage unsaved edit confirmations.
2026-10-19 12:10:42 +02:00

483 lines
24 KiB
C#
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
using System.IO;
using System.Windows;
using System.Windows.Automation;
using System.Windows.Automation.Peers;
using System.Windows.Controls;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Threading;
using Titano.App.Archiving;
using Titano.App.Editor;
using Titano.App.Infrastructure;
using Titano.App.Library;
using Titano.App.Sections;
using Titano.App.Shell;
using Titano.App.Tests.Editor;
using Titano.Core.Export;
using Titano.Core.Localization;
using Titano.Data.Archiving;
using Titano.Testing;
using Titano.Ui.Controls;
using Titano.Ui.Mvvm;
namespace Titano.App.Tests.Windows;
/// <summary>
/// The Edit section's picker (owner review 1, R7) on the capture sample: one list of this PC's and the server's
/// sequences, the search, the empty states, opening with Enter or a double-click, Change sequence and Esc, a sequence
/// that cannot open, the open sequence deleted, and the open sequence's unsaved edit, kept or discarded, asked about once.
/// </summary>
[WindowsOnly]
[Serial]
[Timeout(300_000)]
public sealed class EditSectionTests
{
[Test]
public Task ThePickerListsThisPcAndTheServerNewestFirstAndSearches() => 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();
await app.Shell.Library.RefreshAsync();
var section = app.Shell.Sequence;
app.Shell.Navigate(SectionKey.Edit);
await section.Picker.Loading;
await app.ExpectAsync<SequenceView>("edit-picker");
Assert.True(section.ShowsPicker, "no sequence open: the picker shows");
Assert.Equal(Text("Shell.Nav.Edit"), section.Title);
var items = section.Picker.Items.ToList();
Assert.True(items.Count > 10, "the sample's sequences");
var captures = items.Select(i => i.Sequence.FirstCapture).ToList();
for (var i = 1; i < captures.Count; i++)
Assert.True(captures[i] is not { } after || (captures[i - 1] is { } before && before >= after), $"newest first at row {i}");
Assert.Contains(items, i => i.IsRemote && i.Title == "Sunrise over Superga");
Assert.Same(items[0], section.Picker.Selected, "nothing edited yet: the first row is selected");
// The search narrows the list a moment after the last key; no match offers Clear search.
await SearchAsync(section, "harbour");
Assert.True(section.Picker.Items.Count is > 0 and < 5, "only the harbour sequence");
Assert.True(section.Picker.Items.All(i => i.Title.Contains("Harbour", StringComparison.OrdinalIgnoreCase)));
await SearchAsync(section, "no such sequence");
Assert.True(section.Picker.IsNoMatch);
Assert.False(section.Picker.IsEmptyLibrary);
var shown = section.Picker.Loading;
section.Picker.ClearCommand.Execute(null);
await DebouncedAsync(section, shown);
Assert.Equal(items.Count, section.Picker.Items.Count);
});
[Test]
public Task AnEmptyLibraryOffersImport() => ScreenHost.RunAsync(async () =>
{
await using var app = await ScreenSmokeTests.SampleApp.StartAsync();
var section = app.Shell.Sequence;
app.Shell.Navigate(SectionKey.Edit);
await section.Picker.Loading;
Assert.True(section.Picker.IsEmptyLibrary);
Assert.False(section.Picker.OpenCommand.CanExecute(null));
section.OpenImportCommand.Execute(null);
Assert.Equal(SectionKey.Import, app.Shell.Current.Key);
});
[Test]
public Task EnterOpensTheSequenceAndChangeSequenceComesBackToTheSameEditor() => ScreenHost.RunAsync(async () =>
{
var saves = 0;
await using var app = await ScreenSmokeTests.SampleApp.StartAsync(saveSettings: () => saves++);
await app.Sample.FillAsync();
var section = app.Shell.Sequence;
app.Shell.Navigate(SectionKey.Edit);
await section.Picker.Loading;
await SettleAsync(app.Window);
// The search box has the keyboard; Enter there opens the selected row (the first).
var first = section.Picker.Items[0];
var search = Find<TextBox>(app.Window).Single(t => t.Name == "Search");
Assert.Same(search, FocusManager.GetFocusedElement(app.Window), "the search box has the keyboard when the picker shows");
Press(search, Key.Enter);
var editor = await OpenedAsync(section);
Assert.Equal(first.Id, editor.Session.Content.Sequence.Id);
Assert.False(section.ShowsPicker);
Assert.Equal(first.Id, app.Shell.Services.Settings.LastEditedSequence);
Assert.True(saves > 0, "the sequence edited last is written");
await SettleAsync(app.Window);
// Change sequence: the picker covers the editor, which stays open and laid out; the open sequence is selected.
Assert.True(section.ChangeSequenceCommand.CanExecute(null), "the open has ended");
section.ChangeSequenceCommand.Execute(null);
await section.Picker.Loading;
await SettleAsync(app.Window);
Assert.True(section.ShowsPicker && section.IsPicking);
Assert.Same(search, FocusManager.GetFocusedElement(app.Window), "the search box has the keyboard again");
Assert.Equal(first.Id, section.Picker.Selected?.Id);
Assert.Equal(Text("Shell.Nav.Edit"), section.Title, "the window title names the section while choosing");
var root = Find<Grid>(app.Window).Single(g => g.Name == "EditorRoot");
Assert.Greater(root.ActualWidth, 0, "the editor stays laid out behind the picker");
// Esc with an empty search goes back to the same editor.
Press(search, Key.Escape);
Assert.False(section.IsPicking);
Assert.Same(editor, section.Editor);
// Coming back to Edit leaves a choice on screen; asking for the open sequence (the Library's Open) ends it.
Assert.True(section.ChangeSequenceCommand.CanExecute(null));
section.ChangeSequenceCommand.Execute(null);
app.Shell.Navigate(SectionKey.Library);
app.Shell.Navigate(SectionKey.Edit);
Assert.True(section.IsPicking, "coming back to Edit leaves the choice on screen");
app.Shell.Navigate(SectionKey.Library);
app.Shell.OpenSequence(first.Id);
Assert.Equal(SectionKey.Edit, app.Shell.Current.Key);
Assert.False(section.IsPicking, "opening the open sequence shows it");
Assert.Same(editor, section.Editor);
// Also while Edit is on screen (a toast's Open, a project file of the open sequence).
section.ChangeSequenceCommand.Execute(null);
app.Shell.OpenSequence(first.Id);
Assert.False(section.IsPicking);
Assert.Same(editor, section.Editor);
});
/// <summary>Enter typed within the search's 250 ms opens a match of what was typed, not the row selected before.</summary>
[Test]
public Task EnterRightAfterTypingOpensAMatch() => ScreenHost.RunAsync(async () =>
{
await using var app = await ScreenSmokeTests.SampleApp.StartAsync();
await app.Sample.FillAsync();
var section = app.Shell.Sequence;
app.Shell.Navigate(SectionKey.Edit);
await section.Picker.Loading;
await SettleAsync(app.Window);
Assert.False(section.Picker.Selected!.Title.Contains("Langhe", StringComparison.OrdinalIgnoreCase), "another sequence is selected first");
var search = Find<TextBox>(app.Window).Single(t => t.Name == "Search");
section.Picker.SearchText = "langhe";
Press(search, Key.Enter);
var editor = await OpenedAsync(section);
Assert.True(editor.Title.Contains("Langhe", StringComparison.OrdinalIgnoreCase), $"opened '{editor.Title}'");
});
/// <summary>A double-click on a row opens it, in the picker and in the Library's list and grid (the row takes the mouse-down).</summary>
[Test]
public Task ADoubleClickOnARowOpensIt() => ScreenHost.RunAsync(async () =>
{
await using var app = await ScreenSmokeTests.SampleApp.StartAsync();
await app.Sample.FillAsync();
var section = app.Shell.Sequence;
app.Shell.Navigate(SectionKey.Edit);
await section.Picker.Loading;
await SettleAsync(app.Window);
var list = Find<ListBox>(app.Window).Single(l => l.Name == "List" && l.IsVisible);
var item = section.Picker.Items.Skip(1).First(i => !i.IsRemote);
DoubleClick(Cell(list, item));
var editor = await OpenedAsync(section);
Assert.Equal(item.Id, editor.Session.Content.Sequence.Id, "the row double-clicked opened, not the one selected");
// The Library's list and grid: a double-click opens the sequence in Edit.
foreach (var grid in new[] { false, true })
{
app.Shell.Navigate(SectionKey.Library);
await app.Shell.Library.RefreshAsync();
app.Shell.Library.LayoutIndex = grid ? 0 : 1;
await SettleAsync(app.Window);
var name = grid ? "CardGrid" : "RowList";
var library = Find<ListBox>(app.Window).Single(l => l.Name == name && l.IsVisible);
var target = app.Shell.Library.Items.First(i => !i.IsRemote && i.Id != app.Shell.CurrentSequenceId);
DoubleClick(Cell(library, target));
Assert.Equal(SectionKey.Edit, app.Shell.Current.Key, grid ? "a card" : "a row");
Assert.Equal(target.Id, app.Shell.CurrentSequenceId);
await OpenedAsync(section, target.Id);
}
});
/// <summary>
/// A sequence that cannot open (gone from the index, no server to ask) leaves the open one open behind the picker, with
/// Cancel still there, and the open one again the sequence asked for (owner review 1, R7 review).
/// </summary>
[Test]
public Task ASequenceThatCannotOpenLeavesTheOpenOneOpen() => ScreenHost.RunAsync(async () =>
{
await using var app = await ScreenSmokeTests.SampleApp.StartAsync();
await app.Sample.FillAsync();
var section = app.Shell.Sequence;
app.Shell.Navigate(SectionKey.Edit);
await section.Picker.Loading;
var first = section.Picker.Items.First(i => !i.IsRemote);
await section.PickAsync(first);
var editor = await OpenedAsync(section);
section.ChangeSequenceCommand.Execute(null);
await section.Picker.Loading;
// The window shows and clears the toasts: they are counted as they come.
var errors = 0;
app.Shell.PendingToasts.CollectionChanged += (_, e) => errors += e.NewItems?.OfType<Toast>().Count(t => t.IsError) ?? 0;
var gone = new SequenceItem(first.Sequence with { Id = Guid.CreateVersion7() }, null);
await section.PickAsync(gone);
Assert.Same(editor, section.Editor, "the open sequence stayed open");
Assert.True(section.IsPicking && section.CanCancelPick, "the choice goes on, and Cancel goes back");
Assert.Equal(first.Id, app.Shell.CurrentSequenceId, "the open sequence is again the one asked for");
Assert.Equal(1, errors, "the failure is reported once");
section.CancelPickCommand.Execute(null);
app.Shell.Navigate(SectionKey.Library);
app.Shell.Navigate(SectionKey.Edit);
await SettleAsync(app.Window);
Assert.Same(editor, section.Editor);
Assert.Equal(1, errors, "coming back neither tries again nor reports it again");
});
/// <summary>The open sequence deleted from the Library: the editor closes, and coming back to Edit shows the picker, not a failed open.</summary>
[Test]
public Task DeletingTheOpenSequenceLeavesThePicker() => ScreenHost.RunAsync(async () =>
{
await using var app = await ScreenSmokeTests.SampleApp.StartAsync();
await app.Sample.FillAsync();
var section = app.Shell.Sequence;
app.Shell.Navigate(SectionKey.Edit);
await section.Picker.Loading;
var first = section.Picker.Items.First(i => !i.IsRemote);
await section.PickAsync(first);
await OpenedAsync(section);
var row = Assert.NotNull(await app.Shell.Services.Database!.Sequences.GetAsync(first.Id));
app.Shell.Navigate(SectionKey.Library);
Assert.True(await SequenceDeletion.CloseEditorAsync(app.Shell, new DeletePlan([new DeleteStep(row, null, 0, 0)], [])));
Assert.Null(section.Editor, "the editor closed");
Assert.Null(app.Shell.CurrentSequenceId, "the deleted sequence is no longer asked for");
var errors = 0;
app.Shell.PendingToasts.CollectionChanged += (_, e) => errors += e.NewItems?.OfType<Toast>().Count(t => t.IsError) ?? 0;
app.Shell.Navigate(SectionKey.Edit);
await section.Picker.Loading;
await SettleAsync(app.Window);
Assert.True(section.ShowsPicker);
Assert.False(section.IsLoading);
Assert.Equal(0, errors, "no failed open");
});
/// <summary>
/// The sequence edited last is selected and in view even when it is older than the first page (read on until it comes),
/// and with a sequence open the open one is (owner review 1, R7 review).
/// </summary>
[Test]
public Task TheSequenceEditedLastIsSelectedAndShownBeyondTheFirstPage() => ScreenHost.RunAsync(async () =>
{
await using var app = await ScreenSmokeTests.SampleApp.StartAsync();
app.Window.Width = 1200;
app.Window.Height = 788;
await app.Sample.FillAsync();
var section = app.Shell.Sequence;
app.Shell.Navigate(SectionKey.Edit);
await section.Picker.Loading;
var oldest = section.Picker.Items.Last(i => !i.IsRemote);
Assert.True(section.Picker.Items.IndexOf(oldest) > 20, "an old sequence, far down the list");
app.Shell.Services.Settings.LastEditedSequence = oldest.Id;
section.Picker.PageSize = 5;
await section.Picker.ReloadAsync();
await SettleAsync(app.Window);
Assert.Equal(oldest.Id, section.Picker.Selected?.Id, "read on until the sequence edited last is listed");
var list = Find<ListBox>(app.Window).Single(l => l.Name == "List" && l.IsVisible);
var row = Assert.NotNull(list.ItemContainerGenerator.ContainerFromItem(section.Picker.Selected!) as ListBoxItem, "its row is realised");
var top = row.TranslatePoint(new Point(0, 0), list).Y;
Assert.True(top >= -0.5 && top + row.ActualHeight <= list.ActualHeight + 0.5, "and scrolled into view");
});
/// <summary>
/// At 1200 px in every language each picker row reads as its title to screen readers, and its states (Analysed,
/// Proxies, Remote) are whole inside the row.
/// </summary>
[Test]
public Task PickerRowsReadAsTheirTitleAndKeepTheirStatesWholeInEveryLanguage() => ScreenHost.RunAsync(async () =>
{
await using var app = await ScreenSmokeTests.SampleApp.StartAsync();
app.Window.Width = 1200;
app.Window.Height = 788;
await app.Sample.FillAsync();
await app.Shell.Services.Server.RestoreAsync();
await app.Shell.Services.Sync.RefreshAsync();
await app.Shell.Library.RefreshAsync();
var section = app.Shell.Sequence;
app.Shell.Navigate(SectionKey.Edit);
await section.Picker.Loading;
try
{
foreach (var language in Languages.Shipped)
{
UiLanguage.Apply(language);
await section.Picker.ReloadAsync();
await SettleAsync(app.Window);
var rows = Find<ListBoxItem>(app.Window).Where(r => r.IsVisible && r.DataContext is SequenceItem).ToList();
Assert.True(rows.Count > 5, $"{language}: rows show");
Assert.True(rows.Any(r => ((SequenceItem)r.DataContext).IsRemote), $"{language}: a server row shows");
foreach (var row in rows)
{
var item = (SequenceItem)row.DataContext;
Assert.Equal(item.Title, UIElementAutomationPeer.CreatePeerForElement(row).GetName(), $"{language}: the row reads as its title");
var states = Find<ItemsControl>(row).Single(c => c.ItemsSource is not null && !ReferenceEquals(c, row));
var a = states.TranslatePoint(new Point(0, 0), row).X;
var b = states.TranslatePoint(new Point(states.ActualWidth, 0), row).X;
Assert.True(double.Min(a, b) >= row.Padding.Left - 0.5 && double.Max(a, b) <= row.ActualWidth - row.Padding.Right + 0.5,
$"{language}: the states of '{item.Title}' span {double.Min(a, b):0}–{double.Max(a, b):0} px in a {row.ActualWidth:0} px row");
}
}
}
finally
{
UiLanguage.Apply("en");
}
});
[Test]
public Task AnUnsavedEditIsAskedAboutOnceAndKeptOrDiscarded() => ScreenHost.RunAsync(async () =>
{
var dialogs = new CountingDialogs { Discard = false };
await using var app = await ScreenSmokeTests.SampleApp.StartAsync(dialogs: dialogs);
await app.Sample.FillAsync();
var section = app.Shell.Sequence;
var content = EditorFixture.Content(EditorFixture.Sunset);
var source = new FakeSequenceSource(EditorFixture.Sunset, content);
var editor = new EditorViewModel(app.Shell, new EditorSession(source, content, []), [], EncoderHost.Client);
section.Attach(editor);
app.Shell.KeepSequence(content.Sequence.Id);
app.Shell.Navigate(SectionKey.Edit);
await SettleAsync(app.Window);
section.ChangeSequenceCommand.Execute(null);
await section.Picker.Loading;
var other = section.Picker.Items.First(i => !i.IsRemote);
// The archive stays offline: Keep editing keeps the open sequence, which stays the one asked for.
editor.Session.Edit(p => p with { HeroFrame = 2 });
source.FailSaves = new IOException("The archive drive is gone");
await section.PickAsync(other);
Assert.Equal(1, dialogs.Asked);
Assert.Same(editor, section.Editor);
Assert.False(section.IsPicking);
Assert.Equal(content.Sequence.Id, app.Shell.CurrentSequenceId);
app.Shell.Navigate(SectionKey.Library);
app.Shell.Navigate(SectionKey.Edit);
await SettleAsync(app.Window);
Assert.Equal(1, dialogs.Asked, "coming back to Edit does not ask again");
Assert.Same(editor, section.Editor, "nor opens the other sequence");
Assert.Equal(content.Sequence.Id, app.Shell.CurrentSequenceId);
// Discard: the archive answers again while the question is open (retries would write the edit then), yet the edit is
// dropped unwritten and the other sequence opens.
dialogs.Discard = true;
dialogs.WhileAsked = () =>
{
source.FailSaves = null;
PumpFor(TimeSpan.FromSeconds(2.5));
};
editor.Session.Edit(p => p with { HeroFrame = 3 });
var saves = source.Saves;
await section.PickAsync(other);
Assert.Equal(2, dialogs.Asked);
Assert.Equal(other.Id, section.Editor?.Session.Content.Sequence.Id);
Assert.Equal(saves, source.Saves, "nothing was written once the user chose to discard");
Assert.NotEqual(3, source.Stored.HeroFrame);
});
/// <summary>Types <paramref name="text"/> in the search and waits for the list it reads.</summary>
private static async Task SearchAsync(SequenceViewModel section, string text)
{
var before = section.Picker.Loading;
section.Picker.SearchText = text;
await DebouncedAsync(section, before);
}
/// <summary>Waits for the search's own read (its 250 ms timer fires), then for the list it reads, whatever the machine's speed.</summary>
private static async Task DebouncedAsync(SequenceViewModel section, Task before)
{
for (var i = 0; i < 250 && ReferenceEquals(section.Picker.Loading, before); i++) await Task.Delay(20);
Assert.False(ReferenceEquals(section.Picker.Loading, before), "the search read the list again");
await section.Picker.Loading;
}
/// <summary>Waits until a sequence (<paramref name="id"/>, else any) is open and the whole open, Enter included, has ended.</summary>
private static async Task<EditorViewModel> OpenedAsync(SequenceViewModel section, Guid? id = null)
{
bool Busy() => section.Editor is not { } editor || (id is { } wanted && editor.Session.Content.Sequence.Id != wanted) || section.IsLoading
|| ((AsyncRelayCommand)section.Picker.SearchOpenCommand).IsRunning || ((AsyncRelayCommand)section.Picker.OpenItemCommand).IsRunning;
for (var i = 0; i < 400 && Busy(); i++) await Task.Delay(50);
Assert.False(Busy(), "the sequence opened");
await section.Editor!.WhenIdleAsync(TimeSpan.FromSeconds(30));
return section.Editor;
}
private static void Press(UIElement target, Key key) =>
target.RaiseEvent(new KeyEventArgs(Keyboard.PrimaryDevice, PresentationSource.FromVisual(target)!, 0, key) { RoutedEvent = Keyboard.PreviewKeyDownEvent });
/// <summary>A left double-click as the mouse raises it: a mouse-down with a click count of 2 on a text of the row (else on the row).</summary>
private static void DoubleClick(ListBoxItem row)
{
UIElement target = Find<TextBlock>(row).FirstOrDefault(t => t.IsVisible && t.ActualWidth > 0) as UIElement ?? row;
var down = new MouseButtonEventArgs(Mouse.PrimaryDevice, Environment.TickCount, MouseButton.Left) { RoutedEvent = Mouse.MouseDownEvent };
typeof(MouseButtonEventArgs).GetProperty(nameof(MouseButtonEventArgs.ClickCount))!.SetValue(down, 2);
target.RaiseEvent(down);
}
/// <summary>The row of <paramref name="item"/>, scrolled into view.</summary>
private static ListBoxItem Cell(ListBox list, object item)
{
list.ScrollIntoView(item);
list.UpdateLayout();
return Assert.NotNull(list.ItemContainerGenerator.ContainerFromItem(item) as ListBoxItem, "the row is realised");
}
/// <summary>Runs the dispatcher for <paramref name="time"/> (a modal dialog's loop: timers and saves go on meanwhile).</summary>
private static void PumpFor(TimeSpan time)
{
var frame = new DispatcherFrame();
var timer = new DispatcherTimer(time, DispatcherPriority.Normal, (_, _) => frame.Continue = false, Dispatcher.CurrentDispatcher);
timer.Start();
Dispatcher.PushFrame(frame);
timer.Stop();
}
private static string Text(string key) => Loc.L(key);
private static async Task SettleAsync(Window window)
{
window.UpdateLayout();
await window.Dispatcher.InvokeAsync(() => { }, DispatcherPriority.ApplicationIdle);
await Task.Delay(30);
await window.Dispatcher.InvokeAsync(() => { }, DispatcherPriority.ApplicationIdle);
window.UpdateLayout();
}
private static List<T> Find<T>(DependencyObject root)
where T : DependencyObject
{
var found = new List<T>();
var stack = new Stack<DependencyObject>([root]);
while (stack.TryPop(out var node))
{
if (node is T match) found.Add(match);
for (var i = 0; i < VisualTreeHelper.GetChildrenCount(node); i++) stack.Push(VisualTreeHelper.GetChild(node, i));
}
return found;
}
/// <summary>Counts the confirmations asked and answers them as told (true discards the unsaved edit).</summary>
private sealed class CountingDialogs : IAppDialogs
{
public bool Discard { get; set; }
public int Asked { get; private set; }
/// <summary>Runs while the question is open (before the answer), as the user reads it.</summary>
public Action? WhileAsked { get; set; }
public string? PickFolder(string title, string? initialFolder = null) => null;
public string? PickJsonFile(string title) => null;
public bool Confirm(ConfirmRequest request)
{
Asked++;
WhileAsked?.Invoke();
return Discard;
}
public bool SignIn(string server, string? username, Func<string, string, Task<string?>> signIn) => false;
}
}