This commit is contained in:
Janus C. H. Knudsen 2025-03-07 00:17:08 +01:00
parent 0010a32248
commit ddb6abc14e
14 changed files with 754 additions and 718 deletions

View file

@ -1,3 +1,4 @@
using System.Net;
using Autofac;
using Microsoft.ApplicationInsights;
using Microsoft.ApplicationInsights.Channel;
@ -5,67 +6,66 @@ using Microsoft.ApplicationInsights.DataContracts;
using PlanTempus.Core.Logging;
using PlanTempus.Core.Telemetry;
namespace PlanTempus.Tests.Logging
namespace PlanTempus.X.TDD.Logging;
[TestClass]
public class SeqBackgroundServiceTest : TestFixture
{
[TestClass]
public class SeqBackgroundServiceTest : TestFixture
private CancellationTokenSource _cts;
private IMessageChannel<ITelemetry> _messageChannel;
private SeqBackgroundService _service;
[TestInitialize]
public void SetupThis()
{
private IMessageChannel<ITelemetry> _messageChannel;
private SeqBackgroundService _service;
private CancellationTokenSource _cts;
_messageChannel = new MessageChannel();
var telemetryClient = Container.Resolve<TelemetryClient>();
[TestInitialize]
public void SetupThis()
var config = new SeqConfiguration("http://localhost:5341", null, "MSTEST");
var httpClient = new SeqHttpClient(config);
var logger = new SeqLogger<SeqBackgroundService>(httpClient, config);
_service = new SeqBackgroundService(telemetryClient, _messageChannel, logger);
_cts = new CancellationTokenSource();
}
[TestMethod]
public async Task Messages_ShouldBeProcessedFromQueue()
{
await _service.StartAsync(_cts.Token);
for (var i = 0; i < 5; i++)
{
_messageChannel = new MessageChannel();
var telemetryClient = Container.Resolve<TelemetryClient>();
var eventTelemetry = new EventTelemetry
{
Name = "Test Event",
Timestamp = DateTimeOffset.UtcNow
};
eventTelemetry.Properties.Add("TestId", Guid.NewGuid().ToString());
eventTelemetry.Metrics.Add("TestMetric", 42.0);
var config = new SeqConfiguration("http://localhost:5341", null, "MSTEST");
var httpClient = new SeqHttpClient(config);
var logger = new SeqLogger<SeqBackgroundService>(httpClient, config);
_service = new SeqBackgroundService(telemetryClient, _messageChannel, logger);
_cts = new CancellationTokenSource();
await _messageChannel.Writer.WriteAsync(eventTelemetry);
}
[TestMethod]
public async Task Messages_ShouldBeProcessedFromQueue()
// wait for processing
await Task.Delay(5000);
_cts.Cancel(); //not sure about this, we need to analyse more before this is "the way"
await _service.StopAsync(CancellationToken.None);
var hasMoreMessages = await _messageChannel.Reader.WaitToReadAsync();
Assert.IsFalse(hasMoreMessages, "Queue should be empty after 5 seconds");
}
private class TestMessageHandler : HttpMessageHandler
{
protected override Task<HttpResponseMessage> SendAsync(
HttpRequestMessage request,
CancellationToken cancellationToken)
{
await _service.StartAsync(_cts.Token);
for (int i = 0; i < 5; i++)
{
var eventTelemetry = new EventTelemetry
{
Name = "Test Event",
Timestamp = DateTimeOffset.UtcNow
};
eventTelemetry.Properties.Add("TestId", Guid.NewGuid().ToString());
eventTelemetry.Metrics.Add("TestMetric", 42.0);
await _messageChannel.Writer.WriteAsync(eventTelemetry);
}
// wait for processing
await Task.Delay(5000);
_cts.Cancel(); //not sure about this, we need to analyse more before this is "the way"
await _service.StopAsync(CancellationToken.None);
bool hasMoreMessages = await _messageChannel.Reader.WaitToReadAsync();
Assert.IsFalse(hasMoreMessages, "Queue should be empty after 5 seconds");
}
private class TestMessageHandler : HttpMessageHandler
{
protected override Task<HttpResponseMessage> SendAsync(
HttpRequestMessage request,
CancellationToken cancellationToken)
{
return Task.FromResult(new HttpResponseMessage(System.Net.HttpStatusCode.OK));
}
return Task.FromResult(new HttpResponseMessage(HttpStatusCode.OK));
}
}
}

