| | | 1 | | using Microsoft.Extensions.Logging; |
| | | 2 | | using Microsoft.Extensions.Logging.Testing; |
| | | 3 | | using TUnit.Assertions.Core; |
| | | 4 | | |
| | | 5 | | namespace TestUtilities.FakeLoggerAssertions; |
| | | 6 | | |
| | | 7 | | /// <summary> |
| | | 8 | | /// Asserts that a FakeLogger does NOT contain a log entry at the specified level with the specified content. |
| | | 9 | | /// </summary> |
| | | 10 | | public class FakeLoggerDoesNotContainAssertion<T> : Assertion<FakeLogger<T>> |
| | | 11 | | { |
| | | 12 | | private readonly LogLevel _logLevel; |
| | | 13 | | private readonly string _messageContent; |
| | | 14 | | |
| | | 15 | | public FakeLoggerDoesNotContainAssertion(AssertionContext<FakeLogger<T>> context, LogLevel logLevel, string messageC |
| | 1 | 16 | | : base(context) |
| | | 17 | | { |
| | 1 | 18 | | _logLevel = logLevel; |
| | 1 | 19 | | _messageContent = messageContent; |
| | 1 | 20 | | } |
| | | 21 | | |
| | | 22 | | protected override Task<AssertionResult> CheckAsync(EvaluationMetadata<FakeLogger<T>> metadata) |
| | | 23 | | { |
| | 1 | 24 | | var actualValue = metadata.Value; |
| | | 25 | | |
| | 1 | 26 | | if (actualValue is null) |
| | | 27 | | { |
| | 0 | 28 | | return Task.FromResult(AssertionResult.Failed("logger was null")); |
| | | 29 | | } |
| | | 30 | | |
| | 1 | 31 | | var logs = actualValue.Collector.GetSnapshot(); |
| | 1 | 32 | | var matchingLogs = logs.Where(l => l.Level == _logLevel && l.Message.Contains(_messageContent)).ToList(); |
| | | 33 | | |
| | 1 | 34 | | if (!matchingLogs.Any()) |
| | | 35 | | { |
| | 1 | 36 | | return Task.FromResult(AssertionResult.Passed); |
| | | 37 | | } |
| | | 38 | | |
| | 1 | 39 | | return Task.FromResult(AssertionResult.Failed( |
| | 1 | 40 | | $"{matchingLogs.Count} matching log(s) were found")); |
| | | 41 | | } |
| | | 42 | | |
| | | 43 | | protected override string GetExpectation() |
| | 1 | 44 | | => $"to NOT contain a log at level {_logLevel} with message containing \"{_messageContent}\""; |
| | | 45 | | } |