Files
ScadaBridge/tests/ZB.MOM.WW.ScadaBridge.SiteEventLogging.Tests/EventLogCoverageTests.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

150 lines
6.0 KiB
C#

using Microsoft.Extensions.Logging.Abstractions;
using Microsoft.Extensions.Options;
using ZB.MOM.WW.ScadaBridge.Commons.Messages.RemoteQuery;
namespace ZB.MOM.WW.ScadaBridge.SiteEventLogging.Tests;
/// <summary>
/// Regression tests for Previously untested behaviours —
/// the query service error path and the recorder's disposed-state semantics.
/// </summary>
public class EventLogCoverageTests : IDisposable
{
private readonly string _dbPath;
private readonly TestLocalDb _localDb;
/// <summary>Initializes a new instance of the <c>EventLogCoverageTests</c> class.</summary>
public EventLogCoverageTests()
{
_dbPath = Path.Combine(Path.GetTempPath(), $"test_coverage_{Guid.NewGuid()}.db");
_localDb = TestLocalDb.Create(_dbPath);
}
/// <summary>Releases the resources held by this test class.</summary>
public void Dispose()
{
_localDb.Dispose();
TestLocalDb.DeleteFiles(_dbPath);
GC.SuppressFinalize(this);
}
// Each call gets its own connection from the one shared local database, so the
// loggers these tests dispose mid-test do not tear down the database itself.
private SiteEventLogger NewLogger() => new(
Options.Create(new SiteEventLogOptions { DatabasePath = _dbPath }),
NullLogger<SiteEventLogger>.Instance,
_localDb.Db);
private static EventLogQueryRequest MakeRequest() => new(
CorrelationId: "corr-err",
SiteId: "site-1",
From: null,
To: null,
EventType: null,
Severity: null,
InstanceId: null,
KeywordFilter: null,
ContinuationToken: null,
PageSize: 500,
Timestamp: DateTimeOffset.UtcNow);
/// <summary>Verifies that execute query returns failure response when database unavailable.</summary>
[Fact]
public void ExecuteQuery_ReturnsFailureResponse_WhenDatabaseUnavailable()
{
// The catch block in EventLogQueryService.ExecuteQuery was untested.
// Disposing the recorder makes WithConnection throw ObjectDisposedException;
// the query service must convert that into a Success=false response rather
// than letting the exception escape to the actor.
var logger = NewLogger();
var queryService = new EventLogQueryService(
logger,
Options.Create(new SiteEventLogOptions { DatabasePath = _dbPath }),
NullLogger<EventLogQueryService>.Instance);
logger.Dispose();
var response = queryService.ExecuteQuery(MakeRequest());
Assert.False(response.Success);
Assert.NotNull(response.ErrorMessage);
Assert.Empty(response.Entries);
Assert.Null(response.ContinuationToken);
Assert.Equal("corr-err", response.CorrelationId);
}
/// <summary>Verifies that log event async after dispose faults task not reports success.</summary>
/// <returns>A task that represents the asynchronous operation.</returns>
[Fact]
public async Task LogEventAsync_AfterDispose_FaultsTask_NotReportsSuccess()
{
// When the logger has been disposed the event cannot
// be persisted. The returned Task must FAULT (not complete successfully) so
// an awaiting caller can distinguish a dropped audit event from a written
// one. Per the XML doc contract, the Task "faults if the write fails".
var logger = NewLogger();
logger.Dispose();
var task = logger.LogEventAsync("script", "Info", null, "Source", "After dispose");
await Assert.ThrowsAsync<ObjectDisposedException>(
() => task.WaitAsync(TimeSpan.FromSeconds(5)));
}
/// <summary>Verifies that dispose is idempotent.</summary>
[Fact]
public void Dispose_IsIdempotent()
{
// Re-entrant / repeated Dispose must be a safe no-op.
var logger = NewLogger();
logger.Dispose();
logger.Dispose();
}
/// <summary>Verifies that log event async enqueued then disposed faults task when write cannot complete.</summary>
/// <returns>A task that represents the asynchronous operation.</returns>
[Fact]
public async Task LogEventAsync_EnqueuedThenDisposed_FaultsTask_WhenWriteCannotComplete()
{
// Second path: an event enqueued onto the background
// writer just before disposal must NOT be reported as persisted if the
// writer's WithConnection returns false (logger disposed mid-drain). We
// flood the queue and dispose immediately; any event whose write did not
// actually run must have a faulted Task, never a successful one.
var logger = NewLogger();
var tasks = new List<Task>();
for (int i = 0; i < 200; i++)
{
tasks.Add(logger.LogEventAsync("script", "Info", null, "Source", $"event-{i}"));
}
logger.Dispose();
// Every task must reach a terminal state. None may be left as a successful
// completion for an event the writer never persisted: a task is either
// RanToCompletion (genuinely written before the connection closed) or
// Faulted (could not be persisted). Count persisted vs faulted and assert
// the persisted count matches the actual row count.
await Task.WhenAll(tasks.Select(t => t.ContinueWith(_ => { })));
var succeeded = tasks.Count(t => t.Status == TaskStatus.RanToCompletion);
var faulted = tasks.Count(t => t.IsFaulted);
Assert.Equal(tasks.Count, succeeded + faulted);
long rowCount;
using (var conn = new Microsoft.Data.Sqlite.SqliteConnection($"Data Source={_dbPath}"))
{
conn.Open();
using var cmd = conn.CreateCommand();
cmd.CommandText = "SELECT COUNT(*) FROM site_events";
rowCount = (long)cmd.ExecuteScalar()!;
}
// A successfully-completed Task must correspond to a row that was actually
// written. If the disposed-mid-drain path falsely reported success, the
// success count would exceed the row count.
Assert.Equal(rowCount, succeeded);
}
}