using System.Text.Json; using System.Text.Json.Serialization; using Shouldly; using Xunit; using ZB.MOM.WW.OtOpcUa.AdminUI.Components.Shared.Drivers.Forms; using ZB.MOM.WW.OtOpcUa.Driver.AbCip; namespace ZB.MOM.WW.OtOpcUa.AdminUI.Tests; public sealed class AbCipDriverPageFormSerializationTests { private static readonly JsonSerializerOptions _opts = new() { PropertyNamingPolicy = JsonNamingPolicy.CamelCase, WriteIndented = false, }; private static readonly JsonSerializerOptions TestJsonOpts = new() { PropertyNamingPolicy = JsonNamingPolicy.CamelCase, UnmappedMemberHandling = JsonUnmappedMemberHandling.Skip, }; [Fact] public void RoundTrip_PreservesKnownFields() { var original = new AbCipDriverOptions { Timeout = TimeSpan.FromSeconds(5), EnableControllerBrowse = true, EnableAlarmProjection = true, AlarmPollInterval = TimeSpan.FromSeconds(2), EnableDeclarationOnlyUdtGrouping = true, Probe = new AbCipProbeOptions { Enabled = true, Interval = TimeSpan.FromSeconds(10), Timeout = TimeSpan.FromSeconds(3), ProbeTagPath = "Program:Main.HealthBit", }, ProbeTimeoutSeconds = 10, Devices = [ new AbCipDeviceOptions("ab://10.0.0.1/1,0", AbCipPlcFamily.ControlLogix, "PLC-1"), ], }; var json = JsonSerializer.Serialize(original, _opts); var back = JsonSerializer.Deserialize(json, _opts); back.ShouldNotBeNull(); back.Timeout.ShouldBe(TimeSpan.FromSeconds(5)); back.EnableControllerBrowse.ShouldBeTrue(); back.EnableAlarmProjection.ShouldBeTrue(); back.AlarmPollInterval.ShouldBe(TimeSpan.FromSeconds(2)); back.EnableDeclarationOnlyUdtGrouping.ShouldBeTrue(); back.Probe.Enabled.ShouldBeTrue(); back.Probe.Interval.ShouldBe(TimeSpan.FromSeconds(10)); back.Probe.Timeout.ShouldBe(TimeSpan.FromSeconds(3)); back.Probe.ProbeTagPath.ShouldBe("Program:Main.HealthBit"); back.ProbeTimeoutSeconds.ShouldBe(10); back.Devices.Count.ShouldBe(1); back.Devices[0].HostAddress.ShouldBe("ab://10.0.0.1/1,0"); back.Devices[0].PlcFamily.ShouldBe(AbCipPlcFamily.ControlLogix); } [Fact] public void Deserialize_DropsUnknownFields() { var jsonWithExtra = """{"unknownField":"old-value","probeTimeoutSeconds":10}"""; var optsWithSkip = new JsonSerializerOptions(_opts) { UnmappedMemberHandling = JsonUnmappedMemberHandling.Skip, }; var back = JsonSerializer.Deserialize(jsonWithExtra, optsWithSkip); back.ShouldNotBeNull(); back.ProbeTimeoutSeconds.ShouldBe(10); } // v3 Batch-2 (WP3): the embedded-Devices CollectionEditor + AbCipDeviceRow retired — devices are now // separate Device entities authored via the raw-tree DeviceModal (AbCipDeviceModel, HostAddress/PlcFamily // into DeviceConfig). The former DeviceRow_* / ValidateDeviceRow_* tests were removed. The channel-config // FormModel now lives in AbCipDriverForm; the multi-device Devices array it preserves is covered below. [Fact] public void Device_list_survives_form_serialize_round_trip() { var devices = new List { new("ab://10.0.0.1/1,0", AbCipPlcFamily.ControlLogix, "PLC-1"), new("ab://10.0.0.2/1,0", AbCipPlcFamily.CompactLogix, "PLC-2"), }; var opts = new AbCipDriverForm.FormModel().ToOptions(devices); var json = JsonSerializer.Serialize(opts, TestJsonOpts); var back = JsonSerializer.Deserialize(json, TestJsonOpts)!; back.Devices.Count.ShouldBe(2); back.Devices[0].HostAddress.ShouldBe("ab://10.0.0.1/1,0"); back.Devices[0].PlcFamily.ShouldBe(AbCipPlcFamily.ControlLogix); back.Devices[1].PlcFamily.ShouldBe(AbCipPlcFamily.CompactLogix); } // ---- Task 19: Transport (native AB transport switch) ---- // These drive the form's OWN load/save path (TryDeserialize -> FromOptions -> ToOptions -> Serialize), // which uses the production JsonSerializerOptions, so a numeric enum or a dropped field shows up here. [Theory] [InlineData(AbCipTransport.Libplctag)] [InlineData(AbCipTransport.Native)] [InlineData(null)] public void Transport_survives_FromOptions_ToOptions(AbCipTransport? transport) { var original = new AbCipDriverOptions { Transport = transport }; var back = AbCipDriverForm.FormModel.FromOptions(original).ToOptions([]); back.Transport.ShouldBe(transport); } [Fact] public void Native_transport_serializes_as_a_string() { var form = new AbCipDriverForm.FormModel { Transport = AbCipTransport.Native }; var json = AbCipDriverForm.Serialize(form.ToOptions([])); json.ShouldContain("\"transport\":\"Native\""); } [Theory] [InlineData("Native", AbCipTransport.Native)] [InlineData("Libplctag", AbCipTransport.Libplctag)] public void Editing_an_unrelated_field_preserves_an_explicit_transport(string savedValue, AbCipTransport expected) { // The regression the review found: FromOptions/ToOptions dropped Transport, so an operator who set // a transport was silently reverted the next time they saved ANY other edit. var saved = $$"""{"transport":"{{savedValue}}","timeout":"00:00:02","devices":[]}"""; var loaded = AbCipDriverForm.TryDeserialize(saved); loaded.ShouldNotBeNull(); loaded.Transport.ShouldBe(expected); var form = AbCipDriverForm.FormModel.FromOptions(loaded); form.TimeoutSeconds = 7; var json = AbCipDriverForm.Serialize(form.ToOptions(loaded.Devices)); json.ShouldContain($"\"transport\":\"{savedValue}\""); json.ShouldContain("\"timeoutMs\":7000"); } [Fact] public void A_config_without_transport_loads_as_Default_and_an_unrelated_edit_keeps_the_key_absent() { // Task 22 reverses Task 19's "re-emit an explicit Libplctag": that would pin every edited driver to // a concrete transport and bypass the driver-side default (and AbLegacy's PLC-5 / LogixPccc // exclusion). Absent loads as Default (null) and a save that edits something else still omits it. var loaded = AbCipDriverForm.TryDeserialize("""{"probeTimeoutSeconds":5}"""); loaded.ShouldNotBeNull(); var form = AbCipDriverForm.FormModel.FromOptions(loaded); form.Transport.ShouldBeNull(); form.TimeoutSeconds = 7; var json = AbCipDriverForm.Serialize(form.ToOptions(loaded.Devices)); json.ShouldNotContain("transport", Case.Insensitive); json.ShouldContain("\"timeoutMs\":7000"); } [Fact] public void Choosing_Default_over_an_explicit_transport_drops_the_key() { var loaded = AbCipDriverForm.TryDeserialize("""{"transport":"Libplctag"}"""); loaded.ShouldNotBeNull(); var form = AbCipDriverForm.FormModel.FromOptions(loaded); form.Transport.ShouldBe(AbCipTransport.Libplctag); form.Transport = null; // the "Default (...)" dropdown option AbCipDriverForm.Serialize(form.ToOptions(loaded.Devices)).ShouldNotContain("transport", Case.Insensitive); } // ---- #576: preserve-unknown + MaxConcurrentReads ---- private const string FullConfig = """ {"transport":"Native","timeout":"00:00:05","maxConcurrentReads":3,"enableControllerBrowse":true, "enableDeclarationOnlyUdtGrouping":true,"enableAlarmProjection":true,"alarmPollInterval":"00:00:02", "probeTimeoutSeconds":12, "probe":{"enabled":true,"interval":"00:00:10","timeout":"00:00:03","probeTagPath":"Program:Main.Hb","futureProbeKnob":7}, "devices":[{"hostAddress":"ab://10.0.0.1/1,0","plcFamily":"ControlLogix","deviceName":"PLC-1","futureDeviceKey":"keep"}], "rawTags":[{"rawPath":"a/b"}], "futureOption":{"nested":[1,2,3]},"anotherUnknown":"x"} """; [Fact] public void Editing_one_field_preserves_every_other_option_and_unknown_keys() { var loaded = AbCipDriverForm.TryDeserialize(FullConfig)!; var form = AbCipDriverForm.FormModel.FromOptions(loaded); form.TimeoutSeconds = 9; // the one edit var root = System.Text.Json.Nodes.JsonNode.Parse( AbCipDriverForm.Serialize(form.ToOptions(loaded.Devices), FullConfig))!.AsObject(); root["timeoutMs"]!.GetValue().ShouldBe(9000); root.ContainsKey("timeout").ShouldBeFalse(); root["maxConcurrentReads"]!.GetValue().ShouldBe(3); // was reset to 8 before #576 root["transport"]!.GetValue().ShouldBe("Native"); root["enableControllerBrowse"]!.GetValue().ShouldBeTrue(); root["enableDeclarationOnlyUdtGrouping"]!.GetValue().ShouldBeTrue(); root["enableAlarmProjection"]!.GetValue().ShouldBeTrue(); root["alarmPollIntervalMs"]!.GetValue().ShouldBe(2000); root["probeTimeoutSeconds"]!.GetValue().ShouldBe(12); root["probe"]!["enabled"]!.GetValue().ShouldBeTrue(); root["probe"]!["intervalMs"]!.GetValue().ShouldBe(10000); root["probe"]!["timeoutMs"]!.GetValue().ShouldBe(3000); root["probe"]!["probeTagPath"]!.GetValue().ShouldBe("Program:Main.Hb"); // unknown keys at every level survive root["probe"]!["futureProbeKnob"]!.GetValue().ShouldBe(7); root["devices"]![0]!["futureDeviceKey"]!.GetValue().ShouldBe("keep"); root["rawTags"]![0]!["rawPath"]!.GetValue().ShouldBe("a/b"); root["futureOption"]!["nested"]!.AsArray().Count.ShouldBe(3); root["anotherUnknown"]!.GetValue().ShouldBe("x"); } [Fact] public void Choosing_Default_transport_and_clearing_the_probe_path_removes_those_keys_from_the_overlay() { var loaded = AbCipDriverForm.TryDeserialize(FullConfig)!; var form = AbCipDriverForm.FormModel.FromOptions(loaded); form.Transport = null; form.ProbeTagPath = ""; var root = System.Text.Json.Nodes.JsonNode.Parse( AbCipDriverForm.Serialize(form.ToOptions(loaded.Devices), FullConfig))!.AsObject(); root.ContainsKey("transport").ShouldBeFalse(); root["probe"]!.AsObject().ContainsKey("probeTagPath").ShouldBeFalse(); root["futureOption"].ShouldNotBeNull(); } [Fact] public void A_stored_PascalCase_key_is_replaced_not_duplicated() { var original = """{"Transport":"Native","TimeoutSeconds":1,"futureOption":true}"""; var loaded = AbCipDriverForm.TryDeserialize(original)!; var form = AbCipDriverForm.FormModel.FromOptions(loaded); form.Transport = AbCipTransport.Libplctag; var json = AbCipDriverForm.Serialize(form.ToOptions(loaded.Devices), original); System.Text.RegularExpressions.Regex.Matches(json, "transport", System.Text.RegularExpressions.RegexOptions.IgnoreCase) .Count.ShouldBe(1); json.ShouldContain("\"transport\":\"Libplctag\""); json.ShouldContain("futureOption"); } // ---- #576: the saved JSON must be what the driver FACTORY binds (integer-ms keys) ---- [Fact] public void An_edited_timeout_reaches_the_factory_bound_options() { var original = """{"timeoutMs":5000,"alarmPollIntervalMs":500,"probe":{"enabled":true,"intervalMs":7000,"timeoutMs":1500,"probeTagPath":"Program:Main.Hb"},"devices":[{"hostAddress":"ab://10.0.0.1/1,0"}]}"""; var loaded = AbCipDriverForm.TryDeserialize(original)!; var form = AbCipDriverForm.FormModel.FromJson(original, loaded); form.TimeoutSeconds.ShouldBe(5); // the form SEES the factory-keyed value form.TimeoutSeconds = 11; var saved = AbCipDriverForm.Serialize(form.ToOptions(loaded.Devices), original); var bound = ZB.MOM.WW.OtOpcUa.Driver.AbCip.AbCipDriverFactoryExtensions.ParseOptions("t", saved); bound.Timeout.ShouldBe(TimeSpan.FromSeconds(11)); // untouched durations keep their exact stored value, including sub-second ones bound.AlarmPollInterval.ShouldBe(TimeSpan.FromMilliseconds(500)); bound.Probe.Interval.ShouldBe(TimeSpan.FromSeconds(7)); bound.Probe.Timeout.ShouldBe(TimeSpan.FromMilliseconds(1500)); bound.Probe.ProbeTagPath.ShouldBe("Program:Main.Hb"); } [Fact] public void A_legacy_TimeSpan_string_key_is_loaded_then_migrated_to_ms_and_removed() { var original = """{"timeout":"00:00:05","alarmPollInterval":"00:00:02","probe":{"interval":"00:00:10","timeout":"00:00:03"}}"""; var loaded = AbCipDriverForm.TryDeserialize(original)!; var form = AbCipDriverForm.FormModel.FromJson(original, loaded); form.TimeoutSeconds.ShouldBe(5); form.TimeoutSeconds = 6; var saved = AbCipDriverForm.Serialize(form.ToOptions(loaded.Devices), original); var root = System.Text.Json.Nodes.JsonNode.Parse(saved)!.AsObject(); root.ContainsKey("timeout").ShouldBeFalse(); root.ContainsKey("alarmPollInterval").ShouldBeFalse(); root["probe"]!.AsObject().ContainsKey("interval").ShouldBeFalse(); root["probe"]!.AsObject().ContainsKey("timeout").ShouldBeFalse(); var bound = ZB.MOM.WW.OtOpcUa.Driver.AbCip.AbCipDriverFactoryExtensions.ParseOptions("t", saved); bound.Timeout.ShouldBe(TimeSpan.FromSeconds(6)); bound.AlarmPollInterval.ShouldBe(TimeSpan.FromSeconds(2)); bound.Probe.Interval.ShouldBe(TimeSpan.FromSeconds(10)); bound.Probe.Timeout.ShouldBe(TimeSpan.FromSeconds(3)); } [Fact] public void A_form_saved_config_is_still_accepted_by_the_Test_Connect_probe_parse() { // The probe deserialises the typed options and skips unmapped keys, so the ms keys must not break it. var original = """{"timeoutMs":5000,"devices":[{"hostAddress":"ab://10.0.0.1/1,0"}]}"""; var loaded = AbCipDriverForm.TryDeserialize(original)!; var form = AbCipDriverForm.FormModel.FromJson(original, loaded); form.TimeoutSeconds = 8; var saved = AbCipDriverForm.Serialize(form.ToOptions(loaded.Devices), original); var opts = System.Text.Json.JsonSerializer.Deserialize(saved, TestJsonOpts); opts.ShouldNotBeNull(); opts.Devices[0].HostAddress.ShouldBe("ab://10.0.0.1/1,0"); } // ---- #596: browsePageDelayMs is form-authorable, reaches the factory, and unknown keys survive ---- [Fact] public void BrowsePageDelayMs_is_loaded_edited_and_bound_by_the_factory_without_dropping_unknown_keys() { var original = """{"browsePageDelayMs":40,"futureOption":"keep-me","devices":[{"hostAddress":"ab://10.0.0.1/1,0"}]}"""; var loaded = AbCipDriverForm.TryDeserialize(original)!; var form = AbCipDriverForm.FormModel.FromJson(original, loaded); form.BrowsePageDelayMs.ShouldBe(40); // the form SEES the factory-keyed value var untouched = AbCipDriverForm.Serialize(form.ToOptions(loaded.Devices), original); ZB.MOM.WW.OtOpcUa.Driver.AbCip.AbCipDriverFactoryExtensions.ParseOptions("t", untouched) .BrowsePageDelay.ShouldBe(TimeSpan.FromMilliseconds(40)); form.BrowsePageDelayMs = 125; var saved = AbCipDriverForm.Serialize(form.ToOptions(loaded.Devices), original); ZB.MOM.WW.OtOpcUa.Driver.AbCip.AbCipDriverFactoryExtensions.ParseOptions("t", saved) .BrowsePageDelay.ShouldBe(TimeSpan.FromMilliseconds(125)); saved.ShouldContain("futureOption"); System.Text.Json.Nodes.JsonNode.Parse(saved)!.AsObject().ContainsKey("browsePageDelay").ShouldBeFalse(); } // ---- review R3-m4: the key is emitted only when loaded or changed from the default; negatives are flagged ---- [Fact] public void BrowsePageDelayMs_is_omitted_when_never_set_and_left_at_the_default() { var original = """{"futureOption":"keep-me","devices":[{"hostAddress":"ab://10.0.0.1/1,0"}]}"""; var loaded = AbCipDriverForm.TryDeserialize(original)!; var form = AbCipDriverForm.FormModel.FromJson(original, loaded); var saved = AbCipDriverForm.Serialize(form.ToOptions(loaded.Devices), original, form.EmitsBrowsePageDelay); System.Text.Json.Nodes.JsonNode.Parse(saved)!.AsObject().ContainsKey("browsePageDelayMs").ShouldBeFalse(); saved.ShouldContain("futureOption"); // Control: changing it away from the default DOES write it, and a loaded key is kept even at the default value. form.BrowsePageDelayMs = 125; var changed = AbCipDriverForm.Serialize(form.ToOptions(loaded.Devices), original, form.EmitsBrowsePageDelay); System.Text.Json.Nodes.JsonNode.Parse(changed)!["browsePageDelayMs"]!.GetValue().ShouldBe(125); var withKey = """{"browsePageDelayMs":5,"devices":[{"hostAddress":"ab://10.0.0.1/1,0"}]}"""; var f2 = AbCipDriverForm.FormModel.FromJson(withKey, AbCipDriverForm.TryDeserialize(withKey)!); f2.EmitsBrowsePageDelay.ShouldBeTrue(); } [Fact] public void BrowsePageDelayMs_negative_is_a_validation_error_zero_is_valid() { var form = new AbCipDriverForm.FormModel { BrowsePageDelayMs = -1 }; form.BrowsePageDelayError.ShouldNotBeNull(); form.BrowsePageDelayMs = 0; form.BrowsePageDelayError.ShouldBeNull(); } }