using System.Net; using Autofac; using Microsoft.ApplicationInsights; using Microsoft.ApplicationInsights.Channel; using Microsoft.ApplicationInsights.DataContracts; using SWP.Core.SeqLogging; using SWP.Core.Telemetry; namespace SWP.Core.X.TDD.Logging; [TestClass] public class SeqBackgroundServiceTest : TestFixture { private CancellationTokenSource _cts; private IMessageChannel _messageChannel; private SeqBackgroundService _service; [TestInitialize] public void SetupThis() { _messageChannel = new MessageChannel(); var telemetryClient = Container.Resolve(); var config = new SeqConfiguration("http://localhost:5341", null, "MSTEST"); var httpClient = new SeqHttpClient(config); var logger = new SeqLogger(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++) { 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); var hasMoreMessages = await _messageChannel.Reader.WaitToReadAsync(); Assert.IsFalse(hasMoreMessages, "Queue should be empty after 5 seconds"); } private class TestMessageHandler : HttpMessageHandler { protected override Task SendAsync( HttpRequestMessage request, CancellationToken cancellationToken) { return Task.FromResult(new HttpResponseMessage(HttpStatusCode.OK)); } } }