View file

@ -3,146 +3,143 @@ using Microsoft.ApplicationInsights;
using Microsoft.ApplicationInsights.DataContracts;
using PlanTempus.Core.Logging;
namespace PlanTempus.Tests.Logging
namespace PlanTempus.X.TDD.Logging;
[TestClass]
public class SeqLoggerTests : TestFixture
{
[TestClass]
public class SeqLoggerTests : TestFixture
private readonly string _testId;
private readonly SeqHttpClient _httpClient;
private readonly SeqLogger<SeqLoggerTests> _logger;
public SeqLoggerTests()
{
private SeqLogger<SeqLoggerTests> _logger;
private SeqHttpClient _httpClient;
private readonly string _testId;
_testId = Guid.NewGuid().ToString();
var config = new SeqConfiguration("http://localhost:5341", null, "MSTEST");
_httpClient = new SeqHttpClient(config);
_logger = new SeqLogger<SeqLoggerTests>(_httpClient, config);
}
public SeqLoggerTests()
[TestMethod]
public async Task LogTraceTelemetry_SendsCorrectDataWithErrorLevel()
{
// Arrange
var traceTelemetry = new TraceTelemetry
{
_testId = Guid.NewGuid().ToString();
var config = new SeqConfiguration("http://localhost:5341", null, "MSTEST");
_httpClient = new SeqHttpClient(config);
_logger = new SeqLogger<SeqLoggerTests>(_httpClient, config);
}
Message = "Test trace error message",
SeverityLevel = SeverityLevel.Error,
Timestamp = DateTimeOffset.UtcNow
};
traceTelemetry.Properties.Add("TestId", _testId);
[TestMethod]
public async Task LogTraceTelemetry_SendsCorrectDataWithErrorLevel()
// Act
await _logger.LogAsync(traceTelemetry);
}
[TestMethod]
public async Task LogTraceTelemetry_SendsCorrectDataWithWarningLevel()
{
// Arrange
var traceTelemetry = new TraceTelemetry
{
Message = "Test trace warning message",
SeverityLevel = SeverityLevel.Warning,
Timestamp = DateTimeOffset.UtcNow
};
traceTelemetry.Properties.Add("TestId", _testId);
// Act
await _logger.LogAsync(traceTelemetry);
}
[TestMethod]
public async Task LogEventTelemetry_SendsCorrectData()
{
// Arrange
var eventTelemetry = new EventTelemetry
{
Name = "Test Event",
Timestamp = DateTimeOffset.UtcNow
};
eventTelemetry.Properties.Add("TestId", _testId);
eventTelemetry.Metrics.Add("TestMetric", 42.0);
// Act
await _logger.LogAsync(eventTelemetry);
}
[TestMethod]
public async Task LogExceptionTelemetry_SendsCorrectData()
{
try
{
var t = 0;
var result = 10 / t;
}
catch (Exception e)
{
// Arrange
var traceTelemetry = new TraceTelemetry
var exceptionTelemetry = new ExceptionTelemetry(e)
{
Message = "Test trace error message",
SeverityLevel = SeverityLevel.Error,
Timestamp = DateTimeOffset.UtcNow
};
traceTelemetry.Properties.Add("TestId", _testId);
exceptionTelemetry.Properties.Add("TestId", _testId);
// Act
await _logger.LogAsync(traceTelemetry);
}
[TestMethod]
public async Task LogTraceTelemetry_SendsCorrectDataWithWarningLevel()
{
// Arrange
var traceTelemetry = new TraceTelemetry
{
Message = "Test trace warning message",
SeverityLevel = SeverityLevel.Warning,
Timestamp = DateTimeOffset.UtcNow
};
traceTelemetry.Properties.Add("TestId", _testId);
// Act
await _logger.LogAsync(traceTelemetry);
}
[TestMethod]
public async Task LogEventTelemetry_SendsCorrectData()
{
// Arrange
var eventTelemetry = new EventTelemetry
{
Name = "Test Event",
Timestamp = DateTimeOffset.UtcNow
};
eventTelemetry.Properties.Add("TestId", _testId);
eventTelemetry.Metrics.Add("TestMetric", 42.0);
// Act
await _logger.LogAsync(eventTelemetry);
}
[TestMethod]
public async Task LogExceptionTelemetry_SendsCorrectData()
{
try
{
int t = 0;
var result = 10 / t;
}
catch (Exception e)
{
// Arrange
var exceptionTelemetry = new ExceptionTelemetry(e)
{
Timestamp = DateTimeOffset.UtcNow
};
exceptionTelemetry.Properties.Add("TestId", _testId);
// Act
await _logger.LogAsync(exceptionTelemetry);
}
}
[TestMethod]
public async Task LogDependencyTelemetry_SendsCorrectData()
{
// Arrange
var dependencyTelemetry = new DependencyTelemetry
{
Name = "SQL Query",
Type = "SQL",
Target = "TestDB",
Success = true,
Duration = TimeSpan.FromMilliseconds(100),
Timestamp = DateTimeOffset.UtcNow
};
dependencyTelemetry.Properties.Add("TestId", _testId);
// Act
await _logger.LogAsync(dependencyTelemetry);
}
/// <summary>
/// This is for scope test in SeqLogger. It is not testing anything related to the TelemetryChannel which logs to Seq.
/// </summary>
/// <returns></returns>
[TestMethod]
public async Task LogRequestTelemetryInOperationHolderWithParentChild_SendsCorrectData()
{
var telemetryClient = Container.Resolve<TelemetryClient>();
using (Microsoft.ApplicationInsights.Extensibility.IOperationHolder<RequestTelemetry> parent = telemetryClient.StartOperation<RequestTelemetry>("Parent First"))
{
parent.Telemetry.Duration = TimeSpan.FromMilliseconds(250);
parent.Telemetry.Url = new Uri("http://parent.test.com/api/test");
using (var child = telemetryClient.StartOperation<RequestTelemetry>("Child 1"))
{
child.Telemetry.Success = true;
child.Telemetry.ResponseCode = "200";
child.Telemetry.Duration = TimeSpan.FromMilliseconds(50);
child.Telemetry.Url = new Uri("http://child.test.com/api/test");
child.Telemetry.Timestamp = DateTimeOffset.UtcNow;
child.Telemetry.Properties.Add("httpMethod", HttpMethod.Get.ToString());
child.Telemetry.Properties.Add("TestId", _testId);
await _logger.LogAsync(child);
};
await _logger.LogAsync(parent);
}
await _logger.LogAsync(exceptionTelemetry);
}
}
}
[TestMethod]
public async Task LogDependencyTelemetry_SendsCorrectData()
{
// Arrange
var dependencyTelemetry = new DependencyTelemetry
{
Name = "SQL Query",
Type = "SQL",
Target = "TestDB",
Success = true,
Duration = TimeSpan.FromMilliseconds(100),
Timestamp = DateTimeOffset.UtcNow
};
dependencyTelemetry.Properties.Add("TestId", _testId);
// Act
await _logger.LogAsync(dependencyTelemetry);
}
/// <summary>
/// This is for scope test in SeqLogger. It is not testing anything related to the TelemetryChannel which logs to Seq.
/// </summary>
/// <returns></returns>
[TestMethod]
public async Task LogRequestTelemetryInOperationHolderWithParentChild_SendsCorrectData()
{
var telemetryClient = Container.Resolve<TelemetryClient>();
using (var parent = telemetryClient.StartOperation<RequestTelemetry>("Parent First"))
{
parent.Telemetry.Duration = TimeSpan.FromMilliseconds(250);
parent.Telemetry.Url = new Uri("http://parent.test.com/api/test");
using (var child = telemetryClient.StartOperation<RequestTelemetry>("Child 1"))
{
child.Telemetry.Success = true;
child.Telemetry.ResponseCode = "200";
child.Telemetry.Duration = TimeSpan.FromMilliseconds(50);
child.Telemetry.Url = new Uri("http://child.test.com/api/test");
child.Telemetry.Timestamp = DateTimeOffset.UtcNow;
child.Telemetry.Properties.Add("httpMethod", HttpMethod.Get.ToString());
child.Telemetry.Properties.Add("TestId", _testId);
await _logger.LogAsync(child);
}
;
await _logger.LogAsync(parent);
}
}
}

