86 lines
2.6 KiB
C#
86 lines
2.6 KiB
C#
namespace StellaOps.Plugin.Testing;
|
|
|
|
using StellaOps.Plugin.Abstractions;
|
|
using StellaOps.Plugin.Abstractions.Health;
|
|
|
|
/// <summary>
|
|
/// Test host for running plugins in isolation during testing.
|
|
/// </summary>
|
|
public sealed class PluginTestHost : IAsyncDisposable
|
|
{
|
|
private readonly List<IPlugin> _plugins = new();
|
|
|
|
/// <summary>
|
|
/// Gets the test context for assertions.
|
|
/// </summary>
|
|
public TestPluginContext Context { get; }
|
|
|
|
/// <summary>
|
|
/// Creates a new plugin test host.
|
|
/// </summary>
|
|
/// <param name="configure">Optional configuration action.</param>
|
|
public PluginTestHost(Action<PluginTestHostOptions>? configure = null)
|
|
{
|
|
var options = new PluginTestHostOptions();
|
|
configure?.Invoke(options);
|
|
|
|
Context = new TestPluginContext(options);
|
|
}
|
|
|
|
/// <summary>
|
|
/// Load and initialize a plugin.
|
|
/// </summary>
|
|
/// <typeparam name="T">Plugin type.</typeparam>
|
|
/// <param name="ct">Cancellation token.</param>
|
|
/// <returns>Initialized plugin instance.</returns>
|
|
public async Task<T> LoadPluginAsync<T>(CancellationToken ct = default) where T : IPlugin, new()
|
|
{
|
|
var plugin = new T();
|
|
await plugin.InitializeAsync(Context, ct);
|
|
_plugins.Add(plugin);
|
|
return plugin;
|
|
}
|
|
|
|
/// <summary>
|
|
/// Load and initialize a plugin with custom configuration.
|
|
/// </summary>
|
|
/// <typeparam name="T">Plugin type.</typeparam>
|
|
/// <param name="configuration">Configuration values to set.</param>
|
|
/// <param name="ct">Cancellation token.</param>
|
|
/// <returns>Initialized plugin instance.</returns>
|
|
public async Task<T> LoadPluginAsync<T>(
|
|
Dictionary<string, object> configuration,
|
|
CancellationToken ct = default) where T : IPlugin, new()
|
|
{
|
|
foreach (var (key, value) in configuration)
|
|
{
|
|
Context.Configuration.SetValue(key, value);
|
|
}
|
|
|
|
return await LoadPluginAsync<T>(ct);
|
|
}
|
|
|
|
/// <summary>
|
|
/// Verify plugin health.
|
|
/// </summary>
|
|
/// <typeparam name="T">Plugin type.</typeparam>
|
|
/// <param name="plugin">Plugin to check.</param>
|
|
/// <param name="ct">Cancellation token.</param>
|
|
/// <returns>Health check result.</returns>
|
|
public async Task<HealthCheckResult> CheckHealthAsync<T>(T plugin, CancellationToken ct = default)
|
|
where T : IPlugin
|
|
{
|
|
return await plugin.HealthCheckAsync(ct);
|
|
}
|
|
|
|
/// <inheritdoc />
|
|
public async ValueTask DisposeAsync()
|
|
{
|
|
foreach (var plugin in _plugins)
|
|
{
|
|
await plugin.DisposeAsync();
|
|
}
|
|
_plugins.Clear();
|
|
}
|
|
}
|