using System.Data.Common;
using System.Globalization;
using Microsoft.Data.SqlClient;
using Microsoft.EntityFrameworkCore;
using Xunit;
using ZB.MOM.WW.OtOpcUa.Configuration;
namespace ZB.MOM.WW.OtOpcUa.Configuration.Tests;
///
/// Spins up a dedicated test database, applies the EF migrations against it, and exposes a
/// factory. Disposed at collection teardown (drops the DB).
/// Gated by the OTOPCUA_CONFIG_TEST_SERVER env var so CI runs can opt in explicitly;
/// local runs default to the shared Docker host's SQL Server on 10.100.0.35:14330.
///
public sealed class SchemaComplianceFixture : IDisposable
{
/// The name prefix every Configuration test database carries; also the reaper's LIKE anchor.
internal const string TestDatabasePrefix = "OtOpcUaConfig_Test_";
private const string DefaultServer = "10.100.0.35,14330";
private const string DefaultSaPassword = "OtOpcUaDev_2026!";
/// How long a test database must have existed before the reaper considers it certainly orphaned.
private static readonly TimeSpan OrphanAge = TimeSpan.FromHours(24);
private static readonly Lazy Reaper = new(RunReaper, LazyThreadSafetyMode.ExecutionAndPublication);
/// Gets the name of the test database.
public string DatabaseName { get; }
/// Gets the connection string for the test database.
public string ConnectionString { get; }
/// Initializes a new instance of the SchemaComplianceFixture class.
public SchemaComplianceFixture()
{
var server = Environment.GetEnvironmentVariable("OTOPCUA_CONFIG_TEST_SERVER") ?? DefaultServer;
var saPassword = Environment.GetEnvironmentVariable("OTOPCUA_CONFIG_TEST_SA_PASSWORD") ?? DefaultSaPassword;
// A killed test process never reaches Dispose, so its database outlives the run. Reap the ones old
// enough to be certainly nobody's, once per process. This fixture has no reachability probe, so an
// unreachable server must leave behaviour exactly as it was: the reaper silently does nothing and
// Migrate() below throws as it always has.
_ = Reaper.Value;
DatabaseName = $"{TestDatabasePrefix}{DateTime.UtcNow:yyyyMMddHHmmss}_{Guid.NewGuid():N}";
ConnectionString =
$"Server={server};Database={DatabaseName};User Id=sa;Password={saPassword};TrustServerCertificate=True;Encrypt=False;";
var options = new DbContextOptionsBuilder()
.UseSqlServer(ConnectionString)
.Options;
using var ctx = new OtOpcUaConfigDbContext(options);
ctx.Database.Migrate();
}
/// Opens a new SQL connection to the test database.
/// An open SQL connection.
public SqlConnection OpenConnection()
{
var conn = new SqlConnection(ConnectionString);
conn.Open();
return conn;
}
private static int RunReaper()
{
var server = Environment.GetEnvironmentVariable("OTOPCUA_CONFIG_TEST_SERVER") ?? DefaultServer;
var saPassword = Environment.GetEnvironmentVariable("OTOPCUA_CONFIG_TEST_SA_PASSWORD") ?? DefaultSaPassword;
var master =
$"Server={server};Database=master;User Id=sa;Password={saPassword};TrustServerCertificate=True;Encrypt=False;";
return SqlTestDatabaseReaper.ReapOrphans(master, TestDatabasePrefix, DateTime.UtcNow - OrphanAge).Count;
}
/// Disposes the fixture and drops the test database.
public void Dispose()
{
var masterConnection =
new SqlConnectionStringBuilder(ConnectionString) { InitialCatalog = "master" }.ConnectionString;
using var conn = new SqlConnection(masterConnection);
conn.Open();
using var cmd = conn.CreateCommand();
cmd.CommandText = $@"
IF DB_ID(N'{DatabaseName}') IS NOT NULL
BEGIN
ALTER DATABASE [{DatabaseName}] SET SINGLE_USER WITH ROLLBACK IMMEDIATE;
DROP DATABASE [{DatabaseName}];
END";
cmd.ExecuteNonQuery();
}
}
///
/// Drops test databases that a killed test process left behind on the shared SQL Server.
///
///
///
/// names its database
/// {prefix}{yyyyMMddHHmmss-UTC}_{guid:N} and drops it in Dispose — which a
/// Ctrl-C, a crashed runner or a killed container never reaches, so the database survives
/// forever on an instance nobody gardens.
///
///
/// This is DROP DATABASE against a server other people share, so the rules are deliberately
/// narrow and every one of them is load-bearing:
///
///
/// -
/// the LIKE is an exact prefix with _ escaped (an unescaped _ is a
/// single-character wildcard in T-SQL) — never widen it;
///
/// -
/// a name whose embedded timestamp does not parse is left alone, because an unparseable
/// name is by definition not one this code created;
///
/// -
/// only names strictly older than the cutoff are dropped. At 24 hours that is far beyond
/// any run, so the reaper can never race a live sibling run on the same server; and
///
/// -
/// nothing here ever throws. Unlike this project's Dispose, which deliberately lets a
/// teardown failure surface, opportunistic housekeeping must never fail a green run.
///
///
///
/// Deliberately duplicated from the AdminUI.Tests copy rather than shared: the two suites have no
/// common test-support assembly, and a new one purely for ~100 lines of best-effort housekeeping
/// costs more than the duplication.
///
///
internal static class SqlTestDatabaseReaper
{
private const string TimestampFormat = "yyyyMMddHHmmss";
///
/// Drops every database matching whose embedded creation timestamp is
/// strictly older than .
///
/// A connection string pointed at master.
/// The exact test-database name prefix, e.g. OtOpcUaConfig_Test_.
/// Databases created strictly before this UTC instant are dropped.
/// The names actually dropped; empty when there was nothing to reap or anything went wrong.
internal static IReadOnlyList ReapOrphans(string masterConnectionString, string prefix, DateTime cutoffUtc)
{
var reaped = new List();
try
{
foreach (var name in ListCandidates(masterConnectionString, prefix))
{
if (!TryParseCreatedUtc(name, prefix, out var createdUtc)) continue;
if (createdUtc >= cutoffUtc) continue;
try
{
if (TryDropDatabase(masterConnectionString, name)) reaped.Add(name);
}
catch (Exception)
{
// One stubborn database must not stop the sweep, nor fail the run that triggered it.
}
}
}
catch (Exception)
{
// Enumeration failed (server down, no permission). Reaping is opportunistic housekeeping.
}
if (reaped.Count > 0)
{
Console.WriteLine(
$"[sql-test-reaper] dropped {reaped.Count} orphaned test database(s) older than " +
$"{cutoffUtc:yyyy-MM-dd HH:mm:ss}Z: {string.Join(", ", reaped)}");
}
return reaped;
}
/// Drops the named database, swallowing database errors — reaping is best-effort.
/// A connection string pointed at master.
/// The database to drop.
/// when the statement ran without error.
internal static bool TryDropDatabase(string masterConnectionString, string databaseName)
{
try
{
using var conn = new SqlConnection(masterConnectionString);
conn.Open();
using var cmd = conn.CreateCommand();
cmd.CommandText = $@"
IF DB_ID(N'{databaseName}') IS NOT NULL
BEGIN
ALTER DATABASE [{databaseName}] SET SINGLE_USER WITH ROLLBACK IMMEDIATE;
DROP DATABASE [{databaseName}];
END";
cmd.ExecuteNonQuery();
return true;
}
catch (DbException)
{
return false;
}
}
private static List ListCandidates(string masterConnectionString, string prefix)
{
var names = new List();
using var conn = new SqlConnection(masterConnectionString);
conn.Open();
using var cmd = conn.CreateCommand();
cmd.CommandText = @"SELECT name FROM sys.databases WHERE name LIKE @pattern ESCAPE '\'";
cmd.Parameters.Add(new SqlParameter("@pattern", prefix.Replace("_", @"\_", StringComparison.Ordinal) + "%"));
using var reader = cmd.ExecuteReader();
while (reader.Read()) names.Add(reader.GetString(0));
return names;
}
private static bool TryParseCreatedUtc(string databaseName, string prefix, out DateTime createdUtc)
{
createdUtc = default;
if (!databaseName.StartsWith(prefix, StringComparison.Ordinal)) return false;
var rest = databaseName.AsSpan(prefix.Length);
// Expect exactly "<14-digit timestamp>_" — anything else is not a name this code minted.
if (rest.Length < TimestampFormat.Length + 1 || rest[TimestampFormat.Length] != '_') return false;
return DateTime.TryParseExact(
rest[..TimestampFormat.Length],
TimestampFormat,
CultureInfo.InvariantCulture,
DateTimeStyles.AssumeUniversal | DateTimeStyles.AdjustToUniversal,
out createdUtc);
}
}
[CollectionDefinition(nameof(SchemaComplianceCollection))]
public sealed class SchemaComplianceCollection : ICollectionFixture
{
}