Files
ScadaBridge/tests/ZB.MOM.WW.ScadaBridge.SiteEventLogging.Tests/EventLogCoverageTests.cs
T
Joseph Doherty 0d8a80aa27 feat(localdb): rewire SiteEventLogger onto the consolidated site database
Completes Task 5a of the LocalDb Phase 1 adoption plan. The GUID-id half landed
with Task 2 (727fa48c) because leaving it out would have committed a writer that
could not satisfy site_events.id NOT NULL; this is the connection half, which
was blocked on Task 3.

SiteEventLogger owned a SqliteConnection built from SiteEventLogOptions
.DatabasePath. It now takes ILocalDb and gets that connection from
CreateConnection() - already open, pragma-configured, and carrying the
zb_hlc_next() UDF that site_events' capture triggers call. It still owns and
disposes the connection; WithConnection's signature and locking semantics are
untouched, so EventLogQueryService and EventLogPurgeService are unaffected.

The connectionStringOverride seam is deleted rather than preserved. site_events
is a replicated table, so a raw connection lacks the UDF and fails closed on
every insert - an override could only produce a logger that cannot write. It had
no callers outside this class (the connectionStringOverride hits elsewhere in the
tree belong to SqliteAuditWriter, a different type).

Tests: a shared TestLocalDb helper gives each fixture a real ILocalDb over a temp
file. Real rather than stubbed on purpose - a stub handing back a bare
SqliteConnection would pass today and fail closed the moment the table is
registered, which is exactly the silent-wiring failure mode this family has hit
three times. ServiceWiringTests' DI path also needed AddZbLocalDb, mirroring
SiteServiceRegistration.

Verified: build 0 warnings; SiteEventLogging 70/70, Host 294/294,
SiteRuntime 530/530.

Claude-Session: https://claude.ai/code/session_01BL2Vu1ESDQ9SCN4gVKkdts
2026-07-19 09:07:49 -04:00

142 lines
5.4 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 SiteEventLogging-010: 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;
public EventLogCoverageTests()
{
_dbPath = Path.Combine(Path.GetTempPath(), $"test_coverage_{Guid.NewGuid()}.db");
_localDb = TestLocalDb.Create(_dbPath);
}
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);
[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);
}
[Fact]
public async Task LogEventAsync_AfterDispose_FaultsTask_NotReportsSuccess()
{
// SiteEventLogging-012: 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)));
}
[Fact]
public void Dispose_IsIdempotent()
{
// Re-entrant / repeated Dispose must be a safe no-op.
var logger = NewLogger();
logger.Dispose();
logger.Dispose();
}
[Fact]
public async Task LogEventAsync_EnqueuedThenDisposed_FaultsTask_WhenWriteCannotComplete()
{
// SiteEventLogging-012, 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);
}
}