test(postit): introduce Avalonia UI collection fixture

Own the headless session lifecycle, centralize window cleanup, migrate subscription page bindings, and guard shared runtime access during the progressive migration.

Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
This commit is contained in:
Paul Schneider 2026-11-12 17:19:01 +00:00
commit adb4a8bc42
Signed by: notazof
GPG key ID: AD4B9B545FBD7D12
6 changed files with 219 additions and 19 deletions

View file

@ -0,0 +1,71 @@
using Avalonia;
using Avalonia.Controls;
using Avalonia.Threading;
namespace PostIt.Tests;
[Trait("Category", "non-reg")]
[Collection(AvaloniaUiCollection.Name)]
public sealed class AvaloniaUiFixtureTests(AvaloniaUiFixture ui)
{
[Fact]
public async Task Dispatches_share_the_UI_thread_but_isolate_the_application()
{
Application? firstApplication = null;
var firstThread = 0;
await ui.RunAsync(() =>
{
Dispatcher.UIThread.VerifyAccess();
firstApplication = Application.Current;
firstThread = Environment.CurrentManagedThreadId;
return Task.CompletedTask;
}, TestContext.Current.CancellationToken);
await ui.RunAsync(() =>
{
Dispatcher.UIThread.VerifyAccess();
Assert.Equal(firstThread, Environment.CurrentManagedThreadId);
Assert.NotNull(firstApplication);
Assert.NotNull(Application.Current);
Assert.NotSame(firstApplication, Application.Current);
return Task.CompletedTask;
}, TestContext.Current.CancellationToken);
}
[Theory]
[InlineData(false)]
[InlineData(true)]
public async Task Windows_are_closed_and_unbound_even_when_the_test_fails(bool fail)
{
var expectedFailure = new InvalidOperationException("Test failure");
Window? opened = null;
Control? content = null;
var run = ui.WithWindowAsync(() =>
{
Dispatcher.UIThread.VerifyAccess();
content = new TextBlock { DataContext = new object(), Text = "Fixture" };
return content;
}, window =>
{
opened = window;
Assert.True(window.IsVisible);
Assert.Equal(640, window.Width);
Assert.Equal(480, window.Height);
return fail ? Task.FromException(expectedFailure) : Task.CompletedTask;
}, TestContext.Current.CancellationToken, width: 640, height: 480);
if (fail)
Assert.Same(expectedFailure, await Assert.ThrowsAsync<InvalidOperationException>(() => run));
else
await run;
// The controls still belong to the fixture's UI thread after their application is disposed.
await ui.RunAsync(() =>
{
Assert.NotNull(opened);
Assert.False(opened.IsVisible);
Assert.Null(opened.Content);
Assert.Null(content!.DataContext);
return Task.CompletedTask;
}, TestContext.Current.CancellationToken);
}
}

View file

@ -0,0 +1,69 @@
using Avalonia.Controls;
using Avalonia.Headless;
using Avalonia.Threading;
namespace PostIt.Tests;
[CollectionDefinition(Name, DisableParallelization = true)]
public sealed class AvaloniaUiCollection : ICollectionFixture<AvaloniaUiFixture>
{
public const string Name = "Avalonia UI";
}
public sealed class AvaloniaUiFixture : IAsyncLifetime
{
private HeadlessUnitTestSession? _session;
public async ValueTask InitializeAsync()
{
_session = HeadlessUnitTestSession.StartNew(typeof(TestAppBuilder), AvaloniaTestIsolationLevel.PerTest);
try
{
await RunAsync(() => Task.CompletedTask, CancellationToken.None);
}
catch
{
await DisposeAsync();
throw;
}
}
public async Task RunAsync(Func<Task> action, CancellationToken ct)
{
var session = _session ?? throw new InvalidOperationException("La fixture Avalonia n'est pas initialisee.");
await session.Dispatch(async () =>
{
await action();
return true;
}, ct);
}
public Task WithWindowAsync(Func<Control> createContent, Func<Window, Task> test, CancellationToken ct,
double width = 800, double height = 600) => RunAsync(async () =>
{
var window = new Window { Width = width, Height = height };
try
{
window.Content = createContent();
window.Show();
Dispatcher.UIThread.RunJobs();
window.UpdateLayout();
await test(window);
}
finally
{
window.Close();
if (window.Content is Control content) content.DataContext = null;
window.Content = null;
window.DataContext = null;
Dispatcher.UIThread.RunJobs();
}
}, ct);
public async ValueTask DisposeAsync()
{
if (_session is not { } session) return;
_session = null;
await session.DisposeAsync();
}
}

