mirror of
https://github.com/BinaryAlley/Nemera.git
synced 2026-12-01 18:57:24 +00:00
Guards structured logging with IsEnabled checks
This commit is contained in:
1 parent
ccbd653ee5
commit
2e53449ada
44 files changed
+448
-136
No files matched your search
+23
@@ -43,6 +43,7 @@ public class TranscodingStartupInitializerTests : IDisposable
|
||||
_settings = _transcodingSettingsDtoFixture.Create(ffmpegPath: missingFfmpegPath, cacheDirectory: _cacheDirectory);
|
||||
_toolchainStatus = new TranscodingToolchainStatus();
|
||||
_mockLogger = Substitute.For<ILogger<TranscodingStartupInitializer>>();
|
||||
_mockLogger.IsEnabled(Arg.Any<LogLevel>()).Returns(true);
|
||||
_sut = new TranscodingStartupInitializer(Options.Create(_settings), _toolchainStatus, _mockLogger);
|
||||
}
|
||||
|
||||
@@ -102,6 +103,28 @@ public class TranscodingStartupInitializerTests : IDisposable
|
||||
Arg.Any<Func<object, Exception?, string>>());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task StartAsync_WhenLoggingIsDisabledAndTheDirectoryExistsNonEmptyWithoutTheMarker_ShouldNotLogAnError()
|
||||
{
|
||||
// Arrange
|
||||
_mockLogger.IsEnabled(Arg.Any<LogLevel>()).Returns(false);
|
||||
Directory.CreateDirectory(_cacheDirectory);
|
||||
File.WriteAllText(Path.Combine(_cacheDirectory, "operator-data.txt"), "operator data");
|
||||
|
||||
// Act
|
||||
await _sut.StartAsync(CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.False(TranscodingCachePaths.HasCacheMarker(_cacheDirectory));
|
||||
Assert.False(_toolchainStatus.IsTranscoderAvailable);
|
||||
_mockLogger.DidNotReceive().Log(
|
||||
LogLevel.Error,
|
||||
Arg.Any<EventId>(),
|
||||
Arg.Any<object>(),
|
||||
Arg.Any<Exception?>(),
|
||||
Arg.Any<Func<object, Exception?, string>>());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task StartAsync_WhenTheDirectoryIsMarked_ShouldRemoveOnlyTheEntriesOfTheCacheNamespace()
|
||||
{
|
||||
|
||||
+8
@@ -15,6 +15,7 @@ using Microsoft.Extensions.Logging;
|
||||
using NSubstitute;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Diagnostics;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
@@ -106,6 +107,7 @@ public class BooksMediaLibraryItemDeletionStrategyTests
|
||||
public async Task DeleteItemAsync_WhenDeleteArtworkFails_ShouldStillDeleteTheBook()
|
||||
{
|
||||
// Arrange
|
||||
_mockLogger.IsEnabled(Arg.Any<LogLevel>()).Returns(true);
|
||||
LibraryId libraryId = _libraryIdFixture.Create();
|
||||
BookEntity book = _bookEntityFixture.Create(path: "/books/deleted.epub");
|
||||
LibraryEntity library = _libraryEntityFixture.Create(id: libraryId.Value, title: "My Library");
|
||||
@@ -129,6 +131,12 @@ public class BooksMediaLibraryItemDeletionStrategyTests
|
||||
Assert.True(result.IsSuccess);
|
||||
await _mockBookRepository.Received(1).DeleteByIdAsync(book.Id, Arg.Any<CancellationToken>());
|
||||
await _mockUnitOfWork.Received(1).SaveChangesAsync(Arg.Any<CancellationToken>());
|
||||
_mockLogger.Received(1).Log(
|
||||
LogLevel.Warning,
|
||||
Arg.Any<EventId>(),
|
||||
Arg.Is<object>(state => state.ToString()!.Contains("Failed to delete the stored artwork of the book")),
|
||||
Arg.Any<Exception?>(),
|
||||
Arg.Any<Func<object, Exception?, string>>());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
|
||||
+49
@@ -52,6 +52,7 @@ public class MusicMediaLibraryItemDeletionStrategyTests
|
||||
_mockMusicArtworkRepository = Substitute.For<IMusicArtworkRepository>();
|
||||
_mockMusicArtworkService = Substitute.For<IMusicArtworkService>();
|
||||
_mockLogger = Substitute.For<ILogger<MusicMediaLibraryItemDeletionStrategy>>();
|
||||
_mockLogger.IsEnabled(Arg.Any<LogLevel>()).Returns(true);
|
||||
_mockUnitOfWork.TrackRepository.Returns(_mockTrackRepository);
|
||||
_mockUnitOfWork.AlbumRepository.Returns(_mockAlbumRepository);
|
||||
_mockUnitOfWork.ArtistRepository.Returns(_mockArtistRepository);
|
||||
@@ -293,6 +294,54 @@ public class MusicMediaLibraryItemDeletionStrategyTests
|
||||
Arg.Any<Func<object, Exception?, string>>());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task DeleteItemAsync_WhenLoggingIsDisabledAndDeletingAStoredArtworkFileFails_ShouldNotLogAWarningButStillDeleteTheRow()
|
||||
{
|
||||
// Arrange
|
||||
_mockLogger.IsEnabled(Arg.Any<LogLevel>()).Returns(false);
|
||||
LibraryId libraryId = _libraryIdFixture.Create();
|
||||
Guid albumId = Guid.NewGuid();
|
||||
Guid artistId = Guid.NewGuid();
|
||||
TrackEntity track = _trackEntityFixture.Create(albumId: albumId, path: "/music/deleted.flac");
|
||||
AlbumEntity album = _albumEntityFixture.Create(id: albumId, artistId: artistId, includeTracks: false);
|
||||
AlbumEntity otherAlbum = _albumEntityFixture.Create(artistId: artistId, includeTracks: false);
|
||||
MusicArtworkEntity trackArtwork = _musicArtworkEntityFixture.Create(ownerType: MusicArtworkOwnerType.Track, ownerId: track.Id, fileName: "/media/music/track-cover.jpg");
|
||||
_mockTrackRepository.GetByPathAsync(libraryId.Value, track.Path, Arg.Any<CancellationToken>())
|
||||
.Returns(Result.From<TrackEntity?>(track));
|
||||
_mockMusicArtworkRepository.GetByOwnerAsync(MusicArtworkOwnerType.Track, track.Id, Arg.Any<CancellationToken>())
|
||||
.Returns(Result.From<IReadOnlyList<MusicArtworkEntity>>([trackArtwork]));
|
||||
_mockMusicArtworkService.DeleteStoredArtwork(trackArtwork.FileName!)
|
||||
.Returns(Errors.FileSystemManagement.FileNotFound);
|
||||
_mockMusicArtworkRepository.DeleteByOwnerAsync(MusicArtworkOwnerType.Track, track.Id, Arg.Any<CancellationToken>())
|
||||
.Returns(Result.Deleted);
|
||||
_mockTrackRepository.DeleteByIdAsync(track.Id, Arg.Any<CancellationToken>())
|
||||
.Returns(Result.From(Result.Deleted));
|
||||
_mockAlbumRepository.GetIncludingDeletedByIdAsync(albumId, Arg.Any<CancellationToken>())
|
||||
.Returns(Result.From<AlbumEntity?>(album));
|
||||
_mockTrackRepository.GetByAlbumIdIncludingDeletedAsync(albumId, Arg.Any<CancellationToken>())
|
||||
.Returns(Result.From<IReadOnlyList<TrackEntity>>([track]));
|
||||
_mockMusicArtworkRepository.DeleteByOwnerAsync(MusicArtworkOwnerType.Album, albumId, Arg.Any<CancellationToken>())
|
||||
.Returns(Result.Deleted);
|
||||
_mockAlbumRepository.DeleteByIdAsync(albumId, Arg.Any<CancellationToken>())
|
||||
.Returns(Result.From(Result.Deleted));
|
||||
_mockAlbumRepository.GetByArtistIdIncludingDeletedAsync(artistId, Arg.Any<CancellationToken>())
|
||||
.Returns(Result.From<IReadOnlyList<AlbumEntity>>([otherAlbum]));
|
||||
_mockUnitOfWork.SaveChangesAsync(Arg.Any<CancellationToken>()).Returns(Result.Success);
|
||||
|
||||
// Act
|
||||
Result<Success> result = await _sut.DeleteItemAsync(libraryId.Value, track.Path, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.True(result.IsSuccess);
|
||||
await _mockMusicArtworkRepository.Received(1).DeleteByOwnerAsync(MusicArtworkOwnerType.Track, track.Id, Arg.Any<CancellationToken>());
|
||||
_mockLogger.DidNotReceive().Log(
|
||||
LogLevel.Warning,
|
||||
Arg.Any<EventId>(),
|
||||
Arg.Any<object>(),
|
||||
Arg.Any<Exception?>(),
|
||||
Arg.Any<Func<object, Exception?, string>>());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task DeleteItemAsync_WhenAlbumWasAlreadyRemoved_ShouldPersistTheTrackDeletion()
|
||||
{
|
||||
|
||||
+1
@@ -113,6 +113,7 @@ public class PublicHostValidationHandlerTests
|
||||
{
|
||||
// Arrange
|
||||
ILogger<PublicHostValidationHandler> mockLogger = Substitute.For<ILogger<PublicHostValidationHandler>>();
|
||||
mockLogger.IsEnabled(Arg.Any<LogLevel>()).Returns(true);
|
||||
StubHttpMessageHandler innerHandler = new();
|
||||
PublicHostValidationHandler handler = new(CreateValidator(), mockLogger) { InnerHandler = innerHandler };
|
||||
using HttpClient client = new(handler);
|
||||
|
||||
+8
@@ -23,6 +23,7 @@ using Microsoft.Extensions.Logging;
|
||||
using NSubstitute;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Diagnostics;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Linq;
|
||||
using System.Reflection;
|
||||
@@ -120,6 +121,7 @@ public class PluginDetectionSyncJobTests
|
||||
public async Task StartAsync_WhenUpsertFails_ShouldLogErrorAndContinueWithOtherPlugins()
|
||||
{
|
||||
// Arrange
|
||||
_mockLogger.IsEnabled(Arg.Any<LogLevel>()).Returns(true);
|
||||
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]);
|
||||
@@ -139,6 +141,12 @@ public class PluginDetectionSyncJobTests
|
||||
// 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>());
|
||||
_mockLogger.Received(1).Log(
|
||||
LogLevel.Error,
|
||||
Arg.Any<EventId>(),
|
||||
Arg.Is<object>(state => state.ToString()!.Contains("Failed to persist the detection of plugin")),
|
||||
Arg.Any<Exception?>(),
|
||||
Arg.Any<Func<object, Exception?, string>>());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
|
||||
+8
@@ -9,6 +9,7 @@ using Microsoft.Extensions.Logging;
|
||||
using NSubstitute;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Diagnostics;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Text.Json;
|
||||
using System.Threading;
|
||||
@@ -96,6 +97,7 @@ public class PluginSettingsStoreTests
|
||||
public async Task GetSettingsAsync_WhenRepositoryReturnsFailure_ShouldReturnNullAndLogWarning()
|
||||
{
|
||||
// Arrange
|
||||
_mockLogger.IsEnabled(Arg.Any<LogLevel>()).Returns(true);
|
||||
Guid pluginId = Guid.NewGuid();
|
||||
_mockPluginRepository.GetByIdAsync(pluginId, cancellationToken: Arg.Any<CancellationToken>())
|
||||
.Returns(Error.Failure("Database.Error", "Failed to retrieve the plugin"));
|
||||
@@ -105,5 +107,11 @@ public class PluginSettingsStoreTests
|
||||
|
||||
// Assert
|
||||
Assert.Null(result);
|
||||
_mockLogger.Received(1).Log(
|
||||
LogLevel.Warning,
|
||||
Arg.Any<EventId>(),
|
||||
Arg.Is<object>(state => state.ToString()!.Contains("Failed to read the settings of the plugin")),
|
||||
Arg.Any<Exception?>(),
|
||||
Arg.Any<Func<object, Exception?, string>>());
|
||||
}
|
||||
}
|
||||
+18
-2
@@ -25,6 +25,7 @@ using Microsoft.Extensions.Logging;
|
||||
using NSubstitute;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Diagnostics;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Linq;
|
||||
using System.Reflection;
|
||||
@@ -49,6 +50,7 @@ public class ScheduledJobSchedulerJobTests
|
||||
private readonly IDomainEventPublisher _mockDomainEventPublisher;
|
||||
private readonly IScheduledTaskExecutorFactory _mockTaskExecutorFactory;
|
||||
private readonly IScheduledTaskExecutor _mockTaskExecutor;
|
||||
private readonly ILogger<ScheduledJobSchedulerJob> _mockLogger;
|
||||
private readonly ScheduledJobRuntimeRegistry _runtimeRegistry;
|
||||
private readonly ScheduledJobSchedulerJob _sut;
|
||||
private readonly Dictionary<Type, object> _services;
|
||||
@@ -95,8 +97,8 @@ public class ScheduledJobSchedulerJobTests
|
||||
.Returns(callInfo => _services.TryGetValue((Type)callInfo[0]!, out object? service) ? service : null);
|
||||
|
||||
_runtimeRegistry = new ScheduledJobRuntimeRegistry();
|
||||
ILogger<ScheduledJobSchedulerJob> logger = Substitute.For<ILogger<ScheduledJobSchedulerJob>>();
|
||||
_sut = new ScheduledJobSchedulerJob(_runtimeRegistry, logger, _mockServiceScopeFactory);
|
||||
_mockLogger = Substitute.For<ILogger<ScheduledJobSchedulerJob>>();
|
||||
_sut = new ScheduledJobSchedulerJob(_runtimeRegistry, _mockLogger, _mockServiceScopeFactory);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
@@ -555,6 +557,7 @@ public class ScheduledJobSchedulerJobTests
|
||||
public async Task ExecuteScheduledJobRunAsync_WhenTheTaskPayloadFails_ShouldLogTheFailureAndStillCompleteTheExecution()
|
||||
{
|
||||
// Arrange
|
||||
_mockLogger.IsEnabled(Arg.Any<LogLevel>()).Returns(true);
|
||||
ScheduledJobEntity addedJob = _scheduledJobEntityFixture.Create(status: ScheduledJobStatus.Added, scheduleType: ScheduleType.WithIntervalInMinutes, intervalMinutes: 60);
|
||||
ScheduledJobId scheduledJobId = _scheduledJobIdFixture.Create(addedJob.Id);
|
||||
_mockScheduledJobRepository.GetByIdAsync(Arg.Any<Guid>(), cancellationToken: Arg.Any<CancellationToken>()).Returns(addedJob);
|
||||
@@ -568,12 +571,19 @@ public class ScheduledJobSchedulerJobTests
|
||||
// Assert
|
||||
await _mockTaskExecutor.Received(1).ExecutePayloadAsync(Arg.Any<ScheduledJob>(), Arg.Any<CancellationToken>());
|
||||
await _mockDomainEventPublisher.Received(1).PublishAsync(Arg.Is<ScheduledJobExecutionCompletedDomainEvent>(domainEvent => !domainEvent.IsCycleRun), Arg.Any<CancellationToken>());
|
||||
_mockLogger.Received(1).Log(
|
||||
LogLevel.Warning,
|
||||
Arg.Any<EventId>(),
|
||||
Arg.Is<object>(state => state.ToString()!.Contains("failed:")),
|
||||
Arg.Any<Exception?>(),
|
||||
Arg.Any<Func<object, Exception?, string>>());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteScheduledJobRunAsync_WhenTheTaskPayloadThrows_ShouldLogTheExceptionAndStillCompleteTheExecution()
|
||||
{
|
||||
// Arrange
|
||||
_mockLogger.IsEnabled(Arg.Any<LogLevel>()).Returns(true);
|
||||
ScheduledJobEntity addedJob = _scheduledJobEntityFixture.Create(status: ScheduledJobStatus.Added, scheduleType: ScheduleType.WithIntervalInMinutes, intervalMinutes: 60);
|
||||
ScheduledJobId scheduledJobId = _scheduledJobIdFixture.Create(addedJob.Id);
|
||||
_mockScheduledJobRepository.GetByIdAsync(Arg.Any<Guid>(), cancellationToken: Arg.Any<CancellationToken>()).Returns(addedJob);
|
||||
@@ -586,6 +596,12 @@ public class ScheduledJobSchedulerJobTests
|
||||
|
||||
// Assert
|
||||
await _mockDomainEventPublisher.Received(1).PublishAsync(Arg.Is<ScheduledJobExecutionCompletedDomainEvent>(domainEvent => !domainEvent.IsCycleRun), Arg.Any<CancellationToken>());
|
||||
_mockLogger.Received(1).Log(
|
||||
LogLevel.Error,
|
||||
Arg.Any<EventId>(),
|
||||
Arg.Any<object>(),
|
||||
Arg.Is<Exception>(exception => exception is InvalidOperationException && exception.Message == "The task threw."),
|
||||
Arg.Any<Func<object, Exception?, string>>());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
|
||||
@@ -52,6 +52,7 @@ public class ThemeSynchronizerTests : IDisposable
|
||||
_mockUnitOfWork.ThemeRepository.Returns(_mockThemeRepository);
|
||||
_mockUnitOfWork.SaveChangesAsync(Arg.Any<CancellationToken>()).Returns(Result.Success);
|
||||
_mockLogger = Substitute.For<ILogger>();
|
||||
_mockLogger.IsEnabled(Arg.Any<LogLevel>()).Returns(true);
|
||||
_mockThemeService.GetBundledThemeArchivePaths().Returns([]);
|
||||
_mockThemeService.HasThemePack(Arg.Any<string>()).Returns(true);
|
||||
_mockThemeService.DefaultThemeId.Returns("lumina-default");
|
||||
@@ -79,6 +80,28 @@ public class ThemeSynchronizerTests : IDisposable
|
||||
await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any<CancellationToken>());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task SynchronizeAsync_WhenLoggingIsDisabledAndTheInstalledThemesCannotBeRead_ShouldNotLogAWarning()
|
||||
{
|
||||
// Arrange
|
||||
_mockLogger.IsEnabled(Arg.Any<LogLevel>()).Returns(false);
|
||||
_mockThemeRepository.GetAllAsync<BaseFilterDto>(cancellationToken: Arg.Any<CancellationToken>())
|
||||
.Returns(Error.Failure("Themes.NotFound", "Failed to read the installed themes"));
|
||||
_mockThemeService.GetBundledThemeArchivePaths().Returns(["bundled.zip"]);
|
||||
|
||||
// Act
|
||||
await ThemeSynchronizer.SynchronizeAsync(_mockThemeService, _mockUnitOfWork, _mockLogger, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any<CancellationToken>());
|
||||
_mockLogger.DidNotReceive().Log(
|
||||
LogLevel.Warning,
|
||||
Arg.Any<EventId>(),
|
||||
Arg.Any<object>(),
|
||||
Arg.Any<Exception?>(),
|
||||
Arg.Any<Func<object, Exception?, string>>());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task SynchronizeAsync_WhenABundledArchiveManifestCannotBeRead_ShouldSkipThatArchive()
|
||||
{
|
||||
@@ -235,6 +258,12 @@ public class ThemeSynchronizerTests : IDisposable
|
||||
// Assert
|
||||
await _mockThemeRepository.Received(1).InsertAsync(Arg.Any<ThemeEntity>(), Arg.Any<CancellationToken>());
|
||||
await _mockUnitOfWork.Received(1).SaveChangesAsync(Arg.Any<CancellationToken>());
|
||||
_mockLogger.Received(1).Log(
|
||||
LogLevel.Warning,
|
||||
Arg.Any<EventId>(),
|
||||
Arg.Is<object>(state => state.ToString()!.Contains("Failed to persist the detection of theme")),
|
||||
Arg.Any<Exception?>(),
|
||||
Arg.Any<Func<object, Exception?, string>>());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
|
||||
+8
@@ -14,6 +14,7 @@ using Microsoft.Extensions.Logging;
|
||||
using NSubstitute;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Diagnostics;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.IO;
|
||||
using System.Linq;
|
||||
@@ -154,6 +155,7 @@ public class EventualConsistencyMiddlewareTests
|
||||
httpContext.Request.Path = "/api/v1/probe";
|
||||
httpContext.Response.StatusCode = StatusCodes.Status200OK;
|
||||
ILogger<EventualConsistencyMiddleware> mockLogger = Substitute.For<ILogger<EventualConsistencyMiddleware>>();
|
||||
mockLogger.IsEnabled(Arg.Any<LogLevel>()).Returns(true);
|
||||
EventualConsistencyMiddleware sut = new(_ => Task.CompletedTask, mockLogger);
|
||||
IUnitOfWork mockUnitOfWork = Substitute.For<IUnitOfWork>();
|
||||
mockUnitOfWork
|
||||
@@ -170,6 +172,12 @@ public class EventualConsistencyMiddlewareTests
|
||||
// The completion callback must never leave a transaction open after a failed commit, and it must never publish events that belong to a transaction that did not commit.
|
||||
await mockUnitOfWork.Received(1).RollbackTransactionAsync(Arg.Any<CancellationToken>());
|
||||
await mockPublisher.DidNotReceive().PublishAsync(Arg.Any<IDomainEvent>(), Arg.Any<CancellationToken>());
|
||||
mockLogger.Received(1).Log(
|
||||
LogLevel.Error,
|
||||
Arg.Any<EventId>(),
|
||||
Arg.Any<object>(),
|
||||
Arg.Is<Exception>(exception => exception is InvalidOperationException && exception.Message == "commit failed"),
|
||||
Arg.Any<Func<object, Exception?, string>>());
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
|
||||
+25
@@ -33,6 +33,7 @@ public class ExceptionHandlingMiddlewareTests
|
||||
public ExceptionHandlingMiddlewareTests()
|
||||
{
|
||||
_mockLogger = Substitute.For<ILogger<ExceptionHandlingMiddleware>>();
|
||||
_mockLogger.IsEnabled(Arg.Any<LogLevel>()).Returns(true);
|
||||
_sut = new ExceptionHandlingMiddleware(context => _nextDelegate(context), _mockLogger);
|
||||
}
|
||||
|
||||
@@ -87,6 +88,30 @@ public class ExceptionHandlingMiddlewareTests
|
||||
Arg.Any<Func<object, Exception?, string>>());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task InvokeAsync_WhenLoggingIsDisabledAndNextThrowsException_ShouldNotLogTheException()
|
||||
{
|
||||
// Arrange
|
||||
_mockLogger.IsEnabled(Arg.Any<LogLevel>()).Returns(false);
|
||||
DefaultHttpContext context = new()
|
||||
{
|
||||
Response = { Body = new MemoryStream() }
|
||||
};
|
||||
_nextDelegate = _ => throw new InvalidOperationException("sensitive internal details");
|
||||
|
||||
// Act
|
||||
await _sut.InvokeAsync(context);
|
||||
|
||||
// Assert
|
||||
Assert.Equal(StatusCodes.Status500InternalServerError, context.Response.StatusCode);
|
||||
_mockLogger.DidNotReceive().Log(
|
||||
LogLevel.Error,
|
||||
Arg.Any<EventId>(),
|
||||
Arg.Any<object>(),
|
||||
Arg.Any<Exception?>(),
|
||||
Arg.Any<Func<object, Exception?, string>>());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task InvokeAsync_WhenNextThrowsExceptionAndActivityIsCurrent_ShouldUseTheActivityIdAsTraceId()
|
||||
{
|
||||
|
||||
+22
@@ -41,6 +41,7 @@ public class ExceptionHandlingMiddlewareTests
|
||||
public ExceptionHandlingMiddlewareTests()
|
||||
{
|
||||
_mockLogger = Substitute.For<ILogger<ExceptionHandlingMiddleware>>();
|
||||
_mockLogger.IsEnabled(Arg.Any<LogLevel>()).Returns(true);
|
||||
_mockStringLocalizer = Substitute.For<IStringLocalizer<ExceptionHandlingMiddleware>>();
|
||||
_mockStringLocalizer[Arg.Any<string>()].Returns(callInfo => new LocalizedString(callInfo.Arg<string>(), $"localized:{callInfo.Arg<string>()}"));
|
||||
_mockAuthenticationService = Substitute.For<IAuthenticationService>();
|
||||
@@ -91,6 +92,27 @@ public class ExceptionHandlingMiddlewareTests
|
||||
Arg.Any<Func<object, Exception?, string>>());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task InvokeAsync_WhenLoggingIsDisabledAndNextThrowsNonApiExceptionAndApiRequest_ShouldNotLogError()
|
||||
{
|
||||
// Arrange
|
||||
_mockLogger.IsEnabled(Arg.Any<LogLevel>()).Returns(false);
|
||||
DefaultHttpContext httpContext = CreateHttpContext(isApiRequest: true);
|
||||
_nextDelegate = _ => throw new InvalidOperationException("Unexpected failure");
|
||||
|
||||
// Act
|
||||
await _sut.InvokeAsync(httpContext);
|
||||
|
||||
// Assert
|
||||
Assert.Contains("application/json", httpContext.Response.ContentType);
|
||||
_mockLogger.DidNotReceive().Log(
|
||||
LogLevel.Error,
|
||||
Arg.Any<EventId>(),
|
||||
Arg.Any<object>(),
|
||||
Arg.Any<Exception?>(),
|
||||
Arg.Any<Func<object, Exception?, string>>());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task InvokeAsync_WhenNextThrowsNonApiExceptionAndPageRequest_ShouldWriteHtmlErrorPage()
|
||||
{
|
||||
|
||||
Reference in new issue
Block a user