View file

@ -5,57 +5,56 @@ using Microsoft.ApplicationInsights.DataContracts;
using PlanTempus.Core.Logging;
using PlanTempus.Core.Telemetry;
namespace PlanTempus.Tests.Logging
namespace PlanTempus.X.TDD.Logging;
[TestClass]
public class SeqTelemetryChannelTest : TestFixture
{
[TestClass]
public class SeqTelemetryChannelTest : TestFixture
private CancellationTokenSource _cts;
private IMessageChannel<ITelemetry> _messageChannel;
private SeqBackgroundService _service;
private TelemetryClient _telemetryClient;
[TestInitialize]
public void SetupThis()
{
private IMessageChannel<ITelemetry> _messageChannel;
TelemetryClient _telemetryClient;
private SeqBackgroundService _service;
private CancellationTokenSource _cts;
//it is important to use the same MessageChannel as the BackgroundService uses
//we know that IMessageChannel<ITelemetry> _messageChannel; is registered via Autofac and manually injected into SeqBackgroundService
//so we can get it by calling the Autofac Container in this test.
[TestInitialize]
public void SetupThis()
_messageChannel = Container.Resolve<IMessageChannel<ITelemetry>>();
_service = Container.Resolve<SeqBackgroundService>();
_telemetryClient = Container.Resolve<TelemetryClient>();
_cts = new CancellationTokenSource();
}
[TestMethod]
public async Task Messages_ShouldBeProcessedFromQueue()
{
await _service.StartAsync(_cts.Token);
for (var i = 0; i < 5; i++)
{
//it is important to use the same MessageChannel as the BackgroundService uses
//we know that IMessageChannel<ITelemetry> _messageChannel; is registered via Autofac and manually injected into SeqBackgroundService
//so we can get it by calling the Autofac Container in this test.
_messageChannel = Container.Resolve<IMessageChannel<ITelemetry>>();
_service = Container.Resolve<SeqBackgroundService>();
_telemetryClient = Container.Resolve<TelemetryClient>();
_cts = new CancellationTokenSource();
}
[TestMethod]
public async Task Messages_ShouldBeProcessedFromQueue()
{
await _service.StartAsync(_cts.Token);
for (int i = 0; i < 5; i++)
var eventTelemetry = new EventTelemetry
{
var eventTelemetry = new EventTelemetry
{
Name = "Test Event 3",
Timestamp = DateTimeOffset.UtcNow
};
Name = "Test Event 3",
Timestamp = DateTimeOffset.UtcNow
};
eventTelemetry.Properties.Add("TestId", Guid.NewGuid().ToString());
eventTelemetry.Metrics.Add("TestMetric", 42.0);
eventTelemetry.Properties.Add("TestId", Guid.NewGuid().ToString());
eventTelemetry.Metrics.Add("TestMetric", 42.0);
//we don't write to the _messageChannel.Writer.WriteAsync(eventTelemetry);, but the TelemetryClient which is configured to use SeqTelemetryChannel
_telemetryClient.TrackEvent(eventTelemetry);
}
// wait for processing
await Task.Delay(5000);
await _service.StopAsync(CancellationToken.None);
bool hasMoreMessages = await _messageChannel.Reader.WaitToReadAsync();
Assert.IsFalse(hasMoreMessages, "Queue should be empty after 5 seconds");
//we don't write to the _messageChannel.Writer.WriteAsync(eventTelemetry);, but the TelemetryClient which is configured to use SeqTelemetryChannel
_telemetryClient.TrackEvent(eventTelemetry);
}
// wait for processing
await Task.Delay(5000);
await _service.StopAsync(CancellationToken.None);
var hasMoreMessages = await _messageChannel.Reader.WaitToReadAsync();
Assert.IsFalse(hasMoreMessages, "Queue should be empty after 5 seconds");
}
}