fix(config): #998 deploy gate rejects duplicate ZTag/SAPID, duplicate owned historian tagnames and dangling parent links; NULL-keyed unique indexes enforced; node/cluster edits carry a RowVersion

C-3 ZTag/SAPID uniqueness enforced from the draft (reservation ledger has no writer); UI/doc claim corrected.
C-5 HistorianTagnameDuplicate (owned tags, per cluster, case-insensitive; readOnly exempt).
C-8 UX_NodeAcl_PrincipalScope / UX_LdapGroupRoleMapping_Group_Cluster unfiltered (migration with duplicate pre-check) + friendly service/page checks.
C-9 RowVersion on ClusterNode/ServerCluster, edit pages use it; node delete removes its NodeDeploymentState rows.
C-10 DanglingReference rule; dead PathTooLong/EquipmentUuidImmutable rules + PriorEquipment/Enterprise/Site inputs deleted.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
Joseph Doherty
2026-12-03 10:49:57 -05:00
parent b9955f6946
commit 486628cf0a
24 changed files with 2833 additions and 171 deletions
@@ -0,0 +1,174 @@
using Microsoft.EntityFrameworkCore;
using Shouldly;
using Xunit;
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.Configuration.Tests;
/// <summary>
/// lmxopcua#998 (review 2026-12-02 03-configuration C-8, C-9) against the real SQL schema: the two unique
/// indexes over nullable columns must cover the NULL-key rows, and ClusterNode / ServerCluster carry a
/// concurrency token.
/// </summary>
[Trait("Category", "SchemaCompliance")]
[Collection(nameof(SchemaComplianceCollection))]
public sealed class ConfigurationGapsSchemaTests
{
private readonly SchemaComplianceFixture _fixture;
/// <summary>Initializes a new instance of the <see cref="ConfigurationGapsSchemaTests"/> class.</summary>
/// <param name="fixture">The schema compliance fixture (real SQL DB).</param>
public ConfigurationGapsSchemaTests(SchemaComplianceFixture fixture) => _fixture = fixture;
private OtOpcUaConfigDbContext NewContext() =>
new(new DbContextOptionsBuilder<OtOpcUaConfigDbContext>().UseSqlServer(_fixture.ConnectionString).Options);
private static string Id(string prefix) => $"{prefix}-{Guid.NewGuid():N}";
private string SeedCluster()
{
var clusterId = Id("cl");
using var db = NewContext();
db.ServerClusters.Add(new ServerCluster
{
ClusterId = clusterId, Name = Id("Cluster"), Enterprise = "zb", Site = "dev", NodeCount = 1,
RedundancyMode = RedundancyMode.None, CreatedBy = "t998",
});
db.SaveChanges();
return clusterId;
}
private static NodeAcl ClusterAcl(string clusterId, string principal) => new()
{
NodeAclId = Id("acl"), ClusterId = clusterId, Principal = principal,
ScopeKind = NodeAclScopeKind.Cluster, ScopeId = null, PermissionFlags = NodePermissions.Browse,
};
/// <summary>The recorded index definitions are unfiltered (HasFilter(null)) — the model comment's "one row per key" holds for NULLs too.</summary>
[Fact]
public void The_two_nullable_unique_indexes_are_not_filtered()
{
using var db = NewContext();
var filtered = db.Database.SqlQueryRaw<string>(
"SELECT name AS Value FROM sys.indexes WHERE is_unique = 1 AND has_filter = 1 " +
"AND name IN ('UX_NodeAcl_PrincipalScope', 'UX_LdapGroupRoleMapping_Group_Cluster')").ToList();
filtered.ShouldBeEmpty();
}
/// <summary>Two system-wide mappings for one group (NULL ClusterId) now collide.</summary>
[Fact]
public void Two_system_wide_mappings_for_one_group_are_rejected()
{
var group = Id("cn=grp");
using var db = NewContext();
db.LdapGroupRoleMappings.Add(new LdapGroupRoleMapping { LdapGroup = group, Role = AdminRole.Administrator, IsSystemWide = true });
db.LdapGroupRoleMappings.Add(new LdapGroupRoleMapping { LdapGroup = group, Role = AdminRole.Designer, IsSystemWide = true });
Should.Throw<DbUpdateException>(() => db.SaveChanges());
}
/// <summary>Positive control: a system-wide row plus a cluster row, and one row for another group, are all fine.</summary>
[Fact]
public void System_wide_plus_cluster_scoped_and_other_groups_are_accepted()
{
var group = Id("cn=grp");
var cluster = SeedCluster();
using var db = NewContext();
db.LdapGroupRoleMappings.Add(new LdapGroupRoleMapping { LdapGroup = group, Role = AdminRole.Administrator, IsSystemWide = true });
db.LdapGroupRoleMappings.Add(new LdapGroupRoleMapping { LdapGroup = group, Role = AdminRole.Designer, ClusterId = cluster, IsSystemWide = false });
db.LdapGroupRoleMappings.Add(new LdapGroupRoleMapping { LdapGroup = Id("cn=other"), Role = AdminRole.Administrator, IsSystemWide = true });
Should.NotThrow(() => db.SaveChanges());
}
/// <summary>Two Cluster-scope ACL rows (NULL ScopeId) for one principal in one cluster now collide.</summary>
[Fact]
public void Two_cluster_scope_acls_for_one_principal_are_rejected()
{
var cluster = SeedCluster();
using var db = NewContext();
db.NodeAcls.Add(ClusterAcl(cluster, "grp-a"));
db.NodeAcls.Add(ClusterAcl(cluster, "grp-a"));
Should.Throw<DbUpdateException>(() => db.SaveChanges());
}
/// <summary>Positive control: other principal, and the same principal in another cluster, are fine.</summary>
[Fact]
public void Cluster_scope_acls_for_other_principals_or_clusters_are_accepted()
{
var a = SeedCluster();
var b = SeedCluster();
using var db = NewContext();
db.NodeAcls.Add(ClusterAcl(a, "grp-a"));
db.NodeAcls.Add(ClusterAcl(a, "grp-b"));
db.NodeAcls.Add(ClusterAcl(b, "grp-a"));
Should.NotThrow(() => db.SaveChanges());
}
/// <summary>A stale ClusterNode write (token loaded before a concurrent edit) is refused, not last-writer-wins.</summary>
[Fact]
public void A_stale_cluster_node_edit_is_refused()
{
var cluster = SeedCluster();
var nodeId = Id("node") + ":4053";
using (var seed = NewContext())
{
seed.ClusterNodes.Add(new ClusterNode
{
NodeId = nodeId, ClusterId = cluster, Host = "h", ApplicationUri = "urn:" + Id("n"), CreatedBy = "t998",
});
seed.SaveChanges();
}
byte[] staleToken;
using (var form = NewContext()) staleToken = form.ClusterNodes.AsNoTracking().Single(n => n.NodeId == nodeId).RowVersion;
staleToken.ShouldNotBeEmpty();
using (var other = NewContext())
{
var n = other.ClusterNodes.Single(x => x.NodeId == nodeId);
n.Enabled = false;
other.SaveChanges();
}
using var stale = NewContext();
var entity = stale.ClusterNodes.Single(x => x.NodeId == nodeId);
stale.Entry(entity).Property(e => e.RowVersion).OriginalValue = staleToken;
entity.Host = "changed";
Should.Throw<DbUpdateConcurrencyException>(() => stale.SaveChanges());
}
/// <summary>The same for ServerCluster; positive control: a write with the CURRENT token succeeds.</summary>
[Fact]
public void A_stale_server_cluster_edit_is_refused_but_a_current_one_succeeds()
{
var cluster = SeedCluster();
byte[] staleToken;
using (var form = NewContext()) staleToken = form.ServerClusters.AsNoTracking().Single(c => c.ClusterId == cluster).RowVersion;
using (var other = NewContext())
{
other.ServerClusters.Single(c => c.ClusterId == cluster).Notes = "concurrent";
other.SaveChanges();
}
using (var stale = NewContext())
{
var entity = stale.ServerClusters.Single(c => c.ClusterId == cluster);
stale.Entry(entity).Property(e => e.RowVersion).OriginalValue = staleToken;
entity.Notes = "stale";
Should.Throw<DbUpdateConcurrencyException>(() => stale.SaveChanges());
}
using var current = NewContext();
var fresh = current.ServerClusters.Single(c => c.ClusterId == cluster);
current.Entry(fresh).Property(e => e.RowVersion).OriginalValue = fresh.RowVersion;
fresh.Notes = "current";
Should.NotThrow(() => current.SaveChanges());
}
}
@@ -0,0 +1,241 @@
using Shouldly;
using Xunit;
using ZB.MOM.WW.OtOpcUa.Configuration.Entities;
using ZB.MOM.WW.OtOpcUa.Configuration.Enums;
using ZB.MOM.WW.OtOpcUa.Configuration.Validation;
namespace ZB.MOM.WW.OtOpcUa.Configuration.Tests;
/// <summary>
/// lmxopcua#998 (review 2026-12-02 03-configuration C-3, C-5, C-10) — the deploy-gate rules that make the
/// draft the one authority: ZTag/SAPID duplicates, duplicate historian tagnames, and dangling logical FKs.
/// </summary>
[Trait("Category", "Unit")]
public sealed class DraftValidatorConfigurationGapsTests
{
private static DriverInstance Driver(string id = "drv-1", string cluster = "c1") => new()
{
DriverInstanceId = id, ClusterId = cluster, Name = "drv-" + id, DriverType = "Modbus", DriverConfig = "{}",
};
private static Device Dev(string id = "dev-1", string driver = "drv-1") => new()
{
DeviceId = id, DriverInstanceId = driver, Name = "dev-" + id, DeviceConfig = "{}",
};
private static Tag HistTag(string id, string name, string? tagname = null, bool readOnly = false,
string device = "dev-1", bool historized = true)
{
var cfg = new List<string>();
if (historized) cfg.Add("\"isHistorized\":true");
if (tagname is not null) cfg.Add($"\"historianTagname\":\"{tagname}\"");
if (readOnly) cfg.Add("\"historianReadOnly\":true");
return new Tag
{
TagId = id, DeviceId = device, Name = name, DataType = "Float",
AccessLevel = TagAccessLevel.Read, TagConfig = "{" + string.Join(",", cfg) + "}",
};
}
private static Guid UuidOf(string key) => new(System.Security.Cryptography.MD5.HashData(System.Text.Encoding.UTF8.GetBytes(key)));
/// <summary>The canonical (derived) EquipmentId for <paramref name="key"/>; the validator rejects any other id.</summary>
private static string Id(string key) => DraftValidator.DeriveEquipmentId(UuidOf(key));
private static Equipment Eq(string key, string? ztag = null, string? sap = null) => new()
{
EquipmentUuid = UuidOf(key), EquipmentId = Id(key), Name = "eq-" + key.ToLowerInvariant(), UnsLineId = "line-1",
MachineCode = "m-" + key, ZTag = ztag, SAPID = sap,
};
private static DraftSnapshot Snap(
IReadOnlyList<Tag>? tags = null, IReadOnlyList<Equipment>? equipment = null,
IReadOnlyList<DriverInstance>? drivers = null, IReadOnlyList<Device>? devices = null) => new()
{
GenerationId = 1, ClusterId = "c1",
UnsAreas = [new UnsArea { UnsAreaId = "area-1", ClusterId = "c1", Name = "area" }],
UnsLines = [new UnsLine { UnsLineId = "line-1", UnsAreaId = "area-1", Name = "line" }],
DriverInstances = drivers ?? [Driver()],
Devices = devices ?? [Dev()],
Tags = tags ?? [],
Equipment = equipment ?? [],
};
// ----- C-3: ZTag / SAPID uniqueness -----
/// <summary>Two equipment rows with the same ZTag (no reservation rows at all, as in production) are both named.</summary>
[Fact]
public void Duplicate_ztag_is_rejected_without_any_reservation_rows()
{
var errors = DraftValidator.Validate(Snap(equipment: [Eq("a", ztag: "ZT-001"), Eq("b", ztag: "zt-001 ")]));
var dup = errors.Where(e => e.Code == DraftValidator.DuplicateExternalIdentifierCode).ToList();
dup.Count.ShouldBe(2);
dup.Select(e => e.Context).ShouldBe([Id("a"), Id("b")], ignoreOrder: true);
dup[0].Message.ShouldContain("ZTag");
}
/// <summary>The same rule covers SAPID.</summary>
[Fact]
public void Duplicate_sapid_is_rejected()
{
var errors = DraftValidator.Validate(Snap(equipment: [Eq("a", sap: "S1"), Eq("b", sap: "S1")]));
errors.Count(e => e.Code == DraftValidator.DuplicateExternalIdentifierCode).ShouldBe(2);
}
/// <summary>Positive control: distinct values, repeated nulls and blanks, and a ZTag equal to another row's SAPID are all fine.</summary>
[Fact]
public void Distinct_null_and_blank_external_ids_are_accepted()
{
var errors = DraftValidator.Validate(Snap(equipment:
[
Eq("a", ztag: "ZT-1", sap: "X"), Eq("b", ztag: "ZT-2", sap: "Y"),
Eq("c"), Eq("d"), Eq("e", ztag: " ", sap: ""), Eq("f", ztag: "", sap: " "),
Eq("g", ztag: "X"),
]));
errors.ShouldNotContain(e => e.Code == DraftValidator.DuplicateExternalIdentifierCode);
}
// ----- C-5: historian tagname duplicates -----
/// <summary>A copied override: two owned historized tags with the same override are both named.</summary>
[Fact]
public void Two_owned_tags_with_the_same_historian_override_are_rejected()
{
var errors = DraftValidator.Validate(Snap(tags:
[
HistTag("t1", "speed", "Plant.Speed"), HistTag("t2", "speed2", "plant.speed"),
]));
var dup = errors.Where(e => e.Code == DraftValidator.HistorianTagnameDuplicateCode).ToList();
dup.Select(e => e.Context).ShouldBe(["t1", "t2"], ignoreOrder: true);
}
/// <summary>An override equal to another tag's computed RawPath is the same collision.</summary>
[Fact]
public void An_override_equal_to_another_tags_rawpath_is_rejected()
{
// t1's RawPath = drv-drv-1/dev-dev-1/speed (no RawFolder); t2 overrides to exactly that.
var errors = DraftValidator.Validate(Snap(tags:
[
HistTag("t1", "speed"), HistTag("t2", "other", "drv-drv-1/dev-dev-1/speed"),
]));
errors.Count(e => e.Code == DraftValidator.HistorianTagnameDuplicateCode).ShouldBe(2);
}
/// <summary>Positive controls: distinct names, a non-historized twin, and a historianReadOnly twin (decision: read-only sharing allowed).</summary>
[Fact]
public void Distinct_non_historized_and_read_only_twins_are_accepted()
{
var errors = DraftValidator.Validate(Snap(tags:
[
HistTag("t1", "a", "Plant.A"), HistTag("t2", "b", "Plant.B"),
HistTag("t3", "c", "Plant.A", historized: false),
HistTag("t4", "d", "Plant.A", readOnly: true),
HistTag("t5", "e", "Plant.RO", readOnly: true), HistTag("t6", "f", "Plant.RO", readOnly: true),
]));
errors.ShouldNotContain(e => e.Code == DraftValidator.HistorianTagnameDuplicateCode);
}
/// <summary>The same override in two clusters is not provably a collision (separate historians): accepted.</summary>
[Fact]
public void The_same_override_in_different_clusters_is_accepted()
{
var errors = DraftValidator.Validate(Snap(
drivers: [Driver("drv-1", "c1"), Driver("drv-2", "c2")],
devices: [Dev("dev-1", "drv-1"), Dev("dev-2", "drv-2")],
tags: [HistTag("t1", "a", "Plant.A"), HistTag("t2", "a", "Plant.A", device: "dev-2")]));
errors.ShouldNotContain(e => e.Code == DraftValidator.HistorianTagnameDuplicateCode);
}
// ----- C-10: dangling references -----
/// <summary>The orphan scenario: a tag whose Device was deleted concurrently is named, not silently skipped.</summary>
[Fact]
public void A_tag_under_a_deleted_device_is_rejected()
{
var errors = DraftValidator.Validate(Snap(tags: [HistTag("t1", "a", historized: false, device: "dev-gone")]));
var e = errors.ShouldHaveSingleItem();
e.Code.ShouldBe(DraftValidator.DanglingReferenceCode);
e.Context.ShouldBe("t1");
e.Message.ShouldContain("dev-gone");
}
/// <summary>Positive control: a complete, consistent graph (every link present) produces no error at all.</summary>
[Fact]
public void A_consistent_graph_has_no_dangling_reference()
{
var errors = DraftValidator.Validate(Snap(
tags: [HistTag("t1", "a", historized: false)],
equipment: [Eq("a")]));
errors.ShouldBeEmpty();
}
/// <summary>One case per logical link.</summary>
[Theory]
[InlineData("tag-group")]
[InlineData("tag-device")]
[InlineData("taggroup-device")]
[InlineData("taggroup-parent")]
[InlineData("device-driver")]
[InlineData("driver-folder")]
[InlineData("folder-parent")]
[InlineData("line-area")]
[InlineData("equipment-line")]
[InlineData("ref-tag")]
[InlineData("ref-equipment")]
[InlineData("vtag-equipment")]
[InlineData("alarm-equipment")]
public void Every_logical_parent_link_is_checked(string link)
{
var tag = HistTag("t1", "a", historized: false);
var snap = link switch
{
"tag-group" => Snap(tags: [Mutate(tag, t => t.TagGroupId = "g-gone")]),
"tag-device" => Snap(tags: [Mutate(tag, t => t.DeviceId = "dev-gone")]),
"taggroup-device" => With(Snap(tags: [tag]), tagGroups: [new TagGroup { TagGroupId = "g1", DeviceId = "dev-gone", Name = "g" }]),
"taggroup-parent" => With(Snap(tags: [tag]), tagGroups: [new TagGroup { TagGroupId = "g1", DeviceId = "dev-1", ParentTagGroupId = "g-gone", Name = "g" }]),
"device-driver" => Snap(tags: [tag], devices: [Dev("dev-1", "drv-gone")]),
"driver-folder" => Snap(tags: [tag], drivers: [Mutate(Driver(), d => d.RawFolderId = "f-gone")]),
"folder-parent" => With(Snap(tags: [tag]), rawFolders: [new RawFolder { RawFolderId = "f1", ClusterId = "c1", ParentRawFolderId = "f-gone", Name = "f" }]),
"line-area" => Snap(tags: [tag]),
"equipment-line" => Snap(tags: [tag], equipment: [Mutate(Eq("a"), e => e.UnsLineId = "line-gone")]),
"ref-tag" => With(Snap(tags: [tag], equipment: [Eq("a")]), refs: [new UnsTagReference { UnsTagReferenceId = "r1", EquipmentId = Id("a"), TagId = "t-gone" }]),
"ref-equipment" => With(Snap(tags: [tag], equipment: [Eq("a")]), refs: [new UnsTagReference { UnsTagReferenceId = "r1", EquipmentId = "EQ-gone", TagId = "t1" }]),
"vtag-equipment" => With(Snap(tags: [tag]), vtags: [new VirtualTag { VirtualTagId = "v1", EquipmentId = "EQ-gone", Name = "v", DataType = "Double", ScriptId = "s1", ChangeTriggered = true }], scripts: [Script("s1")]),
"alarm-equipment" => With(Snap(tags: [tag]), alarms: [new ScriptedAlarm { ScriptedAlarmId = "a1", EquipmentId = "EQ-gone", Name = "al", AlarmType = "LimitAlarm", MessageTemplate = "m", PredicateScriptId = "s1" }], scripts: [Script("s1")]),
_ => throw new ArgumentOutOfRangeException(nameof(link)),
};
if (link == "line-area")
snap = new DraftSnapshot
{
GenerationId = 1, ClusterId = "c1", UnsLines = [new UnsLine { UnsLineId = "line-1", UnsAreaId = "area-gone", Name = "line" }],
};
var errors = DraftValidator.Validate(snap).Where(e => e.Code == DraftValidator.DanglingReferenceCode).ToList();
errors.ShouldHaveSingleItem();
}
private static T Mutate<T>(T row, Action<T> change) { change(row); return row; }
private static Script Script(string id) => new() { ScriptId = id, Name = id, SourceCode = "return 1;", SourceHash = "h" };
private static DraftSnapshot With(DraftSnapshot s, IReadOnlyList<TagGroup>? tagGroups = null, IReadOnlyList<RawFolder>? rawFolders = null,
IReadOnlyList<UnsTagReference>? refs = null, IReadOnlyList<VirtualTag>? vtags = null,
IReadOnlyList<ScriptedAlarm>? alarms = null, IReadOnlyList<Script>? scripts = null) => new()
{
GenerationId = s.GenerationId, ClusterId = s.ClusterId, UnsAreas = s.UnsAreas, UnsLines = s.UnsLines,
DriverInstances = s.DriverInstances, Devices = s.Devices, Tags = s.Tags, Equipment = s.Equipment,
TagGroups = tagGroups ?? s.TagGroups, RawFolders = rawFolders ?? s.RawFolders,
UnsTagReferences = refs ?? s.UnsTagReferences, VirtualTags = vtags ?? s.VirtualTags,
ScriptedAlarms = alarms ?? s.ScriptedAlarms, Scripts = scripts ?? s.Scripts,
};
}
@@ -51,24 +51,6 @@ public sealed class DraftValidatorTests
hasUnsError.ShouldBe(!shouldPass);
}
/// <summary>Verifies that equipment UUID must remain immutable across generations.</summary>
[Fact]
public void EquipmentUuid_change_across_generations_is_rejected()
{
var oldUuid = Guid.Parse("11111111-1111-1111-1111-111111111111");
var newUuid = Guid.Parse("22222222-2222-2222-2222-222222222222");
var eid = DraftValidator.DeriveEquipmentId(oldUuid);
var draft = new DraftSnapshot
{
GenerationId = 2, ClusterId = "c",
Equipment = [new Equipment { EquipmentUuid = newUuid, EquipmentId = eid, Name = "eq", UnsLineId = "line-a", MachineCode = "m" }],
PriorEquipment = [new Equipment { EquipmentUuid = oldUuid, EquipmentId = eid, Name = "eq", UnsLineId = "line-a", MachineCode = "m" }],
};
DraftValidator.Validate(draft).ShouldContain(e => e.Code == "EquipmentUuidImmutable");
}
/// <summary>Verifies that a ZTag cannot be reserved by a different equipment UUID.</summary>
[Fact]
public void ZTag_reserved_by_different_uuid_is_rejected()
@@ -489,77 +471,4 @@ public sealed class DraftValidatorTests
Enabled = enabled,
CreatedBy = "t",
};
// ------------------------------------------------------------------------------------
// ValidatePathLength — Enterprise/Site length precision (Configuration-003)
// ------------------------------------------------------------------------------------
/// <summary>Verifies that path length validation uses actual Enterprise and Site lengths.</summary>
[Fact]
public void PathLength_uses_actual_Enterprise_Site_when_provided()
{
var areaId = "area-a";
var lineId = "line-b";
var uuid = Guid.NewGuid();
var eqName = new string('x', 90); // 90 chars — exceeds UNS regex but that's a separate error
var snapshot = new DraftSnapshot
{
GenerationId = 1,
ClusterId = "c",
Enterprise = "zb", // 2 chars (actual)
Site = "s", // 1 char (actual)
UnsAreas = [new UnsArea { UnsAreaId = areaId, ClusterId = "c", Name = new string('a', 32) }],
UnsLines = [new UnsLine { UnsLineId = lineId, UnsAreaId = areaId, Name = new string('b', 32) }],
Equipment =
[
new Equipment
{
EquipmentUuid = uuid,
EquipmentId = DraftValidator.DeriveEquipmentId(uuid),
Name = eqName,
UnsLineId = lineId,
MachineCode = "m",
},
],
};
var errors = DraftValidator.Validate(snapshot);
errors.ShouldNotContain(e => e.Code == "PathTooLong",
"actual Enterprise='zb' + Site='s' keeps total path at 161 chars — under the 200-char limit");
}
/// <summary>Verifies that path length validation uses conservative fallback when Enterprise and Site are absent.</summary>
[Fact]
public void PathLength_conservative_fallback_when_Enterprise_Site_absent()
{
var areaId = "area-x";
var lineId = "line-y";
var uuid = Guid.NewGuid();
var snapshot = new DraftSnapshot
{
GenerationId = 1,
ClusterId = "c",
UnsAreas = [new UnsArea { UnsAreaId = areaId, ClusterId = "c", Name = new string('a', 32) }],
UnsLines = [new UnsLine { UnsLineId = lineId, UnsAreaId = areaId, Name = new string('b', 32) }],
Equipment =
[
new Equipment
{
EquipmentUuid = uuid,
EquipmentId = DraftValidator.DeriveEquipmentId(uuid),
Name = new string('c', 29),
UnsLineId = lineId,
MachineCode = "m",
},
],
};
var errors = DraftValidator.Validate(snapshot);
errors.ShouldNotContain(e => e.Code == "PathTooLong",
"conservative 32+32+32+32+29+4 = 161 chars is still under the 200-char limit");
}
}
@@ -16,6 +16,22 @@ namespace ZB.MOM.WW.OtOpcUa.Configuration.Tests;
[Trait("Category", "Unit")]
public sealed class DraftValidatorUnsLeafNameAndScriptTests
{
private static readonly Guid EqUuid = Guid.Parse("33333333-3333-3333-3333-333333333333");
private static readonly string EqId = DraftValidator.DeriveEquipmentId(EqUuid);
// The logical parents every row needs (DanglingReference, #998): one consistent Area/Line/Equipment + Driver/Device.
private static readonly Equipment Eq = new()
{
EquipmentUuid = EqUuid, EquipmentId = EqId, Name = "eq", UnsLineId = "line-1", MachineCode = "m",
};
private static readonly UnsLine Line = new() { UnsLineId = "line-1", UnsAreaId = "area-1", Name = "line" };
private static readonly UnsArea Area = new() { UnsAreaId = "area-1", ClusterId = "c", Name = "area" };
private static readonly DriverInstance Drv = new()
{
DriverInstanceId = "drv-1", ClusterId = "c", Name = "drv", DriverType = "Modbus", DriverConfig = "{}",
};
private static readonly Device Dev = new() { DeviceId = "dev-1", DriverInstanceId = "drv-1", Name = "dev", DeviceConfig = "{}" };
private static Script ScriptRow(string id) => new()
{
ScriptId = id, Name = id, SourceCode = "return 1;", SourceHash = "h-" + id,
@@ -23,13 +39,13 @@ public sealed class DraftValidatorUnsLeafNameAndScriptTests
private static VirtualTag Vt(string name, string scriptId = "s1", string id = "vt-1") => new()
{
VirtualTagId = id, EquipmentId = "eq-1", Name = name, DataType = "Double", ScriptId = scriptId,
VirtualTagId = id, EquipmentId = EqId, Name = name, DataType = "Double", ScriptId = scriptId,
ChangeTriggered = true, TimerIntervalMs = 1000,
};
private static ScriptedAlarm Alarm(string predicateScriptId, bool enabled = true) => new()
{
ScriptedAlarmId = "al-1", EquipmentId = "eq-1", Name = "HighTemp", AlarmType = "LimitAlarm",
ScriptedAlarmId = "al-1", EquipmentId = EqId, Name = "HighTemp", AlarmType = "LimitAlarm",
MessageTemplate = "hot", PredicateScriptId = predicateScriptId, Enabled = enabled,
};
@@ -41,7 +57,7 @@ public sealed class DraftValidatorUnsLeafNameAndScriptTests
private static UnsTagReference Ref(string? overrideName) => new()
{
UnsTagReferenceId = "ref-1", EquipmentId = "eq-1", TagId = "tag-1", DisplayNameOverride = overrideName,
UnsTagReferenceId = "ref-1", EquipmentId = EqId, TagId = "tag-1", DisplayNameOverride = overrideName,
};
// ----- C-1 / R-5: VirtualTag name -----
@@ -56,11 +72,11 @@ public sealed class DraftValidatorUnsLeafNameAndScriptTests
public void An_illegal_virtual_tag_name_is_rejected(string name)
{
// Premise: this is exactly a name the runtime would throw on.
Should.Throw<ArgumentException>(() => V3NodeIds.Uns("eq-1", name));
Should.Throw<ArgumentException>(() => V3NodeIds.Uns(EqId, name));
var errors = DraftValidator.Validate(new DraftSnapshot
{
GenerationId = 1, ClusterId = "c", VirtualTags = [Vt(name)], Scripts = [ScriptRow("s1")],
GenerationId = 1, ClusterId = "c", Equipment = [Eq], UnsLines = [Line], UnsAreas = [Area], DriverInstances = [Drv], Devices = [Dev], VirtualTags = [Vt(name)], Scripts = [ScriptRow("s1")],
});
errors.ShouldHaveSingleItem().Code.ShouldBe(DraftValidator.VirtualTagNameInvalidCode);
@@ -75,10 +91,10 @@ public sealed class DraftValidatorUnsLeafNameAndScriptTests
[InlineData("_x")]
public void A_legal_virtual_tag_name_is_accepted(string name)
{
V3NodeIds.Uns("eq-1", name).ShouldBe("eq-1/" + name);
V3NodeIds.Uns(EqId, name).ShouldBe(EqId + "/" + name);
DraftValidator.Validate(new DraftSnapshot
{
GenerationId = 1, ClusterId = "c", VirtualTags = [Vt(name)], Scripts = [ScriptRow("s1")],
GenerationId = 1, ClusterId = "c", Equipment = [Eq], UnsLines = [Line], UnsAreas = [Area], DriverInstances = [Drv], Devices = [Dev], VirtualTags = [Vt(name)], Scripts = [ScriptRow("s1")],
}).ShouldBeEmpty();
}
@@ -92,7 +108,7 @@ public sealed class DraftValidatorUnsLeafNameAndScriptTests
{
var errors = DraftValidator.Validate(new DraftSnapshot
{
GenerationId = 1, ClusterId = "c", Tags = [RawTag()], UnsTagReferences = [Ref(overrideName)],
GenerationId = 1, ClusterId = "c", Equipment = [Eq], UnsLines = [Line], UnsAreas = [Area], DriverInstances = [Drv], Devices = [Dev], Tags = [RawTag()], UnsTagReferences = [Ref(overrideName)],
});
var error = errors.ShouldHaveSingleItem();
@@ -109,7 +125,7 @@ public sealed class DraftValidatorUnsLeafNameAndScriptTests
public void A_legal_or_absent_override_is_accepted(string? overrideName) =>
DraftValidator.Validate(new DraftSnapshot
{
GenerationId = 1, ClusterId = "c", Tags = [RawTag()], UnsTagReferences = [Ref(overrideName)],
GenerationId = 1, ClusterId = "c", Equipment = [Eq], UnsLines = [Line], UnsAreas = [Area], DriverInstances = [Drv], Devices = [Dev], Tags = [RawTag()], UnsTagReferences = [Ref(overrideName)],
}).ShouldBeEmpty();
/// <summary>C-4 secondary: an EMPTY-string override means "use the raw tag name" at both compose seams, so
@@ -120,7 +136,7 @@ public sealed class DraftValidatorUnsLeafNameAndScriptTests
{
var errors = DraftValidator.Validate(new DraftSnapshot
{
GenerationId = 1, ClusterId = "c",
GenerationId = 1, ClusterId = "c", Equipment = [Eq], UnsLines = [Line], UnsAreas = [Area], DriverInstances = [Drv], Devices = [Dev],
Tags = [RawTag("speed")],
UnsTagReferences = [Ref("")],
VirtualTags = [Vt("speed")],
@@ -142,7 +158,7 @@ public sealed class DraftValidatorUnsLeafNameAndScriptTests
};
var errors = DraftValidator.Validate(new DraftSnapshot
{
GenerationId = 1, ClusterId = "c",
GenerationId = 1, ClusterId = "c", Equipment = [Eq], UnsLines = [Line], UnsAreas = [Area], DriverInstances = [Drv], Devices = [Dev],
Tags = [RawTag("speed")],
UnsTagReferences = [Ref("")],
VirtualTags = [Vt("computed")],
@@ -161,7 +177,7 @@ public sealed class DraftValidatorUnsLeafNameAndScriptTests
{
var errors = DraftValidator.Validate(new DraftSnapshot
{
GenerationId = 1, ClusterId = "c", VirtualTags = [Vt("computed", scriptId: "s-gone")], Scripts = [ScriptRow("s1")],
GenerationId = 1, ClusterId = "c", Equipment = [Eq], UnsLines = [Line], UnsAreas = [Area], DriverInstances = [Drv], Devices = [Dev], VirtualTags = [Vt("computed", scriptId: "s-gone")], Scripts = [ScriptRow("s1")],
});
var error = errors.ShouldHaveSingleItem();
@@ -177,7 +193,7 @@ public sealed class DraftValidatorUnsLeafNameAndScriptTests
{
var errors = DraftValidator.Validate(new DraftSnapshot
{
GenerationId = 1, ClusterId = "c", ScriptedAlarms = [Alarm("s-gone", enabled)], Scripts = [ScriptRow("s1")],
GenerationId = 1, ClusterId = "c", Equipment = [Eq], UnsLines = [Line], UnsAreas = [Area], DriverInstances = [Drv], Devices = [Dev], ScriptedAlarms = [Alarm("s-gone", enabled)], Scripts = [ScriptRow("s1")],
});
var error = errors.ShouldHaveSingleItem();
@@ -191,7 +207,7 @@ public sealed class DraftValidatorUnsLeafNameAndScriptTests
public void Rows_referencing_an_existing_script_are_accepted() =>
DraftValidator.Validate(new DraftSnapshot
{
GenerationId = 1, ClusterId = "c",
GenerationId = 1, ClusterId = "c", Equipment = [Eq], UnsLines = [Line], UnsAreas = [Area], DriverInstances = [Drv], Devices = [Dev],
VirtualTags = [Vt("computed")],
ScriptedAlarms = [Alarm("s1")],
Scripts = [ScriptRow("s1")],
@@ -35,6 +35,25 @@ public sealed class LdapGroupRoleMappingServiceTests
saved.CreatedAtUtc.ShouldBeGreaterThan(DateTime.UtcNow.AddMinutes(-1));
}
/// <summary>#998 (C-8): a second system-wide row for one group is refused in words; a cluster row, another group and another cluster are not.</summary>
[Fact]
public async Task Create_Rejects_A_Second_Row_For_The_Same_Group_And_Cluster_Bucket()
{
var svc = new LdapGroupRoleMappingService(_db);
await svc.CreateAsync(Make("cn=fleet,dc=x", AdminRole.Administrator), CancellationToken.None);
var ex = await Should.ThrowAsync<InvalidLdapGroupRoleMappingException>(
() => svc.CreateAsync(Make("cn=fleet,dc=x", AdminRole.Designer), CancellationToken.None));
ex.Message.ShouldContain("system-wide");
// Positive controls: the check is per (group, cluster bucket), not per group.
await svc.CreateAsync(Make("cn=fleet,dc=x", AdminRole.Designer, clusterId: "c1"), CancellationToken.None);
await svc.CreateAsync(Make("cn=fleet,dc=x", AdminRole.Designer, clusterId: "c2"), CancellationToken.None);
await svc.CreateAsync(Make("cn=other,dc=x", AdminRole.Administrator), CancellationToken.None);
await Should.ThrowAsync<InvalidLdapGroupRoleMappingException>(
() => svc.CreateAsync(Make("cn=fleet,dc=x", AdminRole.Administrator, clusterId: "c1"), CancellationToken.None));
}
/// <summary>Verifies that Create rejects empty LDAP group.</summary>
[Fact]
public async Task Create_Rejects_EmptyLdapGroup()