using System.Text.Json; using Avalonia.Controls; using Avalonia.Headless.XUnit; using Avalonia.Threading; using Avalonia.VisualTree; using PostIt.Services; using PostIt.ViewModels; using PostIt.Views; using Yavsc.Abstract.Identity; using Yavsc.Abstract.Resources; using Yavsc.Api.Client; namespace PostIt.Tests; [Trait("Category", "non-reg")] public class AdministrationAccessTests { [Fact] public async Task Profile_quota_failure_keeps_the_consumption_visible_without_enabling_profile_changes() { await using var api = new ProfileTransport("Performer") { ExhaustedQuota = true }; var model = new UserProfilePageViewModel(api, usageClient: api.UsageClient); await model.RefreshAsync(); Assert.True(model.ResourceUsage?.IsQuotaReached); Assert.False(model.IsProfileLoaded); Assert.False(model.SaveProfileCommand.CanExecute(null)); Assert.Contains("resource_quota_exceeded", model.StatusMessage); } [Fact] public async Task Administration_quota_failure_keeps_the_authorized_usage_overview() { await using var api = new ProfileTransport("Administrator"); var session = new SessionStatusViewModel { Api = api }; await session.RefreshAsync(); api.ExhaustedQuota = true; var model = new AdministrationPageViewModel(api, api.UsageClient, session); await model.RefreshAsync(); Assert.True(Assert.Single(model.UsageOverview).IsQuotaReached); Assert.Empty(model.Users); Assert.Contains("les usages restent consultables", model.StatusMessage); } [Fact] public async Task Late_role_response_cannot_restore_access_after_logout() { await using var api = new ProfileTransport("Administrator"); var pending = new TaskCompletionSource(); api.PendingProfile = pending.Task; var session = new SessionStatusViewModel { Api = api }; var refresh = session.RefreshAsync(); session.Api = null; session.Refresh(); pending.SetResult(new Me { Roles = ["Administrator"] }); await refresh; Assert.False(session.IsAdministrator); } [Fact] public async Task Role_lookup_failure_denies_access_and_reports_the_error() { await using var api = new ProfileTransport("Administrator") { FailProfile = true }; var session = new SessionStatusViewModel { Api = api }; await session.RefreshAsync(); Assert.False(session.IsAdministrator); Assert.Contains("Impossible de vérifier les droits", session.SessionLabel); } [Fact] public async Task Administration_loads_users_and_usage_and_matches_by_id() { await using var api = new ProfileTransport("Administrator"); var session = new SessionStatusViewModel { Api = api }; await session.RefreshAsync(); var vm = new AdministrationPageViewModel(api, api.UsageClient, session); await vm.RefreshAsync(); vm.SelectedUser = Assert.Single(vm.Users); Assert.Equal("alice", vm.SelectedUsage?.UserName); Assert.Equal(12m, vm.SelectedUsage?.ApiCalls); Assert.Single(vm.UsageOverview); Assert.Contains(api.Requests, path => path.EndsWith("/resource-usage/admin")); Assert.DoesNotContain(api.Requests, path => path.EndsWith("/resource-usage/me")); } [AvaloniaFact] public async Task Administration_displays_both_tabs_and_selected_user_usage() { await using var api = new ProfileTransport("Administrator"); var session = new SessionStatusViewModel { Api = api }; await session.RefreshAsync(); var vm = new AdministrationPageViewModel(api, api.UsageClient, session); await vm.RefreshAsync(); vm.SelectedUser = Assert.Single(vm.Users); var page = new AdministrationPage { DataContext = vm }; var window = new Window { Content = page, Width = 800, Height = 600 }; try { window.Show(); Dispatcher.UIThread.RunJobs(); var tabs = Assert.Single(page.GetVisualDescendants().OfType()); Assert.Equal(7, tabs.Items.Count); Assert.Contains(page.GetVisualDescendants().OfType(), text => text.Text == "Appels API : 12"); tabs.SelectedIndex = 1; Dispatcher.UIThread.RunJobs(); Assert.Contains(page.GetVisualDescendants().OfType(), text => text.Text == "alice-id"); Assert.Contains(page.GetVisualDescendants().OfType(), text => text.Text == "Appels API : 12"); } finally { window.Close(); } } [Fact] public async Task Administration_denies_moderators_without_requesting_private_data() { await using var api = new ProfileTransport("Moderator"); var session = new SessionStatusViewModel { Api = api }; await session.RefreshAsync(); api.Requests.Clear(); var vm = new AdministrationPageViewModel(api, api.UsageClient, session); await vm.RefreshAsync(); Assert.Empty(api.Requests); Assert.Empty(vm.Users); Assert.Contains("Administrator", vm.StatusMessage); } [Fact] public async Task Administration_failure_reports_error_without_falling_back_to_personal_usage() { await using var api = new ProfileTransport("Administrator") { FailUsage = true }; var session = new SessionStatusViewModel { Api = api }; await session.RefreshAsync(); var vm = new AdministrationPageViewModel(api, api.UsageClient, session); await vm.RefreshAsync(); Assert.Empty(vm.Users); Assert.Empty(vm.UsageOverview); Assert.Contains("indisponible", vm.StatusMessage); Assert.DoesNotContain(api.Requests, path => path.EndsWith("/resource-usage/me")); } [Fact] public async Task My_profile_loads_own_profile_enables_saving_and_only_loads_personal_usage() { await using var api = new ProfileTransport("Performer"); var vm = new UserProfilePageViewModel(api, usageClient: api.UsageClient); await vm.RefreshAsync(); Assert.True(vm.IsProfileLoaded); Assert.Equal(12m, vm.ResourceUsage?.ApiCalls); Assert.True(vm.SaveProfileCommand.CanExecute(null)); vm.FullName = "Alice Updated"; Assert.Equal("Alice Updated", vm.BuildProfileUpdateRequest().FullName); Assert.DoesNotContain(api.Requests, path => path.EndsWith("/resource-usage/admin")); } [Fact] public async Task Usage_failure_does_not_disable_profile_management() { await using var api = new ProfileTransport("Performer") { FailUsage = true }; var vm = new UserProfilePageViewModel(api, usageClient: api.UsageClient); await vm.RefreshAsync(); Assert.True(vm.IsProfileLoaded); Assert.True(vm.SaveProfileCommand.CanExecute(null)); Assert.Null(vm.ResourceUsage); Assert.Contains("Impossible de charger mon usage", vm.UsageError); } [Theory] [InlineData(false)] [InlineData(true)] public async Task My_profile_loads_and_includes_the_call_privacy_preference_in_the_save_payload(bool initial) { await using var api = new ProfileTransport("Performer") { HideIpAddressInCalls = initial }; var vm = new UserProfilePageViewModel(api); await vm.RefreshAsync(); Assert.Equal(initial, vm.HideIpAddressInCalls); vm.HideIpAddressInCalls = !initial; Assert.Equal(!initial, vm.BuildProfileUpdateRequest().HideIpAddressInCalls); Assert.True(vm.SaveProfileCommand.CanExecute(null)); Assert.True(vm.IsProfileLoaded); } [AvaloniaFact] public async Task My_profile_privacy_checkbox_is_two_way_and_disabled_before_loading() { await using var api = new ProfileTransport("Performer") { HideIpAddressInCalls = true }; var vm = new UserProfilePageViewModel(api); var page = new UserProfilePage { DataContext = vm }; var window = new Window { Content = page }; try { window.Show(); var checkbox = Assert.Single(page.GetVisualDescendants().OfType(), control => Equals(control.Content, "Masquer mon adresse IP aux autres participants")); Assert.False(checkbox.IsEffectivelyEnabled); await vm.RefreshAsync(); Assert.True(checkbox.IsEffectivelyEnabled); Assert.True(checkbox.IsChecked); checkbox.IsChecked = false; Assert.False(vm.HideIpAddressInCalls); Assert.Equal(false, vm.BuildProfileUpdateRequest().HideIpAddressInCalls); vm.IsBusy = true; Assert.False(checkbox.IsEffectivelyEnabled); } finally { window.Close(); } } [Fact] public async Task Profile_read_failure_prevents_saving_a_default_call_privacy_preference() { await using var api = new ProfileTransport("Performer") { FailProfile = true }; var vm = new UserProfilePageViewModel(api); await vm.RefreshAsync(); Assert.False(vm.IsProfileLoaded); Assert.False(vm.SaveProfileCommand.CanExecute(null)); Assert.Contains("Impossible de charger le profil", vm.StatusMessage); } internal sealed class ProfileTransport : YavscApiClient { private readonly string _tokenPath; private readonly string _role; public List Requests { get; } = []; public Task? PendingProfile { get; set; } public bool FailProfile { get; set; } public bool FailUsage { get; set; } public bool ExhaustedQuota { get; set; } public bool HideIpAddressInCalls { get; set; } public ResourceUsageApiClient UsageClient => new(this, Settings.ApiUrl); public ProfileTransport(string role) : this(role, Path.Combine(Path.GetTempPath(), $"postit-admin-{Guid.NewGuid():N}.json")) { } private ProfileTransport(string role, string path) : base(new Settings(), CreateStore(path)) { _role = role; _tokenPath = path; } private static TokenStore CreateStore(string path) { var store = new TokenStore(path); store.Save(new RefreshTokenRecord("access", "refresh", DateTimeOffset.UtcNow.AddHours(1), null)); return store; } public override async Task CallAsync(HttpMethod method, string path, object? body = null, CancellationToken ct = default) { Requests.Add(path); object result; if (path.EndsWith("/account/me")) { if (ExhaustedQuota) throw new HttpRequestException("resource_quota_exceeded", null, System.Net.HttpStatusCode.TooManyRequests); if (FailProfile) throw new HttpRequestException("Profile unavailable"); result = PendingProfile is not null ? await PendingProfile : new Me { UserId = "alice-id", UserName = "alice", Roles = [_role], HideIpAddressInCalls = HideIpAddressInCalls }; } else if (path.Contains("/resource-usage/")) { if (FailUsage) throw new HttpRequestException("Usage unavailable"); var usage = new ResourceUsageSummary { UserId = "alice-id", UserName = "alice", ApiCalls = 12m, Consumption = ExhaustedQuota ? 10000m : 0.24m, ConsumptionLimit = 10000m, RemainingConsumption = ExhaustedQuota ? 0m : 9999.76m, IsQuotaReached = ExhaustedQuota }; result = path.EndsWith("/admin") ? new List { usage } : usage; } else if (path.EndsWith("/users")) { if (ExhaustedQuota) throw new HttpRequestException("resource_quota_exceeded", null, System.Net.HttpStatusCode.TooManyRequests); result = new List { new() { UserId = "alice-id", UserName = "alice" } }; } else throw new InvalidOperationException($"Unexpected endpoint: {path}"); return JsonSerializer.Deserialize(JsonSerializer.Serialize(result))!; } public new async ValueTask DisposeAsync() { await base.DisposeAsync(); File.Delete(_tokenPath); } } }