Files
Chronos/tests/Titano.App.Tests/Windows/ScreenSmokeTests.cs
T
Claude c6efccf4a9 test(app): smoke tests of every Import state and Archive view in both themes
The screen smoke host's SampleApp becomes internal so the Import and Archive
tests render the same scenes as --capture.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_012iLMBNwBE2GnphAsu4cjaC
2026-10-02 22:24:11 +00:00

328 lines
13 KiB
C#

using System.Windows;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Threading;
using Titano.App.DesignTime;
using Titano.App.Infrastructure;
using Titano.App.Sections;
using Titano.App.Server;
using Titano.App.Settings;
using Titano.App.Shell;
using Titano.Testing;
using Titano.Ui.Controls;
using Titano.Ui.Theming;
using Titano.Ui.Visuals;
namespace Titano.App.Tests.Windows;
/// <summary>
/// Shows the real main window off screen (section templates, client styles) on the sample data used by
/// <c>--capture</c> and renders every screen in both themes: catches XAML, resource, template and view-model wiring
/// errors that compile cleanly. Mirrors <see cref="ScreenCapture"/> step by step.
/// </summary>
[WindowsOnly]
[Serial]
[Timeout(300_000)]
public sealed class ScreenSmokeTests
{
[Test]
public Task EveryScreenRendersWithSampleDataInBothThemes() => ScreenHost.RunAsync(async () =>
{
await using var app = await SampleApp.StartAsync();
var shell = app.Shell;
// First run: empty index, the welcome dialog over the empty Library.
Assert.True(shell.Library.IsLibraryEmpty, "an empty index shows the empty Library");
Assert.False(shell.IsJobActive);
shell.ShowWelcome();
shell.Welcome!.ShowDiscovered(new DiscoveredServer("Studio NAS", "https://nas.local:8443"));
await app.ExpectAsync<WelcomeView>("welcome");
Assert.True(shell.Welcome.IsLocal, "a local archive is the default choice");
shell.CompleteWelcome();
Assert.False(shell.IsWelcomeOpen);
await app.ExpectAsync<LibraryView>("library-empty");
shell.Navigate(SectionKey.Server);
await app.ExpectAsync<ServerView>("server-signedout");
Assert.False(shell.Server.IsConnected);
// A populated archive, jobs in every state, a signed-in server.
await app.Sample.FillAsync();
await shell.Library.RefreshAsync();
await shell.Jobs.ReloadAsync();
await shell.Services.Server.RestoreAsync();
shell.About.SetResult(null);
await shell.Settings.DetectEncodersAsync();
await shell.Settings.SelfTestAsync();
shell.Navigate(SectionKey.Library);
Assert.Equal(36, shell.Library.Items.Count);
Assert.True(shell.Library.IsGrid);
await app.ExpectAsync<LibraryView>("library", waitForThumbnails: true);
Assert.NotEmpty(app.FindAll<SequenceCard>());
// The newest sequence is a RAW: its card shows the embedded preview.
Assert.Equal("Harbour sunset", shell.Library.Items[0].Title);
Assert.NotNull(shell.Library.Items[0].Thumbnail, "embedded preview of the first card");
shell.Library.Items[0].IsSelected = true;
Assert.True(shell.Library.IsSingleSelection);
await app.ExpectAsync<LibraryView>("library-selection", waitForThumbnails: true);
shell.Library.LayoutIndex = 1;
Assert.True(shell.Library.IsList);
await app.ExpectAsync<LibraryView>("library-list", waitForThumbnails: true);
shell.Library.LayoutIndex = 0;
shell.Library.ClearSelectionCommand.Execute(null);
Assert.Equal(0, shell.Library.SelectionCount);
shell.Navigate(SectionKey.Jobs);
Assert.Equal(9, shell.Jobs.Rows.Count);
Assert.True(shell.IsJobActive, "running jobs show in the job bar");
shell.Jobs.Rows[0].IsExpanded = true;
await app.ExpectAsync<JobsView>("jobs");
shell.Navigate(SectionKey.Server);
Assert.True(shell.Server.IsConnected, "the saved session is restored");
await app.ExpectAsync<ServerView>("server");
shell.Navigate(SectionKey.Settings);
Assert.Equal(3, shell.Settings.PreviewNames.Count);
Assert.Equal(6, shell.Settings.Encoders.Count);
foreach (var page in Enum.GetValues<SettingsPage>())
{
shell.Settings.Page = page;
await app.ExpectAsync<SettingsView>("settings-" + page.ToString().ToLowerInvariant());
}
shell.Navigate(SectionKey.About);
await app.ExpectAsync<AboutView>("about");
shell.Navigate(SectionKey.Import);
await app.ExpectAsync<ImportView>("import");
shell.Navigate(SectionKey.Sequence);
await app.ExpectAsync<SequenceView>("sequence");
shell.Navigate(SectionKey.Archive);
await app.ExpectAsync<ArchiveView>("archive");
});
[Test]
public Task TheShellFollowsTheLanguage() => ScreenHost.RunAsync(async () =>
{
await using var app = await SampleApp.StartAsync();
var english = app.Shell.Library.Title;
UiLanguage.Apply("it");
try
{
Assert.NotEqual(english, app.Shell.Library.Title);
await app.ExpectAsync<LibraryView>("library-empty-it");
}
finally
{
UiLanguage.Apply("en");
}
Assert.Equal(english, app.Shell.Library.Title);
});
/// <summary>A <see cref="MainWindow"/> on capture services and sample data, shown off screen like <c>--capture</c>.</summary>
internal sealed class SampleApp : IAsyncDisposable
{
private const double Width = 1440;
private const double Height = 900;
private static readonly AppTheme[] Themes = [AppTheme.Dark, AppTheme.Light];
private readonly AppEnvironment _environment;
private readonly MainWindow _window;
private SampleApp(AppEnvironment environment, AppServices services, SampleData sample, ShellViewModel shell, MainWindow window)
{
_environment = environment;
Services = services;
Sample = sample;
Shell = shell;
_window = window;
}
public AppServices Services { get; }
public SampleData Sample { get; }
public ShellViewModel Shell { get; }
public static async Task<SampleApp> StartAsync()
{
var environment = AppEnvironment.ForCapture();
UiLanguage.Apply("en");
ThemeManager.Apply(AppTheme.Dark);
var services = new AppServices(environment, new AppSettings { Language = "en" }, () => { }, new NoDialogs());
var sample = SampleData.Configure(services);
var shell = new ShellViewModel(services);
// A real window, as in the app: styles and templates apply, and Loaded/IsLoaded drive thumbnail loading.
var window = new MainWindow(shell)
{
WindowStartupLocation = WindowStartupLocation.Manual,
Left = -20000,
Top = -20000,
Width = Width,
Height = Height,
ShowActivated = false,
ShowInTaskbar = false,
};
window.Show();
await sample.OpenEmptyAsync();
await shell.StartAsync();
Assert.Null(services.OpenError);
Assert.NotNull(services.Jobs);
Assert.NotNull(services.Thumbnails);
return new SampleApp(environment, services, sample, shell, window);
}
/// <summary>Renders the current screen in both themes and checks that <typeparamref name="TView"/> is on it.</summary>
public async Task ExpectAsync<TView>(string screen, bool waitForThumbnails = false)
where TView : FrameworkElement
{
var luminance = new Dictionary<AppTheme, double>();
foreach (var theme in Themes)
{
ThemeManager.Apply(theme);
await SettleAsync();
if (waitForThumbnails && Services.Thumbnails is { } thumbnails)
{
for (var i = 0; i < 100 && thumbnails.PendingLoads > 0; i++) await Task.Delay(50);
await SettleAsync();
}
var view = FindAll<TView>().FirstOrDefault(v => v.IsVisible && v.ActualWidth > 0 && v.ActualHeight > 0);
Assert.NotNull(view, $"{screen}: no {typeof(TView).Name} on screen in {theme}");
var bitmap = Render();
luminance[theme] = MeanLuminance(bitmap);
Assert.Greater(Distinct(bitmap), 8, $"{screen} drew almost nothing in {theme}");
}
Assert.Less(luminance[AppTheme.Dark], luminance[AppTheme.Light], $"{screen}: the light theme is not lighter than the dark one");
ThemeManager.Apply(AppTheme.Dark);
}
public List<T> FindAll<T>()
where T : DependencyObject
{
var found = new List<T>();
Collect(_window, found);
return found;
}
public async ValueTask DisposeAsync()
{
ThemeManager.Apply(AppTheme.Dark);
_window.Close();
Shell.Dispose();
await Services.DisposeAsync();
_environment.DeleteCaptureData();
}
private async Task SettleAsync()
{
_window.UpdateLayout();
// Bindings, templates, async continuations and deferred work queued on the dispatcher.
await _window.Dispatcher.InvokeAsync(() => { }, DispatcherPriority.ApplicationIdle);
await Task.Delay(30);
await _window.Dispatcher.InvokeAsync(() => { }, DispatcherPriority.ApplicationIdle);
_window.UpdateLayout();
}
private RenderTargetBitmap Render()
{
var root = (FrameworkElement)VisualTreeHelper.GetChild(_window, 0);
var dpi = VisualTreeHelper.GetDpi(_window);
var width = (int)Math.Ceiling(root.ActualWidth * dpi.DpiScaleX);
var height = (int)Math.Ceiling(root.ActualHeight * dpi.DpiScaleY);
Assert.True(width > 0 && height > 0, "the window has a size");
var bitmap = new RenderTargetBitmap(width, height, dpi.PixelsPerInchX, dpi.PixelsPerInchY, PixelFormats.Pbgra32);
bitmap.Render(root);
return bitmap;
}
private static byte[] Pixels(BitmapSource bitmap)
{
var pixels = new byte[bitmap.PixelWidth * bitmap.PixelHeight * 4];
bitmap.CopyPixels(pixels, bitmap.PixelWidth * 4, 0);
return pixels;
}
private static double MeanLuminance(BitmapSource bitmap)
{
var pixels = Pixels(bitmap);
double sum = 0;
for (var i = 0; i < pixels.Length; i += 4) sum += 0.0722 * pixels[i] + 0.7152 * pixels[i + 1] + 0.2126 * pixels[i + 2];
return sum / (pixels.Length / 4);
}
private static int Distinct(BitmapSource bitmap)
{
var pixels = Pixels(bitmap);
var colours = new HashSet<int>();
for (var i = 0; i < pixels.Length && colours.Count < 1000; i += 4 * 7)
colours.Add(BitConverter.ToInt32(pixels, i));
return colours.Count;
}
private static void Collect<T>(DependencyObject node, List<T> found)
where T : DependencyObject
{
for (var i = 0; i < VisualTreeHelper.GetChildrenCount(node); i++)
{
var child = VisualTreeHelper.GetChild(node, i);
if (child is T match) found.Add(match);
Collect(child, found);
}
}
}
/// <summary>Dialogs that answer like a user who cancels everything.</summary>
private sealed class NoDialogs : IAppDialogs
{
public string? PickFolder(string title, string? initialFolder = null) => null;
public string? PickJsonFile(string title) => null;
public bool Confirm(ConfirmRequest request) => false;
public bool SignIn(string server, string? username, Func<string, string, Task<string?>> signIn) => false;
}
}
/// <summary>
/// The STA dispatcher of the process-wide WPF <see cref="Application"/> (only one may exist per process): reuses the
/// one an earlier WPF test created, otherwise starts it with the Titano theme; then merges the client's styles and
/// section templates, as <c>App.xaml</c> does.
/// </summary>
internal static class ScreenHost
{
private static readonly Uri SectionTemplates = new("pack://application:,,,/Titano;component/Shell/SectionTemplates.xaml", UriKind.Absolute);
private static readonly Lazy<Dispatcher> Dispatcher = new(Start, LazyThreadSafetyMode.ExecutionAndPublication);
public static Task RunAsync(Func<Task> body) => Dispatcher.Value.InvokeAsync(body).Task.Unwrap();
private static Dispatcher Start()
{
var app = Application.Current;
Dispatcher? dispatcher = app?.Dispatcher;
if (dispatcher is null)
{
using var ready = new ManualResetEventSlim();
var thread = new Thread(() =>
{
var created = new Application { ShutdownMode = ShutdownMode.OnExplicitShutdown };
ThemeManager.Initialize(created, AppTheme.Dark);
dispatcher = System.Windows.Threading.Dispatcher.CurrentDispatcher;
ready.Set();
System.Windows.Threading.Dispatcher.Run();
});
thread.SetApartmentState(ApartmentState.STA);
thread.IsBackground = true;
thread.Start();
ready.Wait();
}
dispatcher!.Invoke(() =>
{
var current = Application.Current;
AppResources.Merge(current);
if (!current.Resources.MergedDictionaries.Any(d => d.Source == SectionTemplates))
current.Resources.MergedDictionaries.Add(new ResourceDictionary { Source = SectionTemplates });
});
return dispatcher;
}
}