mirror of
https://github.com/BinaryAlley/Nemera.git
synced 2026-12-03 13:11:10 +00:00
Hardens test assertions and adds missing test coverage.
This commit is contained in:
1 parent
6b86fd5805
commit
1189bbaf36
489 files changed
+39982
-512
No files matched your search
+166
@@ -0,0 +1,166 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Application.Common.DataAccess.Entities.Plugins;
|
||||
using Lumina.Application.Common.DataAccess.Repositories.Plugins;
|
||||
using Lumina.Application.Common.DataAccess.UoW;
|
||||
using Lumina.Application.Common.Infrastructure.Plugins;
|
||||
using Lumina.Domain.Common.Primitives;
|
||||
using Lumina.Domain.SharedKernel.Common.Enums.Plugins;
|
||||
using Lumina.Infrastructure.Core.Plugins;
|
||||
using Lumina.Plugins.Contracts.Core.Plugins;
|
||||
using Microsoft.Extensions.DependencyInjection;
|
||||
using Microsoft.Extensions.Hosting;
|
||||
using Microsoft.Extensions.Logging;
|
||||
using NSubstitute;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Reflection;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Infrastructure.UnitTests.Core.Plugins;
|
||||
|
||||
/// <summary>
|
||||
/// Contains unit tests for the <see cref="PluginDetectionSyncJob"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class PluginDetectionSyncJobTests
|
||||
{
|
||||
private readonly IServiceScopeFactory _mockServiceScopeFactory;
|
||||
private readonly IServiceScope _mockServiceScope;
|
||||
private readonly IServiceProvider _mockServiceProvider;
|
||||
private readonly IUnitOfWork _mockUnitOfWork;
|
||||
private readonly IPluginRepository _mockPluginRepository;
|
||||
private readonly IPluginManager _mockPluginManager;
|
||||
private readonly ILogger<PluginDetectionSyncJob> _mockLogger;
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="PluginDetectionSyncJobTests"/> class.
|
||||
/// </summary>
|
||||
public PluginDetectionSyncJobTests()
|
||||
{
|
||||
_mockServiceScopeFactory = Substitute.For<IServiceScopeFactory>();
|
||||
_mockServiceScope = Substitute.For<IServiceScope>();
|
||||
_mockServiceProvider = Substitute.For<IServiceProvider>();
|
||||
_mockServiceScopeFactory.CreateScope().Returns(_mockServiceScope);
|
||||
_mockServiceScope.ServiceProvider.Returns(_mockServiceProvider);
|
||||
|
||||
_mockUnitOfWork = Substitute.For<IUnitOfWork>();
|
||||
_mockPluginRepository = Substitute.For<IPluginRepository>();
|
||||
_mockUnitOfWork.PluginRepository.Returns(_mockPluginRepository);
|
||||
_mockServiceProvider.GetService(typeof(IUnitOfWork)).Returns(_mockUnitOfWork);
|
||||
|
||||
_mockPluginManager = Substitute.For<IPluginManager>();
|
||||
_mockLogger = Substitute.For<ILogger<PluginDetectionSyncJob>>();
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task StartAsync_WhenPluginsAreLoaded_ShouldPersistTheDetectionOfAllPlugins()
|
||||
{
|
||||
// Arrange
|
||||
IPlugin firstPlugin = CreatePlugin(Guid.NewGuid(), "First Plugin", new Version(1, 2, 3));
|
||||
IPlugin secondPlugin = CreatePlugin(Guid.NewGuid(), "Second Plugin", new Version(2, 0, 0));
|
||||
_mockPluginManager.GetPlugins().Returns([firstPlugin, secondPlugin]);
|
||||
_mockPluginRepository.UpsertAsync(Arg.Any<PluginEntity>(), Arg.Any<CancellationToken>())
|
||||
.Returns(Result.From(Result.Updated));
|
||||
PluginDetectionSyncJob sut = CreateSut();
|
||||
|
||||
// Act
|
||||
await StartAndWaitForExecutionAsync(sut);
|
||||
|
||||
// Assert
|
||||
await _mockPluginRepository.Received(1).UpsertAsync(
|
||||
Arg.Is<PluginEntity>(plugin => plugin.Id == firstPlugin.Id
|
||||
&& plugin.Name == firstPlugin.Name
|
||||
&& plugin.Author == firstPlugin.Author
|
||||
&& plugin.Version == firstPlugin.Version.ToString()
|
||||
&& plugin.Description == firstPlugin.Description
|
||||
&& plugin.LoadStatus == PluginLoadStatus.Loaded),
|
||||
Arg.Any<CancellationToken>());
|
||||
await _mockPluginRepository.Received(1).UpsertAsync(
|
||||
Arg.Is<PluginEntity>(plugin => plugin.Id == secondPlugin.Id
|
||||
&& plugin.Name == secondPlugin.Name
|
||||
&& plugin.LoadStatus == PluginLoadStatus.Loaded),
|
||||
Arg.Any<CancellationToken>());
|
||||
await _mockUnitOfWork.Received(1).SaveChangesAsync(Arg.Any<CancellationToken>());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task StartAsync_WhenUpsertFails_ShouldLogErrorAndContinueWithOtherPlugins()
|
||||
{
|
||||
// Arrange
|
||||
IPlugin failingPlugin = CreatePlugin(Guid.NewGuid(), "Failing Plugin", new Version(1, 0, 0));
|
||||
IPlugin successfulPlugin = CreatePlugin(Guid.NewGuid(), "Successful Plugin", new Version(1, 0, 0));
|
||||
_mockPluginManager.GetPlugins().Returns([failingPlugin, successfulPlugin]);
|
||||
_mockPluginRepository.UpsertAsync(
|
||||
Arg.Is<PluginEntity>(plugin => plugin.Id == failingPlugin.Id),
|
||||
Arg.Any<CancellationToken>())
|
||||
.Returns(Error.Failure("Database.Error", "Failed to persist the plugin"));
|
||||
_mockPluginRepository.UpsertAsync(
|
||||
Arg.Is<PluginEntity>(plugin => plugin.Id == successfulPlugin.Id),
|
||||
Arg.Any<CancellationToken>())
|
||||
.Returns(Result.From(Result.Updated));
|
||||
PluginDetectionSyncJob sut = CreateSut();
|
||||
|
||||
// Act
|
||||
await StartAndWaitForExecutionAsync(sut);
|
||||
|
||||
// Assert
|
||||
await _mockPluginRepository.Received(1).UpsertAsync(Arg.Is<PluginEntity>(plugin => plugin.Id == successfulPlugin.Id), Arg.Any<CancellationToken>());
|
||||
await _mockUnitOfWork.Received(1).SaveChangesAsync(Arg.Any<CancellationToken>());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task StartAsync_WhenNoPluginsAreLoaded_ShouldOnlySaveChanges()
|
||||
{
|
||||
// Arrange
|
||||
_mockPluginManager.GetPlugins().Returns([]);
|
||||
PluginDetectionSyncJob sut = CreateSut();
|
||||
|
||||
// Act
|
||||
await StartAndWaitForExecutionAsync(sut);
|
||||
|
||||
// Assert
|
||||
await _mockPluginRepository.DidNotReceiveWithAnyArgs().UpsertAsync(default!, Arg.Any<CancellationToken>());
|
||||
await _mockUnitOfWork.Received(1).SaveChangesAsync(Arg.Any<CancellationToken>());
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Invokes the protected <see cref="BackgroundService.ExecuteAsync"/> of the job and awaits its completion.
|
||||
/// </summary>
|
||||
/// <param name="sut">The job to execute.</param>
|
||||
private static async Task StartAndWaitForExecutionAsync(PluginDetectionSyncJob sut)
|
||||
{
|
||||
MethodInfo executeAsyncMethod = typeof(PluginDetectionSyncJob).GetMethod("ExecuteAsync", BindingFlags.Instance | BindingFlags.NonPublic)!;
|
||||
Task executingTask = (Task)executeAsyncMethod.Invoke(sut, [CancellationToken.None])!;
|
||||
await executingTask;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Creates the system under test wired to the mocked dependencies.
|
||||
/// </summary>
|
||||
/// <returns>The created job instance.</returns>
|
||||
private PluginDetectionSyncJob CreateSut()
|
||||
{
|
||||
return new PluginDetectionSyncJob(_mockServiceScopeFactory, _mockPluginManager, [], _mockLogger);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Creates a mocked plugin with the provided identity.
|
||||
/// </summary>
|
||||
/// <param name="id">The Id of the plugin.</param>
|
||||
/// <param name="name">The name of the plugin.</param>
|
||||
/// <param name="version">The version of the plugin.</param>
|
||||
/// <returns>The created plugin mock.</returns>
|
||||
private static IPlugin CreatePlugin(Guid id, string name, Version version)
|
||||
{
|
||||
IPlugin plugin = Substitute.For<IPlugin>();
|
||||
plugin.Id.Returns(id);
|
||||
plugin.Name.Returns(name);
|
||||
plugin.Author.Returns("Test Author");
|
||||
plugin.Version.Returns(version);
|
||||
plugin.Description.Returns("Test plugin description");
|
||||
return plugin;
|
||||
}
|
||||
}
|
||||
+106
@@ -0,0 +1,106 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Infrastructure.Core.Plugins;
|
||||
using System;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.IO;
|
||||
using System.Reflection;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Infrastructure.UnitTests.Core.Plugins;
|
||||
|
||||
/// <summary>
|
||||
/// Contains unit tests for the <see cref="PluginLoadContext"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class PluginLoadContextTests
|
||||
{
|
||||
[Fact]
|
||||
public void LoadFromAssemblyName_WhenAssemblyIsResolvableFromDefaultContext_ShouldReturnTheSharedAssembly()
|
||||
{
|
||||
// Arrange
|
||||
using TemporaryPluginDirectory temporaryPluginDirectory = new();
|
||||
PluginLoadContext sut = new(temporaryPluginDirectory.Path, "test-context");
|
||||
|
||||
// Act
|
||||
Assembly result = sut.LoadFromAssemblyName(typeof(object).Assembly.GetName());
|
||||
|
||||
// Assert
|
||||
Assert.NotNull(result);
|
||||
Assert.Equal(typeof(object).Assembly.GetName().Name, result.GetName().Name);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Load_WhenAssemblyExistsOnlyInPluginDirectory_ShouldLoadItFromThePluginDirectory()
|
||||
{
|
||||
// Arrange
|
||||
using TemporaryPluginDirectory temporaryPluginDirectory = new();
|
||||
string destinationPath = temporaryPluginDirectory.CopyDll(Path.Combine(AppContext.BaseDirectory, "Lumina.TestPlugin.dll"), "PluginLocalDependency.dll");
|
||||
PluginLoadContext sut = new(temporaryPluginDirectory.Path, "test-context");
|
||||
MethodInfo loadMethod = typeof(PluginLoadContext).GetMethod("Load", BindingFlags.Instance | BindingFlags.NonPublic)!;
|
||||
|
||||
// Act
|
||||
Assembly? result = (Assembly?)loadMethod.Invoke(sut, [new AssemblyName("PluginLocalDependency")]);
|
||||
|
||||
// Assert
|
||||
Assert.NotNull(result);
|
||||
Assert.Equal("Lumina.TestPlugin", result!.GetName().Name);
|
||||
Assert.Equal(destinationPath, result.Location);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void LoadFromAssemblyName_WhenAssemblyIsNotFoundAnywhere_ShouldThrowFileNotFoundException()
|
||||
{
|
||||
// Arrange
|
||||
using TemporaryPluginDirectory temporaryPluginDirectory = new();
|
||||
PluginLoadContext sut = new(temporaryPluginDirectory.Path, "test-context");
|
||||
|
||||
// Act
|
||||
Action act = () => sut.LoadFromAssemblyName(new AssemblyName($"Definitely.Not.Resolvable.{Guid.NewGuid()}"));
|
||||
|
||||
// Assert
|
||||
Assert.Throws<FileNotFoundException>(act);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Test helper managing a temporary plugins directory, deleted when the test finishes.
|
||||
/// </summary>
|
||||
private sealed class TemporaryPluginDirectory : IDisposable
|
||||
{
|
||||
private bool _disposed;
|
||||
|
||||
public TemporaryPluginDirectory()
|
||||
{
|
||||
Path = System.IO.Path.Combine(System.IO.Path.GetTempPath(), $"lumina-plugin-load-context-{Guid.NewGuid()}");
|
||||
Directory.CreateDirectory(Path);
|
||||
}
|
||||
|
||||
public string Path { get; }
|
||||
|
||||
public string CopyDll(string sourceDllPath, string destinationFileName)
|
||||
{
|
||||
string destinationPath = System.IO.Path.Combine(Path, destinationFileName);
|
||||
File.Copy(sourceDllPath, destinationPath);
|
||||
return destinationPath;
|
||||
}
|
||||
|
||||
public void Dispose()
|
||||
{
|
||||
if (!_disposed)
|
||||
{
|
||||
try
|
||||
{
|
||||
Directory.Delete(Path, recursive: true);
|
||||
}
|
||||
catch (IOException)
|
||||
{
|
||||
// best effort cleanup of the temporary plugins directory
|
||||
}
|
||||
catch (UnauthorizedAccessException)
|
||||
{
|
||||
// the plugin assemblies are still locked by their load contexts, best effort cleanup only
|
||||
}
|
||||
_disposed = true;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,143 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Infrastructure.Common.Models.DTO.Plugins;
|
||||
using Lumina.Infrastructure.Core.Plugins;
|
||||
using Lumina.Plugins.Contracts.Core.Plugins;
|
||||
using Microsoft.Extensions.DependencyInjection;
|
||||
using System;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.IO;
|
||||
using System.Linq;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Infrastructure.UnitTests.Core.Plugins;
|
||||
|
||||
/// <summary>
|
||||
/// Contains unit tests for the <see cref="PluginLoader"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class PluginLoaderTests
|
||||
{
|
||||
[Fact]
|
||||
public void LoadPlugins_WhenDirectoryDoesNotExist_ShouldReturnNoPluginsAndNoErrors()
|
||||
{
|
||||
// Arrange
|
||||
string nonExistentDirectory = Path.Combine(Path.GetTempPath(), $"lumina-plugins-{Guid.NewGuid()}");
|
||||
IServiceCollection services = new ServiceCollection();
|
||||
|
||||
// Act
|
||||
PluginLoadResultDto result = PluginLoader.LoadPlugins(nonExistentDirectory, services);
|
||||
|
||||
// Assert
|
||||
Assert.Empty(result.Plugins);
|
||||
Assert.Empty(result.Errors);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void LoadPlugins_WhenDirectoryContainsInvalidAssembly_ShouldRecordError()
|
||||
{
|
||||
// Arrange
|
||||
using TemporaryPluginDirectory temporaryPluginDirectory = new();
|
||||
temporaryPluginDirectory.CreateFile("invalid.dll", "this is not a valid assembly");
|
||||
IServiceCollection services = new ServiceCollection();
|
||||
|
||||
// Act
|
||||
PluginLoadResultDto result = PluginLoader.LoadPlugins(temporaryPluginDirectory.Path, services);
|
||||
|
||||
// Assert
|
||||
Assert.Empty(result.Plugins);
|
||||
string error = Assert.Single(result.Errors);
|
||||
Assert.Contains("invalid.dll", error);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void LoadPlugins_WhenDirectoryContainsAssemblyWithoutPluginDescriptors_ShouldReturnNoPluginsAndNoErrors()
|
||||
{
|
||||
// Arrange
|
||||
using TemporaryPluginDirectory temporaryPluginDirectory = new();
|
||||
temporaryPluginDirectory.CopyDll(typeof(IPlugin).Assembly.Location);
|
||||
IServiceCollection services = new ServiceCollection();
|
||||
|
||||
// Act
|
||||
PluginLoadResultDto result = PluginLoader.LoadPlugins(temporaryPluginDirectory.Path, services);
|
||||
|
||||
// Assert
|
||||
Assert.Empty(result.Plugins);
|
||||
Assert.Empty(result.Errors);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void LoadPlugins_WhenDirectoryContainsValidPluginAssembly_ShouldLoadPluginAndRegisterItsServices()
|
||||
{
|
||||
// Arrange
|
||||
using TemporaryPluginDirectory temporaryPluginDirectory = new();
|
||||
temporaryPluginDirectory.CopyDll(GetTestPluginAssemblyPath());
|
||||
IServiceCollection services = new ServiceCollection();
|
||||
|
||||
// Act
|
||||
PluginLoadResultDto result = PluginLoader.LoadPlugins(temporaryPluginDirectory.Path, services);
|
||||
|
||||
// Assert
|
||||
IPlugin loadedPlugin = Assert.Single(result.Plugins);
|
||||
Assert.Empty(result.Errors);
|
||||
Assert.Equal(Guid.Parse("7B5A3E5D-9B7F-4A1E-8D9C-2F3A4B5C6D7E"), loadedPlugin.Id);
|
||||
Assert.Equal("Test Plugin", loadedPlugin.Name);
|
||||
Assert.Contains(services, descriptor => descriptor.ImplementationInstance as string == "plugin-services-registered");
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Gets the path of the <c>Lumina.TestPlugin</c> assembly from the test output directory.
|
||||
/// The assembly is referenced by the test project but no type from it is used, so it is not loaded
|
||||
/// into the default load context, which is what makes the plugin loading pipeline testable.
|
||||
/// </summary>
|
||||
/// <returns>The path of the test plugin assembly.</returns>
|
||||
private static string GetTestPluginAssemblyPath()
|
||||
{
|
||||
return Path.Combine(AppContext.BaseDirectory, "Lumina.TestPlugin.dll");
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Test helper managing a temporary plugins directory, deleted when the test finishes.
|
||||
/// </summary>
|
||||
private sealed class TemporaryPluginDirectory : IDisposable
|
||||
{
|
||||
private bool _disposed;
|
||||
|
||||
public TemporaryPluginDirectory()
|
||||
{
|
||||
Path = System.IO.Path.Combine(System.IO.Path.GetTempPath(), $"lumina-plugin-loader-{Guid.NewGuid()}");
|
||||
Directory.CreateDirectory(Path);
|
||||
}
|
||||
|
||||
public string Path { get; }
|
||||
|
||||
public void CreateFile(string fileName, string content)
|
||||
{
|
||||
File.WriteAllText(System.IO.Path.Combine(Path, fileName), content);
|
||||
}
|
||||
|
||||
public void CopyDll(string sourceDllPath)
|
||||
{
|
||||
File.Copy(sourceDllPath, System.IO.Path.Combine(Path, System.IO.Path.GetFileName(sourceDllPath)));
|
||||
}
|
||||
|
||||
public void Dispose()
|
||||
{
|
||||
if (!_disposed)
|
||||
{
|
||||
try
|
||||
{
|
||||
Directory.Delete(Path, recursive: true);
|
||||
}
|
||||
catch (IOException)
|
||||
{
|
||||
// best effort cleanup of the temporary plugins directory
|
||||
}
|
||||
catch (UnauthorizedAccessException)
|
||||
{
|
||||
// the plugin assemblies are still locked by their load contexts, best effort cleanup only
|
||||
}
|
||||
_disposed = true;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,90 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Infrastructure.Core.Plugins;
|
||||
using Lumina.Plugins.Contracts.Core.Plugins;
|
||||
using NSubstitute;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Linq;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Infrastructure.UnitTests.Core.Plugins;
|
||||
|
||||
/// <summary>
|
||||
/// Contains unit tests for the <see cref="PluginManager"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class PluginManagerTests
|
||||
{
|
||||
[Fact]
|
||||
public void GetPlugins_WhenCalled_ShouldReturnAllLoadedPlugins()
|
||||
{
|
||||
// Arrange
|
||||
IPlugin firstPlugin = CreatePlugin(Guid.NewGuid(), "First Plugin");
|
||||
IPlugin secondPlugin = CreatePlugin(Guid.NewGuid(), "Second Plugin");
|
||||
PluginManager sut = new([firstPlugin, secondPlugin]);
|
||||
|
||||
// Act
|
||||
IReadOnlyList<IPlugin> result = sut.GetPlugins();
|
||||
|
||||
// Assert
|
||||
Assert.Equal(2, result.Count);
|
||||
Assert.Contains(firstPlugin, result);
|
||||
Assert.Contains(secondPlugin, result);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void GetPlugins_WhenNoPluginsWereLoaded_ShouldReturnEmptyList()
|
||||
{
|
||||
// Arrange
|
||||
PluginManager sut = new([]);
|
||||
|
||||
// Act
|
||||
IReadOnlyList<IPlugin> result = sut.GetPlugins();
|
||||
|
||||
// Assert
|
||||
Assert.Empty(result);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void GetPlugin_WhenPluginWithIdWasLoaded_ShouldReturnThePlugin()
|
||||
{
|
||||
// Arrange
|
||||
Guid pluginId = Guid.NewGuid();
|
||||
IPlugin expectedPlugin = CreatePlugin(pluginId, "Expected Plugin");
|
||||
PluginManager sut = new([expectedPlugin, CreatePlugin(Guid.NewGuid(), "Other Plugin")]);
|
||||
|
||||
// Act
|
||||
IPlugin? result = sut.GetPlugin(pluginId);
|
||||
|
||||
// Assert
|
||||
Assert.Same(expectedPlugin, result);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void GetPlugin_WhenPluginWithIdWasNotLoaded_ShouldReturnNull()
|
||||
{
|
||||
// Arrange
|
||||
PluginManager sut = new([CreatePlugin(Guid.NewGuid(), "Loaded Plugin")]);
|
||||
|
||||
// Act
|
||||
IPlugin? result = sut.GetPlugin(Guid.NewGuid());
|
||||
|
||||
// Assert
|
||||
Assert.Null(result);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Creates a mocked plugin with the provided identity.
|
||||
/// </summary>
|
||||
/// <param name="id">The Id of the plugin.</param>
|
||||
/// <param name="name">The name of the plugin.</param>
|
||||
/// <returns>The created plugin mock.</returns>
|
||||
private static IPlugin CreatePlugin(Guid id, string name)
|
||||
{
|
||||
IPlugin plugin = Substitute.For<IPlugin>();
|
||||
plugin.Id.Returns(id);
|
||||
plugin.Name.Returns(name);
|
||||
return plugin;
|
||||
}
|
||||
}
|
||||
+128
@@ -0,0 +1,128 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Application.Common.DataAccess.Entities.Plugins;
|
||||
using Lumina.Application.Common.DataAccess.Repositories.Plugins;
|
||||
using Lumina.Application.Common.DataAccess.UoW;
|
||||
using Lumina.Domain.Common.Primitives;
|
||||
using Lumina.Infrastructure.Core.Plugins;
|
||||
using Microsoft.Extensions.Logging;
|
||||
using NSubstitute;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Text.Json;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Infrastructure.UnitTests.Core.Plugins;
|
||||
|
||||
/// <summary>
|
||||
/// Contains unit tests for the <see cref="PluginSettingsStore"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class PluginSettingsStoreTests
|
||||
{
|
||||
private readonly IUnitOfWork _mockUnitOfWork;
|
||||
private readonly IPluginRepository _mockPluginRepository;
|
||||
private readonly ILogger<PluginSettingsStore> _mockLogger;
|
||||
private readonly PluginSettingsStore _sut;
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="PluginSettingsStoreTests"/> class.
|
||||
/// </summary>
|
||||
public PluginSettingsStoreTests()
|
||||
{
|
||||
_mockUnitOfWork = Substitute.For<IUnitOfWork>();
|
||||
_mockPluginRepository = Substitute.For<IPluginRepository>();
|
||||
_mockLogger = Substitute.For<ILogger<PluginSettingsStore>>();
|
||||
_mockUnitOfWork.PluginRepository.Returns(_mockPluginRepository);
|
||||
|
||||
_sut = new PluginSettingsStore(_mockUnitOfWork, _mockLogger);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetSettingsAsync_WhenPluginHasPersistedSettings_ShouldReturnDeserializedSettings()
|
||||
{
|
||||
// Arrange
|
||||
Guid pluginId = Guid.NewGuid();
|
||||
Dictionary<string, string> expectedSettings = new() { ["ApiKey"] = "test-key", ["Enabled"] = "true" };
|
||||
PluginEntity pluginEntity = CreatePluginEntity(pluginId, JsonSerializer.Serialize(expectedSettings));
|
||||
_mockPluginRepository.GetByIdAsync(pluginId, Arg.Any<CancellationToken>())
|
||||
.Returns(Result.From<PluginEntity?>(pluginEntity));
|
||||
|
||||
// Act
|
||||
IReadOnlyDictionary<string, string>? result = await _sut.GetSettingsAsync(pluginId, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.NotNull(result);
|
||||
Assert.Equal(expectedSettings, result);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetSettingsAsync_WhenPluginHasNoPersistedSettings_ShouldReturnNull()
|
||||
{
|
||||
// Arrange
|
||||
Guid pluginId = Guid.NewGuid();
|
||||
PluginEntity pluginEntity = CreatePluginEntity(pluginId, settingsJson: null);
|
||||
_mockPluginRepository.GetByIdAsync(pluginId, Arg.Any<CancellationToken>())
|
||||
.Returns(Result.From<PluginEntity?>(pluginEntity));
|
||||
|
||||
// Act
|
||||
IReadOnlyDictionary<string, string>? result = await _sut.GetSettingsAsync(pluginId, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.Null(result);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetSettingsAsync_WhenPluginDoesNotExist_ShouldReturnNull()
|
||||
{
|
||||
// Arrange
|
||||
Guid pluginId = Guid.NewGuid();
|
||||
_mockPluginRepository.GetByIdAsync(pluginId, Arg.Any<CancellationToken>())
|
||||
.Returns(Result.From<PluginEntity?>(null));
|
||||
|
||||
// Act
|
||||
IReadOnlyDictionary<string, string>? result = await _sut.GetSettingsAsync(pluginId, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.Null(result);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetSettingsAsync_WhenRepositoryReturnsFailure_ShouldReturnNullAndLogWarning()
|
||||
{
|
||||
// Arrange
|
||||
Guid pluginId = Guid.NewGuid();
|
||||
_mockPluginRepository.GetByIdAsync(pluginId, Arg.Any<CancellationToken>())
|
||||
.Returns(Error.Failure("Database.Error", "Failed to retrieve the plugin"));
|
||||
|
||||
// Act
|
||||
IReadOnlyDictionary<string, string>? result = await _sut.GetSettingsAsync(pluginId, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.Null(result);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Creates a plugin entity with the provided identity and serialized settings.
|
||||
/// </summary>
|
||||
/// <param name="id">The Id of the plugin.</param>
|
||||
/// <param name="settingsJson">The serialized settings of the plugin.</param>
|
||||
/// <returns>The created plugin entity.</returns>
|
||||
private static PluginEntity CreatePluginEntity(Guid id, string? settingsJson)
|
||||
{
|
||||
return new PluginEntity
|
||||
{
|
||||
Id = id,
|
||||
Name = "Test Plugin",
|
||||
Author = "Test Author",
|
||||
Version = "1.0.0",
|
||||
Description = "Test plugin description",
|
||||
SettingsJson = settingsJson,
|
||||
CreatedOnUtc = DateTime.UtcNow,
|
||||
CreatedBy = Guid.Empty,
|
||||
UpdatedBy = null
|
||||
};
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user