PlanTempusApp/Tests/Logging/SeqBackgroundServiceTest.cs

77 lines
2.4 KiB
C#
Raw Normal View History

using Autofac;
using Microsoft.ApplicationInsights;
2025-02-14 17:45:49 +01:00
using Microsoft.ApplicationInsights.Channel;
using Microsoft.ApplicationInsights.DataContracts;
using PlanTempus.Core.Logging;
using PlanTempus.Core.Telemetry;
namespace PlanTempus.Tests.Logging
{
[TestClass]
public class SeqBackgroundServiceTest : TestFixture
{
2025-02-14 17:45:49 +01:00
private IMessageChannel<ITelemetry> _messageChannel;
private SeqBackgroundService _service;
private CancellationTokenSource _cts;
[TestInitialize]
public void SetupThis()
{
_messageChannel = new MessageChannel();
var telemetryClient = Container.Resolve<TelemetryClient>();
var config = new SeqConfiguration("http://localhost:5341", null, "MSTEST");
var httpClient = new SeqHttpClient(config);
2025-02-20 17:14:53 +01:00
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 (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);
}
2025-02-14 17:45:49 +01:00
// wait for processing
await Task.Delay(5000);
_cts.Cancel();
await _service.StopAsync(CancellationToken.None);
2025-02-14 17:45:49 +01:00
bool hasMoreMessages = await _messageChannel.Reader.WaitToReadAsync();
2025-02-14 17:45:49 +01:00
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));
}
}
[TestCleanup]
public void Cleanup()
{
_cts?.Dispose();
}
}
}