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:
parent
972b1a5cce
commit
adb4a8bc42
6 changed files with 219 additions and 19 deletions
|
|
@ -6,6 +6,10 @@
|
|||
|
||||
### Added
|
||||
|
||||
* [PostIt/Tests] Add an xUnit collection fixture owning a headless UI session and its thread, with shared window creation, layout, closing and binding cleanup even after failures. Migrate the subscription page binding test as a pilot; retain per-dispatch application isolation and the parallelism guard during coexistence with legacy headless tests.
|
||||
|
||||
* [PostIt/Tests] Disable parallel execution of test collections sharing the Avalonia runtime and static platform state, preventing cross-thread headless initialization and test-case cleanup failures when UI and ordinary tests run together.
|
||||
|
||||
* [PostIt/Calls] Move WebRTC and direct SRTP controls out of the text chat into a dedicated call page, opened for a selected room member or an incoming invitation. Include resolved room-member names in chat snapshots for call targeting, without replacing internal connection identifiers. Preserve the call when leaving the chat for that page and hang up when leaving the call page.
|
||||
|
||||
* [PostIt/Contacts] Add a Contacts page listing circle members and their associated circles, with duplicate members merged. Presence and calling contacts outside a shared chat room are not yet implemented.
|
||||
|
|
|
|||
|
|
@ -31,6 +31,57 @@ bug : ils doivent être **rouges avant le fix, verts après**, et
|
|||
continuer à **casser** si quelqu'un revert le fix. Pas de test
|
||||
qui passe à vide.
|
||||
|
||||
## Isolation des tests PostIt
|
||||
|
||||
L'assemblee `src/PostIt/PostIt.Tests` execute ses collections xUnit sans
|
||||
parallelisme. Les tests `[AvaloniaFact]`/`[AvaloniaTheory]` reinitialisent le
|
||||
runtime Avalonia entre tests ; des tests ordinaires utilisent aussi
|
||||
`App.Current` et les delegates statiques de `Platform`. Leur execution
|
||||
concurrente peut creer le dispatcher sur un autre thread ou utiliser une
|
||||
application appartenant a un test headless en cours, avec une erreur de
|
||||
thread UI signalee comme `Test Case Cleanup`.
|
||||
|
||||
Conserver provisoirement cette isolation dans `Fixtures/TestApp.cs`. Les tests qui exercent
|
||||
intentionnellement plusieurs operations concurrentes peuvent toujours le faire
|
||||
dans leur propre methode ; les autres assemblees de tests ne sont pas affectees.
|
||||
|
||||
### Migration progressive vers une fixture UI
|
||||
|
||||
La collection `[Collection(AvaloniaUiCollection.Name)]` fournit
|
||||
`AvaloniaUiFixture` par injection de constructeur. La fixture possede sa
|
||||
session `HeadlessUnitTestSession`, initialise le runtime sur son thread UI et
|
||||
arrete ce thread a la fin de la collection. Les tests migres utilisent `[Fact]`
|
||||
ou `[Theory]`, pas `[AvaloniaFact]` : la fixture assure elle-meme le dispatch.
|
||||
|
||||
`RunAsync` execute du code sur le thread UI. `WithWindowAsync` cree le contenu
|
||||
et la fenetre sur ce thread, affiche la fenetre, effectue le layout, puis la
|
||||
ferme et detache ses bindings en `finally`, meme si une assertion echoue :
|
||||
|
||||
```csharp
|
||||
[Collection(AvaloniaUiCollection.Name)]
|
||||
public sealed class ExampleTests(AvaloniaUiFixture ui)
|
||||
{
|
||||
[Fact]
|
||||
public Task Page_is_visible() => ui.WithWindowAsync(
|
||||
() => new TextBlock { Text = "Example" },
|
||||
window =>
|
||||
{
|
||||
Assert.True(window.IsVisible);
|
||||
return Task.CompletedTask;
|
||||
},
|
||||
TestContext.Current.CancellationToken,
|
||||
width: 640, height: 480);
|
||||
}
|
||||
```
|
||||
|
||||
Le pilote est `SubscriptionsPageTests`. Le thread est conserve pour la
|
||||
collection, mais l'application reste isolee **par dispatch** : conserver une
|
||||
application unique des maintenant changerait l'isolation des anciens tests
|
||||
et risquerait de partager navigation, services et preferences. Ne pas conserver
|
||||
de controles entre dispatchs dans les tests metier. La protection globale
|
||||
contre le parallelisme reste necessaire tant que les autres consommateurs
|
||||
d'Avalonia et de l'etat statique ne sont pas migres.
|
||||
|
||||
## EF Core en test
|
||||
|
||||
Pour les tests qui ont besoin d'un `ApplicationDbContext`, on
|
||||
|
|
|
|||
71
src/PostIt/PostIt.Tests/AvaloniaUiFixtureTests.cs
Normal file
71
src/PostIt/PostIt.Tests/AvaloniaUiFixtureTests.cs
Normal 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);
|
||||
}
|
||||
}
|
||||
69
src/PostIt/PostIt.Tests/Fixtures/AvaloniaUiFixture.cs
Normal file
69
src/PostIt/PostIt.Tests/Fixtures/AvaloniaUiFixture.cs
Normal 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();
|
||||
}
|
||||
}
|
||||
|
|
@ -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;
|
||||
|
||||
|
|
|
|||
|
|
@ -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]
|
||||
|
|
|
|||
Loading…
Reference in a new issue