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; /// /// v3 WP1: the namespace-binding + Galaxy-FullName rules are retired (Namespace entity gone; /// Tags are raw-only, not equipment-bound). The retained rules (UNS segments, path length, /// EquipmentUuid immutability, external-id reservation preflight, EquipmentId derivation, /// cluster topology, VirtualTag equipment-signal collision) are exercised below against the v3 /// entity shapes. WP4 (Wave C) adds the new v3 rules (raw-name charset, historized-tagname length, /// UNS effective-leaf uniqueness). /// [Trait("Category", "Unit")] public sealed class DraftValidatorTests { /// Verifies that UnsSegment validation rejects uppercase and special characters. /// The segment name to validate. /// Whether the validation should pass for this name. [Theory] [InlineData("valid-name", true)] [InlineData("line-01", true)] [InlineData("_default", true)] [InlineData("UPPER", false)] [InlineData("with space", false)] [InlineData("", false)] public void UnsSegment_rule_accepts_lowercase_or_default_only(string name, bool shouldPass) { var uuid = Guid.NewGuid(); var draft = new DraftSnapshot { GenerationId = 1, ClusterId = "c", Equipment = [ new Equipment { EquipmentUuid = uuid, EquipmentId = DraftValidator.DeriveEquipmentId(uuid), Name = name, UnsLineId = "line-a", MachineCode = "m", }, ], }; var errors = DraftValidator.Validate(draft); var hasUnsError = errors.Any(e => e.Code == "UnsSegmentInvalid"); hasUnsError.ShouldBe(!shouldPass); } /// Verifies that equipment UUID must remain immutable across generations. [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"); } /// Verifies that a ZTag cannot be reserved by a different equipment UUID. [Fact] public void ZTag_reserved_by_different_uuid_is_rejected() { var uuid = Guid.NewGuid(); var otherUuid = Guid.NewGuid(); var draft = new DraftSnapshot { GenerationId = 1, ClusterId = "c", Equipment = [new Equipment { EquipmentUuid = uuid, EquipmentId = DraftValidator.DeriveEquipmentId(uuid), Name = "eq", UnsLineId = "line-a", MachineCode = "m", ZTag = "ZT-001" }], ActiveReservations = [new ExternalIdReservation { Kind = ReservationKind.ZTag, Value = "ZT-001", EquipmentUuid = otherUuid, ClusterId = "c", FirstPublishedBy = "t" }], }; DraftValidator.Validate(draft).ShouldContain(e => e.Code == "BadDuplicateExternalIdentifier"); } /// Verifies that equipment ID must be derived from its UUID. [Fact] public void EquipmentId_that_does_not_match_derivation_is_rejected() { var uuid = Guid.NewGuid(); var draft = new DraftSnapshot { GenerationId = 1, ClusterId = "c", Equipment = [new Equipment { EquipmentUuid = uuid, EquipmentId = "EQ-operator-typed", Name = "eq", UnsLineId = "line-a", MachineCode = "m" }], }; DraftValidator.Validate(draft).ShouldContain(e => e.Code == "EquipmentIdNotDerived"); } /// Verifies that all violations are reported simultaneously (single-pass validation). [Fact] public void Draft_with_multiple_violations_surfaces_all_of_them() { var uuid = Guid.NewGuid(); var draft = new DraftSnapshot { GenerationId = 1, ClusterId = "c", // EQ-wrong is not the canonical derivation, and "BAD NAME" fails the UNS segment regex. Equipment = [new Equipment { EquipmentUuid = uuid, EquipmentId = "EQ-wrong", Name = "BAD NAME", UnsLineId = "line-a", MachineCode = "m" }], }; var errors = DraftValidator.Validate(draft); errors.ShouldContain(e => e.Code == "EquipmentIdNotDerived"); errors.ShouldContain(e => e.Code == "UnsSegmentInvalid"); } /// Probe for the deploy-path gate: a full, realistic v3 config (UNS area/line + /// canonical Equipment + distinct-named VirtualTags) must produce ZERO validation errors so the /// reject-on-any-error deploy gate is safe to activate. [Fact] public void Full_realistic_config_passes_all_rules() { var area = new UnsArea { UnsAreaId = "area-filling", ClusterId = "MAIN", Name = "filling" }; var line = new UnsLine { UnsLineId = "line-1", UnsAreaId = area.UnsAreaId, Name = "line-1" }; var rinserUuid = Guid.NewGuid(); var fillerUuid = Guid.NewGuid(); var rinser = new Equipment { EquipmentUuid = rinserUuid, EquipmentId = DraftValidator.DeriveEquipmentId(rinserUuid), Name = "rinser-01", UnsLineId = line.UnsLineId, MachineCode = "machine_001", }; var filler = new Equipment { EquipmentUuid = fillerUuid, EquipmentId = DraftValidator.DeriveEquipmentId(fillerUuid), Name = "filler-02", UnsLineId = line.UnsLineId, MachineCode = "machine_002", }; var draft = new DraftSnapshot { GenerationId = 0, ClusterId = string.Empty, // global snapshot — matches DraftSnapshotFactory.FromConfigDbAsync UnsAreas = [area], UnsLines = [line], Equipment = [rinser, filler], VirtualTags = [ BuildVirtualTag(equipmentId: rinser.EquipmentId, name: "oee"), BuildVirtualTag(equipmentId: filler.EquipmentId, name: "throughput"), ], }; var errors = DraftValidator.Validate(draft); errors.ShouldBeEmpty( "a realistic canonical deployed config must pass every DraftValidator rule so the " + "reject-on-any-error deploy gate is safe; firing rules: " + string.Join("; ", errors.Select(e => $"[{e.Code}] {e.Message}"))); } // ------------------------------------------------------------------------------------ // ValidateNoEquipmentSignalNameCollision — v3: VirtualTag name uniqueness within equipment // ------------------------------------------------------------------------------------ /// Two VirtualTags sharing (EquipmentId, Name) collide on a single OPC UA NodeId. [Fact] public void Two_VirtualTags_same_equipment_and_name_collide() { var draft = new DraftSnapshot { GenerationId = 1, ClusterId = "c", VirtualTags = [ BuildVirtualTag(equipmentId: "eq-1", name: "speed", suffix: "a"), BuildVirtualTag(equipmentId: "eq-1", name: "speed", suffix: "b"), ], }; DraftValidator.Validate(draft).ShouldContain(e => e.Code == "EquipmentSignalNameCollision"); } /// VirtualTags with the same name under DIFFERENT equipment do not collide. [Fact] public void Same_name_different_equipment_does_not_collide() { var draft = new DraftSnapshot { GenerationId = 1, ClusterId = "c", VirtualTags = [ BuildVirtualTag(equipmentId: "eq-1", name: "speed"), BuildVirtualTag(equipmentId: "eq-2", name: "speed"), ], }; DraftValidator.Validate(draft).ShouldNotContain(e => e.Code == "EquipmentSignalNameCollision"); } private static VirtualTag BuildVirtualTag(string equipmentId, string name, string suffix = "") => new() { VirtualTagId = $"vtag-{equipmentId}-{name}{suffix}", EquipmentId = equipmentId, Name = name, DataType = "Float", ScriptId = "s-1", }; // ------------------------------------------------------------------------------------ // Phase 6.3 task #148 part 2 — ValidateClusterTopology (unchanged in v3) // ------------------------------------------------------------------------------------ /// Verifies that cluster topology validation checks node count against declared redundancy mode. /// The declared cluster node count. /// The declared redundancy mode. /// The number of enabled nodes to include in the topology. /// The number of ClusterRedundancyModeInvalid errors expected. [Theory] [InlineData(1, RedundancyMode.None, 1, 0)] // single-node standalone — ok [InlineData(2, RedundancyMode.Warm, 2, 0)] // 2-node warm — ok [InlineData(2, RedundancyMode.Hot, 2, 0)] // 2-node hot — ok [InlineData(1, RedundancyMode.Warm, 1, 1)] // declared mismatch — should flag [InlineData(2, RedundancyMode.None, 2, 1)] // None with 2 nodes — should flag public void ValidateClusterTopology_checks_declared_pair( byte nodeCount, RedundancyMode mode, int enabledNodes, int expectedDeclaredErrors) { var cluster = BuildCluster(nodeCount: nodeCount, mode: mode); var nodes = Enumerable.Range(0, enabledNodes) .Select(i => BuildNode($"n-{i}", enabled: true)) .ToList(); var errors = DraftValidator.ValidateClusterTopology(cluster, nodes); errors.Count(e => e.Code == "ClusterRedundancyModeInvalid").ShouldBe(expectedDeclaredErrors); } /// Verifies that disabled nodes cause topology validation to fail. [Fact] public void ValidateClusterTopology_flags_disabled_node_mismatch() { var cluster = BuildCluster(nodeCount: 2, mode: RedundancyMode.Hot); var nodes = new[] { BuildNode("primary", enabled: true), BuildNode("backup", enabled: false), }; var errors = DraftValidator.ValidateClusterTopology(cluster, nodes); errors.ShouldContain(e => e.Code == "ClusterEnabledNodeCountMismatch"); } /// Verifies that a valid standalone cluster passes validation. [Fact] public void ValidateClusterTopology_returns_no_errors_on_valid_standalone() { var cluster = BuildCluster(nodeCount: 1, mode: RedundancyMode.None); var nodes = new[] { BuildNode("only", enabled: true) }; var errors = DraftValidator.ValidateClusterTopology(cluster, nodes); errors.ShouldBeEmpty(); } private static ServerCluster BuildCluster(byte nodeCount, RedundancyMode mode) => new() { ClusterId = "c-test", Name = "Test", Enterprise = "zb", Site = "dev", NodeCount = nodeCount, RedundancyMode = mode, Enabled = true, CreatedBy = "t", }; private static ClusterNode BuildNode(string id, bool enabled) => new() { NodeId = id, ClusterId = "c-test", Host = "localhost", OpcUaPort = 4840, DashboardPort = 5001, ApplicationUri = $"urn:{id}", ServiceLevelBase = 200, Enabled = enabled, CreatedBy = "t", }; // ------------------------------------------------------------------------------------ // ValidatePathLength — Enterprise/Site length precision (Configuration-003) // ------------------------------------------------------------------------------------ /// Verifies that path length validation uses actual Enterprise and Site lengths. [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"); } /// Verifies that path length validation uses conservative fallback when Enterprise and Site are absent. [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"); } }