Compare commits

...
Author SHA1 Message Date
9a0b5cc06c
better
All checks were successful
Dotnet build and test / build (pull_request) Successful in 20m29s
2026-11-12 17:59:19 +00:00
bf17c5be5d
fix(api): restore SQLite test isolation and relief problem responses
Recreate the anchored SQLite test schema before seeding, restore haircut command seeds, and preserve problem+json error responses with matching OpenAPI metadata. Add regression coverage for repeated resets and response contracts. Verified all 227 API SQLite tests pass.

Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
2026-11-12 17:55:15 +00:00
f8f2d943aa
test(yavsc): categorize server suites as non-regression
Add Category=non-reg to all 75 test classes across the four server test projects, preserve existing traits, document filtered execution, and remove the empty Services class.

Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
2026-11-12 17:29:36 +00:00
adb4a8bc42
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>
2026-11-12 17:19:01 +00:00
972b1a5cce
feat(postit): separate call interfaces from text chat
Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
2026-11-12 16:49:48 +00:00
c36b7e02c6
feat(postit): restore direct calls and list contacts
Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
2026-11-12 16:36:14 +00:00
107 changed files with 1264 additions and 163 deletions

View file

@ -6,6 +6,22 @@
### Added
* [Yavsc.Api] Preserve `application/problem+json` for resource-usage relief errors instead of overriding it with a JSON-only Produces attribute; document success/error media types in OpenAPI and verify error payloads. Restore the haircut and grouped-haircut commands removed from the test seed while retaining its three catalog prestations, with repeated-reset coverage.
* [Yavsc.Api/Tests] Reset the anchored shared SQLite in-memory database by dropping and recreating its tables before seeding, avoiding duplicate user emails across tests. Restore foreign-key enforcement after cleanup and cover repeated resets with a regression test; leave PostgreSQL cleanup unchanged.
* [Yavsc/Tests] Apply the class-level `Category=non-reg` trait to all test classes in Yavsc.Org.Tests, Yavsc.Api.Tests, Yavsc.Blogs.Tests and Yavsc.Server.Tests, including inherited tests, while preserving existing traits. Remove the empty Services class.
* [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.
* [PostIt/Calls] Restore the direct IPv4/IPv6 VLC/SRTP call panel alongside WebRTC on supported platforms, route invitations to the matching transport, and retain explicit IP disclosure consent and server privacy policy. Add transport routing and lifecycle regressions.
* [PostIt/Administration] Add an administrator-only consumption relief page reachable from Administration: select a user at their limit, preview and confirm an arbitrary point erasure up to current consumption. Protect the quota-exempt API with the Administrator policy, serialize adjustments with accounting, reject stale confirmations, preserve technical counters and disk quotas, and audit the actor. Add API, service, client and responsive-page regressions.
* [PostIt] Upgrade Avalonia to 12.1.6 and align the headless and native Skia test rendering packages.

View file

@ -21,7 +21,7 @@ src/Yavsc/bin/output/wwwroot:
test:
ASPNETCORE_ENVIRONMENT=Development \
TESTINGPLATFORM_EXITCODE_IGNORE="110;1" \
TESTINGPLATFORM_EXITCODE_IGNORE="110" \
dotnet test yavsc.sln \
-- --report-xunit \
--report-xunit-html \
@ -30,7 +30,7 @@ test:
test-postit:
ASPNETCORE_ENVIRONMENT=Development \
TESTINGPLATFORM_EXITCODE_IGNORE="110;1" \
TESTINGPLATFORM_EXITCODE_IGNORE="110" \
dotnet test \
src/PostIt/PostIt.Tests/PostIt.Tests.csproj \
-- --report-xunit \

View file

@ -5,11 +5,18 @@
Ce document décrit l'architecture cible, l'implementation native actuelle et
l'historique du transport direct.
La préférence de confidentialité est persistée et éditable dans le profil.
La signalisation est intégrée au chat, désactivée par défaut. La page du chat
utilise maintenant **WebRTC natif sur Android et Desktop Linux**, avec
ICE/STUN/TURN et masquage IP impose par la politique serveur. L'ancien
transport VLC/SRTP n'est plus raccorde a cette page. Les groupes et les
clients navigateur ne sont pas implementes.
La signalisation est intégrée au chat, désactivée par défaut. Une page d'appel
separee propose **WebRTC natif** et le transport direct VLC/SRTP sur Android et
Desktop Linux. WebRTC utilise ICE/STUN/TURN et le masquage IP impose par la
politique serveur. Le mode SRTP direct ne masque pas les adresses IP et exige
que cette preference soit desactivee pour les deux participants. Les groupes
et les clients navigateur ne sont pas implementes.
Depuis le chat textuel, selectionner un membre present puis « Ouvrir l'appel »
prepare le pair sans demarrer les medias. Les invitations entrantes disposent
d'un bouton pour ouvrir cette meme page sans selection de membre. Passer du
chat a la page d'appel ne raccroche pas ; quitter la page d'appel termine les
medias. Un salon commun reste requis ; les capacites distantes et les appels
depuis Contacts ne sont pas encore raccordes.
Il complète la [topologie de PostIt](postit.md) et les
[mécanismes de notification existants](notifications.md).
La cible couvre :
@ -52,7 +59,11 @@ La cible couvre :
terminent l'appel explicitement. Il n'y a pas d'ICE restart/renegociation
automatique ni de migration transparente d'un appel existant.
Le panneau ne demande plus d'adresse ni de port RTP manuel. Sans masquage,
Le panneau WebRTC ne demande pas d'adresse ni de port RTP manuel. Le panneau
SRTP direct demande une adresse locale, un port UDP pair et le consentement au
partage d'adresse ; il requiert HTTPS pour proteger les cles de signalisation.
Les invitations sont dirigees vers le panneau correspondant, sans bascule
automatique entre transports. Sans masquage,
un consentement explicite au partage IP reste requis. Activer le masquage
dans le profil pendant un appel fait terminer cet appel par le serveur :
il faut rappeler pour appliquer la nouvelle politique.
@ -115,10 +126,10 @@ la camera avant et le microphone Android reels, des sources Linux synthetiques
et un coturn TCP local via USB ; la camera et la sortie audio Linux materielles,
TURN/TLS et les reseaux Internet distincts restent a verifier.
## Historique : premiere implementation SRTP direct IPv4/IPv6
## Implementation SRTP direct IPv4/IPv6
Les paragraphes suivants decrivent le transport precedent, conserve dans le
code et ses tests mais non propose par le panneau d'appel actuel.
Les paragraphes suivants decrivent le transport direct historique, de nouveau
propose a cote de WebRTC dans la page d'appel.
Les adresses IPv4 publiques directement assignees a une interface locale active
sont egalement disponibles, avec la meme validation unicast cote client,
@ -188,10 +199,12 @@ de fichier média temporaire ou de moteur WebRTC Android ajouté.
H.264/AAC. La version Debian 13 a été utilisée pour les essais Linux.
Les deux comptes doivent être présents dans
la même salle existante et ne pas se bloquer mutuellement.
3. Dans « Appel direct IPv4/IPv6 (LAN/VPN ou IP publique) », actualiser les périphériques,
sélectionner la caméra, le microphone et une IPv4 privée locale
accessible depuis le pair. Les adresses RFC1918 et de bouclage sont
acceptées ; pas de DNS, IPv6 ou adresse publique. Le bouclage sert aux
3. Selectionner le destinataire dans les membres presents du chat puis
« Ouvrir l'appel ». Dans la section « Appel direct IPv4/IPv6 SRTP »,
actualiser les périphériques, sélectionner la caméra, le microphone et
une adresse locale accessible depuis le pair. Les adresses IPv4 privées
ou publiques assignées et les IPv6 globales ou ULA sont acceptées, pas
les noms DNS ni les adresses link-local. Le bouclage sert aux
essais sur un même hôte, pas à joindre un second poste.
4. Choisir un port UDP **pair entre 1024 et 65534**, par défaut 5004.
Autoriser l'entrée UDP sur ce port **et le suivant** depuis le pair dans
@ -199,7 +212,7 @@ de fichier média temporaire ou de moteur WebRTC Android ajouté.
Les deux ports doivent être disponibles. Deux clients sur la même
adresse doivent utiliser des paires distinctes.
Aucun pare-feu n'est modifié automatiquement.
5. Saisir le pseudo exact du destinataire, confirmer la divulgation de
5. Verifier le pseudo du destinataire selectionne, confirmer la divulgation de
l'adresse IP locale (LAN/VPN ou publique), puis appeler. Le destinataire choisit ses propres
périphériques et son adresse, confirme et accepte explicitement.
Aucun accès à la caméra/microphone ne commence avant l'acceptation ;

View file

@ -31,6 +31,92 @@ 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.
## Selection des tests serveur
Toutes les classes de tests des projets `Yavsc.Org.Tests`, `Yavsc.Api.Tests`,
`Yavsc.Blogs.Tests` et `Yavsc.Server.Tests`, sous `src/test/`, portent
`[Trait("Category", "non-reg")]`, y compris celles qui heritent de tests.
Conserver ce trait sur toute nouvelle classe de tests ; les fixtures et
les helpers sans tests n'en ont pas besoin. Les autres traits restent inchanges.
Avec le runner Microsoft.Testing.Platform et le SDK .NET 10 :
```bash
dotnet test --project src/test/Yavsc.Org.Tests/Yavsc.Org.Tests.csproj \
--filter-trait 'Category=non-reg'
```
Remplacer le projet pour executer les trois autres suites. Le trait couvre
aussi les tests d'integration qui requierent leurs services/configurations ;
il ne supprime ni ces prerequis ni les exclusions d'autres traits.
Ajouter `--list-tests` pour verifier la selection sans executer les tests.
### Remise a zero SQLite des tests API
`ApiWebServerFixture` conserve une connexion d'ancrage vers la base SQLite
en memoire partagee. `EnsureDeleted()` ne vide pas cette base tant que cette
connexion reste ouverte. Le reset supprime donc les tables, puis recree
explicitement le schema avant le peuplement ; `EnsureCreated()` seul ne suffit
pas car SQLite conserve sa table interne `sqlite_sequence`.
Les cles etrangeres sont desactivees uniquement pendant la suppression et
reactivees en `finally`. Le nettoyage PostgreSQL reste distinct.
`ResetAndSeedHaircutGraph()` inclut le catalogue de trois prestations, une
commande `brush` et une commande groupee `mbrush`, toutes deux pour Alice.
Les tests de facturation s'appuient sur ces commandes initiales ; les tests
CRUD creent et manipulent leurs propres commandes par identifiant.
## 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

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,182 @@
using Avalonia.Headless.XUnit;
using Avalonia.Controls;
using PostIt.Views.Chat;
using PostIt.Services;
using PostIt.ViewModels;
using PostIt.ViewModels.Chat;
using Yavsc.Abstract.Chat.Calls;
namespace PostIt.Tests;
[Trait("Category", "non-reg")]
public sealed class CallTransportRoutingTests
{
[AvaloniaTheory]
[InlineData(CallTransports.LanSrtp)]
[InlineData(CallTransports.WebRtc)]
public async Task Incoming_calls_are_handled_only_by_the_matching_transport(string transport)
{
var signaling = new Signaling();
await using var lan = new LanCallViewModel(signaling);
await using var webRtc = new WebRtcCallViewModel(signaling);
var call = new CallSession(Guid.NewGuid(), "General", "alice", "bob", false,
DateTimeOffset.UtcNow.AddMinutes(1), transport);
signaling.Invite(call);
await WaitAsync(() => lan.Incoming || webRtc.Incoming);
Assert.Equal(transport == CallTransports.LanSrtp, lan.Incoming);
Assert.Equal(transport == CallTransports.WebRtc, webRtc.Incoming);
Assert.Empty(signaling.EndedCalls);
if (lan.Incoming) await lan.HangupAsync();
else await webRtc.HangupAsync();
Assert.Equal([call.Id], signaling.EndedCalls);
Assert.False(lan.Busy);
Assert.False(webRtc.Busy);
}
[AvaloniaFact]
public async Task Unknown_transport_is_rejected_once_without_starting_either_call()
{
var signaling = new Signaling();
await using var lan = new LanCallViewModel(signaling);
await using var webRtc = new WebRtcCallViewModel(signaling);
var call = new CallSession(Guid.NewGuid(), "General", "alice", "bob", false,
DateTimeOffset.UtcNow.AddMinutes(1), "unknown");
signaling.Invite(call);
await WaitAsync(() => signaling.EndedCalls.Count != 0);
Assert.Equal([call.Id], signaling.EndedCalls);
Assert.False(lan.Busy);
Assert.False(webRtc.Busy);
}
[AvaloniaTheory]
[InlineData(CallTransports.LanSrtp)]
[InlineData(CallTransports.WebRtc)]
public async Task Chat_updates_both_rooms_and_disconnects_the_active_transport(string transport)
{
var signaling = new Signaling();
var chat = new ChatViewModel(settings: new Settings());
var lan = new LanCallViewModel(signaling);
var webRtc = new WebRtcCallViewModel(signaling);
chat.LanCall = lan;
chat.VideoCall = webRtc;
chat.SelectedRoom = "General";
Assert.Equal("General", lan.Room);
Assert.Equal("General", webRtc.Room);
var call = new CallSession(Guid.NewGuid(), "General", "alice", "bob", false,
DateTimeOffset.UtcNow.AddMinutes(1), transport);
signaling.Invite(call);
await WaitAsync(() => lan.Incoming || webRtc.Incoming);
await chat.DisconnectAsync();
Assert.Equal([call.Id], signaling.EndedCalls);
Assert.Null(chat.LanCall);
Assert.Null(chat.VideoCall);
Assert.False(lan.Busy);
Assert.False(webRtc.Busy);
signaling.Invite(call);
Assert.False(lan.Incoming);
Assert.False(webRtc.Incoming);
}
private static async Task WaitAsync(Func<bool> condition)
{
using var timeout = CancellationTokenSource.CreateLinkedTokenSource(TestContext.Current.CancellationToken);
timeout.CancelAfter(TimeSpan.FromSeconds(5));
while (!condition()) await Task.Delay(10, timeout.Token);
}
[AvaloniaFact]
public async Task Selecting_a_room_member_prepares_both_transports_without_inviting()
{
var signaling = new Signaling();
await using var lan = new LanCallViewModel(signaling);
await using var webRtc = new WebRtcCallViewModel(signaling);
var chat = new ChatViewModel(settings: new Settings())
{
LanCall = lan, VideoCall = webRtc, IsConnected = true, SelectedRoom = "General",
FocusedUsers = new()
};
chat.FocusedUsers.Add("bob");
Assert.False(chat.OpenCallCommand.CanExecute(null));
chat.SelectedUser = "bob";
Assert.True(chat.OpenCallCommand.CanExecute(null));
var page = chat.PrepareCallPage();
Assert.Same(chat, page.Chat);
Assert.Equal("bob", lan.Target);
Assert.Equal("bob", webRtc.Target);
Assert.False(lan.Busy);
Assert.False(webRtc.Busy);
chat.FocusedUsers.Remove("bob");
Assert.Null(chat.SelectedUser);
Assert.False(chat.OpenCallCommand.CanExecute(null));
chat.FocusedUsers.Add("bob");
chat.SelectedUser = "bob";
chat.SelectedRoom = "Other";
Assert.Null(chat.SelectedUser);
Assert.False(chat.OpenCallCommand.CanExecute(null));
}
[AvaloniaTheory]
[InlineData(CallTransports.LanSrtp)]
[InlineData(CallTransports.WebRtc)]
public async Task Leaving_text_chat_preserves_invitation_and_leaving_call_page_ends_it(string transport)
{
var signaling = new Signaling();
await using var lan = new LanCallViewModel(signaling);
await using var webRtc = new WebRtcCallViewModel(signaling);
var chat = new ChatViewModel(settings: new Settings())
{
LanCall = lan, VideoCall = webRtc, IsConnected = true, SelectedRoom = "General",
FocusedUsers = new()
};
var call = new CallSession(Guid.NewGuid(), "General", "alice", "bob", false,
DateTimeOffset.UtcNow.AddMinutes(1), transport);
signaling.Invite(call);
await WaitAsync(() => lan.Incoming || webRtc.Incoming);
Assert.True(chat.ShowCallCommand.CanExecute(null));
var window = new Window { Content = new ChatPage { DataContext = chat } };
try
{
window.Show();
window.Content = new CallPage { DataContext = new CallPageViewModel(chat) };
Assert.Empty(signaling.EndedCalls);
Assert.True(lan.Incoming || webRtc.Incoming);
window.Content = null;
await WaitAsync(() => signaling.EndedCalls.Count != 0);
Assert.Equal([call.Id], signaling.EndedCalls);
Assert.False(lan.Busy);
Assert.False(webRtc.Busy);
}
finally { window.Close(); }
}
private sealed class Signaling : IWebRtcCallSignaling
{
public event Action<CallSession>? Invitation;
public event Action<CallAccepted>? Accepted;
public event Action<CallEnded>? Ended;
public event Action<Guid, CallSignal>? Signal;
public event Action? Interrupted;
public List<Guid> EndedCalls { get; } = [];
public void Invite(CallSession call) => Invitation?.Invoke(call);
public Task<CallSession> InviteAsync(string room, string user, CancellationToken ct = default) =>
throw new NotSupportedException();
public Task<CallSession> InviteLanAsync(string room, string user, CancellationToken ct = default) =>
throw new NotSupportedException();
public Task AcceptAsync(Guid callId, CancellationToken ct = default) => throw new NotSupportedException();
public Task EndAsync(Guid callId, CancellationToken ct = default)
{
EndedCalls.Add(callId);
return Task.CompletedTask;
}
public Task SendAsync(Guid callId, CallSignal signal, CancellationToken ct = default) =>
throw new NotSupportedException();
}
}

View file

@ -0,0 +1,61 @@
using System.Net;
using System.Text.Json;
using PostIt.ViewModels;
using Yavsc.Api.Client;
namespace PostIt.Tests;
[Trait("Category", "non-reg")]
public sealed class ContactsPageViewModelTests
{
[Fact]
public async Task Contacts_are_deduplicated_and_show_all_their_circles()
{
await using var api = new FakeApi();
var vm = new ContactsPageViewModel(new CircleApiClient(api, "https://example.test/"));
await vm.RefreshAsync();
var contact = Assert.Single(vm.Contacts);
Assert.Equal("bob-id", contact.Id);
Assert.Equal("Bob", contact.DisplayName);
Assert.Equal("Amis, Travail", contact.Circles);
}
[Fact]
public async Task Missing_circle_is_reported_instead_of_showing_incomplete_contacts()
{
await using var api = new FakeApi { MissingCircle = true };
var vm = new ContactsPageViewModel(new CircleApiClient(api, "https://example.test/"));
await vm.RefreshAsync();
Assert.Empty(vm.Contacts);
Assert.Contains("n'est plus disponible", vm.Status);
Assert.False(vm.IsBusy);
}
private sealed class FakeApi : IYavscApiClient
{
public HttpClient Http { get; } = new();
public bool MissingCircle { get; init; }
public Task<T> CallAsync<T>(HttpMethod method, string path, object? body = null, CancellationToken ct = default)
{
string json = path switch
{
"circle" => """[{"id":1,"name":"Travail"},{"id":2,"name":"Amis"}]""",
"circle/1/members" => """[{"id":"bob-id","userName":"bob","fullName":"Bob"}]""",
"circle/2/members" when MissingCircle => "null",
"circle/2/members" => """[{"id":"bob-id","userName":"bob","fullName":"Bob"}]""",
_ => throw new HttpRequestException("Unexpected path", null, HttpStatusCode.NotFound)
};
return Task.FromResult(JsonSerializer.Deserialize<T>(json,
new JsonSerializerOptions { PropertyNameCaseInsensitive = true })!);
}
public Task<T> CallAsync<T>(HttpMethod method, string path, Func<HttpContent> contentFactory, CancellationToken ct = default) =>
throw new NotSupportedException();
public Task CallAsync(HttpMethod method, string path, object? body = null, CancellationToken ct = default) =>
throw new NotSupportedException();
public Task CallAsync(HttpMethod method, string path, Func<HttpContent> contentFactory, CancellationToken ct = default) =>
throw new NotSupportedException();
public ValueTask DisposeAsync() { Http.Dispose(); return ValueTask.CompletedTask; }
}
}

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]

