using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using ZB.MOM.WW.LocalDb;
namespace ZB.MOM.WW.ScadaBridge.Host.Tests;
///
/// Pins that a site node creates the directory holding LocalDb:Path before the
/// database is opened.
///
///
///
/// The guarantee has now had three owners: StoreAndForwardStorage created the
/// directory for its own SQLite file, LocalDb Phase 2 folded that file into the
/// consolidated database and the Host took it over as a SiteLocalDbDirectory shim,
/// and LocalDb 0.1.1 took it into the library itself. This test survived all three moves
/// unchanged in intent, because what a site node needs is the OUTCOME — resolving
/// ILocalDb from the site registration must not fail on a fresh machine — not any
/// particular implementer of it. It is deliberately written against the registration path
/// rather than the mechanism, so a future move costs nothing here.
///
///
/// This is not hypothetical: the default site configuration points at the relative
/// path ./data/site-localdb.db, so any site node whose working directory has no
/// data/ subdirectory hits it. The docker rig escapes only because its volume mount
/// creates /app/data — which is exactly the kind of coincidence that hides a defect
/// until a bare-metal or fresh deployment.
///
///
public class SiteLocalDbDirectoryTests
{
[Fact]
public void SiteRegistration_CreatesTheLocalDbDirectory_WhenItDoesNotExist()
{
var root = Path.Combine(Path.GetTempPath(), "localdb-dir-test-" + Guid.NewGuid().ToString("N"));
var dbPath = Path.Combine(root, "nested", "site-localdb.db");
Assert.False(Directory.Exists(root));
try
{
var config = new ConfigurationBuilder()
.AddInMemoryCollection(new Dictionary
{
["LocalDb:Path"] = dbPath,
})
.Build();
// The registration path under test. Resolving ILocalDb is what actually opens
// the file, so this fails with SQLite Error 14 if the directory step regresses
// — wherever it lives.
var services = new ServiceCollection();
services.AddZbLocalDb(config);
using var provider = services.BuildServiceProvider();
using var scope = provider.CreateScope();
var db = scope.ServiceProvider.GetRequiredService();
Assert.NotNull(db);
Assert.True(Directory.Exists(Path.GetDirectoryName(dbPath)!));
Assert.True(File.Exists(dbPath));
}
finally
{
SqliteConnectionPoolCleanup();
if (Directory.Exists(root))
Directory.Delete(root, recursive: true);
}
}
private static void SqliteConnectionPoolCleanup() =>
Microsoft.Data.Sqlite.SqliteConnection.ClearAllPools();
}