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;
///
/// lmxopcua#1049 (#998 C-9 follow-up): the NodeEdit / ClusterEdit pages against a REAL SQL Server, where
/// rowversion 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
/// NodeDeploymentState rows; a cluster that still has nodes is not deleted and the page says why.
///
[Collection(nameof(AdminUiSqlServerCollection))]
public sealed class ClusterNodeEditConcurrencySqlServerTests : BunitContext
{
private const string ModalSelector = ".modal-dialog";
private readonly AdminUiSqlServerFixture _sql;
/// Registers the fixture's SQL-backed context factory (when the server is available).
/// The AdminUI SQL Server fixture.
public ClusterNodeEditConcurrencySqlServerTests(AdminUiSqlServerFixture sql)
{
_sql = sql;
JSInterop.Setup("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(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;
}
/// Another user's committed edit, on its own context.
private void ConcurrentEdit(Action edit)
{
using var db = _sql.Factory.CreateDbContext();
edit(db);
db.SaveChanges();
}
/// NodeEdit: a stale token is refused with the concurrency message; the other user's edit survives.
[SqlServerFact]
public void NodeEdit_save_with_a_stale_token_is_refused()
{
var clusterId = SeedCluster();
var nodeId = SeedNode(clusterId);
var cut = Render(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");
}
/// Positive control: with no concurrent edit the same save goes through.
[SqlServerFact]
public void NodeEdit_save_with_a_current_token_succeeds()
{
var clusterId = SeedCluster();
var nodeId = SeedNode(clusterId);
var cut = Render(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");
}
/// ClusterEdit: a stale token is refused; positive control on the same page after a reload-equivalent re-render.
[SqlServerFact]
public void ClusterEdit_save_with_a_stale_token_is_refused()
{
var clusterId = SeedCluster();
var cut = Render(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(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");
});
}
/// A node with NodeDeploymentState rows (Restrict FK) deletes together with them — no raw FK error.
[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(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();
// The confirm dialog renders on a later pass than the click: wait for it rather than racing the renderer.
cut.WaitForAssertion(() => cut.Find(".modal-footer .btn-danger"));
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
});
}
/// A cluster that still has nodes is not deleted (Restrict FK) and the page names the reason; positive control: an empty one deletes.
[SqlServerFact]
public void ClusterEdit_delete_of_a_cluster_with_nodes_is_refused_with_a_reason()
{
var busy = SeedCluster();
SeedNode(busy);
var cut = Render(p => p.Add(x => x.ClusterId, busy));
cut.WaitForAssertion(() => cut.Find("button.btn-outline-danger"));
cut.Find("button.btn-outline-danger").Click();
// The confirm dialog renders on a later pass than the click: wait for it rather than racing the renderer.
cut.WaitForAssertion(() => cut.Find(".modal-footer .btn-danger"));
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(p => p.Add(x => x.ClusterId, empty));
cut2.WaitForAssertion(() => cut2.Find("button.btn-outline-danger"));
cut2.Find("button.btn-outline-danger").Click();
// The confirm dialog renders on a later pass than the click: wait for it rather than racing the renderer.
cut2.WaitForAssertion(() => cut2.Find(".modal-footer .btn-danger"));
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 GetAuthenticationStateAsync() =>
Task.FromResult(new AuthenticationState(new System.Security.Claims.ClaimsPrincipal(
new System.Security.Claims.ClaimsIdentity("test"))));
}
}