View file

@ -81,9 +81,11 @@ public static class ServiceCollectionHelpers
AddReusablePage<HomePage>();
AddReusablePage<SignaturePage>();
AddReusablePage<CirclesPage>();
services.AddTransient<ContactsPage>();
AddReusablePage<ActivitiesPage>();
services.AddTransient<CommandFormsPage>();
services.AddTransient<ChatPage>();
services.AddTransient<CallPage>();
services.AddTransient<RdvPage>();
services.AddTransient<BrushPage>();
services.AddTransient<BillingQueriesPage>();
@ -129,6 +131,7 @@ public static class ServiceCollectionHelpers
services.AddTransient<ResourceUsageReliefPageViewModel>();
services.AddSingleton<SignaturePageViewModel>();
services.AddSingleton<CirclesPageViewModel>();
services.AddTransient<ContactsPageViewModel>();
services.AddSingleton<ActivitiesPageViewModel>();
services.AddTransient<SelectableHairPrestationItem>();

View file

@ -7,5 +7,6 @@ namespace PostIt.ViewModels.Chat
{
public string? Name { get; set; }
public List<string> Users { get; set; } = new();
public List<string>? UserNames { get; set; }
}
}

View file

@ -55,6 +55,7 @@ public class ViewLocator : IDataTemplate
AddCircleMemberDialogViewModel => services.GetRequiredService<AddCircleMemberDialog>(),
ConfirmationDialogViewModel => services.GetRequiredService<ConfirmationDialog>(),
CirclesPageViewModel => services.GetRequiredService<CirclesPage>(),
ContactsPageViewModel => services.GetRequiredService<ContactsPage>(),
PostAclDialogViewModel => services.GetRequiredService<PostAclDialog>(),
BillingQueriesPageViewModel => services.GetRequiredService<BillingQueriesPage>(),
BillingQueryDetailsPageViewModel => services.GetRequiredService<BillingQueryDetailsPage>(),
@ -69,6 +70,7 @@ public class ViewLocator : IDataTemplate
AdministrationPageViewModel => services.GetRequiredService<AdministrationPage>(),
ResourceUsageReliefPageViewModel => services.GetRequiredService<ResourceUsageReliefPage>(),
ChatViewModel => services.GetRequiredService<ChatPage>(),
CallPageViewModel => services.GetRequiredService<CallPage>(),
null => new TextBlock { Text = "No view for <null>" },
_ => new TextBlock { Text = $"No view for {data.GetType().Name}" }
};

View file

