using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Hosting; using Serilog; using Serilog.Core; using Serilog.Events; namespace ZB.MOM.WW.Telemetry.Serilog.Tests; /// Regression tests for Telemetry-009 and Telemetry-010 (scadaproj#48). public sealed class ReviewP3Tests { private sealed class MaskApiKey : ILogRedactor { public void Redact(IDictionary properties) { if (properties.ContainsKey("apiKey")) properties["apiKey"] = "***"; } } private sealed class NoOpRedactor : ILogRedactor { public void Redact(IDictionary properties) { } } private sealed class CaptureSink : ILogEventSink { public List Events { get; } = []; public void Emit(LogEvent logEvent) => Events.Add(logEvent); } [Fact] public void Properties_stamped_by_ConfigureLogger_enrichers_are_redacted() { var builder = Host.CreateApplicationBuilder(new HostApplicationBuilderSettings { DisableDefaults = true }); builder.Services.AddSingleton(new MaskApiKey()); var sink = new CaptureSink(); builder.AddZbSerilog( o => o.ServiceName = "t", s => s.ConfigureLogger = (lc, _) => lc.Enrich.WithProperty("apiKey", "s3cret").WriteTo.Sink(sink)); using var host = builder.Build(); host.Services.GetRequiredService().Information("hello"); var evt = Assert.Single(sink.Events); Assert.Equal("***", ((ScalarValue)evt.Properties["apiKey"]).Value); } [Fact] public void Dictionary_keys_that_print_identically_are_all_kept() { var provider = new ServiceCollection().AddSingleton(new NoOpRedactor()).BuildServiceProvider(); var sink = new CaptureSink(); var cfg = new LoggerConfiguration(); ZbSerilogConfig.Apply(cfg, new ZbTelemetryOptions { ServiceName = "t" }, provider); using var logger = cfg.WriteTo.Sink(sink).CreateLogger(); var map = new Dictionary { [new DateTime(2026, 1, 1, 12, 0, 0, 100)] = "first", [new DateTime(2026, 1, 1, 12, 0, 0, 200)] = "second", }; logger.Information("{Map}", map); var dict = Assert.IsType(Assert.Single(sink.Events).Properties["Map"]); Assert.Equal(2, dict.Elements.Count); Assert.Equal( new[] { "first", "second" }, dict.Elements.Select(e => (string)((ScalarValue)e.Value).Value!).Order(StringComparer.Ordinal)); Assert.Equal(2, dict.Elements.Select(e => e.Key.Value).Distinct().Count()); } }