Files
lmxopcua/tests/Server/ZB.MOM.WW.OtOpcUa.AdminUI.Tests/AdminUiSqlServerFixture.cs
T

403 lines
19 KiB
C#

using System.Globalization;
using Microsoft.Data.SqlClient;
using Microsoft.EntityFrameworkCore;
using Xunit;
using ZB.MOM.WW.OtOpcUa.Configuration;
namespace ZB.MOM.WW.OtOpcUa.AdminUI.Tests;
/// <summary>
/// A real SQL Server database for the handful of AdminUI tests whose subject is the SQL Server
/// provider's LINQ <b>translation</b> rather than the C# around it — EF InMemory evaluates those
/// queries in-process, so it can neither fail on an untranslatable shape nor reproduce SQL Server's
/// collation semantics. Creates a uniquely-named database, applies the EF migrations to it, and drops
/// it at collection teardown.
/// </summary>
/// <remarks>
/// <para>
/// Shaped after <c>ZB.MOM.WW.OtOpcUa.Configuration.Tests.SchemaComplianceFixture</c> (same env
/// vars, same unique-name + <c>Migrate()</c> + drop-via-master lifecycle) with <b>one deliberate
/// deviation</b>: that fixture lets the connection failure surface as a constructor throw, so
/// Configuration.Tests fails hard when SQL Server is unreachable. AdminUI.Tests is an ordinary
/// unit suite that must stay green offline, so this fixture probes reachability FIRST and records
/// a <see cref="SkipReason"/> instead of throwing. Tests carry <see cref="SqlServerFactAttribute"/>,
/// which skips them when the probe failed.
/// </para>
/// <para>
/// The skip is an attribute rather than the <c>Assert.Skip(fixture.SkipReason)</c> call the S7
/// integration suite uses, because AdminUI.Tests is one of the three projects pinned to
/// <b>xunit v2</b> by <c>Akka.TestKit.Xunit2</c> (see <c>Directory.Packages.props</c>) and
/// <c>Assert.Skip</c> is xunit v3 only. Overriding <c>FactAttribute.Skip</c> is the v2 equivalent
/// and reports a genuine "skipped", not a vacuous pass. Both the attribute and this fixture read
/// the same one-shot probe in <see cref="AdminUiSqlServer"/>, so a session probes once.
/// </para>
/// <para>
/// The probe being <b>one-shot</b> bounds what "stays green offline" guarantees: it covers SQL
/// being unreachable <i>before the run</i>. A connectivity blip <i>during</i> a run is never
/// re-probed, so the affected tests surface as <c>SqlException</c> <b>failures</b>, not skips.
/// </para>
/// <para>
/// Every test in the collection shares ONE database (migrating is the expensive part), so tests
/// must isolate themselves by seeding uniquely-named rows, or by clearing the table they measure.
/// xunit serialises a collection's tests, so a clear-then-seed is safe.
/// </para>
/// </remarks>
public sealed class AdminUiSqlServerFixture : IDisposable
{
/// <summary>Gets the name of the per-run test database, or <see langword="null"/> when SQL is unreachable.</summary>
public string? DatabaseName { get; }
/// <summary>Gets the connection string for the test database, or <see langword="null"/> when SQL is unreachable.</summary>
public string? ConnectionString { get; }
/// <summary>
/// Gets the reason the SQL-backed tests cannot run (server unreachable, migration failed), or
/// <see langword="null"/> when the database is ready.
/// </summary>
public string? SkipReason { get; }
/// <summary>
/// Gets a context factory pointed at the migrated test database — the seam the services under test
/// (<c>DeploymentDriftProbe</c>, <c>RawTreeService</c>) take. Throws when <see cref="SkipReason"/>
/// is set; guard with <see cref="SqlServerFactAttribute"/>.
/// </summary>
public IDbContextFactory<OtOpcUaConfigDbContext> Factory =>
_factory ?? throw new InvalidOperationException(SkipReason ?? "SQL Server fixture is not available.");
private readonly SqlServerContextFactory? _factory;
/// <summary>Initializes a new instance of the <see cref="AdminUiSqlServerFixture"/> class.</summary>
public AdminUiSqlServerFixture()
{
// Probe FIRST — see the remarks. A dead server must leave this constructor without throwing,
// because xunit builds collection fixtures before it discovers that every test is skipped.
SkipReason = AdminUiSqlServer.SkipReason;
if (SkipReason is not null) return;
// 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, and only after the probe answered).
AdminUiSqlServer.ReapOrphanedTestDatabasesOnce();
// Mint from the same constant the reaper's LIKE anchors on — a rename that touched only one of the
// two would leave every future database unreapable, with nothing to signal it.
DatabaseName =
$"{AdminUiSqlServer.TestDatabasePrefix}{DateTime.UtcNow:yyyyMMddHHmmss}_{Guid.NewGuid():N}";
ConnectionString = AdminUiSqlServer.ConnectionStringFor(DatabaseName);
try
{
var options = new DbContextOptionsBuilder<OtOpcUaConfigDbContext>()
.UseSqlServer(ConnectionString)
.Options;
using var ctx = new OtOpcUaConfigDbContext(options);
ctx.Database.Migrate();
}
catch (Exception ex)
{
// A half-created database would leak, so tear it down before standing the suite down.
TryDropDatabase();
SkipReason = $"Could not migrate the AdminUI SQL test database: {ex.Message}";
DatabaseName = null;
ConnectionString = null;
return;
}
_factory = new SqlServerContextFactory(ConnectionString);
}
/// <summary>Disposes the fixture, dropping the test database.</summary>
public void Dispose() => TryDropDatabase();
private void TryDropDatabase()
{
if (ConnectionString is null || DatabaseName is null) return;
var master = new SqlConnectionStringBuilder(ConnectionString) { InitialCatalog = "master" }.ConnectionString;
SqlTestDatabaseReaper.TryDropDatabase(master, DatabaseName);
}
private sealed class SqlServerContextFactory(string connectionString)
: IDbContextFactory<OtOpcUaConfigDbContext>
{
public OtOpcUaConfigDbContext CreateDbContext() =>
new(new DbContextOptionsBuilder<OtOpcUaConfigDbContext>()
.UseSqlServer(connectionString)
.Options);
public Task<OtOpcUaConfigDbContext> CreateDbContextAsync(CancellationToken cancellationToken = default) =>
Task.FromResult(CreateDbContext());
}
}
/// <summary>
/// One-shot reachability probe + connection-string builder shared by
/// <see cref="AdminUiSqlServerFixture"/> and <see cref="SqlServerFactAttribute"/>. The attribute is
/// constructed at discovery time and the fixture at collection start, so the probe must be cached or
/// a run pays the connect timeout twice.
/// </summary>
internal static class AdminUiSqlServer
{
/// <summary>The name prefix every AdminUI test database carries; also the reaper's LIKE anchor.</summary>
public const string TestDatabasePrefix = "OtOpcUaAdminUi_Test_";
private const string DefaultServer = "10.100.0.35,14330";
private const string DefaultSaPassword = "OtOpcUaDev_2026!";
private const int ProbeTimeoutSeconds = 3;
/// <summary>How long a test database must have existed before the reaper considers it certainly orphaned.</summary>
private static readonly TimeSpan OrphanAge = TimeSpan.FromHours(24);
private static readonly Lazy<string?> Probe = new(RunProbe, LazyThreadSafetyMode.ExecutionAndPublication);
private static readonly Lazy<int> Reaper = new(RunReaper, LazyThreadSafetyMode.ExecutionAndPublication);
/// <summary>Gets the reason SQL Server is unusable, or <see langword="null"/> when it answered.</summary>
public static string? SkipReason => Probe.Value;
/// <summary>
/// Reaps orphaned AdminUI test databases older than 24 hours, at most once per process. Call only
/// after <see cref="SkipReason"/> came back <see langword="null"/> — the reaper never throws, but
/// against a dead server it would just burn a connect timeout for nothing.
/// </summary>
public static void ReapOrphanedTestDatabasesOnce() => _ = Reaper.Value;
/// <summary>Builds a connection string for the named database on the configured test server.</summary>
/// <param name="database">The database to connect to.</param>
/// <returns>The connection string.</returns>
public static string ConnectionStringFor(string database)
{
var server = Environment.GetEnvironmentVariable("OTOPCUA_CONFIG_TEST_SERVER") ?? DefaultServer;
var password = Environment.GetEnvironmentVariable("OTOPCUA_CONFIG_TEST_SA_PASSWORD") ?? DefaultSaPassword;
return $"Server={server};Database={database};User Id=sa;Password={password};" +
"TrustServerCertificate=True;Encrypt=False;";
}
private static int RunReaper() =>
SqlTestDatabaseReaper.ReapOrphans(
ConnectionStringFor("master"),
TestDatabasePrefix,
DateTime.UtcNow - OrphanAge).Count;
private static string? RunProbe()
{
var server = Environment.GetEnvironmentVariable("OTOPCUA_CONFIG_TEST_SERVER") ?? DefaultServer;
try
{
var probe = new SqlConnectionStringBuilder(ConnectionStringFor("master"))
{
ConnectTimeout = ProbeTimeoutSeconds,
}.ConnectionString;
using var conn = new SqlConnection(probe);
conn.Open();
return null;
}
catch (Exception ex)
{
return $"SQL Server at '{server}' is unreachable ({ex.GetType().Name}: {ex.Message}); " +
"set OTOPCUA_CONFIG_TEST_SERVER / OTOPCUA_CONFIG_TEST_SA_PASSWORD to point at a reachable instance.";
}
}
}
/// <summary>
/// Drops test databases that a killed test process left behind on the <b>shared</b> SQL Server.
/// </summary>
/// <remarks>
/// <para>
/// Every fixture here names its database <c>{prefix}{yyyyMMddHHmmss-UTC}_{guid:N}</c> and drops it
/// in <c>Dispose</c> — which a <c>Ctrl-C</c>, a crashed runner or a killed container never reaches,
/// so the database survives forever on an instance nobody gardens.
/// </para>
/// <para>
/// This is <c>DROP DATABASE</c> against a server other people share, so the rules are deliberately
/// narrow and every one of them is load-bearing:
/// </para>
/// <list type="bullet">
/// <item>
/// the <c>LIKE</c> is an <b>exact prefix</b> with <c>_</c> escaped (an unescaped <c>_</c> is a
/// single-character wildcard in T-SQL) — never widen it;
/// </item>
/// <item>
/// a matching name is dropped only when its <b>whole</b> shape is one this code could have
/// minted — prefix, a parseable 14-digit UTC timestamp, <c>_</c>, then 32 hex digits. That is
/// belt <i>and</i> braces against second-order injection: the name is also passed as a
/// <b>parameter</b> through <c>QUOTENAME</c> rather than interpolated into DDL, but the shape
/// check independently guarantees a candidate cannot contain <c>]</c> or <c>'</c>;
/// </item>
/// <item>
/// only names <b>strictly older than the cutoff</b> 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
/// </item>
/// <item>
/// nothing here ever throws. A reaper that fails a green run would be worse than the leak it
/// cleans up.
/// </item>
/// </list>
/// </remarks>
internal static class SqlTestDatabaseReaper
{
private const string TimestampFormat = "yyyyMMddHHmmss";
private const int ConnectTimeoutSeconds = 3;
/// <summary>
/// Drops every database matching <paramref name="prefix"/> whose embedded creation timestamp is
/// strictly older than <paramref name="cutoffUtc"/>.
/// </summary>
/// <param name="masterConnectionString">A connection string pointed at <c>master</c>.</param>
/// <param name="prefix">The exact test-database name prefix, e.g. <c>OtOpcUaAdminUi_Test_</c>.</param>
/// <param name="cutoffUtc">Databases created strictly before this UTC instant are dropped.</param>
/// <returns>The names actually dropped; empty when there was nothing to reap or anything went wrong.</returns>
internal static IReadOnlyList<string> ReapOrphans(string masterConnectionString, string prefix, DateTime cutoffUtc)
{
var reaped = new List<string>();
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;
}
/// <summary>
/// Drops the named database, swallowing every failure — this is called unwrapped from
/// <c>Dispose</c> and from test <c>finally</c> blocks, so it must be genuinely best-effort.
/// </summary>
/// <remarks>
/// The database name is an <b>identifier</b>, which cannot be parameterised directly, so it rides
/// in as a parameter and <c>QUOTENAME</c> escapes it server-side. Interpolating it into the DDL
/// instead would make any attacker-chosen database name on this shared server a second-order
/// injection executed as <c>sa</c>.
/// </remarks>
/// <param name="masterConnectionString">A connection string pointed at <c>master</c>.</param>
/// <param name="databaseName">The database to drop.</param>
/// <returns><see langword="true"/> when the statement ran without error.</returns>
internal static bool TryDropDatabase(string masterConnectionString, string databaseName)
{
try
{
using var conn = new SqlConnection(masterConnectionString);
conn.Open();
using var cmd = conn.CreateCommand();
// The QUOTENAME result must be assembled into a variable first: EXEC(<string>) accepts only a
// concatenation of literals and variables, so the tempting one-liner
// EXEC('ALTER DATABASE ' + QUOTENAME(@name) + …) is a syntax error, not a subtle bug.
cmd.CommandText = @"
DECLARE @sql nvarchar(max);
IF DB_ID(@name) IS NOT NULL
BEGIN
SET @sql = N'ALTER DATABASE ' + QUOTENAME(@name) + N' SET SINGLE_USER WITH ROLLBACK IMMEDIATE; ' +
N'DROP DATABASE ' + QUOTENAME(@name) + N';';
EXEC sp_executesql @sql;
END";
cmd.Parameters.Add(new SqlParameter("@name", databaseName));
cmd.ExecuteNonQuery();
return true;
}
catch (Exception)
{
// Teardown is best-effort: a dropped connection here must not fail an otherwise-green run.
// The database name carries a timestamp, so a leaked one is reaped by the next run instead.
return false;
}
}
private static List<string> ListCandidates(string masterConnectionString, string prefix)
{
var names = new List<string>();
// A short connect timeout, because this runs BEFORE whatever the fixture does next: on an
// unreachable server the default ~15 s would simply be added to the latency the caller already pays.
var probe = new SqlConnectionStringBuilder(masterConnectionString)
{
ConnectTimeout = ConnectTimeoutSeconds,
}.ConnectionString;
using var conn = new SqlConnection(probe);
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>_<32 hex digits>" — anything else is not a name this code
// minted. Validating the GUID tail is what bounds the character set of every candidate name: a
// "N"-format GUID is hex only, so no candidate can carry a ']' or a quote into the drop statement.
if (rest.Length < TimestampFormat.Length + 1 || rest[TimestampFormat.Length] != '_') return false;
if (!Guid.TryParseExact(rest[(TimestampFormat.Length + 1)..], "N", out _)) return false;
return DateTime.TryParseExact(
rest[..TimestampFormat.Length],
TimestampFormat,
CultureInfo.InvariantCulture,
DateTimeStyles.AssumeUniversal | DateTimeStyles.AdjustToUniversal,
out createdUtc);
}
}
/// <summary>
/// A <see cref="FactAttribute"/> that skips itself when the shared test SQL Server is unreachable.
/// The xunit v2 equivalent of xunit v3's <c>Assert.Skip</c> — see
/// <see cref="AdminUiSqlServerFixture"/>'s remarks for why this project cannot use the latter.
/// </summary>
[AttributeUsage(AttributeTargets.Method)]
public sealed class SqlServerFactAttribute : FactAttribute
{
/// <summary>Initializes a new instance of the <see cref="SqlServerFactAttribute"/> class.</summary>
public SqlServerFactAttribute()
{
if (AdminUiSqlServer.SkipReason is { } reason) Skip = reason;
}
}
/// <summary>Collection definition binding the SQL-backed AdminUI tests to one shared database.</summary>
[CollectionDefinition(nameof(AdminUiSqlServerCollection))]
public sealed class AdminUiSqlServerCollection : ICollectionFixture<AdminUiSqlServerFixture>
{
}