diff --git a/src/Nemera.Infrastructure/Core/Themes/ThemeSynchronizer.cs b/src/Nemera.Infrastructure/Core/Themes/ThemeSynchronizer.cs
index dc309bea..7ce1e692 100644
--- a/src/Nemera.Infrastructure/Core/Themes/ThemeSynchronizer.cs
+++ b/src/Nemera.Infrastructure/Core/Themes/ThemeSynchronizer.cs
@@ -1,4 +1,5 @@
#region ========================================================================= USING =====================================================================================
+using Microsoft.Extensions.Logging;
using Nemera.Application.Common.DataAccess.Entities.Themes;
using Nemera.Application.Common.DataAccess.UoW;
using Nemera.Application.Common.DTO.Filtering;
@@ -7,7 +8,6 @@ using Nemera.Application.Common.Infrastructure.Models.DTO.Themes;
using Nemera.Application.Common.Infrastructure.Themes;
using Nemera.Domain.Common.Primitives;
using Nemera.Domain.SharedKernel.Common.Enums.Themes;
-using Microsoft.Extensions.Logging;
using System;
using System.Collections.Generic;
using System.IO;
@@ -32,6 +32,8 @@ internal static class ThemeSynchronizer
/// Cancellation token that can be used to stop the execution.
internal static async Task SynchronizeAsync(IThemeService themeService, IUnitOfWork unitOfWork, ILogger logger, CancellationToken cancellationToken)
{
+ // The installed themes are read tracked, so the current flag that EnsureCurrentThemeExists sets on an existing theme is
+ // persisted by the final SaveChangesAsync; a theme inserted during this synchronization is tracked as added by InsertAsync.
Result> getThemesResult = await unitOfWork.ThemeRepository.GetAllAsync(cancellationToken: cancellationToken).ConfigureAwait(false);
if (getThemesResult.IsFailure)
{
@@ -127,7 +129,7 @@ internal static class ThemeSynchronizer
}
await CleanUpMissingThemePacksAsync(themeService, unitOfWork, themes, logger, cancellationToken).ConfigureAwait(false);
- await EnsureCurrentThemeExistsAsync(themeService, unitOfWork, themes, logger, cancellationToken).ConfigureAwait(false);
+ EnsureCurrentThemeExists(themeService, themes);
Result saveChangesResult = await unitOfWork.SaveChangesAsync(cancellationToken).ConfigureAwait(false);
if (saveChangesResult.IsFailure)
@@ -208,14 +210,11 @@ internal static class ThemeSynchronizer
}
///
- /// Activates the configured default theme when no theme is currently active, so the application always has an active theme.
+ /// Marks the configured default theme as current when no theme is currently active, so the application always has an active theme.
///
/// Injected service for the server-side storage and serving of theme packs.
- /// The unit of work for interacting with the theme repository.
/// The installed themes read from the storage medium.
- /// Injected logger used for logging.
- /// Cancellation token that can be used to stop the execution.
- private static async Task EnsureCurrentThemeExistsAsync(IThemeService themeService, IUnitOfWork unitOfWork, IReadOnlyList themes, ILogger logger, CancellationToken cancellationToken)
+ internal static void EnsureCurrentThemeExists(IThemeService themeService, IReadOnlyList themes)
{
if (themes.Any(theme => !theme.IsDeleted && theme.IsCurrent == true))
return;
@@ -231,10 +230,9 @@ internal static class ThemeSynchronizer
if (defaultTheme is null)
return;
+ // A theme inserted during this synchronization is not in the database yet, so an UpdateAsync call would fail with ThemeNotFound.
+ // The entity is already tracked, as added by InsertAsync or as an existing row from the tracked read, so setting the flag here
+ // is persisted by the SaveChangesAsync that follows the synchronization.
defaultTheme.IsCurrent = true;
- Result updateResult = await unitOfWork.ThemeRepository.UpdateAsync(defaultTheme, cancellationToken).ConfigureAwait(false);
- if (updateResult.IsFailure)
- if (logger.IsEnabled(LogLevel.Warning))
- logger.LogWarning("Failed to activate theme '{ThemeId}': {Error}", defaultTheme.ThemeId, updateResult.FirstError.Description);
}
}
diff --git a/tests/IntegrationTests/Nemera.Infrastructure.IntegrationTests/Core/Themes/ThemeSynchronizerTests.cs b/tests/IntegrationTests/Nemera.Infrastructure.IntegrationTests/Core/Themes/ThemeSynchronizerTests.cs
new file mode 100644
index 00000000..1d31c292
--- /dev/null
+++ b/tests/IntegrationTests/Nemera.Infrastructure.IntegrationTests/Core/Themes/ThemeSynchronizerTests.cs
@@ -0,0 +1,92 @@
+#region ========================================================================= USING =====================================================================================
+using Microsoft.EntityFrameworkCore;
+using Microsoft.Extensions.Logging;
+using Nemera.Application.Common.DataAccess.Entities.Themes;
+using Nemera.Application.Common.Infrastructure.Models.DTO.Themes;
+using Nemera.Application.Common.Infrastructure.Themes;
+using Nemera.Application.Common.Infrastructure.Time;
+using Nemera.Application.Fixtures.Common.Infrastructure.Models.DTO.Themes;
+using Nemera.DataAccess.Core.UoW;
+using Nemera.Domain.Common.Primitives;
+using Nemera.Infrastructure.Core.Themes;
+using NSubstitute;
+using System;
+using System.Diagnostics.CodeAnalysis;
+using System.IO;
+using System.Threading;
+using System.Threading.Tasks;
+#endregion
+
+namespace Nemera.Infrastructure.IntegrationTests.Core.Themes;
+
+///
+/// Contains integration tests for the class.
+///
+[ExcludeFromCodeCoverage]
+public class ThemeSynchronizerTests : IDisposable
+{
+ private readonly DbContextOptions _dbContextOptions;
+ private readonly NemeraDbContext _dbContext;
+ private readonly UnitOfWork _unitOfWork;
+ private readonly IThemeService _mockThemeService;
+ private readonly ILogger _mockLogger;
+ private readonly ThemeManifestDtoFixture _themeManifestDtoFixture = new();
+ private readonly string _archivePath;
+
+ ///
+ /// Initializes a new instance of the class.
+ ///
+ public ThemeSynchronizerTests()
+ {
+ _dbContextOptions = new DbContextOptionsBuilder()
+ .UseInMemoryDatabase(databaseName: Guid.NewGuid().ToString())
+ .Options;
+ _dbContext = new NemeraDbContext(_dbContextOptions);
+ _unitOfWork = new UnitOfWork(_dbContext, Substitute.For());
+ _mockThemeService = Substitute.For();
+ _mockLogger = Substitute.For();
+ _mockLogger.IsEnabled(Arg.Any()).Returns(true);
+ _archivePath = Path.Combine(Path.GetTempPath(), $"nemera-theme-sync-{Guid.NewGuid():N}.zip");
+ }
+
+ [Fact]
+ public async Task SynchronizeAsync_WhenANewBundledThemeIsInstalled_ShouldPersistTheActivatedTheme()
+ {
+ // Arrange
+ ThemeManifestDto manifest = _themeManifestDtoFixture.Create();
+ File.WriteAllText(_archivePath, "theme-pack");
+ _mockThemeService.GetBundledThemeArchivePaths().Returns([_archivePath]);
+ _mockThemeService.ReadManifestFromArchiveAsync(_archivePath, Arg.Any()).Returns(Result.From(manifest));
+ _mockThemeService.InstallAsync(Arg.Any(), Arg.Any()).Returns(Result.From(manifest));
+ _mockThemeService.HasThemePack(Arg.Any()).Returns(true);
+ _mockThemeService.DefaultThemeId.Returns(manifest.Id);
+
+ // Act
+ await ThemeSynchronizer.SynchronizeAsync(_mockThemeService, _unitOfWork, _mockLogger, CancellationToken.None);
+
+ // Assert
+ // Activating an inserted theme must not attempt an update, which the repository would report as a failed activation warning.
+ _mockLogger.DidNotReceive().Log(
+ LogLevel.Warning,
+ Arg.Any(),
+ Arg.Any(),
+ Arg.Any(),
+ Arg.Any>());
+ // Read through a fresh context so the assertion proves SaveChanges wrote the activation, not only that the entity was tracked.
+ using (NemeraDbContext verificationContext = new(_dbContextOptions))
+ {
+ ThemeEntity persistedTheme = Assert.Single(verificationContext.Themes);
+ Assert.True(persistedTheme.IsCurrent);
+ }
+ }
+
+ ///
+ /// Releases the database context and removes the temporary archive file.
+ ///
+ public void Dispose()
+ {
+ _dbContext.Dispose();
+ if (File.Exists(_archivePath))
+ File.Delete(_archivePath);
+ }
+}
diff --git a/tests/IntegrationTests/Nemera.Infrastructure.IntegrationTests/Nemera.Infrastructure.IntegrationTests.csproj b/tests/IntegrationTests/Nemera.Infrastructure.IntegrationTests/Nemera.Infrastructure.IntegrationTests.csproj
index 6e411380..fe742b39 100644
--- a/tests/IntegrationTests/Nemera.Infrastructure.IntegrationTests/Nemera.Infrastructure.IntegrationTests.csproj
+++ b/tests/IntegrationTests/Nemera.Infrastructure.IntegrationTests/Nemera.Infrastructure.IntegrationTests.csproj
@@ -24,6 +24,7 @@
runtime; build; native; contentfiles; analyzers; buildtransitive
+
@@ -40,6 +41,7 @@
+
diff --git a/tests/UnitTests/Nemera.Infrastructure.UnitTests/Core/Themes/ThemeSynchronizerTests.cs b/tests/UnitTests/Nemera.Infrastructure.UnitTests/Core/Themes/ThemeSynchronizerTests.cs
index 0cbf129b..ed622d8d 100644
--- a/tests/UnitTests/Nemera.Infrastructure.UnitTests/Core/Themes/ThemeSynchronizerTests.cs
+++ b/tests/UnitTests/Nemera.Infrastructure.UnitTests/Core/Themes/ThemeSynchronizerTests.cs
@@ -1,9 +1,9 @@
#region ========================================================================= USING =====================================================================================
+using Microsoft.Extensions.Logging;
using Nemera.Application.Common.DataAccess.Entities.Themes;
using Nemera.Application.Common.DataAccess.Repositories.Themes;
using Nemera.Application.Common.DataAccess.UoW;
using Nemera.Application.Common.DTO.Filtering;
-using Nemera.Application.Common.DTO.Pagination;
using Nemera.Application.Common.Infrastructure.Models.DTO.Themes;
using Nemera.Application.Common.Infrastructure.Themes;
using Nemera.Application.Fixtures.Common.DataAccess.Entities.Themes;
@@ -12,14 +12,10 @@ using Nemera.Application.Fixtures.Common.Infrastructure.Models.DTO.Themes;
using Nemera.Domain.Common.Primitives;
using Nemera.Domain.SharedKernel.Common.Enums.Themes;
using Nemera.Infrastructure.Core.Themes;
-using Microsoft.Extensions.Logging;
using NSubstitute;
using System;
-using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.IO;
-using System.Linq;
-using System.Reflection;
using System.Threading;
using System.Threading.Tasks;
#endregion
@@ -56,7 +52,7 @@ public class ThemeSynchronizerTests : IDisposable
_mockThemeService.GetBundledThemeArchivePaths().Returns([]);
_mockThemeService.HasThemePack(Arg.Any()).Returns(true);
_mockThemeService.DefaultThemeId.Returns("nemera-default");
- _mockThemeRepository.GetAllAsync(cancellationToken: Arg.Any()).Returns(Result.From(_paginatedResultDtoFixture.Create(data: [], currentPage: 1, perPage: 0, count: 0, numberOfPages: 1)));
+ _mockThemeRepository.GetAllAsync(shouldTrackEntities: true, cancellationToken: Arg.Any()).Returns(Result.From(_paginatedResultDtoFixture.Create(data: [], currentPage: 1, perPage: 0, count: 0, numberOfPages: 1)));
_mockThemeRepository.InsertAsync(Arg.Any(), Arg.Any()).Returns(Result.Created);
_mockThemeRepository.UpdateAsync(Arg.Any(), Arg.Any()).Returns(Result.Updated);
_mockThemeRepository.DeleteByIdAsync(Arg.Any(), Arg.Any()).Returns(Result.Deleted);
@@ -68,7 +64,7 @@ public class ThemeSynchronizerTests : IDisposable
public async Task SynchronizeAsync_WhenTheInstalledThemesCannotBeRead_ShouldLogAndReturn()
{
// Arrange
- _mockThemeRepository.GetAllAsync(cancellationToken: Arg.Any())
+ _mockThemeRepository.GetAllAsync(shouldTrackEntities: true, cancellationToken: Arg.Any())
.Returns(Error.Failure("Themes.NotFound", "Failed to read the installed themes"));
_mockThemeService.GetBundledThemeArchivePaths().Returns(["bundled.zip"]);
@@ -85,7 +81,7 @@ public class ThemeSynchronizerTests : IDisposable
{
// Arrange
_mockLogger.IsEnabled(Arg.Any()).Returns(false);
- _mockThemeRepository.GetAllAsync(cancellationToken: Arg.Any())
+ _mockThemeRepository.GetAllAsync(shouldTrackEntities: true, cancellationToken: Arg.Any())
.Returns(Error.Failure("Themes.NotFound", "Failed to read the installed themes"));
_mockThemeService.GetBundledThemeArchivePaths().Returns(["bundled.zip"]);
@@ -124,7 +120,7 @@ public class ThemeSynchronizerTests : IDisposable
// Arrange
ThemeManifestDto manifest = _themeManifestDtoFixture.Create(version: "1.2.3");
ThemeEntity installedTheme = _themeEntityFixture.Create(themeId: manifest.Id, version: "1.2.3", installSource: ThemeInstallSource.Bundled, isDeleted: false, includeIsCurrent: true, isCurrent: true);
- _mockThemeRepository.GetAllAsync(cancellationToken: Arg.Any()).Returns(Result.From(_paginatedResultDtoFixture.Create(data: [installedTheme], currentPage: 1, perPage: 1, count: 1, numberOfPages: 1)));
+ _mockThemeRepository.GetAllAsync(shouldTrackEntities: true, cancellationToken: Arg.Any()).Returns(Result.From(_paginatedResultDtoFixture.Create(data: [installedTheme], currentPage: 1, perPage: 1, count: 1, numberOfPages: 1)));
_mockThemeService.GetBundledThemeArchivePaths().Returns(["bundled.zip"]);
_mockThemeService.ReadManifestFromArchiveAsync("bundled.zip", Arg.Any()).Returns(Result.From(manifest));
@@ -143,7 +139,7 @@ public class ThemeSynchronizerTests : IDisposable
// Arrange
ThemeManifestDto manifest = _themeManifestDtoFixture.Create(version: "2.0.0");
ThemeEntity installedTheme = _themeEntityFixture.Create(themeId: manifest.Id, version: "1.0.0", installSource: ThemeInstallSource.Bundled, isDeleted: false, includeIsCurrent: true, isCurrent: true);
- _mockThemeRepository.GetAllAsync(cancellationToken: Arg.Any()).Returns(Result.From(_paginatedResultDtoFixture.Create(data: [installedTheme], currentPage: 1, perPage: 1, count: 1, numberOfPages: 1)));
+ _mockThemeRepository.GetAllAsync(shouldTrackEntities: true, cancellationToken: Arg.Any()).Returns(Result.From(_paginatedResultDtoFixture.Create(data: [installedTheme], currentPage: 1, perPage: 1, count: 1, numberOfPages: 1)));
string archivePath = CreateArchiveFile();
_mockThemeService.GetBundledThemeArchivePaths().Returns([archivePath]);
_mockThemeService.ReadManifestFromArchiveAsync(archivePath, Arg.Any()).Returns(Result.From(manifest));
@@ -164,7 +160,7 @@ public class ThemeSynchronizerTests : IDisposable
// Arrange
ThemeManifestDto manifest = _themeManifestDtoFixture.Create();
ThemeEntity deletedTheme = _themeEntityFixture.Create(themeId: manifest.Id, installSource: ThemeInstallSource.Bundled, isDeleted: true);
- _mockThemeRepository.GetAllAsync(cancellationToken: Arg.Any()).Returns(Result.From(_paginatedResultDtoFixture.Create(data: [deletedTheme], currentPage: 1, perPage: 1, count: 1, numberOfPages: 1)));
+ _mockThemeRepository.GetAllAsync(shouldTrackEntities: true, cancellationToken: Arg.Any()).Returns(Result.From(_paginatedResultDtoFixture.Create(data: [deletedTheme], currentPage: 1, perPage: 1, count: 1, numberOfPages: 1)));
_mockThemeService.GetBundledThemeArchivePaths().Returns(["bundled.zip"]);
_mockThemeService.ReadManifestFromArchiveAsync("bundled.zip", Arg.Any()).Returns(Result.From(manifest));
@@ -182,7 +178,7 @@ public class ThemeSynchronizerTests : IDisposable
// Arrange
ThemeManifestDto manifest = _themeManifestDtoFixture.Create();
ThemeEntity damagedTheme = _themeEntityFixture.Create(themeId: manifest.Id, installSource: ThemeInstallSource.Bundled, isDeleted: false, includeIsCurrent: true, isCurrent: true);
- _mockThemeRepository.GetAllAsync(cancellationToken: Arg.Any()).Returns(Result.From(_paginatedResultDtoFixture.Create(data: [damagedTheme], currentPage: 1, perPage: 1, count: 1, numberOfPages: 1)));
+ _mockThemeRepository.GetAllAsync(shouldTrackEntities: true, cancellationToken: Arg.Any()).Returns(Result.From(_paginatedResultDtoFixture.Create(data: [damagedTheme], currentPage: 1, perPage: 1, count: 1, numberOfPages: 1)));
string archivePath = CreateArchiveFile();
_mockThemeService.GetBundledThemeArchivePaths().Returns([archivePath]);
// The first pack check happens before the repair and reports the files as missing; the later checks report the files as present.
@@ -204,7 +200,7 @@ public class ThemeSynchronizerTests : IDisposable
// Arrange
ThemeManifestDto manifest = _themeManifestDtoFixture.Create();
ThemeEntity damagedTheme = _themeEntityFixture.Create(themeId: manifest.Id, installSource: ThemeInstallSource.Bundled, isDeleted: false, includeIsCurrent: true, isCurrent: true);
- _mockThemeRepository.GetAllAsync(cancellationToken: Arg.Any()).Returns(Result.From(_paginatedResultDtoFixture.Create(data: [damagedTheme], currentPage: 1, perPage: 1, count: 1, numberOfPages: 1)));
+ _mockThemeRepository.GetAllAsync(shouldTrackEntities: true, cancellationToken: Arg.Any()).Returns(Result.From(_paginatedResultDtoFixture.Create(data: [damagedTheme], currentPage: 1, perPage: 1, count: 1, numberOfPages: 1)));
string archivePath = CreateArchiveFile();
_mockThemeService.GetBundledThemeArchivePaths().Returns([archivePath]);
_mockThemeService.HasThemePack(damagedTheme.ThemeId).Returns(false, true);
@@ -309,7 +305,7 @@ public class ThemeSynchronizerTests : IDisposable
{
// Arrange
ThemeEntity healthyTheme = _themeEntityFixture.Create(installSource: ThemeInstallSource.Bundled, isDeleted: false, includeIsCurrent: true, isCurrent: true);
- _mockThemeRepository.GetAllAsync(cancellationToken: Arg.Any()).Returns(Result.From(_paginatedResultDtoFixture.Create(data: [healthyTheme], currentPage: 1, perPage: 1, count: 1, numberOfPages: 1)));
+ _mockThemeRepository.GetAllAsync(shouldTrackEntities: true, cancellationToken: Arg.Any()).Returns(Result.From(_paginatedResultDtoFixture.Create(data: [healthyTheme], currentPage: 1, perPage: 1, count: 1, numberOfPages: 1)));
// Act
await ThemeSynchronizer.SynchronizeAsync(_mockThemeService, _mockUnitOfWork, _mockLogger, CancellationToken.None);
@@ -324,7 +320,7 @@ public class ThemeSynchronizerTests : IDisposable
{
// Arrange
ThemeEntity brokenTheme = _themeEntityFixture.Create(installSource: ThemeInstallSource.Bundled, isDeleted: false, includeIsCurrent: true, isCurrent: true);
- _mockThemeRepository.GetAllAsync(cancellationToken: Arg.Any()).Returns(Result.From(_paginatedResultDtoFixture.Create(data: [brokenTheme], currentPage: 1, perPage: 1, count: 1, numberOfPages: 1)));
+ _mockThemeRepository.GetAllAsync(shouldTrackEntities: true, cancellationToken: Arg.Any()).Returns(Result.From(_paginatedResultDtoFixture.Create(data: [brokenTheme], currentPage: 1, perPage: 1, count: 1, numberOfPages: 1)));
_mockThemeService.HasThemePack(brokenTheme.ThemeId).Returns(false);
_mockThemeService.RestoreBundledThemeAsync(brokenTheme.ThemeId, Arg.Any()).Returns(Result.Success);
@@ -342,7 +338,7 @@ public class ThemeSynchronizerTests : IDisposable
{
// Arrange
ThemeEntity lastBundledTheme = _themeEntityFixture.Create(installSource: ThemeInstallSource.Bundled, isDeleted: false, includeIsCurrent: true, isCurrent: true);
- _mockThemeRepository.GetAllAsync(cancellationToken: Arg.Any()).Returns(Result.From(_paginatedResultDtoFixture.Create(data: [lastBundledTheme], currentPage: 1, perPage: 1, count: 1, numberOfPages: 1)));
+ _mockThemeRepository.GetAllAsync(shouldTrackEntities: true, cancellationToken: Arg.Any()).Returns(Result.From(_paginatedResultDtoFixture.Create(data: [lastBundledTheme], currentPage: 1, perPage: 1, count: 1, numberOfPages: 1)));
_mockThemeService.HasThemePack(lastBundledTheme.ThemeId).Returns(false);
_mockThemeService.RestoreBundledThemeAsync(lastBundledTheme.ThemeId, Arg.Any())
.Returns(Error.Failure("Theme.Restore", "Failed to restore the theme"));
@@ -361,7 +357,7 @@ public class ThemeSynchronizerTests : IDisposable
// Arrange
ThemeEntity brokenBundledTheme = _themeEntityFixture.Create(installSource: ThemeInstallSource.Bundled, isDeleted: false);
ThemeEntity healthyBundledTheme = _themeEntityFixture.Create(installSource: ThemeInstallSource.Bundled, isDeleted: false, includeIsCurrent: true, isCurrent: true);
- _mockThemeRepository.GetAllAsync(cancellationToken: Arg.Any()).Returns(Result.From(_paginatedResultDtoFixture.Create(data: [brokenBundledTheme, healthyBundledTheme], currentPage: 1, perPage: 2, count: 2, numberOfPages: 1)));
+ _mockThemeRepository.GetAllAsync(shouldTrackEntities: true, cancellationToken: Arg.Any()).Returns(Result.From(_paginatedResultDtoFixture.Create(data: [brokenBundledTheme, healthyBundledTheme], currentPage: 1, perPage: 2, count: 2, numberOfPages: 1)));
_mockThemeService.HasThemePack(brokenBundledTheme.ThemeId).Returns(false);
_mockThemeService.RestoreBundledThemeAsync(brokenBundledTheme.ThemeId, Arg.Any())
.Returns(Error.Failure("Theme.Restore", "Failed to restore the theme"));
@@ -381,7 +377,7 @@ public class ThemeSynchronizerTests : IDisposable
// Arrange
ThemeEntity brokenBundledTheme = _themeEntityFixture.Create(installSource: ThemeInstallSource.Bundled, isDeleted: false);
ThemeEntity healthyBundledTheme = _themeEntityFixture.Create(installSource: ThemeInstallSource.Bundled, isDeleted: false, includeIsCurrent: true, isCurrent: true);
- _mockThemeRepository.GetAllAsync(cancellationToken: Arg.Any()).Returns(Result.From(_paginatedResultDtoFixture.Create(data: [brokenBundledTheme, healthyBundledTheme], currentPage: 1, perPage: 2, count: 2, numberOfPages: 1)));
+ _mockThemeRepository.GetAllAsync(shouldTrackEntities: true, cancellationToken: Arg.Any()).Returns(Result.From(_paginatedResultDtoFixture.Create(data: [brokenBundledTheme, healthyBundledTheme], currentPage: 1, perPage: 2, count: 2, numberOfPages: 1)));
_mockThemeService.HasThemePack(brokenBundledTheme.ThemeId).Returns(false);
_mockThemeService.RestoreBundledThemeAsync(brokenBundledTheme.ThemeId, Arg.Any())
.Returns(Error.Failure("Theme.Restore", "Failed to restore the theme"));
@@ -401,7 +397,7 @@ public class ThemeSynchronizerTests : IDisposable
{
// Arrange
ThemeEntity brokenUserTheme = _themeEntityFixture.Create(installSource: ThemeInstallSource.Uploaded, isDeleted: false, includeIsCurrent: true, isCurrent: true);
- _mockThemeRepository.GetAllAsync(cancellationToken: Arg.Any()).Returns(Result.From(_paginatedResultDtoFixture.Create(data: [brokenUserTheme], currentPage: 1, perPage: 1, count: 1, numberOfPages: 1)));
+ _mockThemeRepository.GetAllAsync(shouldTrackEntities: true, cancellationToken: Arg.Any()).Returns(Result.From(_paginatedResultDtoFixture.Create(data: [brokenUserTheme], currentPage: 1, perPage: 1, count: 1, numberOfPages: 1)));
_mockThemeService.HasThemePack(brokenUserTheme.ThemeId).Returns(false);
// Act
@@ -416,7 +412,7 @@ public class ThemeSynchronizerTests : IDisposable
{
// Arrange
ThemeEntity brokenUserTheme = _themeEntityFixture.Create(installSource: ThemeInstallSource.Uploaded, isDeleted: false, includeIsCurrent: true, isCurrent: true);
- _mockThemeRepository.GetAllAsync(cancellationToken: Arg.Any()).Returns(Result.From(_paginatedResultDtoFixture.Create(data: [brokenUserTheme], currentPage: 1, perPage: 1, count: 1, numberOfPages: 1)));
+ _mockThemeRepository.GetAllAsync(shouldTrackEntities: true, cancellationToken: Arg.Any()).Returns(Result.From(_paginatedResultDtoFixture.Create(data: [brokenUserTheme], currentPage: 1, perPage: 1, count: 1, numberOfPages: 1)));
_mockThemeService.HasThemePack(brokenUserTheme.ThemeId).Returns(false);
_mockThemeRepository.DeleteByIdAsync(Arg.Any(), Arg.Any())
.Returns(Error.Failure("Themes.DeleteFailed", "Failed to delete the theme"));
@@ -435,7 +431,7 @@ public class ThemeSynchronizerTests : IDisposable
// Arrange
ThemeEntity throwingBundledTheme = _themeEntityFixture.Create(installSource: ThemeInstallSource.Bundled, isDeleted: false);
ThemeEntity healthyBundledTheme = _themeEntityFixture.Create(installSource: ThemeInstallSource.Bundled, isDeleted: false, includeIsCurrent: true, isCurrent: true);
- _mockThemeRepository.GetAllAsync(cancellationToken: Arg.Any()).Returns(Result.From(_paginatedResultDtoFixture.Create(data: [throwingBundledTheme, healthyBundledTheme], currentPage: 1, perPage: 2, count: 2, numberOfPages: 1)));
+ _mockThemeRepository.GetAllAsync(shouldTrackEntities: true, cancellationToken: Arg.Any()).Returns(Result.From(_paginatedResultDtoFixture.Create(data: [throwingBundledTheme, healthyBundledTheme], currentPage: 1, perPage: 2, count: 2, numberOfPages: 1)));
_mockThemeService.HasThemePack(Arg.Any()).Returns(false);
_mockThemeService.RestoreBundledThemeAsync(throwingBundledTheme.ThemeId, Arg.Any())
.Returns(Task.FromException>(new InvalidOperationException("Unexpected failure")));
@@ -456,7 +452,7 @@ public class ThemeSynchronizerTests : IDisposable
{
// Arrange
ThemeEntity brokenBundledTheme = _themeEntityFixture.Create(installSource: ThemeInstallSource.Bundled, isDeleted: false);
- _mockThemeRepository.GetAllAsync(cancellationToken: Arg.Any()).Returns(Result.From(_paginatedResultDtoFixture.Create(data: [brokenBundledTheme], currentPage: 1, perPage: 1, count: 1, numberOfPages: 1)));
+ _mockThemeRepository.GetAllAsync(shouldTrackEntities: true, cancellationToken: Arg.Any()).Returns(Result.From(_paginatedResultDtoFixture.Create(data: [brokenBundledTheme], currentPage: 1, perPage: 1, count: 1, numberOfPages: 1)));
_mockThemeService.HasThemePack(brokenBundledTheme.ThemeId).Returns(false);
_mockThemeService.RestoreBundledThemeAsync(brokenBundledTheme.ThemeId, Arg.Any())
.Returns(Task.FromException>(new OperationCanceledException()));
@@ -489,7 +485,7 @@ public class ThemeSynchronizerTests : IDisposable
updatedBy: Guid.NewGuid());
DateTime? initialUpdatedOnUtc = installedTheme.UpdatedOnUtc;
Guid? initialUpdatedBy = installedTheme.UpdatedBy;
- _mockThemeRepository.GetAllAsync(cancellationToken: Arg.Any()).Returns(Result.From(_paginatedResultDtoFixture.Create(data: [installedTheme], currentPage: 1, perPage: 1, count: 1, numberOfPages: 1)));
+ _mockThemeRepository.GetAllAsync(shouldTrackEntities: true, cancellationToken: Arg.Any()).Returns(Result.From(_paginatedResultDtoFixture.Create(data: [installedTheme], currentPage: 1, perPage: 1, count: 1, numberOfPages: 1)));
string archivePath = CreateArchiveFile();
_mockThemeService.GetBundledThemeArchivePaths().Returns([archivePath]);
_mockThemeService.HasThemePack(installedTheme.ThemeId).Returns(true);
@@ -515,7 +511,7 @@ public class ThemeSynchronizerTests : IDisposable
// Arrange
ThemeManifestDto manifest = _themeManifestDtoFixture.Create(version: "3.0.0");
ThemeEntity installedTheme = _themeEntityFixture.Create(themeId: manifest.Id, version: "1.0.0", installSource: ThemeInstallSource.Bundled, isDeleted: false, includeIsCurrent: true, isCurrent: true);
- _mockThemeRepository.GetAllAsync(cancellationToken: Arg.Any()).Returns(Result.From(_paginatedResultDtoFixture.Create(data: [installedTheme], currentPage: 1, perPage: 1, count: 1, numberOfPages: 1)));
+ _mockThemeRepository.GetAllAsync(shouldTrackEntities: true, cancellationToken: Arg.Any()).Returns(Result.From(_paginatedResultDtoFixture.Create(data: [installedTheme], currentPage: 1, perPage: 1, count: 1, numberOfPages: 1)));
string archivePath = CreateArchiveFile();
_mockThemeService.GetBundledThemeArchivePaths().Returns([archivePath]);
_mockThemeService.HasThemePack(installedTheme.ThemeId).Returns(true);
@@ -544,7 +540,7 @@ public class ThemeSynchronizerTests : IDisposable
// Arrange
ThemeManifestDto manifest = _themeManifestDtoFixture.Create(version: "2.0.0");
ThemeEntity uploadedTheme = _themeEntityFixture.Create(themeId: manifest.Id, version: "1.0.0", installSource: ThemeInstallSource.Uploaded, isDeleted: false, includeIsCurrent: true, isCurrent: true);
- _mockThemeRepository.GetAllAsync(cancellationToken: Arg.Any()).Returns(Result.From(_paginatedResultDtoFixture.Create(data: [uploadedTheme], currentPage: 1, perPage: 1, count: 1, numberOfPages: 1)));
+ _mockThemeRepository.GetAllAsync(shouldTrackEntities: true, cancellationToken: Arg.Any()).Returns(Result.From(_paginatedResultDtoFixture.Create(data: [uploadedTheme], currentPage: 1, perPage: 1, count: 1, numberOfPages: 1)));
_mockThemeService.GetBundledThemeArchivePaths().Returns(["bundled.zip"]);
_mockThemeService.HasThemePack(uploadedTheme.ThemeId).Returns(true);
_mockThemeService.ReadManifestFromArchiveAsync("bundled.zip", Arg.Any()).Returns(Result.From(manifest));
@@ -564,7 +560,7 @@ public class ThemeSynchronizerTests : IDisposable
// Arrange
ThemeManifestDto manifest = _themeManifestDtoFixture.Create(version: "1.5.0");
ThemeEntity installedTheme = _themeEntityFixture.Create(themeId: manifest.Id, version: "1.5.0", installSource: ThemeInstallSource.Bundled, isDeleted: false, includeIsCurrent: true, isCurrent: true);
- _mockThemeRepository.GetAllAsync(cancellationToken: Arg.Any()).Returns(Result.From(_paginatedResultDtoFixture.Create(data: [installedTheme], currentPage: 1, perPage: 1, count: 1, numberOfPages: 1)));
+ _mockThemeRepository.GetAllAsync(shouldTrackEntities: true, cancellationToken: Arg.Any()).Returns(Result.From(_paginatedResultDtoFixture.Create(data: [installedTheme], currentPage: 1, perPage: 1, count: 1, numberOfPages: 1)));
string archivePath = CreateArchiveFile();
_mockThemeService.GetBundledThemeArchivePaths().Returns([archivePath]);
_mockThemeService.HasThemePack(installedTheme.ThemeId).Returns(true);
@@ -580,37 +576,35 @@ public class ThemeSynchronizerTests : IDisposable
}
[Fact]
- public async Task EnsureCurrentThemeExistsAsync_WhenANonDeletedThemeIsCurrent_ShouldNotSelectAnotherTheme()
+ public void EnsureCurrentThemeExists_WhenANonDeletedThemeIsCurrent_ShouldNotSelectAnotherTheme()
{
// Arrange
ThemeEntity currentTheme = _themeEntityFixture.Create(installSource: ThemeInstallSource.Bundled, isDeleted: false, includeIsCurrent: true, isCurrent: true);
ThemeEntity otherTheme = _themeEntityFixture.Create(installSource: ThemeInstallSource.Uploaded, isDeleted: false);
// Act
- await InvokeEnsureCurrentThemeExistsAsync([currentTheme, otherTheme]);
+ ThemeSynchronizer.EnsureCurrentThemeExists(_mockThemeService, [currentTheme, otherTheme]);
// Assert
Assert.True(currentTheme.IsCurrent);
Assert.NotEqual(true, otherTheme.IsCurrent);
- await _mockThemeRepository.DidNotReceive().UpdateAsync(Arg.Any(), Arg.Any());
}
[Fact]
- public async Task EnsureCurrentThemeExistsAsync_WhenNoThemeCanBeSelected_ShouldNotSelectAnyTheme()
+ public void EnsureCurrentThemeExists_WhenNoThemeCanBeSelected_ShouldNotSelectAnyTheme()
{
// Arrange
ThemeEntity deletedTheme = _themeEntityFixture.Create(installSource: ThemeInstallSource.Bundled, isDeleted: true);
// Act
- await InvokeEnsureCurrentThemeExistsAsync([deletedTheme]);
+ ThemeSynchronizer.EnsureCurrentThemeExists(_mockThemeService, [deletedTheme]);
// Assert
Assert.NotEqual(true, deletedTheme.IsCurrent);
- await _mockThemeRepository.DidNotReceive().UpdateAsync(Arg.Any(), Arg.Any());
}
[Fact]
- public async Task EnsureCurrentThemeExistsAsync_WhenNoThemeIsCurrent_ShouldActivateTheDefaultTheme()
+ public void EnsureCurrentThemeExists_WhenNoThemeIsCurrent_ShouldActivateTheDefaultTheme()
{
// Arrange
ThemeEntity defaultTheme = _themeEntityFixture.Create(themeId: "nemera-default", installSource: ThemeInstallSource.Bundled, isDeleted: false);
@@ -619,35 +613,33 @@ public class ThemeSynchronizerTests : IDisposable
_mockThemeService.HasThemePack(userTheme.ThemeId).Returns(false);
// Act
- await InvokeEnsureCurrentThemeExistsAsync([userTheme, defaultTheme]);
+ ThemeSynchronizer.EnsureCurrentThemeExists(_mockThemeService, [userTheme, defaultTheme]);
// Assert
Assert.True(defaultTheme.IsCurrent);
- await _mockThemeRepository.Received(1).UpdateAsync(Arg.Is(theme => theme.Id == defaultTheme.Id), Arg.Any());
}
[Fact]
- public async Task EnsureCurrentThemeExistsAsync_WhenActivatingTheDefaultThemeFails_ShouldLogAndNotThrow()
+ public async Task SynchronizeAsync_WhenANewBundledThemeIsInstalled_ShouldMarkTheInsertedThemeCurrentWithoutUpdatingIt()
{
// Arrange
- ThemeEntity defaultTheme = _themeEntityFixture.Create(themeId: "nemera-default", installSource: ThemeInstallSource.Bundled, isDeleted: false);
- _mockThemeService.HasThemePack(defaultTheme.ThemeId).Returns(true);
- _mockThemeRepository.UpdateAsync(Arg.Any(), Arg.Any())
- .Returns(Error.Failure("Themes.UpdateFailed", "Failed to activate the theme"));
+ ThemeManifestDto manifest = _themeManifestDtoFixture.Create();
+ string archivePath = CreateArchiveFile();
+ _mockThemeService.GetBundledThemeArchivePaths().Returns([archivePath]);
+ _mockThemeService.ReadManifestFromArchiveAsync(archivePath, Arg.Any()).Returns(Result.From(manifest));
+ _mockThemeService.InstallAsync(Arg.Any(), Arg.Any()).Returns(Result.From(manifest));
+ ThemeEntity? insertedTheme = null;
+ _mockThemeRepository.InsertAsync(Arg.Do(theme => insertedTheme = theme), Arg.Any()).Returns(Result.Created);
// Act
- await InvokeEnsureCurrentThemeExistsAsync([defaultTheme]);
+ await ThemeSynchronizer.SynchronizeAsync(_mockThemeService, _mockUnitOfWork, _mockLogger, CancellationToken.None);
// Assert
- Assert.True(defaultTheme.IsCurrent);
- await _mockThemeRepository.Received(1).UpdateAsync(Arg.Is(theme => theme.Id == defaultTheme.Id), Arg.Any());
- // A failed activation must not be silent, so it is logged instead of being discarded.
- _mockLogger.Received(1).Log(
- LogLevel.Warning,
- Arg.Any(),
- Arg.Any(),
- Arg.Any(),
- Arg.Any>());
+ Assert.NotNull(insertedTheme);
+ Assert.True(insertedTheme!.IsCurrent);
+ // A theme inserted in this synchronization is not in the database yet, so UpdateAsync would fail with ThemeNotFound.
+ await _mockThemeRepository.DidNotReceive().UpdateAsync(Arg.Any(), Arg.Any());
+ await _mockUnitOfWork.Received(1).SaveChangesAsync(Arg.Any());
}
///
@@ -661,19 +653,6 @@ public class ThemeSynchronizerTests : IDisposable
return archivePath;
}
- ///
- /// Invokes the private EnsureCurrentThemeExistsAsync method of the synchronizer.
- ///
- /// The installed themes passed to the method.
- /// A task that represents the asynchronous operation.
- private async Task InvokeEnsureCurrentThemeExistsAsync(IReadOnlyList themes)
- {
- MethodInfo method = typeof(ThemeSynchronizer).GetMethod("EnsureCurrentThemeExistsAsync", BindingFlags.Static | BindingFlags.NonPublic)
- ?? throw new InvalidOperationException("The method 'EnsureCurrentThemeExistsAsync' was not found on the theme synchronizer.");
- Task task = (Task)method.Invoke(null, [_mockThemeService, _mockUnitOfWork, themes, _mockLogger, CancellationToken.None])!;
- await task.ConfigureAwait(false);
- }
-
///
/// Removes the temporary files created by the tests.
///