Files
lmxopcua/tests/Server/ZB.MOM.WW.OtOpcUa.AdminUI.Tests/Pages/ClusterNodeEditConcurrencySqlServerTests.cs
T
Joseph Doherty 49213e52e4 test(config): #1049 real-DB DanglingReference race + snapshot isolation; NodeEdit/ClusterEdit stale-token and delete against SQL Server
DanglingReferenceSqlServerTests: the review's emptiness-check/add/delete race interleaved on two
real connections commits both and the deploy snapshot names the orphan; a consistent device+tag
commit landing mid-read (after Devices, before Tags) is invisible under the factory's SNAPSHOT
transaction, while the same interleave read READ COMMITTED produces exactly the false
DanglingReference (positive control).

ClusterNodeEditConcurrencySqlServerTests (bUnit on the AdminUI SQL fixture — InMemory generates no
rowversion and has no FKs): stale-token saves on NodeEdit/ClusterEdit are refused and the other
user's edit survives, current-token saves succeed, a deployed node deletes with its
NodeDeploymentState rows, a cluster with nodes is not deleted and the page says why.
2026-12-03 15:18:16 -05:00

203 lines
9.1 KiB
C#

using Bunit;
using Microsoft.AspNetCore.Components.Authorization;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.DependencyInjection;
using Shouldly;
using Xunit;
using ZB.MOM.WW.OtOpcUa.AdminUI.Components.Pages.Clusters;
using ZB.MOM.WW.OtOpcUa.Configuration;
using ZB.MOM.WW.OtOpcUa.Configuration.Entities;
using ZB.MOM.WW.OtOpcUa.Configuration.Enums;
namespace ZB.MOM.WW.OtOpcUa.AdminUI.Tests.Pages;
/// <summary>
/// lmxopcua#1049 (#998 C-9 follow-up): the NodeEdit / ClusterEdit pages against a REAL SQL Server, where
/// <c>rowversion</c> is generated and the Restrict FKs exist (the InMemory provider has neither). A save carrying
/// the token the page loaded is refused once another user has changed the row — the other user's edit survives —
/// and a save with a current token succeeds; a node that was deployed to deletes together with its
/// <c>NodeDeploymentState</c> rows; a cluster that still has nodes is not deleted and the page says why.
/// </summary>
[Collection(nameof(AdminUiSqlServerCollection))]
public sealed class ClusterNodeEditConcurrencySqlServerTests : BunitContext
{
private const string ModalSelector = ".modal-dialog";
private readonly AdminUiSqlServerFixture _sql;
/// <summary>Registers the fixture's SQL-backed context factory (when the server is available).</summary>
/// <param name="sql">The AdminUI SQL Server fixture.</param>
public ClusterNodeEditConcurrencySqlServerTests(AdminUiSqlServerFixture sql)
{
_sql = sql;
JSInterop.Setup<bool>("otDialog.activate", _ => true).SetResult(true);
JSInterop.SetupVoid("otDialog.update", _ => true).SetVoidResult();
JSInterop.SetupVoid("otDialog.deactivate", _ => true).SetVoidResult();
if (sql.SkipReason is null) Services.AddSingleton(sql.Factory);
Services.AddSingleton<AuthenticationStateProvider>(new FakeAuth());
}
private static string Id(string prefix) => $"{prefix}-{Guid.NewGuid():N}"[..(prefix.Length + 21)];
private string SeedCluster()
{
var clusterId = Id("C");
using var db = _sql.Factory.CreateDbContext();
db.ServerClusters.Add(new ServerCluster
{
ClusterId = clusterId, Name = Id("Cluster"), Enterprise = "zb", Site = "s1", NodeCount = 1,
RedundancyMode = RedundancyMode.None, CreatedBy = "t1049",
});
db.SaveChanges();
return clusterId;
}
private string SeedNode(string clusterId)
{
var nodeId = Id("n");
using var db = _sql.Factory.CreateDbContext();
db.ClusterNodes.Add(new ClusterNode
{
NodeId = nodeId, ClusterId = clusterId, Host = "h-original", ApplicationUri = "urn:" + nodeId, CreatedBy = "t1049",
});
db.SaveChanges();
return nodeId;
}
/// <summary>Another user's committed edit, on its own context.</summary>
private void ConcurrentEdit(Action<OtOpcUaConfigDbContext> edit)
{
using var db = _sql.Factory.CreateDbContext();
edit(db);
db.SaveChanges();
}
/// <summary>NodeEdit: a stale token is refused with the concurrency message; the other user's edit survives.</summary>
[SqlServerFact]
public void NodeEdit_save_with_a_stale_token_is_refused()
{
var clusterId = SeedCluster();
var nodeId = SeedNode(clusterId);
var cut = Render<NodeEdit>(p => p.Add(x => x.ClusterId, clusterId).Add(x => x.NodeId, nodeId));
cut.WaitForAssertion(() => cut.Find("#host").GetAttribute("value").ShouldBe("h-original"));
ConcurrentEdit(db => db.ClusterNodes.Single(n => n.NodeId == nodeId).Host = "h-other-user");
cut.Find("#host").Change("h-stale");
cut.Find("form").Submit();
cut.WaitForAssertion(() => cut.Markup.ShouldContain("Another user changed this node"));
using var db = _sql.Factory.CreateDbContext();
db.ClusterNodes.AsNoTracking().Single(n => n.NodeId == nodeId).Host.ShouldBe("h-other-user");
}
/// <summary>Positive control: with no concurrent edit the same save goes through.</summary>
[SqlServerFact]
public void NodeEdit_save_with_a_current_token_succeeds()
{
var clusterId = SeedCluster();
var nodeId = SeedNode(clusterId);
var cut = Render<NodeEdit>(p => p.Add(x => x.ClusterId, clusterId).Add(x => x.NodeId, nodeId));
cut.WaitForAssertion(() => cut.Find("#host").GetAttribute("value").ShouldBe("h-original"));
cut.Find("#host").Change("h-saved");
cut.Find("form").Submit();
cut.WaitForAssertion(() =>
{
using var db = _sql.Factory.CreateDbContext();
db.ClusterNodes.AsNoTracking().Single(n => n.NodeId == nodeId).Host.ShouldBe("h-saved");
});
cut.Markup.ShouldNotContain("Another user changed this node");
}
/// <summary>ClusterEdit: a stale token is refused; positive control on the same page after a reload-equivalent re-render.</summary>
[SqlServerFact]
public void ClusterEdit_save_with_a_stale_token_is_refused()
{
var clusterId = SeedCluster();
var cut = Render<ClusterEdit>(p => p.Add(x => x.ClusterId, clusterId));
cut.WaitForAssertion(() => cut.Find("#notes"));
ConcurrentEdit(db => db.ServerClusters.Single(c => c.ClusterId == clusterId).Notes = "other user");
cut.Find("#notes").Change("stale");
cut.Find("form").Submit();
cut.WaitForAssertion(() => cut.Markup.ShouldContain("Another user changed this cluster"));
using (var db = _sql.Factory.CreateDbContext())
db.ServerClusters.AsNoTracking().Single(c => c.ClusterId == clusterId).Notes.ShouldBe("other user");
var fresh = Render<ClusterEdit>(p => p.Add(x => x.ClusterId, clusterId));
fresh.WaitForAssertion(() => fresh.Find("#notes"));
fresh.Find("#notes").Change("current");
fresh.Find("form").Submit();
fresh.WaitForAssertion(() =>
{
using var db = _sql.Factory.CreateDbContext();
db.ServerClusters.AsNoTracking().Single(c => c.ClusterId == clusterId).Notes.ShouldBe("current");
});
}
/// <summary>A node with NodeDeploymentState rows (Restrict FK) deletes together with them — no raw FK error.</summary>
[SqlServerFact]
public void NodeEdit_delete_of_a_deployed_node_removes_its_deployment_states()
{
var clusterId = SeedCluster();
var nodeId = SeedNode(clusterId);
var deploymentId = Guid.NewGuid();
using (var seed = _sql.Factory.CreateDbContext())
{
seed.Deployments.Add(new Deployment { DeploymentId = deploymentId, RevisionHash = new string('a', 64), CreatedBy = "t1049" });
seed.NodeDeploymentStates.Add(new NodeDeploymentState { NodeId = nodeId, DeploymentId = deploymentId, Status = NodeDeploymentStatus.Applied });
seed.SaveChanges();
}
var cut = Render<NodeEdit>(p => p.Add(x => x.ClusterId, clusterId).Add(x => x.NodeId, nodeId));
cut.WaitForAssertion(() => cut.Find("button.btn-outline-danger"));
cut.Find("button.btn-outline-danger").Click();
cut.Find(".modal-footer .btn-danger").Click();
cut.WaitForAssertion(() =>
{
using var db = _sql.Factory.CreateDbContext();
db.ClusterNodes.Any(n => n.NodeId == nodeId).ShouldBeFalse();
db.NodeDeploymentStates.Any(s => s.NodeId == nodeId).ShouldBeFalse();
db.Deployments.Any(d => d.DeploymentId == deploymentId).ShouldBeTrue(); // the deployment itself is history, kept
});
}
/// <summary>A cluster that still has nodes is not deleted (Restrict FK) and the page names the reason; positive control: an empty one deletes.</summary>
[SqlServerFact]
public void ClusterEdit_delete_of_a_cluster_with_nodes_is_refused_with_a_reason()
{
var busy = SeedCluster();
SeedNode(busy);
var cut = Render<ClusterEdit>(p => p.Add(x => x.ClusterId, busy));
cut.WaitForAssertion(() => cut.Find("button.btn-outline-danger"));
cut.Find("button.btn-outline-danger").Click();
cut.Find(".modal-footer .btn-danger").Click();
cut.WaitForAssertion(() => cut.Markup.ShouldContain("remove them first"));
using (var db = _sql.Factory.CreateDbContext())
db.ServerClusters.Any(c => c.ClusterId == busy).ShouldBeTrue();
var empty = SeedCluster();
var cut2 = Render<ClusterEdit>(p => p.Add(x => x.ClusterId, empty));
cut2.WaitForAssertion(() => cut2.Find("button.btn-outline-danger"));
cut2.Find("button.btn-outline-danger").Click();
cut2.Find(".modal-footer .btn-danger").Click();
cut2.WaitForAssertion(() =>
{
using var db = _sql.Factory.CreateDbContext();
db.ServerClusters.Any(c => c.ClusterId == empty).ShouldBeFalse();
});
}
private sealed class FakeAuth : AuthenticationStateProvider
{
public override Task<AuthenticationState> GetAuthenticationStateAsync() =>
Task.FromResult(new AuthenticationState(new System.Security.Claims.ClaimsPrincipal(
new System.Security.Claims.ClaimsIdentity("test"))));
}
}