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.AbLegacy; using ZB.MOM.WW.OtOpcUa.Driver.AbLegacy.PlcFamilies; namespace ZB.MOM.WW.OtOpcUa.AdminUI.Tests; public sealed class AbLegacyDriverPageFormSerializationTests { 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 AbLegacyDriverOptions { Timeout = TimeSpan.FromSeconds(4), Probe = new AbLegacyProbeOptions { Enabled = true, Interval = TimeSpan.FromSeconds(8), Timeout = TimeSpan.FromSeconds(3), ProbeAddress = "N7:0", }, ProbeTimeoutSeconds = 10, Devices = [ new AbLegacyDeviceOptions("10.0.0.10", AbLegacyPlcFamily.Slc500, "PLC-A"), new AbLegacyDeviceOptions("10.0.0.11", AbLegacyPlcFamily.MicroLogix), ], }; var json = JsonSerializer.Serialize(original, _opts); var back = JsonSerializer.Deserialize(json, _opts); back.ShouldNotBeNull(); back.Timeout.ShouldBe(TimeSpan.FromSeconds(4)); back.Probe.Enabled.ShouldBeTrue(); back.Probe.Interval.ShouldBe(TimeSpan.FromSeconds(8)); back.Probe.Timeout.ShouldBe(TimeSpan.FromSeconds(3)); back.Probe.ProbeAddress.ShouldBe("N7:0"); back.ProbeTimeoutSeconds.ShouldBe(10); back.Devices.Count.ShouldBe(2); back.Devices[0].HostAddress.ShouldBe("10.0.0.10"); back.Devices[0].PlcFamily.ShouldBe(AbLegacyPlcFamily.Slc500); back.Devices[0].DeviceName.ShouldBe("PLC-A"); back.Devices[1].PlcFamily.ShouldBe(AbLegacyPlcFamily.MicroLogix); } [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 + AbLegacyDeviceRow retired — devices are now // separate Device entities authored via the raw-tree DeviceModal (AbLegacyDeviceModel, HostAddress/PlcFamily // into DeviceConfig). The former DeviceRow_* / ValidateDeviceRow_* tests were removed. The channel-config // FormModel now lives in AbLegacyDriverForm; 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("10.0.0.10", AbLegacyPlcFamily.Slc500, "PLC-1"), new("10.0.0.11", AbLegacyPlcFamily.MicroLogix, "PLC-2"), }; var opts = new AbLegacyDriverForm.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("10.0.0.10"); back.Devices[0].PlcFamily.ShouldBe(AbLegacyPlcFamily.Slc500); back.Devices[1].PlcFamily.ShouldBe(AbLegacyPlcFamily.MicroLogix); } // ---- 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(AbLegacyTransport.Libplctag)] [InlineData(AbLegacyTransport.Native)] [InlineData(null)] public void Transport_survives_FromOptions_ToOptions(AbLegacyTransport? transport) { var original = new AbLegacyDriverOptions { Transport = transport }; var back = AbLegacyDriverForm.FormModel.FromOptions(original).ToOptions([]); back.Transport.ShouldBe(transport); } [Fact] public void Native_transport_serializes_as_a_string() { var form = new AbLegacyDriverForm.FormModel { Transport = AbLegacyTransport.Native }; var json = AbLegacyDriverForm.Serialize(form.ToOptions([])); json.ShouldContain("\"transport\":\"Native\""); } [Theory] [InlineData("Native", AbLegacyTransport.Native)] [InlineData("Libplctag", AbLegacyTransport.Libplctag)] public void Editing_an_unrelated_field_preserves_an_explicit_transport(string savedValue, AbLegacyTransport 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 = AbLegacyDriverForm.TryDeserialize(saved); loaded.ShouldNotBeNull(); loaded.Transport.ShouldBe(expected); var form = AbLegacyDriverForm.FormModel.FromOptions(loaded); form.TimeoutSeconds = 7; var json = AbLegacyDriverForm.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 (Libplctag since final review I3). Absent loads as Default (null) and a save that edits something else still omits it. var loaded = AbLegacyDriverForm.TryDeserialize("""{"probeTimeoutSeconds":5}"""); loaded.ShouldNotBeNull(); var form = AbLegacyDriverForm.FormModel.FromOptions(loaded); form.Transport.ShouldBeNull(); form.TimeoutSeconds = 7; var json = AbLegacyDriverForm.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 = AbLegacyDriverForm.TryDeserialize("""{"transport":"Libplctag"}"""); loaded.ShouldNotBeNull(); var form = AbLegacyDriverForm.FormModel.FromOptions(loaded); form.Transport.ShouldBe(AbLegacyTransport.Libplctag); form.Transport = null; // the "Default (...)" dropdown option AbLegacyDriverForm.Serialize(form.ToOptions(loaded.Devices)).ShouldNotContain("transport", Case.Insensitive); } /// /// Final review I3: the dropdown labels must say what an absent key does (libplctag) and that Native is /// opt-in. Source scan (no bUnit in this repo); the labels are static option text. /// [Fact] public void The_transport_dropdown_labels_name_libplctag_as_the_default_and_native_as_opt_in() { var dir = new DirectoryInfo(AppContext.BaseDirectory); while (dir is not null && !File.Exists(Path.Combine(dir.FullName, "ZB.MOM.WW.OtOpcUa.slnx"))) dir = dir.Parent; dir.ShouldNotBeNull("could not locate the repository root"); var razor = File.ReadAllText(Path.Combine(dir!.FullName, "src", "Server", "ZB.MOM.WW.OtOpcUa.AdminUI", "Components", "Shared", "Drivers", "Forms", "AbLegacyDriverForm.razor")); razor.ShouldContain(""); razor.ShouldContain(""); razor.ShouldContain(""); razor.ShouldNotContain("Default (Native"); } // ---- #576: preserve-unknown ---- private const string FullConfig = """ {"transport":"Native","timeout":"00:00:05","probeTimeoutSeconds":12, "probe":{"enabled":true,"interval":"00:00:10","timeout":"00:00:03","probeAddress":"S:1","futureProbeKnob":7}, "devices":[{"hostAddress":"ab://10.0.0.1/1,0","plcFamily":"Slc500","futureDeviceKey":"keep"}], "rawTags":[{"rawPath":"a/b"}], "futureOption":{"nested":[1,2,3]}} """; [Fact] public void Editing_one_field_preserves_every_other_option_and_unknown_keys() { var loaded = AbLegacyDriverForm.TryDeserialize(FullConfig)!; var form = AbLegacyDriverForm.FormModel.FromOptions(loaded); form.TimeoutSeconds = 9; var root = System.Text.Json.Nodes.JsonNode.Parse( AbLegacyDriverForm.Serialize(form.ToOptions(loaded.Devices), FullConfig))!.AsObject(); root["timeoutMs"]!.GetValue().ShouldBe(9000); root.ContainsKey("timeout").ShouldBeFalse(); root["transport"]!.GetValue().ShouldBe("Native"); root["probeTimeoutSeconds"]!.GetValue().ShouldBe(12); root["probe"]!["enabled"]!.GetValue().ShouldBeTrue(); root["probe"]!["intervalMs"]!.GetValue().ShouldBe(10000); root["probe"]!["timeoutMs"]!.GetValue().ShouldBe(3000); root["probe"]!["probeAddress"]!.GetValue().ShouldBe("S:1"); 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); } [Fact] public void Choosing_Default_transport_removes_the_key_but_keeps_unknown_ones() { var loaded = AbLegacyDriverForm.TryDeserialize(FullConfig)!; var form = AbLegacyDriverForm.FormModel.FromOptions(loaded); form.Transport = null; var root = System.Text.Json.Nodes.JsonNode.Parse( AbLegacyDriverForm.Serialize(form.ToOptions(loaded.Devices), FullConfig))!.AsObject(); root.ContainsKey("transport").ShouldBeFalse(); root["futureOption"].ShouldNotBeNull(); } // ---- #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,"probe":{"enabled":true,"intervalMs":7000,"timeoutMs":1500,"probeAddress":"S:1"},"devices":[{"hostAddress":"ab://10.0.0.1/1,0","plcFamily":"Slc500"}]}"""; var loaded = AbLegacyDriverForm.TryDeserialize(original)!; var form = AbLegacyDriverForm.FormModel.FromJson(original, loaded); form.TimeoutSeconds.ShouldBe(5); form.TimeoutSeconds = 11; var saved = AbLegacyDriverForm.Serialize(form.ToOptions(loaded.Devices), original); var bound = ZB.MOM.WW.OtOpcUa.Driver.AbLegacy.AbLegacyDriverFactoryExtensions.ParseOptions("t", saved); bound.Timeout.ShouldBe(TimeSpan.FromSeconds(11)); bound.Probe.Interval.ShouldBe(TimeSpan.FromSeconds(7)); bound.Probe.Timeout.ShouldBe(TimeSpan.FromMilliseconds(1500)); bound.Probe.ProbeAddress.ShouldBe("S:1"); } [Fact] public void A_legacy_TimeSpan_string_key_is_loaded_then_migrated_to_ms_and_removed() { var original = """{"timeout":"00:00:05","probe":{"interval":"00:00:10","timeout":"00:00:03"}}"""; var loaded = AbLegacyDriverForm.TryDeserialize(original)!; var form = AbLegacyDriverForm.FormModel.FromJson(original, loaded); form.TimeoutSeconds.ShouldBe(5); form.TimeoutSeconds = 6; var saved = AbLegacyDriverForm.Serialize(form.ToOptions(loaded.Devices), original); var root = System.Text.Json.Nodes.JsonNode.Parse(saved)!.AsObject(); root.ContainsKey("timeout").ShouldBeFalse(); root["probe"]!.AsObject().ContainsKey("interval").ShouldBeFalse(); root["probe"]!.AsObject().ContainsKey("timeout").ShouldBeFalse(); var bound = ZB.MOM.WW.OtOpcUa.Driver.AbLegacy.AbLegacyDriverFactoryExtensions.ParseOptions("t", saved); bound.Timeout.ShouldBe(TimeSpan.FromSeconds(6)); bound.Probe.Interval.ShouldBe(TimeSpan.FromSeconds(10)); bound.Probe.Timeout.ShouldBe(TimeSpan.FromSeconds(3)); } }