@ -0,0 +1,66 @@
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Threading.Tasks;
using CommunityToolkit.Mvvm.ComponentModel;
using CommunityToolkit.Mvvm.Input;
using Yavsc.Api.Client;
using Yavsc.Api.Client.Dtos;
namespace PostIt.ViewModels;
public sealed record ContactEntry(string Id, string UserName, string DisplayName, string Circles);
public partial class ContactsPageViewModel(CircleApiClient client) : ViewModelBase
{
public ObservableCollection<ContactEntry> Contacts { get; } = [];
[ObservableProperty]
public partial bool IsBusy { get; set; }
[ObservableProperty]
public partial string Status { get; set; } = "Pret.";
public override bool CanNavigateNext { get; protected set; } = false;
public override bool CanNavigatePrevious { get; protected set; } = true;
[RelayCommand]
public async Task RefreshAsync()
{
IsBusy = true;
try
{
var circles = await client.GetMyCirclesAsync()
?? throw new InvalidOperationException("Le serveur n'a pas renvoye les cercles.");
var members = new List<(CircleDto Circle, CircleMemberDto Member)>();
foreach (var circle in circles)
{
var list = await client.GetMembersAsync(circle.Id)
?? throw new InvalidOperationException($"Le cercle {circle.Name} n'est plus disponible.");
members.AddRange(list.Select(member => (circle, member)));
}
var contacts = members.GroupBy(item => item.Member.Id, StringComparer.Ordinal)
.Select(group =>
{
var member = group.First().Member;
if (string.IsNullOrWhiteSpace(member.Id) || string.IsNullOrWhiteSpace(member.UserName))
throw new InvalidOperationException("Un membre de cercle n'a pas d'identifiant ou de pseudo.");
return new ContactEntry(member.Id, member.UserName,
string.IsNullOrWhiteSpace(member.FullName) ? member.UserName : member.FullName,
string.Join(", ", group.Select(item => item.Circle.Name).Distinct().OrderBy(name => name)));
})
.OrderBy(contact => contact.DisplayName, StringComparer.CurrentCultureIgnoreCase)
.ToArray();
Contacts.Clear();
foreach (var contact in contacts) Contacts.Add(contact);
Status = $"{Contacts.Count} contact(s).";
}
catch (Exception error)
{
Contacts.Clear();
Status = $"Impossible de charger les contacts : {error.Message}";
}
finally { IsBusy = false; }
}
}

View file

@ -0,0 +1,12 @@
using System.Threading.Tasks;
namespace PostIt.ViewModels.Chat;
public sealed class CallPageViewModel(ChatViewModel chat) : ViewModelBase
{
public ChatViewModel Chat { get; } = chat;
public override bool CanNavigateNext { get; protected set; } = false;
public override bool CanNavigatePrevious { get; protected set; } = true;
public Task HangupAsync() => Chat.HangupCallsAsync();
}

View file

@ -1,6 +1,7 @@
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Collections.Specialized;
using System.Threading.Tasks;
using System.Threading;
using CommunityToolkit.Mvvm.ComponentModel;
@ -59,9 +60,21 @@ namespace PostIt.ViewModels.Chat
public bool SupportsVideoCalls => Platform.CreateWebRtcMedia != null ||
(OperatingSystem.IsLinux() && !OperatingSystem.IsAndroid());
public bool SupportsLanCalls => Platform.CreateLanCallMedia != null ||
(OperatingSystem.IsLinux() && !OperatingSystem.IsAndroid());
[ObservableProperty]
[NotifyCanExecuteChangedFor(nameof(OpenCallCommand), nameof(ShowCallCommand))]
public partial WebRtcCallViewModel? VideoCall { get; set; }
[ObservableProperty]
[NotifyCanExecuteChangedFor(nameof(OpenCallCommand), nameof(ShowCallCommand))]
public partial LanCallViewModel? LanCall { get; set; }
[ObservableProperty]
[NotifyCanExecuteChangedFor(nameof(OpenCallCommand))]
public partial string? SelectedUser { get; set; }
[ObservableProperty]
public partial string CurrentRoom { get; set; } = "General";
@ -73,6 +86,7 @@ namespace PostIt.ViewModels.Chat
[ObservableProperty]
[NotifyCanExecuteChangedFor(nameof(SendMessageCommand))]
[NotifyCanExecuteChangedFor(nameof(OpenCallCommand), nameof(ShowCallCommand))]
public partial bool IsConnected { get; set; } = false;
[ObservableProperty]
@ -86,6 +100,7 @@ namespace PostIt.ViewModels.Chat
// alors les notifications système.
[ObservableProperty]
[NotifyCanExecuteChangedFor(nameof(SendMessageCommand))]
[NotifyCanExecuteChangedFor(nameof(OpenCallCommand))]
public partial string? SelectedRoom { get; set; }
// Notifications globales (connexion, erreurs de join, ...)
@ -104,15 +119,87 @@ namespace PostIt.ViewModels.Chat
[ObservableProperty]
public partial ObservableCollection<string> FocusedUsers { get; set; } = _noUsers;
partial void OnFocusedUsersChanging(ObservableCollection<string> value) =>
FocusedUsers.CollectionChanged -= OnFocusedUsersCollectionChanged;
partial void OnFocusedUsersChanged(ObservableCollection<string> value)
{
value.CollectionChanged += OnFocusedUsersCollectionChanged;
OpenCallCommand.NotifyCanExecuteChanged();
}
private void OnFocusedUsersCollectionChanged(object? sender, NotifyCollectionChangedEventArgs args)
{
if (SelectedUser != null && !FocusedUsers.Contains(SelectedUser)) SelectedUser = null;
OpenCallCommand.NotifyCanExecuteChanged();
}
private void UpdateRoomUsers(string type, string room, string user)
{
if (!_usersByRoom.TryGetValue(room, out var users)) return;
if (string.Equals(type, NotificationTypes.UserJoin, StringComparison.OrdinalIgnoreCase))
{
if (!users.Contains(user)) users.Add(user);
}
else if (string.Equals(type, NotificationTypes.UserPart, StringComparison.OrdinalIgnoreCase) ||
string.Equals(type, NotificationTypes.Kick, StringComparison.OrdinalIgnoreCase))
{
var separator = user.IndexOf(':');
users.Remove(separator < 0 ? user : user[..separator]);
}
}
partial void OnSelectedRoomChanged(string? value)
{
SelectedUser = null;
if (VideoCall != null) VideoCall.Room = value ?? "";
if (LanCall != null) LanCall.Room = value ?? "";
FocusedMessages = value != null && _messagesByRoom.TryGetValue(value, out var msgs)
? msgs : _systemMessages;
FocusedUsers = value != null && _usersByRoom.TryGetValue(value, out var users)
? users : _noUsers;
}
private bool CanShowCall() => IsConnected && (VideoCall != null || LanCall != null);
private bool CanOpenCall() => CanShowCall() && SelectedRoom != null &&
!string.IsNullOrWhiteSpace(SelectedUser) && FocusedUsers.Contains(SelectedUser);
internal CallPageViewModel PrepareCallPage()
{
if (!CanOpenCall())
throw new InvalidOperationException("Selectionnez un utilisateur present dans le salon et connectez le chat.");
if (VideoCall?.Busy != true && LanCall?.Busy != true)
{
if (VideoCall != null) VideoCall.Target = SelectedUser!;
if (LanCall != null) LanCall.Target = SelectedUser!;
}
return new CallPageViewModel(this);
}
[RelayCommand(CanExecute = nameof(CanOpenCall))]
private Task OpenCallAsync() => NavigateToCallAsync(configureTarget: true);
[RelayCommand(CanExecute = nameof(CanShowCall))]
private Task ShowCallAsync() => NavigateToCallAsync(configureTarget: false);
private async Task NavigateToCallAsync(bool configureTarget)
{
try
{
var app = App.Current as App ?? throw new InvalidOperationException("Application indisponible.");
var page = configureTarget ? PrepareCallPage() : new CallPageViewModel(this);
await app.PushPageAsync(page);
}
catch (Exception error) { Log($"Impossible d'ouvrir l'appel : {error.Message}"); }
}
public async Task HangupCallsAsync()
{
if (VideoCall != null) await VideoCall.HangupAsync();
if (LanCall != null) await LanCall.HangupAsync();
}
// Trace une notification système dans la vue courante
// (et dans le journal global pour consultation ultérieure).
private void Log(string line)
@ -160,7 +247,7 @@ namespace PostIt.ViewModels.Chat
if (_transport == null || room == null) return;
try
{
if (VideoCall != null) await VideoCall.HangupAsync();
await HangupCallsAsync();
await _transport.LeaveAsync(room);
JoinedRooms.Remove(room);
_messagesByRoom.Remove(room);
@ -210,12 +297,8 @@ namespace PostIt.ViewModels.Chat
private async Task DisconnectCoreAsync()
{
Exception? callError = null;
if (VideoCall != null)
{
try { await VideoCall.DisposeAsync(); }
catch (Exception error) { callError = error; }
finally { VideoCall = null; }
}
try { await DisposeCallViewModelsAsync(); }
catch (Exception error) { callError = error; }
Calls?.Dispose();
Calls = null;
try
@ -239,6 +322,24 @@ namespace PostIt.ViewModels.Chat
}
}
private async Task DisposeCallViewModelsAsync()
{
Exception? callError = null;
if (VideoCall != null)
{
try { await VideoCall.DisposeAsync(); }
catch (Exception error) { callError = error; }
finally { VideoCall = null; }
}
if (LanCall != null)
{
try { await LanCall.DisposeAsync(); }
catch (Exception error) { callError = callError == null ? error : new AggregateException(callError, error); }
finally { LanCall = null; }
}
if (callError != null) throw callError;
}
public async Task ConnectAsync()
{
if (_api?.IsSigningOut == true)
@ -269,13 +370,12 @@ namespace PostIt.ViewModels.Chat
return;
if (_connection != null)
{
if (VideoCall != null)
try { await DisposeCallViewModelsAsync(); }
finally
{
await VideoCall.DisposeAsync();
VideoCall = null;
Calls?.Dispose();
Calls = null;
}
Calls?.Dispose();
Calls = null;
}
Status = new StatusNotice("Connexion en cours...", StatusSeverity.Info,
new RelayCheckCommand("Vérifier la connexion", async () => await CheckConnectionAsync()));
@ -298,9 +398,15 @@ namespace PostIt.ViewModels.Chat
Calls = new CallSignalingClient(_connection);
if (SupportsVideoCalls)
VideoCall = new WebRtcCallViewModel(Calls, settings: _settings) { Room = SelectedRoom ?? "" };
else
Calls.Invitation += call => PostForCurrentSession(() =>
Log($"Invitation audio-vidéo de {call.Caller} dans {call.RoomName} ; transport non disponible sur cette plateforme."));
if (SupportsLanCalls)
LanCall = new LanCallViewModel(Calls, settings: _settings) { Room = SelectedRoom ?? "" };
Calls.Invitation += call =>
{
if ((call.Transport == Yavsc.Abstract.Chat.Calls.CallTransports.LanSrtp && !SupportsLanCalls) ||
(call.Transport != Yavsc.Abstract.Chat.Calls.CallTransports.LanSrtp && !SupportsVideoCalls))
PostForCurrentSession(() =>
Log($"Invitation audio-vidéo de {call.Caller} dans {call.RoomName} ; transport non disponible sur cette plateforme."));
};
Calls.Ended += call => PostForCurrentSession(() =>
Log($"Appel terminé : {call.Reason}."));
@ -324,9 +430,7 @@ namespace PostIt.ViewModels.Chat
roomLog.Add($"*{user} a interagi avec le salon {room} (Action: {type})");
else
Log($"*{user} a interagi avec le salon {room} (Action: {type})");
if (type == "UserJoin" && _usersByRoom.TryGetValue(room, out var users)
&& !users.Contains(user))
users.Add(user);
UpdateRoomUsers(type, room, user);
});
});
@ -395,7 +499,7 @@ namespace PostIt.ViewModels.Chat
roomLog = _messagesByRoom[roomName] = new();
roomLog.Add($"Salon rejoint avec succès : {roomName}");
var users = _usersByRoom[roomName] = new();
foreach (var u in roomInfo.Users) users.Add(u);
foreach (var u in roomInfo.UserNames ?? roomInfo.Users) users.Add(u);
if (!JoinedRooms.Contains(roomName))
JoinedRooms.Add(roomName);
SelectedRoom = roomName;

