513fa1aa16
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.
129 lines
5.5 KiB
C#
129 lines
5.5 KiB
C#
using System.Diagnostics;
|
|
using Microsoft.Data.Sqlite;
|
|
using Microsoft.Extensions.Logging.Abstractions;
|
|
using Microsoft.Extensions.Options;
|
|
|
|
namespace ZB.MOM.WW.ScadaBridge.SiteEventLogging.Tests;
|
|
|
|
/// <summary>
|
|
/// Regression tests for non-blocking logging (synchronous I/O on the caller thread)
|
|
/// and surfaced write failures (failures silently swallowed).
|
|
/// </summary>
|
|
public class SiteEventLoggerAsyncTests : IDisposable
|
|
{
|
|
private readonly SiteEventLogger _logger;
|
|
private readonly string _dbPath;
|
|
private readonly TestLocalDb _localDb;
|
|
|
|
/// <summary>Initializes the test class with a temporary LocalDb-backed event logger.</summary>
|
|
public SiteEventLoggerAsyncTests()
|
|
{
|
|
_dbPath = Path.Combine(Path.GetTempPath(), $"test_async_{Guid.NewGuid()}.db");
|
|
var options = Options.Create(new SiteEventLogOptions { DatabasePath = _dbPath });
|
|
_localDb = TestLocalDb.Create(_dbPath);
|
|
_logger = new SiteEventLogger(options, NullLogger<SiteEventLogger>.Instance, _localDb.Db);
|
|
}
|
|
|
|
/// <summary>Releases the resources held by this test class.</summary>
|
|
public void Dispose()
|
|
{
|
|
_logger.Dispose();
|
|
_localDb.Dispose();
|
|
TestLocalDb.DeleteFiles(_dbPath);
|
|
}
|
|
|
|
/// <summary>Verifies that logging an event does not block the caller when the write is slow.</summary>
|
|
/// <returns>A task that represents the asynchronous operation.</returns>
|
|
[Fact]
|
|
public async Task LogEventAsync_DoesNotBlockCaller_WhenWriteIsSlow()
|
|
{
|
|
// LogEventAsync must not perform the SQLite write
|
|
// inline on the caller's thread. We hold the recorder busy on a long
|
|
// database operation from one thread, then time how long it takes the
|
|
// caller of LogEventAsync to get control back. If recording is offloaded
|
|
// to a background writer, the caller returns essentially immediately even
|
|
// though the database is busy. If recording is synchronous (the bug), the
|
|
// caller blocks on the write lock for the full busy period.
|
|
var busyStarted = new ManualResetEventSlim(false);
|
|
var releaseBusy = new ManualResetEventSlim(false);
|
|
|
|
var busyThread = new Thread(() =>
|
|
{
|
|
_logger.WithConnection(_ =>
|
|
{
|
|
busyStarted.Set();
|
|
// Hold the connection lock until the test releases it.
|
|
releaseBusy.Wait(TimeSpan.FromSeconds(10));
|
|
});
|
|
});
|
|
busyThread.Start();
|
|
|
|
Assert.True(busyStarted.Wait(TimeSpan.FromSeconds(5)), "Busy thread did not start.");
|
|
|
|
var sw = Stopwatch.StartNew();
|
|
var recordTask = _logger.LogEventAsync("script", "Info", null, "Caller", "Should not block");
|
|
sw.Stop();
|
|
|
|
// The CALL must return quickly even though the database is busy for ~1s.
|
|
Assert.True(sw.ElapsedMilliseconds < 500,
|
|
$"LogEventAsync blocked the caller for {sw.ElapsedMilliseconds} ms — recording is not offloaded.");
|
|
|
|
// Release the busy thread; the record must still complete successfully.
|
|
releaseBusy.Set();
|
|
busyThread.Join(TimeSpan.FromSeconds(10));
|
|
|
|
await recordTask.WaitAsync(TimeSpan.FromSeconds(10));
|
|
}
|
|
|
|
/// <summary>Verifies that the logging task completes only after the event is persisted.</summary>
|
|
/// <returns>A task that represents the asynchronous operation.</returns>
|
|
[Fact]
|
|
public async Task LogEventAsync_TaskCompletes_AfterEventIsPersisted()
|
|
{
|
|
// Awaiting the returned Task must guarantee the row is durably written.
|
|
await _logger.LogEventAsync("script", "Info", "inst-1", "Source", "Persisted event");
|
|
|
|
var count = _logger.WithConnection(connection =>
|
|
{
|
|
using var cmd = connection.CreateCommand();
|
|
cmd.CommandText = "SELECT COUNT(*) FROM site_events";
|
|
return (long)cmd.ExecuteScalar()!;
|
|
});
|
|
Assert.Equal(1, count);
|
|
}
|
|
|
|
/// <summary>Verifies that a write error faults the logging task and increments the failure count.</summary>
|
|
/// <returns>A task that represents the asynchronous operation.</returns>
|
|
[Fact]
|
|
public async Task LogEventAsync_FaultsTask_AndCountsFailure_OnWriteError()
|
|
{
|
|
// A write failure must not be silently swallowed.
|
|
// The returned Task must fault and the failure counter must increment so
|
|
// Health Monitoring can surface a logging outage.
|
|
using var failingConnection = new SqliteConnection("Data Source=:memory:");
|
|
failingConnection.Open();
|
|
var failDbPath = Path.Combine(Path.GetTempPath(), $"test_fail_{Guid.NewGuid()}.db");
|
|
var options = Options.Create(new SiteEventLogOptions { DatabasePath = failDbPath });
|
|
using var failLocalDb = TestLocalDb.Create(failDbPath);
|
|
var logger = new SiteEventLogger(options, NullLogger<SiteEventLogger>.Instance, failLocalDb.Db);
|
|
|
|
// Drop the table so every write fails with "no such table".
|
|
logger.WithConnection(connection =>
|
|
{
|
|
using var cmd = connection.CreateCommand();
|
|
cmd.CommandText = "DROP TABLE site_events";
|
|
cmd.ExecuteNonQuery();
|
|
});
|
|
|
|
await Assert.ThrowsAnyAsync<SqliteException>(() =>
|
|
logger.LogEventAsync("script", "Error", null, "Source", "Failing write"));
|
|
|
|
Assert.True(logger.FailedWriteCount > 0,
|
|
"FailedWriteCount must increment when an event write fails.");
|
|
|
|
logger.Dispose();
|
|
failLocalDb.Dispose();
|
|
TestLocalDb.DeleteFiles(failDbPath);
|
|
}
|
|
}
|