f2efeb37b7
Tasks 5 and 6 of the Phase 2 plan, committed together because their test
fallout is entangled — several fixtures construct both stores.
StoreAndForwardStorage and SiteStorageService now take ILocalDb. Connections
come from ILocalDb.CreateConnection(), which hands out an already-open,
pragma-configured connection carrying the zb_hlc_next() UDF the capture triggers
call; a raw connection would lack the UDF and every write to a replicated table
would fail closed. Deleted with the connection strings: S&F's
EnsureDatabaseDirectoryExists and its per-open busy_timeout pragma, and the site
service's BusyTimeoutFloorSeconds normalization — LocalDb owns all of it now.
DI: AddSiteRuntime's string overload is gone (nothing left to supply), so the
Host calls the no-arg form. ScadaBridge:Database:SiteDbPath and
StoreAndForwardOptions.SqliteDbPath survive only as the migrator's source
locations in Tasks 8/9.
Two things the plan did not anticipate, both worth reading:
1. FOUND A REAL LATENT DEFECT, from Phase 1, now fixed. The plan assumed
directory creation simply moved to LocalDb along with file ownership. It did
not: the LocalDb library never creates the parent directory, and
SqliteLocalDb opens the file eagerly in its constructor — so a missing
directory is a hard boot failure ("SQLite Error 14: unable to open database
file"), not a degraded start. The default site config points at the RELATIVE
path ./data/site-localdb.db, so any site node without a pre-existing data/
directory fails to boot. The docker rig escapes only because its volume mount
happens to create /app/data — a coincidence that would have hidden this until
a bare-metal or fresh deployment. This has been latent since Phase 1 made
LocalDb:Path required; deleting S&F's EnsureDatabaseDirectoryExists here
would have widened it. Re-established the guarantee at the layer that now
owns the path (SiteLocalDbDirectory.Ensure, called before AddZbLocalDb) and
pinned it with SiteLocalDbDirectoryTests. Non-vacuity is not assumed: two
tests written against the wrong assumption failed with exactly this
SQLite Error 14 before the fix existed.
2. Test fallout was ~7x the plan's estimate. The plan named "fixtures" in one
project; the constructor change actually reaches 40 files across 7 test
projects, and most used Mode=Memory;Cache=Shared — which LocalDb has no
equivalent for, so every one had to move to a real temp file. Rather than
copy the Phase 1 TestLocalDb fixture into 7 projects, added a shared
tests/ZB.MOM.WW.ScadaBridge.TestSupport library (not a test project) so the
WAL-sidecar cleanup and the "real, not stubbed" rationale live in one place.
Retargeted rather than deleted, in both directions: the S&F WAL test now asserts
against the LocalDb-backed store (WAL genuinely is LocalDb's job), while the
directory-creation test moved to Host.Tests (that guarantee is NOT LocalDb's).
SiteStorageServiceTests.Initialize_EnablesWalJournalMode got the same treatment.
DeploymentManagerMediumFindingsTests induced a persistence failure via an
unopenable path, which no longer reaches the assertion since the fixture now
throws first; it induces the same failure shape via an uninitialized store.
Verified: full solution build 0 warnings; SiteRuntime 532, Host 318,
AuditLog 355, ExternalSystemGateway 142, HealthMonitoring 97,
StoreAndForward 153 — 1597 passed, 0 failed.
Claude-Session: https://claude.ai/code/session_01BL2Vu1ESDQ9SCN4gVKkdts
224 lines
8.7 KiB
C#
224 lines
8.7 KiB
C#
using Microsoft.Extensions.Logging.Abstractions;
|
|
using ZB.MOM.WW.ScadaBridge.SiteRuntime.Persistence;
|
|
using ZB.MOM.WW.ScadaBridge.TestSupport;
|
|
|
|
namespace ZB.MOM.WW.ScadaBridge.SiteRuntime.Tests.Persistence;
|
|
|
|
/// <summary>
|
|
/// WP-33: Local Artifact Storage tests — shared scripts, external systems,
|
|
/// database connections, notification lists.
|
|
/// </summary>
|
|
/// <remarks>
|
|
/// Backed by a real temp-file LocalDb: <see cref="SiteStorageService"/> takes an
|
|
/// <c>ILocalDb</c> rather than a connection string, and LocalDb has no in-memory mode.
|
|
/// </remarks>
|
|
public class ArtifactStorageTests : IAsyncLifetime, IDisposable
|
|
{
|
|
private readonly TestLocalDb _localDb;
|
|
private SiteStorageService _storage = null!;
|
|
|
|
public ArtifactStorageTests()
|
|
{
|
|
_localDb = TestLocalDb.CreateTemp("artifact-test");
|
|
}
|
|
|
|
public async Task InitializeAsync()
|
|
{
|
|
_storage = new SiteStorageService(
|
|
_localDb.Db,
|
|
NullLogger<SiteStorageService>.Instance);
|
|
await _storage.InitializeAsync();
|
|
}
|
|
|
|
public Task DisposeAsync() => Task.CompletedTask;
|
|
|
|
public void Dispose()
|
|
{
|
|
// Dispose first — the master connection anchors the WAL, so the sidecars
|
|
// cannot be removed while it is open.
|
|
var path = _localDb.Path;
|
|
_localDb.Dispose();
|
|
TestLocalDb.DeleteFiles(path);
|
|
}
|
|
|
|
// ── Shared Script Storage ──
|
|
|
|
[Fact]
|
|
public async Task StoreSharedScript_RoundTrips()
|
|
{
|
|
await _storage.StoreSharedScriptAsync("CalcAvg", "return 42;", "{}", "int");
|
|
|
|
var scripts = await _storage.GetAllSharedScriptsAsync();
|
|
Assert.Single(scripts);
|
|
Assert.Equal("CalcAvg", scripts[0].Name);
|
|
Assert.Equal("return 42;", scripts[0].Code);
|
|
Assert.Equal("{}", scripts[0].ParameterDefinitions);
|
|
Assert.Equal("int", scripts[0].ReturnDefinition);
|
|
}
|
|
|
|
[Fact]
|
|
public async Task StoreSharedScript_Upserts_OnConflict()
|
|
{
|
|
await _storage.StoreSharedScriptAsync("CalcAvg", "return 1;", null, null);
|
|
await _storage.StoreSharedScriptAsync("CalcAvg", "return 2;", "{\"x\":\"int\"}", "int");
|
|
|
|
var scripts = await _storage.GetAllSharedScriptsAsync();
|
|
Assert.Single(scripts);
|
|
Assert.Equal("return 2;", scripts[0].Code);
|
|
Assert.Equal("{\"x\":\"int\"}", scripts[0].ParameterDefinitions);
|
|
}
|
|
|
|
[Fact]
|
|
public async Task StoreSharedScript_MultipleScripts()
|
|
{
|
|
await _storage.StoreSharedScriptAsync("Script1", "1", null, null);
|
|
await _storage.StoreSharedScriptAsync("Script2", "2", null, null);
|
|
await _storage.StoreSharedScriptAsync("Script3", "3", null, null);
|
|
|
|
var scripts = await _storage.GetAllSharedScriptsAsync();
|
|
Assert.Equal(3, scripts.Count);
|
|
}
|
|
|
|
[Fact]
|
|
public async Task StoreSharedScript_NullableFields()
|
|
{
|
|
await _storage.StoreSharedScriptAsync("Simple", "42", null, null);
|
|
|
|
var scripts = await _storage.GetAllSharedScriptsAsync();
|
|
Assert.Single(scripts);
|
|
Assert.Null(scripts[0].ParameterDefinitions);
|
|
Assert.Null(scripts[0].ReturnDefinition);
|
|
}
|
|
|
|
// ── External System Storage ──
|
|
|
|
[Fact]
|
|
public async Task StoreExternalSystem_DoesNotThrow()
|
|
{
|
|
await _storage.StoreExternalSystemAsync(
|
|
"WeatherAPI", "https://api.weather.com",
|
|
"ApiKey", "{\"key\":\"abc\"}", "{\"getForecast\":{}}");
|
|
|
|
// No exception = success. Query verification would need a Get method.
|
|
}
|
|
|
|
[Fact]
|
|
public async Task StoreExternalSystem_Upserts()
|
|
{
|
|
await _storage.StoreExternalSystemAsync("API1", "https://v1", "Basic", null, null);
|
|
await _storage.StoreExternalSystemAsync("API1", "https://v2", "ApiKey", "{}", null);
|
|
|
|
// Upsert should not throw
|
|
}
|
|
|
|
// ── Database Connection Storage ──
|
|
|
|
[Fact]
|
|
public async Task StoreDatabaseConnection_DoesNotThrow()
|
|
{
|
|
await _storage.StoreDatabaseConnectionAsync(
|
|
"MainDB", "Server=localhost;Database=main", 3, TimeSpan.FromSeconds(1));
|
|
}
|
|
|
|
[Fact]
|
|
public async Task StoreDatabaseConnection_Upserts()
|
|
{
|
|
await _storage.StoreDatabaseConnectionAsync(
|
|
"DB1", "Server=old", 3, TimeSpan.FromSeconds(1));
|
|
await _storage.StoreDatabaseConnectionAsync(
|
|
"DB1", "Server=new", 5, TimeSpan.FromSeconds(2));
|
|
|
|
// Upsert should not throw
|
|
}
|
|
|
|
// ── DeploymentManager-025 / SiteRuntime-031: central-only notif/SMTP purge ──
|
|
//
|
|
// Notification config is central-only. The site-side write paths and
|
|
// SiteNotificationRepository were removed 2026-07-10 (arch-review 08 §1.3/#23);
|
|
// PurgeCentralOnlyNotificationConfigAsync is retained as the security cleanup for
|
|
// DBs written by older builds. These tests seed the (still-present) tables via raw
|
|
// SQL — the only way rows can now exist — and assert the purge empties them.
|
|
|
|
private async Task SeedNotificationRowAsync(string name, string emailsJson)
|
|
{
|
|
// Seeded through the service's own (already-open) LocalDb connection — a raw
|
|
// SqliteConnection would lack the pragmas and the zb_hlc_next() UDF the site
|
|
// tables' capture triggers call.
|
|
await using var connection = _storage.CreateConnection();
|
|
await using var command = connection.CreateCommand();
|
|
command.CommandText =
|
|
"INSERT INTO notification_lists (name, recipient_emails, updated_at) VALUES (@n, @e, @u)";
|
|
command.Parameters.AddWithValue("@n", name);
|
|
command.Parameters.AddWithValue("@e", emailsJson);
|
|
command.Parameters.AddWithValue("@u", DateTimeOffset.UtcNow.ToString("O"));
|
|
await command.ExecuteNonQueryAsync();
|
|
}
|
|
|
|
private async Task SeedSmtpRowAsync(string name, string password)
|
|
{
|
|
await using var connection = _storage.CreateConnection();
|
|
await using var command = connection.CreateCommand();
|
|
command.CommandText =
|
|
@"INSERT INTO smtp_configurations (name, server, port, auth_mode, from_address, username, password, oauth_config, updated_at)
|
|
VALUES (@n, 'smtp.example.com', 587, 'BasicAuth', 'noreply@example.com', 'smtpuser', @p, NULL, @u)";
|
|
command.Parameters.AddWithValue("@n", name);
|
|
command.Parameters.AddWithValue("@p", password);
|
|
command.Parameters.AddWithValue("@u", DateTimeOffset.UtcNow.ToString("O"));
|
|
await command.ExecuteNonQueryAsync();
|
|
}
|
|
|
|
private async Task<long> RowCountAsync(string table)
|
|
{
|
|
await using var connection = _storage.CreateConnection();
|
|
await using var command = connection.CreateCommand();
|
|
command.CommandText = $"SELECT COUNT(*) FROM {table}";
|
|
return (long)(await command.ExecuteScalarAsync())!;
|
|
}
|
|
|
|
[Fact]
|
|
public async Task PurgeCentralOnlyNotificationConfig_RemovesPersistedNotificationListsAndSmtpRows()
|
|
{
|
|
// Simulate a pre-fix build that already shipped a notification list and an
|
|
// SMTP config (with a plaintext password) to the site.
|
|
await SeedNotificationRowAsync("Ops Team", "[\"ops@example.com\"]");
|
|
await SeedSmtpRowAsync("smtp.example.com:587", "PLAINTEXT-SECRET");
|
|
|
|
Assert.Equal(1, await RowCountAsync("notification_lists"));
|
|
Assert.Equal(1, await RowCountAsync("smtp_configurations"));
|
|
|
|
// The fix: every artifact apply/deploy purges these central-only rows.
|
|
await _storage.PurgeCentralOnlyNotificationConfigAsync();
|
|
|
|
// Both tables are now empty — the plaintext SMTP credential is gone.
|
|
Assert.Equal(0, await RowCountAsync("notification_lists"));
|
|
Assert.Equal(0, await RowCountAsync("smtp_configurations"));
|
|
}
|
|
|
|
[Fact]
|
|
public async Task PurgeCentralOnlyNotificationConfig_IsIdempotent_OnEmptyTables()
|
|
{
|
|
// No rows present — purge must not throw and must leave the tables empty.
|
|
await _storage.PurgeCentralOnlyNotificationConfigAsync();
|
|
await _storage.PurgeCentralOnlyNotificationConfigAsync();
|
|
|
|
Assert.Equal(0, await RowCountAsync("notification_lists"));
|
|
Assert.Equal(0, await RowCountAsync("smtp_configurations"));
|
|
}
|
|
|
|
// ── Schema includes all WP-33 tables ──
|
|
|
|
[Fact]
|
|
public async Task Initialize_CreatesAllArtifactTables()
|
|
{
|
|
// The initialize already ran. Verify by storing to each table.
|
|
await _storage.StoreSharedScriptAsync("s", "code", null, null);
|
|
await _storage.StoreExternalSystemAsync("e", "url", "None", null, null);
|
|
await _storage.StoreDatabaseConnectionAsync("d", "connstr", 1, TimeSpan.Zero);
|
|
|
|
// notification_lists / smtp_configurations remain in the schema (kept for the
|
|
// security purge) — their presence is exercised by the purge tests above.
|
|
|
|
// All succeeded without exceptions = tables exist
|
|
}
|
|
}
|