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

217 lines
9.7 KiB
C#

using System.Data.Common;
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;
DatabaseName = $"OtOpcUaAdminUi_Test_{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;
try
{
var master = new SqlConnectionStringBuilder(ConnectionString) { InitialCatalog = "master" }.ConnectionString;
using var conn = new SqlConnection(master);
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();
}
catch (DbException)
{
// 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 identifiable.
}
}
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
{
private const string DefaultServer = "10.100.0.35,14330";
private const string DefaultSaPassword = "OtOpcUaDev_2026!";
private const int ProbeTimeoutSeconds = 3;
private static readonly Lazy<string?> Probe = new(RunProbe, 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>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 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>
/// 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>
{
}