View file

@ -2,6 +2,8 @@ using Avalonia;
using Avalonia.Headless;
[assembly: AvaloniaTestApplication(typeof(PostIt.Tests.TestAppBuilder))]
// Ordinary tests also use App.Current and Platform while headless tests reset the shared runtime.
[assembly: Xunit.CollectionBehavior(DisableTestParallelization = true)]
namespace PostIt.Tests;

View file

@ -2,7 +2,6 @@ using System.Net.Http;
using System.Text.Json;
using System.Globalization;
using Avalonia.Controls;
using Avalonia.Headless.XUnit;
using PostIt.ViewModels;
using PostIt.Views;
using Yavsc.Abstract.Resources;
@ -11,29 +10,33 @@ using Yavsc.Api.Client;
namespace PostIt.Tests;
[Trait("Category", "non-reg")]
public sealed class SubscriptionsPageTests
[Collection(AvaloniaUiCollection.Name)]
public sealed class SubscriptionsPageTests(AvaloniaUiFixture ui)
{
[AvaloniaFact]
[Fact]
public async Task Page_binds_server_offers_prices_and_balance()
{
await using var api = new FakeApi();
var model = Model(api);
await model.InitializeAsync();
var page = new SubscriptionsPage { DataContext = model };
Assert.IsType<SubscriptionsPage>(new ViewLocator().Build(model));
var selector = page.FindControl<ComboBox>("OfferSelector")!;
Assert.Equal(2, selector.ItemCount);
Assert.Equal(1.2m, model.SelectedOffer?.PriceIncludingTax);
Assert.Equal($"Prix TTC : {1.2m.ToString("F2", CultureInfo.CurrentCulture)} EUR / mois",
page.FindControl<TextBlock>("OfferPrice")!.Text);
selector.SelectedIndex = 1;
Assert.Equal("Premium", model.SelectedOffer?.Pack);
Assert.Equal($"Prix TTC : {2.4m.ToString("F2", CultureInfo.CurrentCulture)} EUR / mois",
page.FindControl<TextBlock>("OfferPrice")!.Text);
Assert.Equal(45m, model.Usage?.Consumption);
Assert.Null(model.StatusMessage);
Assert.True(model.SubscribeCommand.CanExecute(null));
Assert.False(model.CancelSubscriptionCommand.CanExecute(null));
await ui.WithWindowAsync(() => new SubscriptionsPage { DataContext = model }, async window =>
{
await model.InitializeAsync();
var page = Assert.IsType<SubscriptionsPage>(window.Content);
Assert.IsType<SubscriptionsPage>(new ViewLocator().Build(model));
var selector = page.FindControl<ComboBox>("OfferSelector")!;
Assert.Equal(2, selector.ItemCount);
Assert.Equal(1.2m, model.SelectedOffer?.PriceIncludingTax);
Assert.Equal($"Prix TTC : {1.2m.ToString("F2", CultureInfo.CurrentCulture)} EUR / mois",
page.FindControl<TextBlock>("OfferPrice")!.Text);
selector.SelectedIndex = 1;
Assert.Equal("Premium", model.SelectedOffer?.Pack);
Assert.Equal($"Prix TTC : {2.4m.ToString("F2", CultureInfo.CurrentCulture)} EUR / mois",
page.FindControl<TextBlock>("OfferPrice")!.Text);
Assert.Equal(45m, model.Usage?.Consumption);
Assert.Null(model.StatusMessage);
Assert.True(model.SubscribeCommand.CanExecute(null));
Assert.False(model.CancelSubscriptionCommand.CanExecute(null));
}, TestContext.Current.CancellationToken);
}
[Fact]