Files
Heimdall/tests/Heimdall.Web.Tests/Components/MudTestBase.cs
T

280 lines
13 KiB
C#
Raw Normal View History

using Bunit;
using Heimdall.Web.Services;
using Microsoft.Extensions.DependencyInjection;
using MudBlazor;
using MudBlazor.Services;
using System.Globalization;
using System.Reflection;
using System.Threading;
namespace Heimdall.Web.Tests.Components;
/// <summary>
/// Base TestContext for MudBlazor component tests.
/// Registers MudBlazor services with NSubstitute-mocked IKeyInterceptorService
/// (avoids IAsyncDisposable-only conflict with bUnit's sync Dispose).
/// </summary>
public abstract class MudTestBase : TestContext
{
static MudTestBase()
{
// Deterministic rendering regardless of the machine/CI locale.
// Without this, {Confidence:P0} renders "87 %" (fr-FR, space) vs
// "87%" (en-US), making format-sensitive assertions flaky across runners.
var culture = CultureInfo.GetCultureInfo("en-US");
CultureInfo.DefaultThreadCurrentCulture = culture;
CultureInfo.DefaultThreadCurrentUICulture = culture;
}
protected MudTestBase()
{
// Also pin the current thread (xUnit may reuse a pooled thread whose
// culture was set before the static ctor ran).
var culture = CultureInfo.GetCultureInfo("en-US");
Thread.CurrentThread.CurrentCulture = culture;
Thread.CurrentThread.CurrentUICulture = culture;
var services = (IServiceCollection)Services;
// Shared components now resolve text through UiText. Register the
// same localization services for every component test context.
services.AddScoped<UiLanguageService>();
services.AddScoped<UiText>();
// Register all MudBlazor services except KeyInterceptorService
services.AddMudServices(config =>
{
config.SnackbarConfiguration.PositionClass = "mud-alert-center-top";
config.SnackbarConfiguration.PreventDuplicates = true;
config.SnackbarConfiguration.ShowCloseIcon = true;
config.SnackbarConfiguration.VisibleStateDuration = 4000;
});
// Replace KeyInterceptorService with a manual mock that implements
// both IDisposable and IAsyncDisposable (NSubstitute Castle proxy
// only implements IAsyncDisposable, causing disposal failures)
services.RemoveService<IKeyInterceptorService>();
services.AddScoped<IKeyInterceptorService>(_ =>
{
var mock = new ManualMockKeyInterceptorService();
return mock;
});
// PopoverService only implements IAsyncDisposable — the generic sweep
// below (WrapIAsyncDisposableOnlyServices) wraps it in an
// IDisposable+IAsyncDisposable proxy, so the REAL PopoverService can
// stay registered and MudPopoverProvider/MudDialogProvider render
// correctly in tests (pages use inline MudDialog components).
services.WrapIAsyncDisposableOnlyServices();
// Loose mode: any unconfigured JSInterop call auto-resolves instead of
// throwing. MudBlazor has dozens of internal helpers (lockScroll,
// popover position updates, resize observers...) that pages invoke
// only when interactions happen; enumerating them all is fragile.
JSInterop.Mode = JSRuntimeMode.Loose;
// JSInterop setup for MudBlazor internals.
// MudBlazor invokes these with varying argument counts (e.g.
// addOnBlurEvent(elementRef, dotNetObjectRef)); a bare SetupVoid(id)
// only matches zero-argument invocations, and a predicate setup without
// SetVoidResult() leaves the invocation hanging. Predicate + result is
// the combination that matches any invocation shape.
JSInterop.SetupVoid("mudKeyInterceptor.connect", _ => true).SetVoidResult();
JSInterop.SetupVoid("mudKeyInterceptor.disconnect", _ => true).SetVoidResult();
JSInterop.SetupVoid("mudPopover.connect", _ => true).SetVoidResult();
JSInterop.SetupVoid("mudPopover.disconnect", _ => true).SetVoidResult();
JSInterop.SetupVoid("mudPopover.initialize", _ => true).SetVoidResult();
JSInterop.SetupVoid("mudPopover.dispose", _ => true).SetVoidResult();
JSInterop.SetupVoid("mudPopoverHandler.connect", _ => true).SetVoidResult();
JSInterop.SetupVoid("mudPopoverHandler.disconnect", _ => true).SetVoidResult();
JSInterop.SetupVoid("mudElementReference.captureElement", _ => true).SetVoidResult();
JSInterop.SetupVoid("mudElementRef.addOnBlurEvent", _ => true).SetVoidResult();
JSInterop.SetupVoid("mudElementRef.removeOnBlurEvent", _ => true).SetVoidResult();
JSInterop.SetupVoid("mudTextField.focus", _ => true).SetVoidResult();
JSInterop.SetupVoid("mudScrollManager.scrollTo", _ => true).SetVoidResult();
JSInterop.SetupVoid("mudScrollManager.scrollToBottom", _ => true).SetVoidResult();
JSInterop.SetupVoid("mudScrollListener.listen", _ => true).SetVoidResult();
JSInterop.SetupVoid("mudScrollListener.cancel", _ => true).SetVoidResult();
JSInterop.SetupVoid("mudResizeListener.listen", _ => true).SetVoidResult();
JSInterop.SetupVoid("mudResizeListener.cancel", _ => true).SetVoidResult();
JSInterop.SetupVoid("mudResizeObserver.connect", _ => true).SetVoidResult();
JSInterop.SetupVoid("mudResizeObserver.disconnect", _ => true).SetVoidResult();
JSInterop.SetupVoid("mudTable.initialize", _ => true).SetVoidResult();
JSInterop.SetupVoid("mudTable.destroy", _ => true).SetVoidResult();
JSInterop.SetupVoid("mudToolbar.initialize", _ => true).SetVoidResult();
JSInterop.SetupVoid("mudToolbar.destroy", _ => true).SetVoidResult();
JSInterop.SetupVoid("mudDragAndDrop.initializeDropZone", _ => true).SetVoidResult();
JSInterop.SetupVoid("mudDragAndDrop.initializeSortableList", _ => true).SetVoidResult();
}
}
/// <summary>
/// Manual mock for IKeyInterceptorService that implements both IDisposable
/// and IAsyncDisposable. Required because NSubstitute Castle proxies only
/// implement IAsyncDisposable, which breaks bUnit's sync service provider Dispose.
/// </summary>
internal sealed class ManualMockKeyInterceptorService : IKeyInterceptorService, IDisposable, IAsyncDisposable
{
public void Dispose() { }
public ValueTask DisposeAsync() { GC.SuppressFinalize(this); return ValueTask.CompletedTask; }
public Task SubscribeAsync(IKeyInterceptorObserver observer, KeyInterceptorOptions options)
=> Task.CompletedTask;
public Task SubscribeAsync(string elementId, KeyInterceptorOptions options,
Action<KeyMapBuilder> builder) => Task.CompletedTask;
public Task SubscribeAsync(string elementId, KeyInterceptorOptions options,
IKeyDownObserver? keyDown, IKeyUpObserver? keyUp) => Task.CompletedTask;
public Task SubscribeAsync(string elementId, KeyInterceptorOptions options,
Action<Microsoft.AspNetCore.Components.Web.KeyboardEventArgs>? keyDown,
Action<Microsoft.AspNetCore.Components.Web.KeyboardEventArgs>? keyUp) => Task.CompletedTask;
public Task SubscribeAsync(string elementId, KeyInterceptorOptions options,
Func<Microsoft.AspNetCore.Components.Web.KeyboardEventArgs, Task>? keyDown,
Func<Microsoft.AspNetCore.Components.Web.KeyboardEventArgs, Task>? keyUp) => Task.CompletedTask;
public Task UnsubscribeAsync(string elementId) => Task.CompletedTask;
public Task UnsubscribeAsync(IKeyInterceptorObserver observer) => Task.CompletedTask;
public Task DispatchAsync(string elementId, KeyEventKind kind,
Microsoft.AspNetCore.Components.Web.KeyboardEventArgs args) => Task.CompletedTask;
public Task UpdateKeyAsync(IKeyInterceptorObserver observer, KeyOptions options) => Task.CompletedTask;
public Task UpdateKeyAsync(string elementId, KeyOptions options) => Task.CompletedTask;
}
internal static class ServiceCollectionExtensions
{
public static void RemoveService<T>(this IServiceCollection services) where T : class
{
var descriptor = services.FirstOrDefault(d => d.ServiceType == typeof(T));
if (descriptor is not null)
services.Remove(descriptor);
}
/// <summary>
/// Replaces registrations whose concrete type only implements
/// IAsyncDisposable with a DispatchProxy wrapper that also implements
/// IDisposable. bUnit disposes the test container synchronously, and the
/// built-in Microsoft DI throws if a resolved service only implements
/// IAsyncDisposable — which is the case for several MudBlazor services
/// (PopoverService, PointerEventsNoneService, ...).
/// </summary>
public static void WrapIAsyncDisposableOnlyServices(this IServiceCollection services)
{
foreach (var descriptor in services.ToList())
{
if (descriptor.ServiceType == typeof(IAsyncDisposable) ||
descriptor.ServiceType == typeof(IDisposable))
continue;
var implType = descriptor.ImplementationType;
if (implType is null)
continue;
bool implementsIAsyncDisposable = typeof(IAsyncDisposable).IsAssignableFrom(implType);
bool implementsIDisposable = typeof(IDisposable).IsAssignableFrom(implType);
if (!implementsIAsyncDisposable || implementsIDisposable)
continue;
var originalFactory = descriptor.ImplementationFactory;
if (originalFactory is null)
{
// Build the concrete type with its constructor dependencies
// resolved from the provider (ActivatorUtilities), then wrap.
var concreteType = implType;
originalFactory = sp => ActivatorUtilities.CreateInstance(sp, concreteType);
}
var wrappedDescriptor = new ServiceDescriptor(
descriptor.ServiceType,
sp => AsyncDisposableProxy.Create(descriptor.ServiceType, originalFactory(sp)),
descriptor.Lifetime);
services.Remove(descriptor);
services.Add(wrappedDescriptor);
}
}
}
/// <summary>
/// A DispatchProxy that forwards every interface call to a real instance and
/// additionally implements IDisposable + IAsyncDisposable. Used to wrap
/// IAsyncDisposable-only MudBlazor services so bUnit's sync Dispose works.
/// </summary>
// CA1852 wants this sealed, but DispatchProxy.Create requires a non-sealed
// proxy base type — suppress with justification.
#pragma warning disable CA1852
internal class AsyncDisposableProxy : DispatchProxy, IDisposable, IAsyncDisposable
#pragma warning restore CA1852
{
private object? _target;
private bool _disposed;
public static T Create<T>(object target) where T : class
{
var proxy = DispatchProxy.Create<T, AsyncDisposableProxy>();
((AsyncDisposableProxy)(object)proxy)._target = target;
return proxy;
}
public static object Create(Type serviceType, object target)
{
// DispatchProxy cannot proxy interfaces whose methods are "final"
// (sealed/static patterns in some MudBlazor services), so use Castle
// DynamicProxy (already referenced via NSubstitute) with a mixin that
// adds IDisposable to the proxy.
var generator = new Castle.DynamicProxy.ProxyGenerator();
var options = new Castle.DynamicProxy.ProxyGenerationOptions();
options.AddMixinInstance(new DisposeMixin(target));
return generator.CreateInterfaceProxyWithTarget(serviceType, target, options);
}
protected override object? Invoke(MethodInfo? targetMethod, object?[]? args)
=> targetMethod?.Invoke(_target, args);
public void Dispose()
{
if (_disposed) return;
_disposed = true;
if (_target is IAsyncDisposable ad)
ad.DisposeAsync().AsTask().GetAwaiter().GetResult();
}
public async ValueTask DisposeAsync()
{
if (_disposed) return;
_disposed = true;
if (_target is IAsyncDisposable ad)
await ad.DisposeAsync();
}
/// <summary>
/// Castle mixin that forwards IDisposable.Dispose to the wrapped target.
/// This is what makes the generated proxy disposable synchronously.
/// </summary>
private sealed class DisposeMixin(object target) : IDisposable
{
public void Dispose()
{
if (target is IAsyncDisposable ad)
ad.DisposeAsync().AsTask().GetAwaiter().GetResult();
}
}
}
/// <summary>
/// Manual mock for IPopoverService that implements both IDisposable and
/// IAsyncDisposable, so bUnit's sync service provider Dispose does not throw
/// on MudPopoverProvider rendering.
/// </summary>
internal sealed class ManualMockPopoverService : IPopoverService, IDisposable, IAsyncDisposable
{
public PopoverOptions PopoverOptions { get; } = new();
public IEnumerable<IMudPopoverHolder> ActivePopovers => [];
public bool IsInitialized => true;
public void Dispose() { }
public ValueTask DisposeAsync() { GC.SuppressFinalize(this); return ValueTask.CompletedTask; }
public Task CreatePopoverAsync(IPopover popover) => Task.CompletedTask;
public Task<bool> UpdatePopoverAsync(IPopover popover) => Task.FromResult(true);
public Task<bool> DestroyPopoverAsync(IPopover popover) => Task.FromResult(true);
public ValueTask<int> GetProviderCountAsync() => ValueTask.FromResult(0);
public void Subscribe(IPopoverObserver observer) { }
public void Unsubscribe(IPopoverObserver observer) { }
}