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.
215 lines
9.2 KiB
C#
215 lines
9.2 KiB
C#
using Microsoft.Data.Sqlite;
|
|
using Microsoft.Extensions.Logging.Abstractions;
|
|
using Microsoft.Extensions.Options;
|
|
|
|
namespace ZB.MOM.WW.ScadaBridge.SiteEventLogging.Tests;
|
|
|
|
public class SiteEventLoggerTests : IDisposable
|
|
{
|
|
private readonly SiteEventLogger _logger;
|
|
private readonly SqliteConnection _verifyConnection;
|
|
private readonly string _dbPath;
|
|
private readonly TestLocalDb _localDb;
|
|
|
|
/// <summary>Initializes the test class with a temporary LocalDb-backed logger.</summary>
|
|
public SiteEventLoggerTests()
|
|
{
|
|
_dbPath = Path.Combine(Path.GetTempPath(), $"test_events_{Guid.NewGuid()}.db");
|
|
var options = Options.Create(new SiteEventLogOptions { DatabasePath = _dbPath });
|
|
_localDb = TestLocalDb.Create(_dbPath);
|
|
_logger = new SiteEventLogger(options, NullLogger<SiteEventLogger>.Instance, _localDb.Db);
|
|
|
|
// Separate connection for verification queries
|
|
_verifyConnection = new SqliteConnection($"Data Source={_dbPath}");
|
|
_verifyConnection.Open();
|
|
}
|
|
|
|
/// <summary>Releases the resources held by this instance.</summary>
|
|
public void Dispose()
|
|
{
|
|
_verifyConnection.Dispose();
|
|
_logger.Dispose();
|
|
_localDb.Dispose();
|
|
TestLocalDb.DeleteFiles(_dbPath);
|
|
}
|
|
|
|
/// <summary>Verifies that logging an event inserts a record.</summary>
|
|
/// <returns>A task that represents the asynchronous operation.</returns>
|
|
[Fact]
|
|
public async Task LogEventAsync_InsertsRecord()
|
|
{
|
|
await _logger.LogEventAsync("script", "Error", "inst-1", "ScriptActor:Monitor", "Script failed", "{\"stack\":\"...\"}");
|
|
|
|
using var cmd = _verifyConnection.CreateCommand();
|
|
cmd.CommandText = "SELECT COUNT(*) FROM site_events";
|
|
var count = (long)cmd.ExecuteScalar()!;
|
|
Assert.Equal(1, count);
|
|
}
|
|
|
|
/// <summary>Verifies that logging an event stores all of its fields.</summary>
|
|
/// <returns>A task that represents the asynchronous operation.</returns>
|
|
[Fact]
|
|
public async Task LogEventAsync_StoresAllFields()
|
|
{
|
|
await _logger.LogEventAsync("alarm", "Warning", "inst-2", "AlarmActor:TempHigh", "Alarm triggered", "{\"value\":95}");
|
|
|
|
using var cmd = _verifyConnection.CreateCommand();
|
|
cmd.CommandText = "SELECT event_type, severity, instance_id, source, message, details FROM site_events LIMIT 1";
|
|
using var reader = cmd.ExecuteReader();
|
|
Assert.True(reader.Read());
|
|
Assert.Equal("alarm", reader.GetString(0));
|
|
Assert.Equal("Warning", reader.GetString(1));
|
|
Assert.Equal("inst-2", reader.GetString(2));
|
|
Assert.Equal("AlarmActor:TempHigh", reader.GetString(3));
|
|
Assert.Equal("Alarm triggered", reader.GetString(4));
|
|
Assert.Equal("{\"value\":95}", reader.GetString(5));
|
|
}
|
|
|
|
/// <summary>Verifies that the nullable fields may be left empty.</summary>
|
|
/// <returns>A task that represents the asynchronous operation.</returns>
|
|
[Fact]
|
|
public async Task LogEventAsync_NullableFieldsAllowed()
|
|
{
|
|
await _logger.LogEventAsync("deployment", "Info", null, "DeploymentManager", "Deployed instance");
|
|
|
|
using var cmd = _verifyConnection.CreateCommand();
|
|
cmd.CommandText = "SELECT instance_id, details FROM site_events LIMIT 1";
|
|
using var reader = cmd.ExecuteReader();
|
|
Assert.True(reader.Read());
|
|
Assert.True(reader.IsDBNull(0));
|
|
Assert.True(reader.IsDBNull(1));
|
|
}
|
|
|
|
/// <summary>Verifies that the stored timestamp is an ISO 8601 UTC value.</summary>
|
|
/// <returns>A task that represents the asynchronous operation.</returns>
|
|
[Fact]
|
|
public async Task LogEventAsync_StoresIso8601UtcTimestamp()
|
|
{
|
|
await _logger.LogEventAsync("connection", "Info", null, "DCL", "Connected");
|
|
|
|
using var cmd = _verifyConnection.CreateCommand();
|
|
cmd.CommandText = "SELECT timestamp FROM site_events LIMIT 1";
|
|
var ts = (string)cmd.ExecuteScalar()!;
|
|
var parsed = DateTimeOffset.Parse(ts);
|
|
Assert.Equal(TimeSpan.Zero, parsed.Offset);
|
|
}
|
|
|
|
/// <summary>Verifies that an empty event type throws.</summary>
|
|
/// <returns>A task that represents the asynchronous operation.</returns>
|
|
[Fact]
|
|
public async Task LogEventAsync_ThrowsOnEmptyEventType()
|
|
{
|
|
await Assert.ThrowsAsync<ArgumentException>(() =>
|
|
_logger.LogEventAsync("", "Info", null, "Source", "Message"));
|
|
}
|
|
|
|
/// <summary>Verifies that an empty severity throws.</summary>
|
|
/// <returns>A task that represents the asynchronous operation.</returns>
|
|
[Fact]
|
|
public async Task LogEventAsync_ThrowsOnEmptySeverity()
|
|
{
|
|
await Assert.ThrowsAsync<ArgumentException>(() =>
|
|
_logger.LogEventAsync("script", "", null, "Source", "Message"));
|
|
}
|
|
|
|
/// <summary>Verifies that an empty source throws.</summary>
|
|
/// <returns>A task that represents the asynchronous operation.</returns>
|
|
[Fact]
|
|
public async Task LogEventAsync_ThrowsOnEmptySource()
|
|
{
|
|
await Assert.ThrowsAsync<ArgumentException>(() =>
|
|
_logger.LogEventAsync("script", "Info", null, "", "Message"));
|
|
}
|
|
|
|
/// <summary>Verifies that an empty message throws.</summary>
|
|
/// <returns>A task that represents the asynchronous operation.</returns>
|
|
[Fact]
|
|
public async Task LogEventAsync_ThrowsOnEmptyMessage()
|
|
{
|
|
await Assert.ThrowsAsync<ArgumentException>(() =>
|
|
_logger.LogEventAsync("script", "Info", null, "Source", ""));
|
|
}
|
|
|
|
/// <summary>Verifies that multiple events each get a distinct application-minted id.</summary>
|
|
/// <returns>A task that represents the asynchronous operation.</returns>
|
|
[Fact]
|
|
public async Task LogEventAsync_MultipleEvents_GetDistinctApplicationMintedIds()
|
|
{
|
|
// Replaces LogEventAsync_MultipleEvents_AutoIncrementIds. Ids are no longer
|
|
// server-minted autoincrement integers: under LocalDb replication the site pair
|
|
// converges by last-writer-wins on the primary key, so both nodes issuing 1, 2,
|
|
// 3... for unrelated events would silently overwrite each other on sync.
|
|
//
|
|
// The invariant is therefore uniqueness, NOT monotonicity — ordering is carried
|
|
// by the timestamp column, which is what the query and purge paths sort on.
|
|
await _logger.LogEventAsync("script", "Info", null, "S1", "First");
|
|
await _logger.LogEventAsync("script", "Info", null, "S2", "Second");
|
|
await _logger.LogEventAsync("script", "Info", null, "S3", "Third");
|
|
|
|
using var cmd = _verifyConnection.CreateCommand();
|
|
cmd.CommandText = "SELECT id FROM site_events ORDER BY timestamp";
|
|
using var reader = cmd.ExecuteReader();
|
|
var ids = new List<string>();
|
|
while (reader.Read()) ids.Add(reader.GetString(0));
|
|
|
|
Assert.Equal(3, ids.Count);
|
|
Assert.All(ids, id => Assert.False(string.IsNullOrWhiteSpace(id)));
|
|
Assert.Equal(3, ids.Distinct(StringComparer.Ordinal).Count());
|
|
Assert.All(ids, id => Assert.True(Guid.TryParseExact(id, "N", out _),
|
|
$"Event id '{id}' is not a GUID in 'N' format."));
|
|
}
|
|
|
|
/// <summary>Verifies that all event types are accepted.</summary>
|
|
/// <returns>A task that represents the asynchronous operation.</returns>
|
|
[Fact]
|
|
public async Task AllEventTypes_Accepted()
|
|
{
|
|
var types = new[] { "script", "alarm", "deployment", "connection", "store_and_forward", "instance_lifecycle" };
|
|
foreach (var t in types)
|
|
{
|
|
await _logger.LogEventAsync(t, "Info", null, "Test", $"Event type: {t}");
|
|
}
|
|
|
|
using var cmd = _verifyConnection.CreateCommand();
|
|
cmd.CommandText = "SELECT COUNT(DISTINCT event_type) FROM site_events";
|
|
var count = (long)cmd.ExecuteScalar()!;
|
|
Assert.Equal(6, count);
|
|
}
|
|
|
|
// --- Severity validation against the closed set ---
|
|
|
|
/// <summary>Verifies that an unknown severity throws.</summary>
|
|
/// <param name="badSeverity">The bad severity.</param>
|
|
/// <returns>A task that represents the asynchronous operation.</returns>
|
|
[Theory]
|
|
[InlineData("info")] // wrong casing
|
|
[InlineData("warn")] // abbreviation
|
|
[InlineData("ERROR")] // wrong casing
|
|
[InlineData("Debug")] // not in set
|
|
[InlineData("Critical")] // not in set
|
|
public async Task LogEventAsync_ThrowsOnUnknownSeverity(string badSeverity)
|
|
{
|
|
var ex = await Assert.ThrowsAsync<ArgumentException>(
|
|
() => _logger.LogEventAsync("script", badSeverity, null, "Source", "Message"));
|
|
Assert.Contains(badSeverity, ex.Message);
|
|
Assert.Contains("Info, Warning, Error", ex.Message);
|
|
}
|
|
|
|
/// <summary>Verifies that every documented severity is accepted.</summary>
|
|
/// <param name="severity">The severity.</param>
|
|
/// <returns>A task that represents the asynchronous operation.</returns>
|
|
[Theory]
|
|
[InlineData("Info")]
|
|
[InlineData("Warning")]
|
|
[InlineData("Error")]
|
|
public async Task LogEventAsync_AcceptsAllDocumentedSeverities(string severity)
|
|
{
|
|
await _logger.LogEventAsync("script", severity, null, "Source", "Message");
|
|
|
|
using var cmd = _verifyConnection.CreateCommand();
|
|
cmd.CommandText = "SELECT severity FROM site_events";
|
|
var stored = (string)cmd.ExecuteScalar()!;
|
|
Assert.Equal(severity, stored);
|
|
}
|
|
}
|