using System.Text.Json;
using System.Text.Json.Serialization;
using Shouldly;
using Xunit;
namespace ZB.MOM.WW.OtOpcUa.Driver.Modbus.Tests;
///
/// Regression guard for the 2026-06-19 enum-serialization bug (the FB-9 Modbus-Int64 authoring
/// case). The AdminUI Modbus page now serialises tag enums (,
/// , byte-order) as STRINGS. This proves the factory parses that
/// AdminUI-shaped Int64-tag blob, and documents that the pre-fix NUMERIC form threw because the
/// ModbusTagDto enum fields are string?.
///
public sealed class ModbusDriverConfigEnumSerializationTests
{
// Mirrors the (now fixed) AdminUI ModbusDriverPage._jsonOpts: camelCase + string enums.
private static readonly JsonSerializerOptions _adminPageOpts = new()
{
PropertyNamingPolicy = JsonNamingPolicy.CamelCase,
Converters = { new JsonStringEnumConverter() },
};
/// Verifies the factory parses an AdminUI-authored Modbus config carrying an Int64
/// holding-register tag (string enums) without throwing.
[Fact]
public void Factory_parses_admin_authored_int64_string_enum_config()
{
var tag = new ModbusTagDefinition("Int64Tag", ModbusRegion.HoldingRegisters, (ushort)100, ModbusDataType.Int64);
var opts = new ModbusDriverOptions { Host = "10.0.0.5", Port = 502, UnitId = 1, Tags = new[] { tag } };
var blob = JsonSerializer.Serialize(opts, _adminPageOpts);
// The fixed AdminUI page must emit tag enums as strings, not numbers.
blob.ShouldContain("\"dataType\":\"Int64\"");
using var driver = ModbusDriverFactoryExtensions.CreateInstance("mb-test", blob);
driver.DriverType.ShouldBe("Modbus");
}
/// Documents the original bug: the pre-fix AdminUI page emitted numeric tag enums
/// ("dataType":5,"region":3) which the string-typed tag DTO cannot bind, so the factory throws.
[Fact]
public void Factory_throws_on_the_numeric_enum_form_the_pre_fix_page_emitted()
{
const string numericBlob =
"{\"host\":\"10.0.0.5\",\"port\":502,\"unitId\":1,\"tags\":[" +
"{\"name\":\"Int64Tag\",\"region\":3,\"address\":100,\"dataType\":5}]}";
Should.Throw(() => ModbusDriverFactoryExtensions.CreateInstance("mb-test", numericBlob));
}
}