Files
Chronos/tests/Titano.App.Tests/Editor/EditPathSmokeTests.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

391 lines
20 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.Windows;
using System.Windows.Automation;
using System.Windows.Controls;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Threading;
using Titano.App.Editor;
using Titano.App.Infrastructure;
using Titano.App.Sections;
using Titano.App.Shell;
using Titano.App.Tests.Windows;
using Titano.Core.Export;
using Titano.Core.Localization;
using Titano.Testing;
namespace Titano.App.Tests.Editor;
/// <summary>
/// The Edit path in the real main window at the 1200 × 788 capture size (owner review 1, R7): the step bar for screen
/// readers and the keyboard, Previous and Next, the findings' way to their step, the step memory and right to left.
/// </summary>
[WindowsOnly]
[Serial]
[Timeout(300_000)]
public sealed class EditPathSmokeTests
{
[Test]
public Task TheStepBarNamesEachStepItsStateAndItsShortcut() => ScreenHost.RunAsync(async () =>
{
await using var app = await ScreenSmokeTests.SampleApp.StartAsync();
var (editor, view) = await OpenAsync(app);
await using (editor)
{
var steps = StepItems(view);
Assert.Count(8, steps);
for (var i = 0; i < steps.Count; i++)
{
var tab = (EditorTab)steps[i].DataContext;
Assert.Equal(i + 1, tab.Number);
Assert.Equal(tab.Header, AutomationProperties.GetName(steps[i]));
Assert.Equal(tab.StateText, AutomationProperties.GetItemStatus(steps[i]));
Assert.Equal($"Alt+{i + 1}", AutomationProperties.GetAcceleratorKey(steps[i]));
Assert.True(((string)steps[i].ToolTip).EndsWith($"Alt+{i + 1}", StringComparison.Ordinal), $"{tab.Key}: the tooltip names the shortcut");
Assert.False(string.IsNullOrEmpty(tab.StateText), $"{tab.Key}: a state");
}
Assert.Equal(EditPath.Frames, editor.SelectedTab.Key, "an analysed sequence opens on Frames");
Assert.True(editor.Frames.IsVisited);
Assert.False(editor.Exposure.IsVisited);
// Previous waits on the first step; Next names where it goes.
editor.SelectedTab = editor.Analysis;
Assert.False(editor.PreviousStepCommand.CanExecute(null));
Assert.Equal(Loc.L("Tooltips.Editor.Step.First"), editor.PreviousToolTip);
Assert.Equal(Loc.L("Tooltips.Editor.Step.Next", editor.Frames.Header), editor.NextToolTip);
Assert.Equal("1 / 8", editor.StepCounter);
editor.NextStepCommand.Execute(null);
Assert.Same(editor.Frames, editor.SelectedTab);
Assert.Equal(Loc.L("Editor.Step.Announce", 2, 8, editor.Frames.Header, editor.Frames.StateText), editor.StepAnnouncement);
// Alt+3 opens the third step; Ctrl+PgDn and Ctrl+PgUp move one step and stop at the ends.
var root = Find<Grid>(view).Single(g => g.Name == "EditorRoot");
var alt3 = root.InputBindings.OfType<KeyBinding>().Single(b => b.Key == Key.D3 && b.Modifiers == ModifierKeys.Alt);
alt3.Command.Execute(alt3.CommandParameter);
Assert.Same(editor.Exposure, editor.SelectedTab);
Assert.Equal(1, SequenceView.StepDelta(Key.PageDown, ModifierKeys.Control));
Assert.Equal(-1, SequenceView.StepDelta(Key.PageUp, ModifierKeys.Control));
Assert.Null(SequenceView.StepDelta(Key.PageDown, ModifierKeys.None), "Page Down alone stays the filmstrip's");
editor.MoveStep(-10);
Assert.Same(editor.Exposure, editor.SelectedTab, "a move past the first step does nothing");
Assert.False(root.InputBindings.OfType<KeyBinding>().Any(b => b.Modifiers == ModifierKeys.Alt && b.Key is >= Key.NumPad0 and <= Key.NumPad9),
"no Alt+NumPad binding: those type characters into text fields");
// On the last step, Next chooses the next sequence: the picker covers the editor, which stays open.
editor.SelectedTab = editor.Tabs[^1];
Assert.Equal(Loc.L("Editor.Step.NextSequence"), editor.NextText);
editor.NextStepCommand.Execute(null);
Assert.True(app.Shell.Sequence.IsPicking);
Assert.Same(editor, app.Shell.Sequence.Editor);
app.Shell.Sequence.CancelPickCommand.Execute(null);
Assert.False(app.Shell.Sequence.IsPicking);
}
});
[Test]
public Task AFindingOpensTheStepThatDealsWithIt() => ScreenHost.RunAsync(async () =>
{
await using var app = await ScreenSmokeTests.SampleApp.StartAsync();
var (editor, view) = await OpenAsync(app);
await using (editor)
{
editor.SelectedTab = editor.Analysis;
await SettleAsync(app.Window);
var finding = Assert.Contains(editor.Analysis.Findings, f => f.Step is not null && !ReferenceEquals(f.Step, editor.Analysis));
var row = Find<ListBoxItem>(view).Single(i => ReferenceEquals(i.DataContext, finding));
var goTo = Find<Button>(row).Single(b => b.IsVisible);
Assert.Equal(finding.Step!.Header, AutomationProperties.GetName(goTo));
Assert.Equal(Loc.L("Tooltips.Editor.Analysis.GoTo", finding.Step.Header, finding.Step.Number), goTo.ToolTip);
goTo.Command.Execute(goTo.CommandParameter);
Assert.Same(finding.Step, editor.SelectedTab);
// The panel lists the other steps with where each stands; the measurements of the deep analysis show.
editor.SelectedTab = editor.Analysis;
await SettleAsync(app.Window);
Assert.Count(7, editor.Analysis.PathSteps);
Assert.True(editor.Analysis.Rows.OfType<InfoRow>().All(r => r.IsApplicable), "the sequence is analysed: every measurement shows");
}
});
[Test]
public Task TheSectionRemembersTheStepOfEachSequence() => ScreenHost.RunAsync(async () =>
{
await using var app = await ScreenSmokeTests.SampleApp.StartAsync();
var (editor, _) = await OpenAsync(app);
editor.SelectedTab = editor.Tabs.OfType<CameraTab>().Single();
editor.SelectedTab = editor.Exposure;
await app.Shell.Sequence.CloseAsync();
var again = new EditorViewModel(app.Shell, new EditorSession(new FakeSequenceSource(EditorFixture.Sunset, editor.Session.Content), editor.Session.Content, []),
[], EncoderHost.Client);
app.Shell.Sequence.Attach(again);
await using (again)
{
Assert.Same(again.Exposure, again.SelectedTab, "the step shown last");
Assert.True(again.Tabs.OfType<CameraTab>().Single().IsVisited, "and the steps visited");
Assert.False(again.Tabs.OfType<StackTab>().Single().IsVisited);
}
});
/// <summary>
/// At 1200 px every step's tooltip starts with its name (a name cut by an ellipsis reads whole), and every English and
/// Italian name fits its cell, also in semibold as the step shown (owner review 1, R7 review).
/// </summary>
[Test]
public Task StepNamesFitInEnglishAndItalianAndEveryTooltipStartsWithTheName() => ScreenHost.RunAsync(async () =>
{
await using var app = await ScreenSmokeTests.SampleApp.StartAsync();
var (editor, view) = await OpenAsync(app);
await using (editor)
{
try
{
foreach (var language in Languages.Shipped)
{
UiLanguage.Apply(language);
await SettleAsync(app.Window);
foreach (var item in StepItems(view))
{
var tab = (EditorTab)item.DataContext;
Assert.True(((string)item.ToolTip).StartsWith(tab.Header, StringComparison.Ordinal), $"{language}: the {tab.Key} tooltip starts with its name");
if (language is not ("en" or "it")) continue;
var label = Find<TextBlock>(item).Single(t => t.Name == "Label");
var dock = (FrameworkElement)VisualTreeHelper.GetParent(label);
// The badge takes 22 px; the rest of the cell, without the label's margins, is the name's.
var room = dock.ActualWidth - 22 - label.Margin.Left - label.Margin.Right;
Assert.True(Width(label, FontWeights.Normal) <= room + 0.5 && Width(label, FontWeights.SemiBold) <= room + 0.5,
$"{language}: '{tab.Header}' needs {Width(label, FontWeights.SemiBold):0} px in semibold, the cell gives {room:0}");
}
}
}
finally
{
UiLanguage.Apply("en");
}
}
});
/// <summary>On the last step, Previous and "Next sequence" are whole in every language: the counter gives way first.</summary>
[Test]
public Task PreviousAndNextSequenceAreWholeInEveryLanguage() => ScreenHost.RunAsync(async () =>
{
await using var app = await ScreenSmokeTests.SampleApp.StartAsync();
var (editor, view) = await OpenAsync(app);
await using (editor)
{
editor.SelectedTab = editor.Tabs[^1];
try
{
foreach (var language in Languages.Shipped)
{
UiLanguage.Apply(language);
await SettleAsync(app.Window);
var previous = Find<Button>(view).Single(b => b.Name == "PreviousStep");
var next = Find<Button>(view).Single(b => b.Name == "NextStep");
var row = (FrameworkElement)VisualTreeHelper.GetParent(next);
foreach (var button in new[] { previous, next })
{
var shown = button.ActualWidth;
button.Measure(new Size(double.PositiveInfinity, double.PositiveInfinity));
var wanted = button.DesiredSize.Width;
button.InvalidateMeasure();
Assert.True(wanted <= shown + 0.5, $"{language}: '{AutomationProperties.GetName(button)}{button.Content}' needs {wanted:0} px, has {shown:0}");
var left = button.TranslatePoint(new Point(0, 0), row).X;
var right = button.TranslatePoint(new Point(button.ActualWidth, 0), row).X;
Assert.True(double.Min(left, right) >= -0.5 && double.Max(left, right) <= row.ActualWidth + 0.5, $"{language}: inside the column");
}
app.Window.UpdateLayout();
}
}
finally
{
UiLanguage.Apply("en");
}
}
});
/// <summary>
/// A step's own button (a finding's) and Previous turning itself off on the first step leave the keyboard on the new
/// step's cell, so the editor's shortcuts keep working (it used to fall to the window).
/// </summary>
[Test]
public Task TheKeyboardFollowsTheStep() => ScreenHost.RunAsync(async () =>
{
await using var app = await ScreenSmokeTests.SampleApp.StartAsync();
var (editor, view) = await OpenAsync(app);
await using (editor)
{
editor.SelectedTab = editor.Analysis;
await SettleAsync(app.Window);
var finding = Assert.Contains(editor.Analysis.Findings, f => f.Step is not null);
var row = Find<ListBoxItem>(view).Single(i => ReferenceEquals(i.DataContext, finding));
var goTo = Find<Button>(row).Single(b => b.IsVisible);
FocusManager.SetFocusedElement(app.Window, goTo);
goTo.Command.Execute(goTo.CommandParameter);
await SettleAsync(app.Window);
Assert.Same(StepItems(view)[finding.Step!.Number - 1], FocusManager.GetFocusedElement(app.Window), "the new step's cell has the keyboard");
editor.SelectedTab = editor.Frames;
await SettleAsync(app.Window);
var previous = Find<Button>(view).Single(b => b.Name == "PreviousStep");
FocusManager.SetFocusedElement(app.Window, previous);
previous.Command.Execute(null);
await SettleAsync(app.Window);
Assert.False(previous.IsEnabled, "Previous waits on the first step");
Assert.Same(StepItems(view)[0], FocusManager.GetFocusedElement(app.Window));
}
});
/// <summary>Space on the step shown plays, as everywhere in the editor (the step bar used to swallow it).</summary>
[Test]
public Task SpaceOnTheStepShownPlays() => ScreenHost.RunAsync(async () =>
{
await using var app = await ScreenSmokeTests.SampleApp.StartAsync();
var (editor, view) = await OpenAsync(app);
await using (editor)
{
var cell = StepItems(view)[editor.SelectedTab.Number - 1];
Assert.False(editor.IsPlaying);
cell.RaiseEvent(new KeyEventArgs(Keyboard.PrimaryDevice, PresentationSource.FromVisual(cell)!, 0, Key.Space) { RoutedEvent = Keyboard.PreviewKeyDownEvent });
Assert.True(editor.IsPlaying);
editor.PlayCommand.Execute(null);
Assert.True(cell.IsSelected, "the step stays the current one");
}
});
/// <summary>
/// The title button names the sequence first (accessible name and tooltip); Export gives its preset cards more of the
/// height than the preview (Export.html); the findings read as their sentences, and only those with a frame offer a seek.
/// </summary>
[Test]
public Task TheTitleTheExportLayoutAndTheFindingRows() => ScreenHost.RunAsync(async () =>
{
await using var app = await ScreenSmokeTests.SampleApp.StartAsync();
var (editor, view) = await OpenAsync(app);
await using (editor)
{
var title = Find<Button>(view).Single(b => b.Name == "ChangeSequence");
Assert.True(AutomationProperties.GetName(title).StartsWith(editor.Title, StringComparison.Ordinal), "its name starts with its visible text");
Assert.True(((string)title.ToolTip).StartsWith(editor.Title, StringComparison.Ordinal), "a cut title reads whole on hover");
editor.SelectedTab = editor.Tabs[^1];
await SettleAsync(app.Window);
Assert.True(editor.IsTallMeasure);
var measure = Find<ContentControl>(view).Single(c => c.Name == "StepMeasure");
var preview = Find<Titano.Ui.Visuals.PreviewViewport>(view).Single(v => v.IsVisible);
Assert.Greater(measure.ActualHeight, preview.ActualHeight, "the preset cards take more room than the preview");
editor.SelectedTab = editor.Analysis;
await SettleAsync(app.Window);
Assert.True(editor.Analysis.Findings.Any(f => f.Frame is null) && editor.Analysis.Findings.Any(f => f.Frame is not null), "the fixture has both kinds");
foreach (var finding in editor.Analysis.Findings)
{
var row = Find<ListBoxItem>(view).Single(i => ReferenceEquals(i.DataContext, finding));
Assert.Equal(finding.Text, System.Windows.Automation.Peers.UIElementAutomationPeer.CreatePeerForElement(row).GetName());
Assert.Equal(finding.Frame is null, row.ToolTip is null, $"'{finding.Text}': a seek is offered only with a frame");
}
}
});
/// <summary>A deep analysis that ended while the sequence was closed leaves only the step shown visited when it opens again.</summary>
[Test]
public Task AnAnalysisThatEndedWhileClosedResetsTheVisitedSteps() => ScreenHost.RunAsync(async () =>
{
await using var app = await ScreenSmokeTests.SampleApp.StartAsync();
var bare = EditorFixture.Content(EditorFixture.Sunset, deep: false);
var editor = new EditorViewModel(app.Shell, new EditorSession(new FakeSequenceSource(EditorFixture.Sunset, bare), bare, []), [], EncoderHost.Client);
app.Shell.Sequence.Attach(editor);
app.Shell.Navigate(SectionKey.Edit);
await SettleAsync(app.Window);
editor.SelectedTab = editor.Frames;
editor.SelectedTab = editor.Exposure;
await app.Shell.Sequence.CloseAsync();
var analysed = bare with { Deep = EditorFixture.Content(EditorFixture.Sunset).Deep };
var again = new EditorViewModel(app.Shell, new EditorSession(new FakeSequenceSource(EditorFixture.Sunset, analysed), analysed, []), [], EncoderHost.Client);
app.Shell.Sequence.Attach(again);
await using (again)
{
Assert.Same(again.Exposure, again.SelectedTab, "the step shown last");
Assert.True(again.Exposure.IsVisited);
Assert.False(again.Frames.IsVisited, "the analysis changed the steps: they are to be looked at again");
Assert.False(again.Analysis.IsVisited);
}
});
[Test]
public Task TheStepsRunFromTheRightInArabic() => ScreenHost.RunAsync(async () =>
{
await using var app = await ScreenSmokeTests.SampleApp.StartAsync("ar");
var (editor, view) = await OpenAsync(app);
await using (editor)
{
var steps = StepItems(view);
var first = steps[0].PointToScreen(new Point(steps[0].ActualWidth / 2, 0)).X;
var second = steps[1].PointToScreen(new Point(steps[1].ActualWidth / 2, 0)).X;
Assert.Greater(first, second, "step 1 sits to the right of step 2");
}
});
/// <summary>The synthetic sunset, analysed, open in Edit at 1200 × 788.</summary>
private static async Task<(EditorViewModel Editor, SequenceView View)> OpenAsync(ScreenSmokeTests.SampleApp app)
{
app.Window.Width = 1200;
app.Window.Height = 788;
var content = EditorFixture.Content(EditorFixture.Sunset);
var editor = new EditorViewModel(app.Shell, new EditorSession(new FakeSequenceSource(EditorFixture.Sunset, content), content, []), [], EncoderHost.Client);
app.Shell.Sequence.Attach(editor);
app.Shell.Navigate(SectionKey.Edit);
await SettleAsync(app.Window);
Assert.True(await editor.WhenIdleAsync(TimeSpan.FromSeconds(60)), "the editor settled");
await SettleAsync(app.Window);
return (editor, Find<SequenceView>(app.Window).Single(v => v.IsVisible));
}
private static List<ListBoxItem> StepItems(SequenceView view)
{
var bar = Find<ListBox>(view).Single(l => l.Name == "Steps");
return [.. bar.Items.Cast<object>().Select(item => (ListBoxItem)bar.ItemContainerGenerator.ContainerFromItem(item))];
}
/// <summary>The width <paramref name="text"/>'s text needs in <paramref name="weight"/>, measured by the same layout engine.</summary>
private static double Width(TextBlock text, FontWeight weight)
{
var probe = new TextBlock
{
Text = text.Text,
FontFamily = text.FontFamily,
FontSize = text.FontSize,
FontStyle = text.FontStyle,
FontWeight = weight,
FontStretch = text.FontStretch,
FlowDirection = text.FlowDirection,
Language = text.Language,
};
TextOptions.SetTextFormattingMode(probe, TextOptions.GetTextFormattingMode(text));
probe.Measure(new Size(double.PositiveInfinity, double.PositiveInfinity));
return probe.DesiredSize.Width;
}
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;
}
}