Files
ScadaBridge/tests/ZB.MOM.WW.ScadaBridge.SiteRuntime.Tests/Actors/AlarmScriptLogTargetTests.cs
T
Joseph Doherty 513fa1aa16 docs(tests): fix CommentChecker findings across tests/ — 13,392 → 0 (repo-wide scan clean)
Comment/XML-doc changes only:
- add summaries to ~10k test methods, fixtures, fakes and helpers
  (+ <param> on theories, <returns> on async Task methods,
  <inheritdoc/> on interface implementations the checker can resolve)
- strip ~2.6k project-tracking references (WP*, P*-*, row-NN, Task N,
  #NN, Component-0NN) from comments, keeping the explanatory text;
  reword false positives in comments only
- real docs on fakes implementing BCL/library interfaces
  (IDisposable, ILogger, IOptionsMonitor, IAsyncLifetime)
- reword the last 5 src/ false positives (CWE-1236, failures-1,
  year-0001, M365)

Only non-comment edits: four one-line nested classes split across lines
so members can carry docs. Build 0 errors / 0 warnings.
2026-10-07 15:05:49 -04:00

135 lines
7.5 KiB
C#

using Moq;
using Akka.Actor;
using Akka.TestKit.Xunit2;
using Microsoft.CodeAnalysis.CSharp.Scripting;
using Microsoft.CodeAnalysis.Scripting;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Logging.Abstractions;
using ZB.MOM.WW.ScadaBridge.Commons.Messages.Streaming;
using ZB.MOM.WW.ScadaBridge.Commons.Types.Flattening;
using ZB.MOM.WW.ScadaBridge.SiteRuntime.Actors;
using ZB.MOM.WW.ScadaBridge.SiteRuntime.Scripts;
namespace ZB.MOM.WW.ScadaBridge.SiteRuntime.Tests.Actors;
/// <summary>
/// Regression: an alarm on-trigger run's <c>ScriptRuntimeContext</c> was built without a
/// <c>sourceScript</c>, so the context's <c>_logTarget</c> — which names the script on every
/// <c>Log.*</c> line and on the run's trace rows — fell back to the INSTANCE name. The launcher now
/// passes the same <c>AlarmActor:{alarmName}</c> source key it already uses for this alarm's site
/// events, from which the context derives the alarm's own name.
/// </summary>
public class AlarmScriptLogTargetTests : TestKit, IDisposable
{
private sealed record Entry(LogLevel Level, string Message);
/// <summary>A minimal recording logger — the alarm path hands its own ILogger down to the script logger.</summary>
private sealed class RecordingLogger<T> : ILogger<T>
{
/// <summary>Gets the log entries recorded so far.</summary>
public List<Entry> Entries { get; } = [];
/// <summary>Returns no scope.</summary>
/// <typeparam name="TState">The scope state type.</typeparam>
/// <param name="state">The scope state.</param>
/// <returns>Always null.</returns>
public IDisposable? BeginScope<TState>(TState state) where TState : notnull => null;
/// <summary>Reports every log level as enabled.</summary>
/// <param name="logLevel">The log level.</param>
/// <returns>Always true.</returns>
public bool IsEnabled(LogLevel logLevel) => true;
/// <summary>Records the log entry for later assertions.</summary>
/// <typeparam name="TState">The log state type.</typeparam>
/// <param name="level">The log level.</param>
/// <param name="eventId">The event id.</param>
/// <param name="state">The log state.</param>
/// <param name="exception">The associated exception, if any.</param>
/// <param name="formatter">Formats the state and exception into a message.</param>
public void Log<TState>(LogLevel level, EventId eventId, TState state, Exception? exception, Func<TState, Exception?, string> formatter)
{
lock (Entries) Entries.Add(new Entry(level, formatter(state, exception)));
}
}
private readonly SharedScriptLibrary _sharedLibrary = new(
new ScriptCompilationService(NullLogger<ScriptCompilationService>.Instance),
NullLogger<SharedScriptLibrary>.Instance);
/// <inheritdoc />
void IDisposable.Dispose() => Shutdown();
/// <summary>Verifies that an alarm on-trigger run attributes its log lines to the alarm, not just the instance.</summary>
[Fact]
public void AlarmOnTriggerRun_AttributesItsLogLinesToTheALARM_NotJustTheInstance()
{
var options = new SiteRuntimeOptions
{
ScriptExecutionTimeoutSeconds = 10,
MaxScriptCallDepth = 10,
};
var scriptOptions = ScriptOptions.Default
.WithReferences(typeof(object).Assembly, typeof(Enumerable).Assembly, typeof(ScriptGlobals).Assembly)
.WithImports("System", "System.Threading.Tasks");
var compiled = CSharpScript.Create<object?>("Log.Info(\"alarm handler ran\"); return null;", scriptOptions, typeof(ScriptGlobals));
compiled.Compile();
var logger = new RecordingLogger<AlarmActor>();
using var scheduler = new ScriptExecutionScheduler(1);
var config = new ResolvedAlarm
{
CanonicalName = "HighTemp",
TriggerType = "ValueMatch",
TriggerConfiguration = "{\"attributeName\":\"Status\",\"matchValue\":\"Critical\"}",
PriorityLevel = 100,
};
var alarm = ActorOfAsTestActorRef<AlarmActor>(
Props.Create(() => new AlarmActor(
"HighTemp", "Inst1", CreateTestProbe().Ref, config, compiled, _sharedLibrary, options,
logger, null, null, null, null, null, scheduler, null)),
"alarm-logtarget-" + Guid.NewGuid().ToString("N"));
alarm.Tell(new AttributeValueChanged("Inst1", "Status", "Status", "Critical", "Good", DateTimeOffset.UtcNow));
AwaitAssert(
() =>
{
Entry[] snapshot;
lock (logger.Entries) snapshot = [.. logger.Entries];
// "[script] {Instance}/{Script} {ExecutionId}: {Message}" — the script half is the
// alarm's name because the launcher passed "AlarmActor:HighTemp" as the source.
Assert.Contains(snapshot, e => e.Message.StartsWith("[script] Inst1/HighTemp ", StringComparison.Ordinal)
&& e.Message.EndsWith(": alarm handler ran", StringComparison.Ordinal));
},
TimeSpan.FromSeconds(15));
}
/// <summary>Verifies that an alarm run resolves and disposes its scoped integration services.</summary>
[Fact]
public void SR2_AlarmRunResolvesAndDisposesScopedIntegrationServices()
{
var store = new Moq.Mock<ZB.MOM.WW.ScadaBridge.Commons.Interfaces.IOperationTrackingStore>();
store.Setup(s => s.GetStatusAsync(Moq.It.IsAny<ZB.MOM.WW.ScadaBridge.Commons.Types.TrackedOperationId>(), Moq.It.IsAny<CancellationToken>()))
.ReturnsAsync((ZB.MOM.WW.ScadaBridge.Commons.Types.TrackingStatusSnapshot?)null);
store.As<IDisposable>().Setup(s => s.Dispose());
using var provider = Microsoft.Extensions.DependencyInjection.ServiceCollectionContainerBuilderExtensions.BuildServiceProvider(
Microsoft.Extensions.DependencyInjection.ServiceCollectionServiceExtensions.AddScoped<ZB.MOM.WW.ScadaBridge.Commons.Interfaces.IOperationTrackingStore>(
new Microsoft.Extensions.DependencyInjection.ServiceCollection(), _ => store.Object));
var options = ScriptOptions.Default.WithReferences(typeof(object).Assembly, typeof(ScriptGlobals).Assembly,
typeof(ZB.MOM.WW.ScadaBridge.Commons.Types.TrackedOperationId).Assembly)
.WithImports("ZB.MOM.WW.ScadaBridge.Commons.Types");
var compiled = CSharpScript.Create<object?>("await Instance.Tracking.Status(TrackedOperationId.New()); return null;", options, typeof(ScriptGlobals));
Assert.DoesNotContain(compiled.Compile(), d => d.Severity == Microsoft.CodeAnalysis.DiagnosticSeverity.Error);
using var scheduler = new ScriptExecutionScheduler(1);
var done = CreateTestProbe();
var logger = new RecordingLogger<AlarmActor>();
ScriptRunLauncher.LaunchAlarmScript("alarm", "instance", ZB.MOM.WW.ScadaBridge.Commons.Types.Enums.AlarmLevel.High,
1, "alarm", compiled, CreateTestProbe().Ref, _sharedLibrary, new SiteRuntimeOptions(), done.Ref,
logger, null, provider, 1, 10, null, scheduler);
Assert.True(done.ExpectMsg<AlarmActor.AlarmExecutionCompleted>(TimeSpan.FromSeconds(10)).Success, string.Join(";", logger.Entries.Select(e => e.Message)));
store.Verify(s => s.GetStatusAsync(Moq.It.IsAny<ZB.MOM.WW.ScadaBridge.Commons.Types.TrackedOperationId>(), Moq.It.IsAny<CancellationToken>()), Moq.Times.Once);
AwaitAssert(() => store.As<IDisposable>().Verify(s => s.Dispose(), Moq.Times.Once));
}
}