View file

@ -243,22 +243,22 @@ public partial class LanCallViewModel : ObservableObject, IAsyncDisposable
return RunAsync(() => StopAsync("Appel termine.", true));
}
private void OnInvitation(CallSession call) => Queue(async () =>
private void OnInvitation(CallSession call)
{
if (call.Transport != CallTransports.LanSrtp)
if (call.Transport != CallTransports.LanSrtp) return;
Queue(async () =>
{
await _signaling.EndAsync(call.Id, _lifetime.Token);
Status = "Invitation WebRTC non prise en charge par le mode LAN.";
return;
}
if (_call != null) throw new InvalidOperationException("Invitation concurrente inattendue.");
if (call.RelayOnly) throw new InvalidOperationException("Le mode LAN ne peut pas masquer les adresses IP.");
_call = call;
Busy = true;
Incoming = true;
Status = $"{call.Caller} propose un appel SRTP dans {call.RoomName}. Acceptez ou refusez.";
await Task.CompletedTask;
});
if (_call != null) throw new InvalidOperationException("Invitation concurrente inattendue.");
if (call.RelayOnly) throw new InvalidOperationException("Le mode LAN ne peut pas masquer les adresses IP.");
_call = call;
Room = call.RoomName;
Target = call.Caller;
Busy = true;
Incoming = true;
Status = $"{call.Caller} propose un appel SRTP dans {call.RoomName}. Acceptez ou refusez.";
await Task.CompletedTask;
});
}
private void OnAccepted(CallAccepted accepted) => Queue(async () =>
{

View file

@ -156,22 +156,28 @@ public partial class WebRtcCallViewModel : ObservableObject, IAsyncDisposable
return RunAsync(() => StopAsync("Appel termine.", true));
}
private void OnInvitation(CallSession call) => Queue(async () =>
private void OnInvitation(CallSession call)
{
if (call.Transport != CallTransports.WebRtc || _call is not null)
if (call.Transport == CallTransports.LanSrtp) return;
Queue(async () =>
{
await _signaling.EndAsync(call.Id, _lifetime.Token);
Status = "Invitation refusee : transport incompatible ou appel deja en cours.";
return;
}
_call = call;
_caller = false;
_callLifetime = CancellationTokenSource.CreateLinkedTokenSource(_lifetime.Token);
Busy = Incoming = true;
Status = $"{call.Caller} propose un appel dans {call.RoomName}. "
+ (call.RelayOnly ? "Masquage IP : relais TURN obligatoire. " : "Mode direct : consentement au partage IP requis. ")
+ "Acceptez ou refusez.";
});
if (call.Transport != CallTransports.WebRtc || _call is not null)
{
await _signaling.EndAsync(call.Id, _lifetime.Token);
Status = "Invitation refusee : transport incompatible ou appel deja en cours.";
return;
}
_call = call;
Room = call.RoomName;
Target = call.Caller;
_caller = false;
_callLifetime = CancellationTokenSource.CreateLinkedTokenSource(_lifetime.Token);
Busy = Incoming = true;
Status = $"{call.Caller} propose un appel dans {call.RoomName}. "
+ (call.RelayOnly ? "Masquage IP : relais TURN obligatoire. " : "Mode direct : consentement au partage IP requis. ")
+ "Acceptez ou refusez.";
});
}
private void OnAccepted(CallAccepted accepted) => Queue(async () =>
{

View file

@ -78,6 +78,7 @@ public class HomePageViewModel : ViewModelBase
OpenPerformerConfiguration = new AsyncRelayCommand(OpenPerformerConfigurationAsync);
OpenAdministration = new AsyncRelayCommand(OpenAdministrationAsync, () => SessionStatus.IsAdministrator);
OpenChat = new AsyncRelayCommand(OpenChatAsync);
OpenContacts = new AsyncRelayCommand(OpenContactsAsync);
OpenPodcasts = new AsyncRelayCommand(async () =>
{
var app = Application.Current as App ?? throw new InvalidOperationException("Application indisponible.");
@ -89,6 +90,7 @@ public class HomePageViewModel : ViewModelBase
public IAsyncRelayCommand OpenChat { get; }
public IAsyncRelayCommand OpenContacts { get; }
public IAsyncRelayCommand OpenPodcasts { get; }
public bool SupportsPodcasts => Platform.IsPodcastSupported;
public IAsyncRelayCommand OpenBlogs { get; }
@ -264,6 +266,15 @@ public class HomePageViewModel : ViewModelBase
}
private async Task OpenContactsAsync()
{
var app = Application.Current as App ?? throw new InvalidOperationException("Application indisponible.");
var vm = app.ServiceProvider?.GetRequiredService<ContactsPageViewModel>()
?? throw new InvalidOperationException("Page contacts indisponible.");
await app.PushPageAsync(vm);
await vm.RefreshAsync();
}
/// <summary>
/// Ouvre la page « Mes fichiers » (espace de stockage personnel),
/// servie par le host Blogs via <c>api/v1/fs</c>.

View file

@ -0,0 +1,23 @@
<ContentPage
x:Class="PostIt.Views.ContactsPage"
xmlns="https://github.com/avaloniaui"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:vm="using:PostIt.ViewModels"
x:DataType="vm:ContactsPageViewModel"
Header="Contacts">
<Grid Margin="16" RowDefinitions="Auto,Auto,*">
<Button Content="Actualiser" Command="{Binding RefreshCommand}" IsEnabled="{Binding !IsBusy}" />
<TextBlock Grid.Row="1" Margin="0,8" Text="{Binding Status}" TextWrapping="Wrap" />
<ListBox Grid.Row="2" ItemsSource="{Binding Contacts}">
<ListBox.ItemTemplate>
<DataTemplate x:DataType="vm:ContactEntry">
<StackPanel Margin="4" Spacing="3">
<TextBlock FontWeight="SemiBold" Text="{Binding DisplayName}" />
<TextBlock Text="{Binding UserName}" />
<TextBlock Text="{Binding Circles}" TextWrapping="Wrap" />
</StackPanel>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
</Grid>
</ContentPage>

View file

@ -0,0 +1,8 @@
using Avalonia.Controls;
namespace PostIt.Views;
public partial class ContactsPage : ContentPage
{
public ContactsPage() => InitializeComponent();
}

View file

@ -0,0 +1,101 @@
<ContentPage
x:Class="PostIt.Views.Chat.CallPage"
xmlns="https://github.com/avaloniaui"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:vm="using:PostIt.ViewModels.Chat"
xmlns:services="using:PostIt.Services"
x:DataType="vm:CallPageViewModel"
Header="Appel audio-video">
<ScrollViewer HorizontalScrollBarVisibility="Disabled">
<StackPanel Margin="16" Spacing="16">
<TextBlock Text="Choisissez WebRTC ou SRTP direct. Les deux participants doivent etre presents dans le meme salon. Quitter cette page termine l'appel."
TextWrapping="Wrap" />
<StackPanel IsVisible="{Binding Chat.SupportsVideoCalls}">
<TextBlock Text="Appel video WebRTC" FontSize="20" FontWeight="SemiBold" Margin="0,0,0,8" />
<StackPanel DataContext="{Binding Chat.VideoCall}" x:DataType="vm:WebRtcCallViewModel"
IsEnabled="{Binding $parent[ContentPage].((vm:CallPageViewModel)DataContext).Chat.IsConnected}" Spacing="8">
<TextBlock Text="Android et Linux : medias chiffres par WebRTC (DTLS-SRTP), ICE/STUN/TURN. Activez le masquage IP dans votre profil pour imposer un relais TURN aux deux participants, sans repli direct. La camera et le microphone ne demarrent qu'apres acceptation."
TextWrapping="Wrap" />
<WrapPanel IsEnabled="{Binding CanConfigure}" IsVisible="{Binding !RemoteVideo}">
<Button Content="Actualiser les peripheriques" Command="{Binding RefreshDevicesCommand}" Margin="0,0,8,4" />
<ComboBox Width="190" ItemsSource="{Binding Cameras}" SelectedItem="{Binding Camera}"
PlaceholderText="Camera" Margin="0,0,8,4">
<ComboBox.ItemTemplate>
<DataTemplate x:DataType="services:CaptureDevice">
<TextBlock Text="{Binding Name}" />
</DataTemplate>
</ComboBox.ItemTemplate>
</ComboBox>
<ComboBox Width="190" ItemsSource="{Binding Microphones}" SelectedItem="{Binding Microphone}"
PlaceholderText="Microphone" Margin="0,0,8,4">
<ComboBox.ItemTemplate>
<DataTemplate x:DataType="services:CaptureDevice">
<TextBlock Text="{Binding Name}" />
</DataTemplate>
</ComboBox.ItemTemplate>
</ComboBox>
<TextBlock Text="{Binding Target}" VerticalAlignment="Center" Margin="0,0,8,4" />
</WrapPanel>
<CheckBox Content="Si le masquage IP est desactive, je consens a partager mon adresse IP avec le pair."
IsChecked="{Binding AllowAddressDisclosure}" IsEnabled="{Binding CanConfigure}"
IsVisible="{Binding !RemoteVideo}" />
<WrapPanel>
<Button Content="Appeler dans la salle active" Command="{Binding InviteCommand}" IsEnabled="{Binding !Busy}" Margin="0,0,8,4" />
<Button Content="Accepter" Command="{Binding AcceptCommand}" IsEnabled="{Binding Incoming}" Margin="0,0,8,4" />
<Button Content="Refuser / Raccrocher" Command="{Binding HangupCommand}" IsEnabled="{Binding Busy}" Margin="0,0,8,4" />
</WrapPanel>
<TextBlock Text="{Binding Status}" TextWrapping="Wrap" />
<Grid ColumnDefinitions="*,2*" Height="280" IsVisible="{Binding !!RemoteVideo}">
<ContentControl Content="{Binding LocalVideo}" Margin="0,0,8,0" />
<ContentControl Grid.Column="1" Content="{Binding RemoteVideo}" />
</Grid>
</StackPanel>
</StackPanel>
<StackPanel IsVisible="{Binding Chat.SupportsLanCalls}">
<TextBlock Text="Appel direct IPv4/IPv6 SRTP (LAN/VPN ou IP publique)"
FontSize="20" FontWeight="SemiBold" TextWrapping="Wrap" Margin="0,0,0,8" />
<StackPanel DataContext="{Binding Chat.LanCall}" x:DataType="vm:LanCallViewModel"
IsEnabled="{Binding $parent[ContentPage].((vm:CallPageViewModel)DataContext).Chat.IsConnected}" Spacing="8">
<TextBlock Text="Connexion directe sans TURN ni traversee NAT : le pair connait votre IP. Le masquage IP doit etre desactive dans les profils des deux participants. Les medias sont chiffres par SRTP. Ouvrez le port UDP pair choisi et le suivant ; HTTPS est requis pour la signalisation. Casque recommande."
TextWrapping="Wrap" />
<WrapPanel IsEnabled="{Binding CanConfigure}" IsVisible="{Binding !RemoteVideo}">
<Button Content="Actualiser les peripheriques" Command="{Binding RefreshDevicesCommand}" Margin="0,0,8,4" />
<ComboBox Width="160" ItemsSource="{Binding Addresses}" SelectedItem="{Binding Address}"
PlaceholderText="Adresse IPv4/IPv6 de cette machine" Margin="0,0,8,4" />
<TextBox Width="80" Text="{Binding Port}" PlaceholderText="Port pair" Margin="0,0,8,4" />
<ComboBox Width="190" ItemsSource="{Binding Cameras}" SelectedItem="{Binding Camera}"
PlaceholderText="Camera" Margin="0,0,8,4">
<ComboBox.ItemTemplate>
<DataTemplate x:DataType="services:CaptureDevice">
<TextBlock Text="{Binding Name}" />
</DataTemplate>
</ComboBox.ItemTemplate>
</ComboBox>
<ComboBox Width="190" ItemsSource="{Binding Microphones}" SelectedItem="{Binding Microphone}"
PlaceholderText="Microphone" Margin="0,0,8,4">
<ComboBox.ItemTemplate>
<DataTemplate x:DataType="services:CaptureDevice">
<TextBlock Text="{Binding Name}" />
</DataTemplate>
</ComboBox.ItemTemplate>
</ComboBox>
<TextBlock Text="{Binding Target}" VerticalAlignment="Center" Margin="0,0,8,4" />
</WrapPanel>
<CheckBox Content="Je consens a partager mon adresse IP avec le pair."
IsChecked="{Binding AllowAddressDisclosure}" IsEnabled="{Binding CanConfigure}"
IsVisible="{Binding !RemoteVideo}" />
<WrapPanel>
<Button Content="Appeler dans la salle active" Command="{Binding InviteCommand}" IsEnabled="{Binding !Busy}" Margin="0,0,8,4" />
<Button Content="Accepter" Command="{Binding AcceptCommand}" IsEnabled="{Binding Incoming}" Margin="0,0,8,4" />
<Button Content="Refuser / Raccrocher" Command="{Binding HangupCommand}" IsEnabled="{Binding Busy}" Margin="0,0,8,4" />
</WrapPanel>
<TextBlock Text="{Binding Status}" TextWrapping="Wrap" />
<Grid ColumnDefinitions="*,2*" Height="280" IsVisible="{Binding !!RemoteVideo}">
<ContentControl Content="{Binding LocalVideo}" Margin="0,0,8,0" />
<ContentControl Grid.Column="1" Content="{Binding RemoteVideo}" />
</Grid>
</StackPanel>
</StackPanel>
</StackPanel>
</ScrollViewer>
</ContentPage>

View file

@ -0,0 +1,16 @@
using Avalonia;
using Avalonia.Controls;
using PostIt.ViewModels.Chat;
namespace PostIt.Views.Chat;
public partial class CallPage : ContentPage
{
public CallPage() => InitializeComponent();
protected override async void OnDetachedFromVisualTree(VisualTreeAttachmentEventArgs e)
{
base.OnDetachedFromVisualTree(e);
if (DataContext is CallPageViewModel call) await call.HangupAsync();
}
}

View file

@ -2,15 +2,8 @@
x:Class="PostIt.Views.Chat.ChatPage"
xmlns="https://github.com/avaloniaui"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:AvaloniaEdit="clr-namespace:AvaloniaEdit;assembly=AvaloniaEdit"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:md="using:MarkdownViewer.Core.Controls"
xmlns:models="using:Yavsc.Blogspot"
xmlns:postitControls="using:PostIt.Controls"
xmlns:views="using:PostIt.Views.Chat"
xmlns:vm="using:PostIt.ViewModels.Chat"
xmlns:services="using:PostIt.Services"
x:DataType="vm:ChatViewModel"
>
<Design.DataContext>
@ -66,7 +59,7 @@
Margin="10,0,0,0"
BorderBrush="#E0E0E0"
BorderThickness="1">
<Grid RowDefinitions="Auto, *">
<Grid RowDefinitions="Auto, *, Auto">
<TextBlock
Grid.Row="0"
Margin="5"
@ -76,7 +69,10 @@
<ListBox
Grid.Row="1"
BorderThickness="0"
ItemsSource="{Binding FocusedUsers}" />
ItemsSource="{Binding FocusedUsers}"
SelectedItem="{Binding SelectedUser}" />
<Button Grid.Row="2" Margin="5" Content="Ouvrir l'appel"
Command="{Binding OpenCallCommand}" />
</Grid>
</Border>
</Grid>
@ -104,48 +100,12 @@
Content="Envoyer" />
</Grid>
<Expander Grid.Row="3" Header="Appel video WebRTC" IsVisible="{Binding SupportsVideoCalls}" IsExpanded="True"
IsEnabled="{Binding IsConnected}" Margin="0,0,0,8">
<ScrollViewer MaxHeight="520">
<StackPanel DataContext="{Binding VideoCall}" x:DataType="vm:WebRtcCallViewModel" Spacing="8">
<TextBlock Text="Android et Linux : medias chiffres par WebRTC (DTLS-SRTP), ICE/STUN/TURN. Activez le masquage IP dans votre profil pour imposer un relais TURN aux deux participants, sans repli direct. La camera et le microphone ne demarrent qu'apres acceptation."
TextWrapping="Wrap" />
<WrapPanel IsEnabled="{Binding CanConfigure}" IsVisible="{Binding !RemoteVideo}">
<Button Content="Actualiser les peripheriques" Command="{Binding RefreshDevicesCommand}" Margin="0,0,8,4" />
<ComboBox Width="190" ItemsSource="{Binding Cameras}" SelectedItem="{Binding Camera}"
PlaceholderText="Camera" Margin="0,0,8,4">
<ComboBox.ItemTemplate>
<DataTemplate x:DataType="services:CaptureDevice">
<TextBlock Text="{Binding Name}" />
</DataTemplate>
</ComboBox.ItemTemplate>
</ComboBox>
<ComboBox Width="190" ItemsSource="{Binding Microphones}" SelectedItem="{Binding Microphone}"
PlaceholderText="Microphone" Margin="0,0,8,4">
<ComboBox.ItemTemplate>
<DataTemplate x:DataType="services:CaptureDevice">
<TextBlock Text="{Binding Name}" />
</DataTemplate>
</ComboBox.ItemTemplate>
</ComboBox>
<TextBox Width="170" Text="{Binding Target}" PlaceholderText="Pseudo du pair" Margin="0,0,8,4" />
</WrapPanel>
<CheckBox Content="Si le masquage IP est desactive, je consens a partager mon adresse IP avec le pair."
IsChecked="{Binding AllowAddressDisclosure}" IsEnabled="{Binding CanConfigure}"
IsVisible="{Binding !RemoteVideo}" />
<WrapPanel>
<Button Content="Appeler dans la salle active" Command="{Binding InviteCommand}" IsEnabled="{Binding !Busy}" Margin="0,0,8,4" />
<Button Content="Accepter" Command="{Binding AcceptCommand}" IsEnabled="{Binding Incoming}" Margin="0,0,8,4" />
<Button Content="Refuser / Raccrocher" Command="{Binding HangupCommand}" IsEnabled="{Binding Busy}" Margin="0,0,8,4" />
</WrapPanel>
<TextBlock Text="{Binding Status}" TextWrapping="Wrap" />
<Grid ColumnDefinitions="*,2*" Height="280" IsVisible="{Binding !!RemoteVideo}">
<ContentControl Content="{Binding LocalVideo}" Margin="0,0,8,0" />
<ContentControl Grid.Column="1" Content="{Binding RemoteVideo}" />
</Grid>
</StackPanel>
</ScrollViewer>
</Expander>
<StackPanel Grid.Row="3" Margin="0,0,0,8" Spacing="4">
<Button Content="Repondre a l'invitation WebRTC" Command="{Binding ShowCallCommand}"
IsVisible="{Binding VideoCall.Incoming}" />
<Button Content="Repondre a l'invitation SRTP directe" Command="{Binding ShowCallCommand}"
IsVisible="{Binding LanCall.Incoming}" />
</StackPanel>
<postitControls:StatusBar
x:Name="StatusBar"

View file

@ -1,6 +1,4 @@
using Avalonia;
using Avalonia.Controls;
using PostIt.ViewModels.Chat;
namespace PostIt.Views.Chat;
public partial class ChatPage : ContentPage
{
@ -9,11 +7,4 @@ public partial class ChatPage : ContentPage
{
InitializeComponent();
}
protected override async void OnDetachedFromVisualTree(VisualTreeAttachmentEventArgs e)
{
base.OnDetachedFromVisualTree(e);
if (DataContext is ChatViewModel { VideoCall: { } call })
await call.HangupAsync();
}
}

View file

@ -26,6 +26,10 @@
Label="Podcasts : directs et replays" />
</CommandBar.PrimaryCommands>
<CommandBar.SecondaryCommands>
<CommandBarButton
Command="{Binding OpenContacts}"
IsEnabled="{Binding SessionStatus.IsLoggedIn}"
Label="Contacts" />
<CommandBarButton
HorizontalAlignment="Center"
Command="{Binding OpenChat}"

View file

@ -10,7 +10,6 @@ namespace Yavsc.ApiControllers.Administration;
[Authorize("AdministratorOnly")]
[ResourceUsageExempt]
[Route(Constants.APIPrefix + "/" + Constants.ResourceUsagePath + "/admin")]
[Produces("application/json")]
[ResponseCache(NoStore = true, Location = ResponseCacheLocation.None)]
public sealed class ResourceUsageReliefApiController(
IResourceUsageService usage, ILogger<ResourceUsageReliefApiController> logger) : ControllerBase
@ -18,12 +17,12 @@ public sealed class ResourceUsageReliefApiController(
[HttpPost("{userId}/erase")]
[EndpointSummary("Effacer des points de consommation d’un utilisateur ayant atteint sa limite")]
[EndpointDescription("Conserve les compteurs techniques, refuse les montants supérieurs à la consommation et les confirmations périmées, sans crédit futur.")]
[ProducesResponseType<ResourceUsageSummary>(200)]
[ProducesResponseType<ProblemDetails>(400)]
[ProducesResponseType<ResourceUsageSummary>(200, "application/json")]
[ProducesResponseType<ProblemDetails>(400, "application/problem+json")]
[ProducesResponseType(401)]
[ProducesResponseType(403)]
[ProducesResponseType<ProblemDetails>(404)]
[ProducesResponseType<ProblemDetails>(409)]
[ProducesResponseType<ProblemDetails>(404, "application/problem+json")]
[ProducesResponseType<ProblemDetails>(409, "application/problem+json")]
public async Task<ActionResult<ResourceUsageSummary>> Erase(
string userId, EraseResourceUsageRequest request, CancellationToken ct)
{

View file

@ -163,8 +163,19 @@ namespace Yavsc.Server.Hubs
}
_logger.LogInformation($"returning channel info");
await Clients.Caller.SendAsync("joint", channelInfo);
return channelInfo;
var snapshot = new ChatRoomInfo
{
Name = channelInfo.Name,
Topic = channelInfo.Topic,
Users = [.. channelInfo.Users],
Ops = [.. channelInfo.Ops],
Hops = [.. channelInfo.Hops],
UserNames = channelInfo.Users.Concat(channelInfo.Ops).Concat(channelInfo.Hops)
.Select(id => _cxManager.GetUserName(id))
.Where(name => !string.IsNullOrWhiteSpace(name)).Distinct().ToList()
};
await Clients.Caller.SendAsync("joint", snapshot);
return snapshot;
}
public void Register(string room)

View file

@ -25,6 +25,7 @@ namespace Yavsc
{
public string Name;
public List<string> Users = new List<string>();
public List<string>? UserNames { get; set; }
public List<string> Ops = new List<string>();
public List<string> Hops = new List<string>();
public string Topic;

View file

@ -16,6 +16,7 @@ using Yavsc.Settings;
namespace Yavsc.Api.Test;
[Trait("Category", "non-reg")]
[Collection("Yavsc Api")]
public sealed class AccountCallPreferenceTests(ApiWebServerFixture fixture) : IClassFixture<ApiWebServerFixture>
{

View file

@ -8,6 +8,7 @@ using Yavsc.Tests.Shared;
namespace Yavsc.Api.Test;
[Trait("Category", "non-reg")]
[Collection("Yavsc Api")]
public sealed class ActivityApiControllerTests : IClassFixture<ApiWebServerFixture>
{

View file

@ -0,0 +1,73 @@
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.DependencyInjection;
using Yavsc.Api.Test.Fixtures;
using Yavsc.Models;
namespace Yavsc.Api.Test;
[Trait("Category", "non-reg")]
[Collection("Yavsc Api")]
public sealed class ApiWebServerFixtureTests(ApiWebServerFixture fixture) : IClassFixture<ApiWebServerFixture>
{
[Fact]
public void Haircut_reset_seeds_catalog_and_both_command_types()
{
for (var reset = 0; reset < 2; reset++)
{
fixture.ResetAndSeedHaircutGraph();
using var scope = fixture.Services.CreateScope();
var db = scope.ServiceProvider.GetRequiredService<ApplicationDbContext>();
Assert.Equal(3, db.HairPrestation.Count());
var haircut = Assert.Single(db.HairCutQueries.Include(query => query.Prestation));
Assert.Equal("brush", haircut.ActivityCode);
Assert.Equal("alice", haircut.PerformerId);
Assert.NotNull(haircut.Prestation);
var grouped = Assert.Single(db.HairMultiCutQueries.Include(query => query.Prestations));
Assert.Equal("mbrush", grouped.ActivityCode);
Assert.Equal("alice", grouped.PerformerId);
Assert.Equal(2, grouped.Prestations.Count);
}
}
[Fact]
public void Repeated_reset_removes_previous_data_and_reseeds_unique_users()
{
fixture.ResetAndSeedActivityGraph();
using (var scope = fixture.Services.CreateScope())
{
var db = scope.ServiceProvider.GetRequiredService<ApplicationDbContext>();
db.Users.Add(new ApplicationUser
{
Id = "previous-test-user",
UserName = "previous-test-user",
Email = "previous-test-user@example.test",
});
db.SaveChanges();
}
for (var reset = 0; reset < 2; reset++)
{
fixture.ResetAndSeedActivityGraph();
using var scope = fixture.Services.CreateScope();
var db = scope.ServiceProvider.GetRequiredService<ApplicationDbContext>();
Assert.Equal(new[] { "alice", "bob" }, db.Users.OrderBy(user => user.Id).Select(user => user.Id).ToArray());
Assert.Equal(2, db.Performers.Count());
Assert.Single(db.Locations);
if (db.Database.IsSqlite())
{
db.Database.OpenConnection();
try
{
using var command = db.Database.GetDbConnection().CreateCommand();
command.CommandText = "PRAGMA foreign_keys;";
Assert.Equal(1L, command.ExecuteScalar());
}
finally
{
db.Database.CloseConnection();
}
}
}
}
}

View file

@ -13,6 +13,7 @@ using Yavsc.Tests.Shared;
namespace Yavsc.Api.Test;
[Trait("Category", "non-reg")]
[Collection("Yavsc Api")]
public sealed class BillingControllerTests : IClassFixture<ApiWebServerFixture>
{

View file

@ -10,6 +10,7 @@ using Yavsc.Models.Billing;
namespace Yavsc.Api.Test;
[Trait("Category", "non-reg")]
[Collection("Yavsc Api")]
public sealed class BillingSignatureNotificationTests(ApiWebServerFixture fixture) : IClassFixture<ApiWebServerFixture>
{

View file

@ -10,6 +10,7 @@ using Yavsc.Tests.Shared;
namespace Yavsc.Api.Test;
[Trait("Category", "non-reg")]
[Collection("Yavsc Api")]
public sealed class DismissClicksApiControllerTests(ApiWebServerFixture fixture) : IClassFixture<ApiWebServerFixture>
{

View file

@ -12,6 +12,7 @@ using Yavsc.Tests.Shared;
namespace Yavsc.Api.Test;
[Trait("Category", "non-reg")]
[Collection("Yavsc Api")]
public sealed class EstimateApiControllerTests : IClassFixture<ApiWebServerFixture>
{

View file

@ -26,6 +26,7 @@ namespace Yavsc.Api.Test;
/// exercised in <c>Yavsc.Blogs.Tests</c>; these tests cover only the
/// metadata/relationship endpoints that live on the API host.</para>
/// </summary>
[Trait("Category", "non-reg")]
[Collection("Yavsc Api")]
public sealed class EstimateAttachmentsApiTests : IClassFixture<ApiWebServerFixture>
{

View file

@ -20,6 +20,7 @@ namespace Yavsc.Api.Test;
// The PDF test requires the system `lualatex` (and the TeX Live packages
// listed in the README runtime-deps section) on the host running the
// tests. On hosts without lualatex it skips cleanly rather than failing.
[Trait("Category", "non-reg")]
public sealed class EstimatePdfGenerationTests
{
// A provider signature: a downstroke, a cross, and a tap (dot).

View file

@ -1,7 +1,9 @@
using Microsoft.AspNetCore.Builder;
using Microsoft.Data.Sqlite;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Infrastructure;
using Microsoft.EntityFrameworkCore.Metadata;
using Microsoft.EntityFrameworkCore.Storage;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.IdentityModel.Tokens;
using Npgsql;
@ -375,7 +377,44 @@ public sealed class ApiWebServerFixture : WebHostFixture
return;
}
db.Database.EnsureDeleted();
// EnsureDeleted cannot clear a shared in-memory database kept alive by the anchor.
db.Database.OpenConnection();
try
{
using var command = db.Database.GetDbConnection().CreateCommand();
command.CommandText = "SELECT name FROM sqlite_master WHERE type = 'table' AND name NOT GLOB 'sqlite_*';";
var tables = new List<string>();
using (var reader = command.ExecuteReader())
{
while (reader.Read())
tables.Add(reader.GetString(0));
}
command.CommandText = "PRAGMA foreign_keys = OFF;";
command.ExecuteNonQuery();
try
{
using var transaction = db.Database.BeginTransaction();
command.Transaction = transaction.GetDbTransaction();
foreach (var table in tables)
{
command.CommandText = $"DROP TABLE \"{table.Replace("\"", "\"\"")}\";";
command.ExecuteNonQuery();
}
transaction.Commit();
}
finally
{
command.Transaction = null;
command.CommandText = "PRAGMA foreign_keys = ON;";
command.ExecuteNonQuery();
}
}
finally
{
db.Database.CloseConnection();
}
// SQLite retains sqlite_sequence, so EnsureCreated would incorrectly see an existing schema.
db.GetService<IRelationalDatabaseCreator>().CreateTables();
}
public void ResetAndSeedRdvQueryGraph()
@ -491,6 +530,46 @@ public sealed class ApiWebServerFixture : WebHostFixture
db.HairPrestation.AddRange(prestation1, prestation2, prestation3);
db.SaveChanges();
db.HairCutQueries.Add(new HairCutQuery
{
ActivityCode = "brush",
ClientId = "alice",
PerformerId = "alice",
Consent = true,
UserCreated = "alice",
UserModified = "alice",
DateCreated = DateTime.UtcNow,
DateModified = DateTime.UtcNow,
EventDate = DateTime.UtcNow.AddDays(3),
Location = location,
PrestationId = prestation1.Id,
Prestation = prestation1,
AdditionalInfo = "Coupe test",
Status = Yavsc.QueryStatus.Inserted,
Description = "Haircut seed",
});
db.HairMultiCutQueries.Add(new HairMultiCutQuery
{
ActivityCode = "mbrush",
ClientId = "alice",
PerformerId = "alice",
Consent = true,
UserCreated = "alice",
UserModified = "alice",
DateCreated = DateTime.UtcNow,
DateModified = DateTime.UtcNow,
EventDate = DateTime.UtcNow.AddDays(4),
Location = location,
Prestations = new List<HairPrestationCollectionItem>
{
new() { PrestationId = prestation1.Id, Prestation = prestation1 },
new() { PrestationId = prestation2.Id, Prestation = prestation2 },
},
Status = Yavsc.QueryStatus.Inserted,
});
db.SaveChanges();
}
public override void Dispose()

View file

@ -14,6 +14,7 @@ using Yavsc.Services;
namespace Yavsc.Api.Test;
[Trait("Category", "non-reg")]
[Collection("Yavsc Api")]
public sealed class FrontOfficeApiControllerTests : IClassFixture<ApiWebServerFixture>
{

View file

@ -26,6 +26,7 @@ namespace Yavsc.Api.Test;
/// belong to the caller, and listing is open to both parties
/// (client/provider) plus admin. A third party is refused.</para>
/// </summary>
[Trait("Category", "non-reg")]
[Collection("Yavsc Api")]
public sealed class FrontOfficeQueryAttachmentsApiTests : IClassFixture<ApiWebServerFixture>
{

View file

@ -15,6 +15,7 @@ using Yavsc.Tests.Shared;
namespace Yavsc.Api.Test;
[Trait("Category", "non-reg")]
[Collection("Yavsc Api")]
public sealed class HairCutQueryApiControllerTests : IClassFixture<ApiWebServerFixture>
{

View file

@ -11,6 +11,7 @@ using Yavsc.Tests.Shared;
namespace Yavsc.Api.Test;
[Trait("Category", "non-reg")]
[Collection("Yavsc Api")]
public sealed class HairMultiCutQueryApiControllerTests : IClassFixture<ApiWebServerFixture>
{

View file

@ -14,6 +14,7 @@ using Yavsc.Models.Workflow;
namespace Yavsc.Api.Test;
[Trait("Category", "non-reg")]
[Collection("Yavsc Api")]
public sealed class HomeControllerTests : IClassFixture<ApiWebServerFixture>
{

View file

@ -15,6 +15,7 @@ using Yavsc.Tests.Shared;
namespace Yavsc.Api.Test;
[Trait("Category", "non-reg")]
[Collection("Yavsc Api")]
public sealed class InvoiceApiTests(ApiWebServerFixture fixture) : IClassFixture<ApiWebServerFixture>
{

View file

@ -9,6 +9,7 @@ using Yavsc.Services;
namespace Yavsc.Api.Test;
[Trait("Category", "non-reg")]
public sealed class LiveProcessorTests : IDisposable
{
private readonly string _root = Path.Combine(Path.GetTempPath(), $"yavsc-podcast-unit-{Guid.NewGuid():N}");

View file

@ -13,6 +13,7 @@ using Yavsc.Tests.Shared;
namespace Yavsc.Api.Test;
[Trait("Category", "non-reg")]
[Collection("Yavsc Api")]
public sealed class PerformerDonationSettingsTests(ApiWebServerFixture fixture) : IClassFixture<ApiWebServerFixture>
{

View file

@ -9,6 +9,7 @@ using Yavsc.Tests.Shared;
namespace Yavsc.Api.Test;
[Trait("Category", "non-reg")]
[Collection("Yavsc Api")]
public sealed class PodcastControllerTests(ApiWebServerFixture fixture) : IClassFixture<ApiWebServerFixture>
{

View file

@ -17,6 +17,7 @@ using Yavsc.Settings;
namespace Yavsc.Api.Test;
[Trait("Category", "non-reg")]
public sealed class PodcastObsTests : IAsyncDisposable
{
private static CancellationToken Ct => TestContext.Current.CancellationToken;

View file

@ -9,6 +9,7 @@ using Yavsc.Services;
namespace Yavsc.Api.Test;
[Trait("Category", "non-reg")]
public sealed class PodcastReplayTests : IDisposable
{
private readonly string _root = Path.Combine(Path.GetTempPath(), $"yavsc-replay-{Guid.NewGuid():N}");

View file

@ -10,6 +10,7 @@ using Yavsc.Models;
namespace Yavsc.Api.Test;
[Trait("Category", "non-reg")]
[Collection("Yavsc Api")]
public sealed class PodcastScheduleTests(ApiWebServerFixture fixture) : IClassFixture<ApiWebServerFixture>
{

View file

@ -11,6 +11,7 @@ using Yavsc.Services;
namespace Yavsc.Api.Test;
[Trait("Category", "non-reg")]
[Collection("Yavsc Api")]
public sealed class RdvQueryApiControllerTests : IClassFixture<ApiWebServerFixture>
{

View file

@ -12,6 +12,7 @@ using Yavsc.Tests.Shared;
namespace Yavsc.Api.Test;
[Trait("Category", "non-reg")]
[Collection("Yavsc Api")]
public sealed class ResourceUsageApiControllerTests : IClassFixture<ApiWebServerFixture>
{

View file

@ -14,6 +14,7 @@ using Yavsc.Tests.Shared;
namespace Yavsc.Api.Test;
[Trait("Category", "non-reg")]
[Collection("Yavsc Api")]
public sealed class ResourceUsageReliefApiTests(ApiWebServerFixture fixture) : IClassFixture<ApiWebServerFixture>
{
@ -75,6 +76,7 @@ public sealed class ResourceUsageReliefApiTests(ApiWebServerFixture fixture) : I
var request = new EraseResourceUsageRequest { Points = 200.12545678m, ExpectedCredits = 0m };
using var response = await admin.PostAsJsonAsync($"{Root}/{id}/erase", request, Ct);
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
Assert.Equal("application/json", response.Content.Headers.ContentType?.MediaType);
Assert.True(response.Headers.CacheControl?.NoStore);
var summary = await response.Content.ReadFromJsonAsync<ResourceUsageSummary>(Ct);
Assert.NotNull(summary);
@ -105,6 +107,10 @@ public sealed class ResourceUsageReliefApiTests(ApiWebServerFixture fixture) : I
using var response = await client.PostAsync($"{Root}/{id}/erase", body, Ct);
Assert.Equal(HttpStatusCode.BadRequest, response.StatusCode);
Assert.Equal("application/problem+json", response.Content.Headers.ContentType?.MediaType);
var problem = await response.Content.ReadFromJsonAsync<Microsoft.AspNetCore.Mvc.ProblemDetails>(Ct);
Assert.NotNull(problem);
Assert.Equal((int)response.StatusCode, problem.Status);
Assert.False(string.IsNullOrWhiteSpace(problem.Title));
using var scope = fixture.Services.CreateScope();
Assert.Equal(0m, (await scope.ServiceProvider.GetRequiredService<ApplicationDbContext>()
.ResourceUsageRecords.SingleAsync(r => r.UserId == id, Ct)).CreditPoints);
@ -127,6 +133,10 @@ public sealed class ResourceUsageReliefApiTests(ApiWebServerFixture fixture) : I
}, Ct);
Assert.Equal(status, response.StatusCode);
Assert.Equal("application/problem+json", response.Content.Headers.ContentType?.MediaType);
var problem = await response.Content.ReadFromJsonAsync<Microsoft.AspNetCore.Mvc.ProblemDetails>(Ct);
Assert.NotNull(problem);
Assert.Equal((int)status, problem.Status);
Assert.False(string.IsNullOrWhiteSpace(problem.Title));
}
[Fact]
@ -151,5 +161,10 @@ public sealed class ResourceUsageReliefApiTests(ApiWebServerFixture fixture) : I
Assert.False(string.IsNullOrWhiteSpace(operation.GetProperty("summary").GetString()));
foreach (var status in new[] { "200", "400", "401", "403", "404", "409" })
Assert.True(operation.GetProperty("responses").TryGetProperty(status, out _));
Assert.True(operation.GetProperty("responses").GetProperty("200").GetProperty("content")
.TryGetProperty("application/json", out _));
foreach (var status in new[] { "400", "404", "409" })
Assert.True(operation.GetProperty("responses").GetProperty(status).GetProperty("content")
.TryGetProperty("application/problem+json", out _));
}
}

View file

@ -16,6 +16,7 @@ using Yavsc.Tests.Shared;
namespace Yavsc.Api.Test;
[Trait("Category", "non-reg")]
[Collection("Yavsc Api")]
public sealed class SiteAdministrationApiTests(ApiWebServerFixture fixture) : IClassFixture<ApiWebServerFixture>
{

View file

@ -35,6 +35,7 @@ namespace Yavsc.Blogs.Tests;
/// (the existing <c>BlogPost</c> and <c>Circle</c>) are not
/// attached to the DbContext in the same change-tracker graph.</para>
/// </summary>
[Trait("Category", "non-reg")]
[Collection("Yavsc Blogs")]
public sealed class BlogAclApiTests : IClassFixture<BlogsWebServerFixture>
{

View file

@ -12,6 +12,7 @@ using Yavsc.Blogs.Tests.Fixtures;
namespace Yavsc.Blogs.Tests;
[Trait("Category", "non-reg")]
[Collection("JwtClaimMapping")]
public sealed class BlogApiMappedClaimsTests :
IClassFixture<MappedClaimsBlogsWebServerFixture>

View file

@ -9,6 +9,7 @@ namespace Yavsc.Blogs.Tests;
/// surface. The first behavioural test (GET /api/v1/blog returns
/// 200) lands in a follow-up commit.
/// </summary>
[Trait("Category", "non-reg")]
[Collection("Yavsc Blogs")]
public sealed class BlogApiSmokeTests : IClassFixture<BlogsWebServerFixture>
{

View file

@ -26,6 +26,7 @@ namespace Yavsc.Blogs.Tests;
/// header (or sending a token signed with the wrong key) gets a
/// 401 back from the framework.
/// </summary>
[Trait("Category", "non-reg")]
[Collection("Yavsc Blogs")]
public sealed class BlogApiTests : IClassFixture<BlogsWebServerFixture>
{

View file

@ -28,6 +28,7 @@ namespace Yavsc.Blogs.Tests;
/// <see cref="BlogsWebServerFixture"/>) is resolved from DI and run
/// end-to-end — no mocking.</para>
/// </summary>
[Trait("Category", "non-reg")]
[Collection("Yavsc Blogs")]
public sealed class BlogSpotServiceIndexTests : IClassFixture<BlogsWebServerFixture>
{

View file

@ -30,6 +30,7 @@ namespace Yavsc.Blogs.Tests;
/// through the DbContext the same way the production code
/// would.</para>
/// </summary>
[Trait("Category", "non-reg")]
[Collection("JwtClaimMapping")]
public sealed class CircleMembersApiTests : IClassFixture<BlogsWebServerFixture>
{

View file

@ -47,6 +47,7 @@ namespace Yavsc.Blogs.Tests;
/// <c>[Collection("Yavsc Blogs")]</c> + <c>IClassFixture</c> so the
/// one shared host serves both legs without spinning a second one.
/// </summary>
[Trait("Category", "non-reg")]
[Collection("Yavsc Blogs")]
public sealed class CreateMultipartContentTests : IClassFixture<BlogsWebServerFixture>
{

View file

@ -35,6 +35,7 @@ namespace Yavsc.Blogs.Tests;
/// download endpoint lives here and not on the API host.</description></item>
/// </list>
/// </summary>
[Trait("Category", "non-reg")]
[Collection("Yavsc Blogs")]
public sealed class FileSystemApiTests : IClassFixture<BlogsWebServerFixture>
{

View file

@ -8,6 +8,7 @@ using Yavsc.Server.Helpers;
namespace Yavsc.Blogs.Tests;
[Trait("Category", "non-reg")]
public sealed class FilterFileNameTests
{
[Theory]

View file

@ -29,6 +29,7 @@ namespace Yavsc.Blogs.Tests;
/// where it manifested in production (PostIt showing a published
/// post's status as <c>false</c>).</para>
/// </summary>
[Trait("Category", "non-reg")]
public sealed class IBlogPostWireShapeTests
{
private static readonly JsonSerializerOptions WebDefaults

View file

@ -25,6 +25,7 @@ namespace Yavsc.Blogs.Tests;
/// in-memory <c>ApplicationDbContext</c>, JWT bearer auth
/// via <see cref="TestTokenIssuer"/>.</para>
/// </summary>
[Trait("Category", "non-reg")]
[Collection("Yavsc Blogs")]
public sealed class PublishEndpointTests : IClassFixture<BlogsWebServerFixture>
{

View file

@ -21,6 +21,7 @@ namespace Yavsc.Org.Tests;
/// encoding of the thumbprint, which is independent of the key
/// type and the cert issuer.
/// </remarks>
[Trait("Category", "non-reg")]
public class ComputeKidTests : IDisposable
{
private readonly string _tempDir;

View file

@ -21,6 +21,7 @@ namespace Yavsc.Org.Tests.Controllers;
/// production policy to honour that header, sidestepping the login flow
/// (which is itself not exercised by these tests).
/// </summary>
[Trait("Category", "non-reg")]
[Collection("Yavsc Server")]
public class ClientControllerCollectionTests : IClassFixture<TestWebApplicationFactory>
{

View file

@ -5,6 +5,7 @@ using Xunit;
namespace Yavsc.Org.Tests.Controllers;
[Trait("Category", "non-reg")]
public class CommandFormsControllerTests : IClassFixture<TestWebApplicationFactory>
{
private readonly TestWebApplicationFactory _factory;

View file

@ -10,6 +10,7 @@ using Xunit;
namespace Yavsc.Org.Tests.Controllers;
[Trait("Category", "non-reg")]
public class CommentsApiIntegrationTests : IClassFixture<TestWebApplicationFactory>
{
private readonly TestWebApplicationFactory _factory;

View file

@ -9,6 +9,7 @@ using Xunit;
namespace Yavsc.Org.Tests.Controllers;
[Trait("Category", "non-reg")]
public class CommentsControllerTests
{
[Fact]

View file

@ -19,6 +19,7 @@ using Xunit;
namespace Yavsc.Org.Tests.Controllers;
[Trait("Category", "non-reg")]
public sealed class PerformerDonationTests : IClassFixture<PerformerDonationTests.Factory>
{
private readonly Factory _factory;

View file

@ -25,6 +25,7 @@ using Xunit;
namespace Yavsc.Org.Tests.Controllers;
[Trait("Category", "non-reg")]
public sealed class PodcastWebTests : IClassFixture<PodcastWebTests.Factory>
{
private readonly Factory _factory;

View file

@ -22,6 +22,7 @@ using Xunit;
namespace Yavsc.Org.Tests.Controllers;
[Trait("Category", "non-reg")]
public sealed class ResourceSubscriptionControllerTests : IClassFixture<ResourceSubscriptionControllerTests.Factory>
{
private readonly Factory _factory;

View file

@ -6,6 +6,7 @@ using Xunit;
namespace Yavsc.Org.Tests.Controllers;
[Trait("Category", "non-reg")]
public sealed class ResourceUsageTermsTests
{
[Fact]

View file

@ -27,6 +27,7 @@ namespace Yavsc.Org.Tests.Controllers;
/// straight to the DbContext is the same code path the production
/// code uses, so it is the right surface to assert against.
/// </summary>
[Trait("Category", "non-reg")]
public class TestWebApplicationFactoryIsolationTests
{
[Fact]

View file

@ -6,6 +6,7 @@ using Xunit;
namespace Yavsc.Org.Tests;
[Trait("Category", "non-reg")]
public class DictionnaireMetierTests
{
[Fact]

View file

@ -8,6 +8,7 @@ using Yavsc.Server.Models.IT;
namespace Yavsc.Org.Tests
{
[Trait("Category", "non-reg")]
[Collection("Yavsc Server")]
[Trait("regression", "oui")]
public abstract class BaseTestContext : IClassFixture<WebServerFixture>, IDisposable

View file

@ -8,6 +8,7 @@ using Yavsc.Server.Helpers;
namespace Yavsc.Org.Tests
{
[Trait("Category", "non-reg")]
[Collection("Yavsc Server")]
[Trait("regression", "oui")]
public class Remoting : BaseTestContext, IClassFixture<WebServerFixture>

View file

@ -1,12 +0,0 @@
namespace Yavsc.Org.Tests.Mandatory;
using Xunit;
[Collection("Yavsc Server")]
[Trait("regression", "oui")]
public class Services : BaseTestContext, IClassFixture<WebServerFixture>
{
public Services(ITestOutputHelper output, WebServerFixture fixture) : base(output, fixture)
{
}
}

View file

@ -4,6 +4,7 @@ using Xunit;
namespace Yavsc
{
[Trait("Category", "non-reg")]
[Collection("Yavsc Abstract tests")]
[Trait("regression", "II")]
public class AbstractTests

View file

@ -14,6 +14,7 @@ using Xunit;
/// statiquement que le cshtml ne porte plus l'accès fautif. Si
/// quelqu'un revert la ligne, ce test casse.
/// </summary>
[Trait("Category", "non-reg")]
public class ApplicationUserDisplayTemplateTests
{
[Fact]

View file

@ -6,6 +6,7 @@ using Xunit;
/// for missing files. The pipeline falls back to static defaults under
/// /images/Users/icon_user*.png.
/// </summary>
[Trait("Category", "non-reg")]
public class AvatarFallbackTests : IClassFixture<TestWebApplicationFactory>
{
private readonly TestWebApplicationFactory _factory;

View file

@ -17,6 +17,7 @@ namespace Yavsc
// breaking the idempotency count assertion (a flaky failure that
// surfaces whenever the fixture's timing shifts). Pinning the class
// to the same collection serializes it with the host build.
[Trait("Category", "non-reg")]
[Collection("Yavsc Server")]
[Trait("regression", "II")]
public class BillingServiceTests

View file

@ -2,6 +2,7 @@ namespace Yavsc.Org.Tests.Mandatory
{
using Xunit;
[Trait("Category", "non-reg")]
[Collection("Database")]
[Trait("regression", "II")]
[Trait("dev", "wip")]

View file

@ -20,6 +20,7 @@ namespace Yavsc.Org.Tests
{
[Trait("Category", "non-reg")]
[Collection("EMaillingTeststCollection")]
[Trait("regression", "II")]
public class EMaillingTests : IClassFixture<WebServerFixture>

View file

@ -3,6 +3,7 @@ using Yavsc.Abstract.Files;
namespace Yavsc.Org.Tests.NonRegression;
using Xunit;
[Trait("Category", "non-reg")]
public class FileServerUrlHelpersTests
{
[Fact]

View file

@ -18,6 +18,7 @@ namespace Yavsc
/// must reference an ApiResource, and the seed's translation to
/// SQL must stay valid.
/// </summary>
[Trait("Category", "non-reg")]
[Trait("regression", "OIDC seed")]
public class OidcSeedTests
{

View file

@ -5,6 +5,7 @@ using Xunit;
namespace Yavsc.Tests.NonRegression;
[Trait("Category", "non-reg")]
public class PerformerCodeInputValidationTests
{
[Fact]

View file

@ -7,6 +7,7 @@ namespace Yavsc.Org.Tests.NonRegression;
/// - client-side SIREN validation is wired to country-specific regex rules
/// - controller exposes the validation catalog to the view
/// </summary>
[Trait("Category", "non-reg")]
public class SetActivityCountryValidationViewTests
{
[Fact]

View file

@ -17,6 +17,7 @@ namespace Yavsc.Org.Tests.NonRegression;
/// donnée partielle. Ces tests couvrent les trois formes de
/// "donnée absente" : user null, UserName vide, UserName whitespace.
/// </summary>
[Trait("Category", "non-reg")]
public class UserDisplayHelpersTests
{
[Fact]

View file

@ -8,6 +8,7 @@ using Xunit;
namespace Yavsc.Org.Tests.Services;
[Trait("Category", "non-reg")]
public class FileSystemAuthManagerTests
{
[Fact]

View file

@ -23,6 +23,7 @@ namespace Yavsc.Org.Tests.Smoke;
/// entire pipeline (routing + Razor + IdentityServer + EF + DI)
/// is wired correctly end-to-end.
/// </summary>
[Trait("Category", "non-reg")]
public class AccountSmokeTests : IClassFixture<TestWebApplicationFactory>
{
private readonly TestWebApplicationFactory _factory;

View file

@ -16,6 +16,7 @@ namespace Yavsc.Org.Tests.Smoke;
/// <c>doc/architecture/decoupage-organisation.md</c>. The smoke
/// here asserts the front-end side of the BC.
/// </summary>
[Trait("Category", "non-reg")]
public class BlogSmokeTests : BaseTestContext, IClassFixture<TestWebApplicationFactory>
{
private readonly TestWebApplicationFactory _factory;

View file

@ -24,6 +24,7 @@ using Xunit;
/// Once the WebServerFixture is stable in CI, this test can be
/// deleted.
/// </summary>
[Trait("Category", "non-reg")]
public class StaticAssetsPathsTests
{
private readonly ITestOutputHelper _output;

View file

@ -13,6 +13,7 @@ using Yavsc.Web.Services;
namespace Yavsc.Server.Tests;
[Trait("Category", "non-reg")]
public sealed class AccountWithdrawalTests : IDisposable
{
private readonly string root = Path.Combine(Path.GetTempPath(), "yavsc-withdrawal-" + Guid.NewGuid().ToString("N"));

View file

@ -26,6 +26,7 @@ namespace Yavsc.Server.Tests;
/// before the one <see cref="BlogSpotService.Details"/> reads through,
/// mirroring the per-request DbContext lifetime in production.</para>
/// </summary>
[Trait("Category", "non-reg")]
[Collection("Yavsc Server")]
public sealed class BlogSpotServiceDetailsTests : IClassFixture<ServerServicesFixture>
{

View file

@ -5,6 +5,7 @@ using Yavsc.Services;
namespace Yavsc.Server.Tests;
[Trait("Category", "non-reg")]
public sealed class CallConnectionPresenceTests
{
[Fact]

View file

@ -17,6 +17,7 @@ using Yavsc.ViewModels.Chat;
namespace Yavsc.Server.Tests;
[Trait("Category", "non-reg")]
public sealed class CallHubTests
{
private sealed class Fixture : IDisposable
@ -88,6 +89,51 @@ public sealed class CallHubTests
public HttpContext? HttpContext { get; set; } = context;
}
[Fact]
public async Task Room_snapshot_resolves_all_members_without_changing_internal_connection_ids()
{
using var f = new Fixture();
f.Connections.OnConnected("alice-2", "alice", false);
f.Connections.RoomInfo.Users.AddRange(["bob-1", "alice-2"]);
f.Connections.RoomInfo.Ops.Add("alice-1");
using var hub = f.Hub("alice", "alice-1");
hub.Groups = new Groups();
hub.Clients = new RoomClients(f.Delivery);
var snapshot = await hub.Join("General");
Assert.Equal(["bob", "alice"], snapshot.UserNames);
Assert.Equal(["bob-1", "alice-2"], snapshot.Users);
Assert.Equal(["alice-1"], snapshot.Ops);
Assert.Null(f.Connections.RoomInfo.UserNames);
Assert.NotSame(f.Connections.RoomInfo.Users, snapshot.Users);
Assert.Same(snapshot, Assert.Single(f.Delivery.Messages).Arguments[0]);
}
private sealed class Groups : IGroupManager
{
public Task AddToGroupAsync(string connectionId, string groupName, CancellationToken ct = default) =>
Task.CompletedTask;
public Task RemoveFromGroupAsync(string connectionId, string groupName, CancellationToken ct = default) =>
throw new NotSupportedException();
}
private sealed class RoomClients(RecordingCallHub delivery) : IHubCallerClients
{
public IClientProxy Caller => delivery.Client("alice-1");
public IClientProxy All => throw new NotSupportedException();
public IClientProxy Others => throw new NotSupportedException();
public IClientProxy AllExcept(IReadOnlyList<string> ids) => throw new NotSupportedException();
public IClientProxy Client(string id) => throw new NotSupportedException();
public IClientProxy Clients(IReadOnlyList<string> ids) => throw new NotSupportedException();
public IClientProxy Group(string name) => throw new NotSupportedException();
public IClientProxy GroupExcept(string name, IReadOnlyList<string> ids) => throw new NotSupportedException();
public IClientProxy Groups(IReadOnlyList<string> names) => throw new NotSupportedException();
public IClientProxy OthersInGroup(string name) => throw new NotSupportedException();
public IClientProxy User(string id) => throw new NotSupportedException();
public IClientProxy Users(IReadOnlyList<string> ids) => throw new NotSupportedException();
}
[Fact]
public async Task Invitation_requires_existing_accounts_presence_and_the_authenticated_connection()
{
@ -174,6 +220,7 @@ public sealed class CallHubTests
private sealed class Connections : IConnexionManager
{
public HashSet<string> Present { get; } = ["alice", "bob"];
public ChatRoomInfo RoomInfo { get; } = new() { Name = "General" };
private readonly Dictionary<string, string> _names = [];
public string GetUserName(string cxId) => _names.GetValueOrDefault(cxId)!;
public bool IsConnected(string user) => _names.ContainsValue(user);
@ -189,7 +236,11 @@ public sealed class CallHubTests
public bool DeOp(string room, string user) => throw new NotSupportedException();
public bool Hop(string room, string user) => throw new NotSupportedException();
public bool DeHop(string room, string user) => throw new NotSupportedException();
public bool TryGetChanInfo(string room, out ChatRoomInfo info) => throw new NotSupportedException();
public bool TryGetChanInfo(string room, out ChatRoomInfo info)
{
info = RoomInfo;
return room == RoomInfo.Name;
}
public IEnumerable<ChannelShortInfo> ListChannels(string pattern) => throw new NotSupportedException();
}
}

View file

@ -7,6 +7,7 @@ using Yavsc.Settings;
namespace Yavsc.Server.Tests;
[Trait("Category", "non-reg")]
public sealed class CallLanSignalingTests
{
private static LanCallEndpoint Endpoint(string address = "192.168.1.2", int port = 5004) =>

Some files were not shown because too many files have changed in this diff Show more