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; /// /// 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. /// [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(); 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))); /// The canonical (derived) EquipmentId for ; the validator rejects any other id. 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? tags = null, IReadOnlyList? equipment = null, IReadOnlyList? drivers = null, IReadOnlyList? 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 ----- /// Two equipment rows with the same ZTag (no reservation rows at all, as in production) are both named. [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"); } /// The same rule covers SAPID. [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); } /// Positive control: distinct values, repeated nulls and blanks, and a ZTag equal to another row's SAPID are all fine. [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 ----- /// A copied override: two owned historized tags with the same override are both named. [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); } /// An override equal to another tag's computed RawPath is the same collision. [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); } /// Positive controls: distinct names, a non-historized twin, and a historianReadOnly twin (decision: read-only sharing allowed). [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); } /// The same override in two clusters is not provably a collision (separate historians): accepted. [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 ----- /// The orphan scenario: a tag whose Device was deleted concurrently is named, not silently skipped. [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"); } /// Positive control: a complete, consistent graph (every link present) produces no error at all. [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(); } /// One case per logical link. [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 row, Action 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? tagGroups = null, IReadOnlyList? rawFolders = null, IReadOnlyList? refs = null, IReadOnlyList? vtags = null, IReadOnlyList? alarms = null, IReadOnlyList