Merge branch 'master' into fix/832-docker-dev-batch
This commit is contained in:
+78
@@ -0,0 +1,78 @@
|
||||
using Microsoft.Extensions.Logging.Abstractions;
|
||||
using Shouldly;
|
||||
using Xunit;
|
||||
using ZB.MOM.WW.OtOpcUa.AdminUI.Browsing;
|
||||
using ZB.MOM.WW.OtOpcUa.Commons.Browsing;
|
||||
using ZB.MOM.WW.OtOpcUa.Core.Abstractions;
|
||||
|
||||
namespace ZB.MOM.WW.OtOpcUa.AdminUI.Tests.Browsing;
|
||||
|
||||
/// <summary>
|
||||
/// lmxopcua#815: the AdminUI live browse (Galaxy / OpcUaClient bespoke browsers, and the Discover-backed universal
|
||||
/// browser) resolves the config's credential references and sends them to the author-chosen endpoint — an
|
||||
/// out-of-namespace reference is refused before any browser is opened.
|
||||
/// </summary>
|
||||
[Trait("Category", "Unit")]
|
||||
public sealed class BrowserSessionCredentialScopeTests
|
||||
{
|
||||
[Theory]
|
||||
[InlineData(DriverTypeNames.Galaxy, """{"Gateway":{"Endpoint":"http://evil:5001","ApiKeySecretRef":"env:ConnectionStrings__ConfigDb"}}""")]
|
||||
[InlineData(DriverTypeNames.OpcUaClient, """{"EndpointUrl":"opc.tcp://evil:4840","Password":"secret:otopcua/historian/api-key"}""")]
|
||||
[InlineData(DriverTypeNames.Heidenhain, """{"Access":{"InspectPassword":"secret:galaxy/main/apikey"}}""")]
|
||||
public async Task Out_of_namespace_reference_never_opens_a_browser(string driverType, string config)
|
||||
{
|
||||
var bespoke = new RecordingBrowser(DriverTypeNames.Galaxy);
|
||||
var bespoke2 = new RecordingBrowser(DriverTypeNames.OpcUaClient);
|
||||
var universal = new RecordingUniversal();
|
||||
var svc = new BrowserSessionService(
|
||||
[bespoke, bespoke2], new BrowseSessionRegistry(), NullLogger<BrowserSessionService>.Instance, universal, null!, null!);
|
||||
|
||||
var result = await svc.OpenAsync(driverType, config, TestContext.Current.CancellationToken);
|
||||
|
||||
result.Ok.ShouldBeFalse();
|
||||
result.Message.ShouldNotBeNull().ShouldContain("lmxopcua#815");
|
||||
bespoke.Opens.ShouldBe(0);
|
||||
bespoke2.Opens.ShouldBe(0);
|
||||
universal.Opens.ShouldBe(0);
|
||||
}
|
||||
|
||||
/// <summary>Positive control: a namespaced reference reaches the browser.</summary>
|
||||
[Fact]
|
||||
public async Task A_namespaced_reference_reaches_the_browser()
|
||||
{
|
||||
var bespoke = new RecordingBrowser(DriverTypeNames.Galaxy);
|
||||
var svc = new BrowserSessionService(
|
||||
[bespoke], new BrowseSessionRegistry(), NullLogger<BrowserSessionService>.Instance, new RecordingUniversal(), null!, null!);
|
||||
|
||||
await svc.OpenAsync(DriverTypeNames.Galaxy, """{"Gateway":{"ApiKeySecretRef":"secret:galaxy/main/apikey"}}""",
|
||||
TestContext.Current.CancellationToken);
|
||||
|
||||
bespoke.Opens.ShouldBe(1);
|
||||
}
|
||||
|
||||
private sealed class RecordingBrowser(string driverType) : IDriverBrowser
|
||||
{
|
||||
public int Opens { get; private set; }
|
||||
|
||||
public string DriverType => driverType;
|
||||
|
||||
public Task<IBrowseSession> OpenAsync(string configJson, CancellationToken cancellationToken)
|
||||
{
|
||||
Opens++;
|
||||
throw new InvalidOperationException("opened");
|
||||
}
|
||||
}
|
||||
|
||||
private sealed class RecordingUniversal : IUniversalDriverBrowser
|
||||
{
|
||||
public int Opens { get; private set; }
|
||||
|
||||
public bool CanBrowse(string driverType, string configJson) => true;
|
||||
|
||||
public Task<IBrowseSession> OpenAsync(string driverType, string configJson, CancellationToken ct)
|
||||
{
|
||||
Opens++;
|
||||
throw new InvalidOperationException("opened");
|
||||
}
|
||||
}
|
||||
}
|
||||
+177
@@ -0,0 +1,177 @@
|
||||
using System.Text;
|
||||
using Microsoft.Extensions.DependencyInjection;
|
||||
using Microsoft.Extensions.Hosting;
|
||||
using Microsoft.Extensions.Logging;
|
||||
using Shouldly;
|
||||
using Xunit;
|
||||
using ZB.MOM.WW.OtOpcUa.AdminUI.Deployments;
|
||||
using ZB.MOM.WW.OtOpcUa.AdminUI.Tests.Uns;
|
||||
using ZB.MOM.WW.OtOpcUa.Commons.Messages.Drivers;
|
||||
using ZB.MOM.WW.OtOpcUa.Configuration;
|
||||
using ZB.MOM.WW.OtOpcUa.Configuration.Entities;
|
||||
using ZB.MOM.WW.OtOpcUa.Core.Abstractions;
|
||||
|
||||
namespace ZB.MOM.WW.OtOpcUa.AdminUI.Tests.Deployments;
|
||||
|
||||
/// <summary>
|
||||
/// lmxopcua#815 upgrade preflight: stored (draft) and deployed configs with out-of-namespace credential references
|
||||
/// are listed and logged — driver, device, field, allowed form — and never the value; nothing is resolved.
|
||||
/// </summary>
|
||||
[Trait("Category", "Unit")]
|
||||
public sealed class CredentialReferencePreflightTests
|
||||
{
|
||||
private static CancellationToken Ct => TestContext.Current.CancellationToken;
|
||||
|
||||
private const string LegacyGalaxy = """{"Gateway":{"Endpoint":"http://gw:5001","ApiKeySecretRef":"env:MX_API_KEY"}}""";
|
||||
|
||||
private static string SeedLegacy()
|
||||
{
|
||||
var name = RawTreeTestDb.SeedFresh();
|
||||
using var db = RawTreeTestDb.CreateNamed(name);
|
||||
// Written straight to the DB, as a pre-#815 build would have — the save gate now refuses it.
|
||||
db.DriverInstances.Add(new DriverInstance
|
||||
{
|
||||
DriverInstanceId = "gx-old", ClusterId = RawTreeTestDb.ClusterId, Name = "Galaxy main",
|
||||
DriverType = DriverTypeNames.Galaxy, DriverConfig = LegacyGalaxy,
|
||||
});
|
||||
db.Devices.Add(new Device
|
||||
{
|
||||
DeviceId = "ouc-dev", DriverInstanceId = "gx-old", Name = "gw1",
|
||||
DeviceConfig = """{"AlarmAck":{"FallbackPasswordSecretRef":"file:C:\\keys\\ack.txt"}}""",
|
||||
});
|
||||
db.DriverInstances.Add(new DriverInstance
|
||||
{
|
||||
DriverInstanceId = "mb", ClusterId = RawTreeTestDb.ClusterId, Name = "modbus",
|
||||
DriverType = DriverTypeNames.Modbus, DriverConfig = """{"Password":"env:ConnectionStrings__ConfigDb"}""",
|
||||
});
|
||||
var artifact = """
|
||||
{"DriverInstances":[{"DriverInstanceId":"ouc","Name":"Upstream","DriverType":"OpcUaClient",
|
||||
"DriverConfig":"{\"Password\":\"secret:plant/opcua-pw\"}"}]}
|
||||
""";
|
||||
db.Deployments.Add(new Deployment { RevisionHash = "abc", CreatedBy = "t", ArtifactBlob = Encoding.UTF8.GetBytes(artifact) });
|
||||
db.SaveChanges();
|
||||
return name;
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Scan_lists_draft_rows_devices_and_the_deployed_artifact_without_values()
|
||||
{
|
||||
var findings = await new CredentialReferencePreflight(RawTreeTestDb.Factory(SeedLegacy())).ScanAsync(Ct);
|
||||
|
||||
findings.ShouldContain(f => f.Source == CredentialFindingSource.Draft && f.DriverName == "Galaxy main"
|
||||
&& f.DeviceName == null && f.Problem.Contains("Gateway.ApiKeySecretRef")
|
||||
&& f.Problem.Contains("env:OTOPCUA_GALAXY_<NAME>"));
|
||||
findings.ShouldContain(f => f.Source == CredentialFindingSource.Draft && f.DeviceName == "gw1"
|
||||
&& f.Problem.Contains("AlarmAck.FallbackPasswordSecretRef"));
|
||||
findings.ShouldContain(f => f.Source == CredentialFindingSource.Deployed && f.DriverName == "Upstream"
|
||||
&& f.Problem.Contains("secret:opcuaclient/<name>"));
|
||||
findings.ShouldNotContain(f => f.DriverInstanceId == "mb"); // not a credential-resolving driver
|
||||
findings.ShouldAllBe(f => !f.Problem.Contains("MX_API_KEY") && !f.Problem.Contains("plant/opcua-pw")
|
||||
&& !f.Problem.Contains("ack.txt"));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task A_clean_database_has_no_findings()
|
||||
=> (await new CredentialReferencePreflight(RawTreeTestDb.Factory(RawTreeTestDb.SeedFresh())).ScanAsync(Ct)).ShouldBeEmpty();
|
||||
|
||||
[Fact]
|
||||
public async Task The_boot_pass_logs_one_warning_per_finding_and_publishes_the_state()
|
||||
{
|
||||
var services = new ServiceCollection()
|
||||
.AddSingleton(RawTreeTestDb.Factory(SeedLegacy()))
|
||||
.BuildServiceProvider();
|
||||
var state = new CredentialReferencePreflightState();
|
||||
var logger = new CaptureLogger();
|
||||
var svc = new CredentialReferencePreflightService(services, new FakeLifetime(), state, logger) { StartDelay = TimeSpan.Zero };
|
||||
|
||||
var findings = await svc.RunOnceAsync(Ct);
|
||||
|
||||
findings.Count.ShouldBe(3);
|
||||
state.Current.Findings.Count.ShouldBe(3);
|
||||
state.Current.ScannedAtUtc.ShouldNotBeNull();
|
||||
var warnings = logger.Entries.Where(e => e.Level == LogLevel.Warning).ToList();
|
||||
warnings.Count.ShouldBe(3);
|
||||
warnings.ShouldAllBe(w => w.Message.Contains("lmxopcua#815") && !w.Message.Contains("MX_API_KEY"));
|
||||
warnings.ShouldContain(w => w.Message.Contains("Galaxy main") && w.Message.Contains("Gateway.ApiKeySecretRef"));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task A_node_without_a_config_db_skips_quietly()
|
||||
{
|
||||
var svc = new CredentialReferencePreflightService(
|
||||
new ServiceCollection().BuildServiceProvider(), new FakeLifetime(), new CredentialReferencePreflightState(), new CaptureLogger());
|
||||
(await svc.RunOnceAsync(Ct)).ShouldBeEmpty();
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task The_hosted_service_waits_for_ApplicationStarted_before_scanning()
|
||||
{
|
||||
var services = new ServiceCollection().AddSingleton(RawTreeTestDb.Factory(SeedLegacy())).BuildServiceProvider();
|
||||
var lifetime = new FakeLifetime();
|
||||
var state = new CredentialReferencePreflightState();
|
||||
var svc = new CredentialReferencePreflightService(services, lifetime, state, new CaptureLogger()) { StartDelay = TimeSpan.Zero };
|
||||
|
||||
await svc.StartAsync(Ct);
|
||||
await Task.Delay(100, Ct);
|
||||
state.Current.ScannedAtUtc.ShouldBeNull(); // nothing before the host has started
|
||||
|
||||
lifetime.Start();
|
||||
var deadline = DateTime.UtcNow.AddSeconds(10);
|
||||
while (state.Current.ScannedAtUtc is null && DateTime.UtcNow < deadline) await Task.Delay(20, Ct);
|
||||
state.Current.Findings.Count.ShouldBe(3);
|
||||
await svc.StopAsync(Ct);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Running_drivers_reporting_warn_only_resolution_are_surfaced_from_driver_health()
|
||||
{
|
||||
var snapshots = new[]
|
||||
{
|
||||
new DriverHealthChanged("c", "gx-old", "Healthy", null, null, 0, DateTime.UtcNow,
|
||||
Diagnostics: new Dictionary<string, string>
|
||||
{
|
||||
[LegacyCredentialReferenceTracker.DiagnosticsKeyPrefix + "Gateway.ApiKeySecretRef"] = "deprecated …",
|
||||
["s7.pdu"] = "480",
|
||||
}),
|
||||
new DriverHealthChanged("c", "mb", "Healthy", null, null, 0, DateTime.UtcNow),
|
||||
};
|
||||
|
||||
var running = CredentialReferencePreflight.RunningFindings(snapshots);
|
||||
|
||||
running.ShouldHaveSingleItem().ShouldSatisfyAllConditions(
|
||||
f => f.Source.ShouldBe(CredentialFindingSource.Running),
|
||||
f => f.DriverInstanceId.ShouldBe("gx-old"),
|
||||
f => f.Problem.ShouldStartWith("Gateway.ApiKeySecretRef"));
|
||||
}
|
||||
|
||||
private sealed class FakeLifetime : IHostApplicationLifetime
|
||||
{
|
||||
private readonly CancellationTokenSource _started = new();
|
||||
|
||||
public CancellationToken ApplicationStarted => _started.Token;
|
||||
|
||||
public CancellationToken ApplicationStopping => CancellationToken.None;
|
||||
|
||||
public CancellationToken ApplicationStopped => CancellationToken.None;
|
||||
|
||||
public void Start() => _started.Cancel();
|
||||
|
||||
public void StopApplication()
|
||||
{
|
||||
}
|
||||
}
|
||||
|
||||
private sealed class CaptureLogger : ILogger<CredentialReferencePreflightService>
|
||||
{
|
||||
public List<(LogLevel Level, string Message)> Entries { get; } = new();
|
||||
|
||||
public IDisposable? BeginScope<TState>(TState state) where TState : notnull => null;
|
||||
|
||||
public bool IsEnabled(LogLevel logLevel) => true;
|
||||
|
||||
public void Log<TState>(LogLevel logLevel, EventId eventId, TState state, Exception? exception, Func<TState, Exception?, string> formatter)
|
||||
{
|
||||
lock (Entries) Entries.Add((logLevel, formatter(state, exception)));
|
||||
}
|
||||
}
|
||||
}
|
||||
+25
@@ -180,6 +180,31 @@ public sealed class OpcUaClientDriverPageFormSerializationTests
|
||||
def.DiscoveryUrl.ShouldBeNull();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// #816: the server host-name check is tri-state. Unset must stay unset through the form (so a later change of
|
||||
/// the driver default reaches configs nobody chose for), and an explicit opt-in / NAT opt-out must survive.
|
||||
/// </summary>
|
||||
[Theory]
|
||||
[InlineData(null)]
|
||||
[InlineData(true)]
|
||||
[InlineData(false)]
|
||||
public void FormModel_RoundTrip_PreservesHostNameValidationTriState(bool? value)
|
||||
{
|
||||
var formOpts = new JsonSerializerOptions(_opts) { Converters = { new JsonStringEnumConverter() } };
|
||||
var original = new OpcUaClientDriverOptions
|
||||
{
|
||||
CertificateValidation = new OpcUaCertificateValidationOptions { ValidateServerHostName = value },
|
||||
};
|
||||
|
||||
var back = OpcUaClientDriverForm.OpcUaClientFormModel.FromRecord(original).ToRecord([]);
|
||||
back.CertificateValidation.ValidateServerHostName.ShouldBe(value);
|
||||
|
||||
var reparsed = JsonSerializer.Deserialize<OpcUaClientDriverOptions>(
|
||||
JsonSerializer.Serialize(back, formOpts), formOpts)!;
|
||||
reparsed.CertificateValidation.ValidateServerHostName.ShouldBe(value);
|
||||
reparsed.CertificateValidation.EffectiveValidateServerHostName.ShouldBe(value ?? false);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// #648: stored DriverConfig JSON from before <c>targetNamespaceKind</c>/<c>unsMappingTable</c> were removed
|
||||
/// must still load into the form (the form's options use <c>UnmappedMemberHandling.Skip</c>) and the legacy
|
||||
|
||||
@@ -0,0 +1,77 @@
|
||||
using Shouldly;
|
||||
using Xunit;
|
||||
using ZB.MOM.WW.OtOpcUa.AdminUI.Uns;
|
||||
using ZB.MOM.WW.OtOpcUa.Core.Abstractions;
|
||||
|
||||
namespace ZB.MOM.WW.OtOpcUa.AdminUI.Tests.Uns;
|
||||
|
||||
/// <summary>
|
||||
/// lmxopcua#815 at the SAVE path (RawTreeService): a Galaxy / OpcUaClient credential reference outside the
|
||||
/// driver's namespace never reaches the config DB, through driver and device create + update.
|
||||
/// </summary>
|
||||
[Trait("Category", "Unit")]
|
||||
public sealed class CredentialReferenceSavePathTests
|
||||
{
|
||||
private static CancellationToken Ct => TestContext.Current.CancellationToken;
|
||||
|
||||
[Theory]
|
||||
[InlineData(DriverTypeNames.Galaxy, """{"Gateway":{"Endpoint":"http://evil:5001","ApiKeySecretRef":"env:ConnectionStrings__ConfigDb"}}""")]
|
||||
[InlineData(DriverTypeNames.Galaxy, """{"Gateway":{"ApiKeySecretRef":"file:appsettings.json"}}""")]
|
||||
[InlineData(DriverTypeNames.Galaxy, """{"AlarmAck":{"FallbackPasswordSecretRef":"secret:otopcua/apikeys/ab/galaxy-ack-password"}}""")]
|
||||
[InlineData(DriverTypeNames.OpcUaClient, """{"EndpointUrl":"opc.tcp://evil:4840","Password":"secret:otopcua/historian/api-key"}""")]
|
||||
[InlineData(DriverTypeNames.OpcUaClient, """{"UserCertificatePassword":"env:ServerHistorian__ApiKey"}""")]
|
||||
public async Task CreateDriver_refuses_an_out_of_namespace_reference_and_persists_nothing(string type, string config)
|
||||
{
|
||||
var name = RawTreeTestDb.SeedFresh();
|
||||
var svc = new RawTreeService(RawTreeTestDb.Factory(name));
|
||||
var result = await svc.CreateDriverAsync(RawTreeTestDb.ClusterId, null, "d815", type, config, Ct);
|
||||
result.Ok.ShouldBeFalse();
|
||||
result.Error!.ShouldContain("lmxopcua#815");
|
||||
using var db = RawTreeTestDb.CreateNamed(name);
|
||||
db.DriverInstances.ShouldNotContain(d => d.Name == "d815");
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Update_paths_refuse_and_keep_the_stored_config()
|
||||
{
|
||||
var name = RawTreeTestDb.SeedFresh();
|
||||
var svc = new RawTreeService(RawTreeTestDb.Factory(name));
|
||||
var created = await svc.CreateDriverAsync(RawTreeTestDb.ClusterId, null, "gx", DriverTypeNames.Galaxy,
|
||||
"""{"Gateway":{"Endpoint":"http://gw:5001","ApiKeySecretRef":"secret:galaxy/gx/apikey"}}""", Ct);
|
||||
created.Ok.ShouldBeTrue(created.Error);
|
||||
|
||||
byte[] rv;
|
||||
string deviceId;
|
||||
byte[] deviceRv;
|
||||
using (var db = RawTreeTestDb.CreateNamed(name))
|
||||
{
|
||||
rv = db.DriverInstances.Single(d => d.DriverInstanceId == created.CreatedId).RowVersion;
|
||||
var device = db.Devices.Single(d => d.DriverInstanceId == created.CreatedId);
|
||||
deviceId = device.DeviceId;
|
||||
deviceRv = device.RowVersion;
|
||||
}
|
||||
|
||||
(await svc.UpdateDriverAsync(created.CreatedId!, "gx",
|
||||
"""{"Gateway":{"ApiKeySecretRef":"env:ConnectionStrings__ConfigDb"}}""", null, rv, Ct)).Ok.ShouldBeFalse();
|
||||
(await svc.UpdateDeviceAsync(deviceId, "dev",
|
||||
"""{"Gateway":{"ApiKeySecretRef":"env:ConnectionStrings__ConfigDb"}}""", true, deviceRv, Ct)).Ok.ShouldBeFalse();
|
||||
(await svc.CreateDeviceAsync(created.CreatedId!, "dev2",
|
||||
"""{"Gateway":{"ApiKeySecretRef":"secret:otopcua/historian/api-key"}}""", Ct)).Ok.ShouldBeFalse();
|
||||
|
||||
using var check = RawTreeTestDb.CreateNamed(name);
|
||||
check.DriverInstances.Single(d => d.DriverInstanceId == created.CreatedId).DriverConfig.ShouldContain("secret:galaxy/gx/apikey");
|
||||
check.Devices.Where(d => d.DriverInstanceId == created.CreatedId)
|
||||
.ShouldAllBe(d => !d.DeviceConfig.Contains("ConnectionStrings") && !d.DeviceConfig.Contains("historian"));
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData(DriverTypeNames.Galaxy, """{"Gateway":{"ApiKeySecretRef":"env:GALAXY_MXGW_API_KEY"},"AlarmAck":{"FallbackPasswordSecretRef":"secret:otopcua/galaxy/ack-fallback"}}""")]
|
||||
[InlineData(DriverTypeNames.OpcUaClient, """{"Password":"literal-password","UserCertificatePassword":"secret:opcuaclient/plant/cert"}""")]
|
||||
public async Task Namespaced_references_save(string type, string config)
|
||||
{
|
||||
var name = RawTreeTestDb.SeedFresh();
|
||||
var svc = new RawTreeService(RawTreeTestDb.Factory(name));
|
||||
var result = await svc.CreateDriverAsync(RawTreeTestDb.ClusterId, null, "ok815", type, config, Ct);
|
||||
result.Ok.ShouldBeTrue(result.Error);
|
||||
}
|
||||
}
|
||||
@@ -53,7 +53,10 @@ public sealed class HeidenhainAuthoringTests
|
||||
{
|
||||
var m = HeidenhainDriverFormModel.FromJson("{}");
|
||||
m.DncPassword = "hunter2";
|
||||
m.Validate()!.ShouldNotContain("hunter2");
|
||||
// #830: the credential refusal is the hosting modal's (the save gate), reported once — not the form's too.
|
||||
var refusal = DriverConfigSaveGate.Validate(DriverTypeNames.Heidenhain, m.ToJson());
|
||||
refusal.ShouldNotBeNull();
|
||||
refusal.ShouldNotContain("hunter2");
|
||||
m.DncPassword = null;
|
||||
m.StatusMs = 10;
|
||||
m.Validate().ShouldNotBeNull();
|
||||
@@ -66,7 +69,7 @@ public sealed class HeidenhainAuthoringTests
|
||||
d.Port.ShouldBe(19000);
|
||||
d.Validate().ShouldBeNull();
|
||||
d.DataPassword = "plain";
|
||||
d.Validate().ShouldNotBeNull();
|
||||
DriverConfigSaveGate.Validate(DriverTypeNames.Heidenhain, d.ToJson()).ShouldNotBeNull(); // #830: the modal's gate
|
||||
d.DataPassword = "env:OTOPCUA_HEIDENHAIN_DATA";
|
||||
var json = d.ToJson();
|
||||
JsonNode.Parse(json)!["Note"]!.GetValue<string>().ShouldBe("keep");
|
||||
|
||||
@@ -0,0 +1,176 @@
|
||||
using Shouldly;
|
||||
using Xunit;
|
||||
using ZB.MOM.WW.OtOpcUa.AdminUI.Components.Shared.Drivers.DeviceForms;
|
||||
using ZB.MOM.WW.OtOpcUa.AdminUI.Components.Shared.Drivers.Forms;
|
||||
using ZB.MOM.WW.OtOpcUa.AdminUI.Uns;
|
||||
using ZB.MOM.WW.OtOpcUa.AdminUI.Uns.TagEditors;
|
||||
using ZB.MOM.WW.OtOpcUa.Configuration.Enums;
|
||||
using ZB.MOM.WW.OtOpcUa.Core.Abstractions;
|
||||
using ZB.MOM.WW.OtOpcUa.Driver.Heidenhain;
|
||||
|
||||
namespace ZB.MOM.WW.OtOpcUa.AdminUI.Tests.Uns;
|
||||
|
||||
/// <summary>
|
||||
/// lmxopcua#830 authoring UX: (a) the CSV review grid previews the SAME row rule the commit applies, (b) the
|
||||
/// driver-dictated data type is a lock, never a silent rewrite, (c) a credential refusal is reported once.
|
||||
/// Plus the #831 ALARM: authoring seams (editor seeding, native-alarm editor visibility).
|
||||
/// </summary>
|
||||
[Trait("Category", "Unit")]
|
||||
public sealed class HeidenhainAuthoringUxTests
|
||||
{
|
||||
private static CancellationToken Ct => TestContext.Current.CancellationToken;
|
||||
|
||||
private const string Header = "Name,DataType,AccessLevel,TagConfigJson";
|
||||
|
||||
private static string Csv(params string[] rows) => Header + "\n" + string.Join("\n", rows);
|
||||
|
||||
private static string Json(string json) => "\"" + json.Replace("\"", "\"\"") + "\"";
|
||||
|
||||
// ---- (a) CSV preview == commit ----
|
||||
|
||||
[Fact]
|
||||
public void Csv_preview_flags_ReadWrite_and_data_type_mismatch_rows_like_the_commit()
|
||||
{
|
||||
var exec = Json("""{"address":"Status/ExecutionState"}""");
|
||||
var result = RawTagCsvMapper.Parse(DriverTypeNames.Heidenhain, Csv(
|
||||
$"ok,Int32,Read,{exec}",
|
||||
$"rw,Int32,ReadWrite,{exec}",
|
||||
$"dt,Double,Read,{exec}",
|
||||
$"feed,Int32,Read,{Json("""{"address":"Overrides/Feed"}""")}"));
|
||||
|
||||
result.FatalError.ShouldBeNull();
|
||||
var rows = result.Rows;
|
||||
rows[0].Ok.ShouldBeTrue(rows[0].Error);
|
||||
rows[1].Error!.ShouldContain("read-only");
|
||||
rows[2].Error!.ShouldContain("Int32");
|
||||
rows[3].Error!.ShouldContain("Double"); // a Float64 leaf publishes Double — picked as Int32 it used to preview OK
|
||||
result.CanCommit.ShouldBeFalse();
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Csv_preview_and_ImportTags_agree_row_for_row()
|
||||
{
|
||||
var exec = Json("""{"address":"Status/ExecutionState"}""");
|
||||
var csv = Csv($"ok,Int32,Read,{exec}", $"rw,Int32,ReadWrite,{exec}", $"dt,String,Read,{exec}",
|
||||
$"plc,Int64,Read,{Json("""{"address":"PLC:DWORD:0","dataType":"Int64"}""")}");
|
||||
var preview = RawTagCsvMapper.Parse(DriverTypeNames.Heidenhain, csv);
|
||||
|
||||
var name = RawTreeTestDb.SeedFresh();
|
||||
var svc = new RawTreeService(RawTreeTestDb.Factory(name));
|
||||
var created = await svc.CreateDriverAsync(RawTreeTestDb.ClusterId, null, "hh1", DriverTypeNames.Heidenhain, "{}", Ct);
|
||||
string deviceId;
|
||||
using (var db = RawTreeTestDb.CreateNamed(name)) deviceId = db.Devices.Single(d => d.DriverInstanceId == created.CreatedId).DeviceId;
|
||||
|
||||
// Feed EVERY parsed row (the invalid ones too, rebuilt from their cells) to the commit and compare verdicts.
|
||||
foreach (var row in preview.Rows)
|
||||
{
|
||||
var dataType = row.Cells[1];
|
||||
var access = Enum.Parse<TagAccessLevel>(row.Cells[2]);
|
||||
var input = new RawTagInput(row.Cells[0], dataType, access, false, null, row.Cells[3]);
|
||||
var outcome = await svc.ImportTagsAsync(deviceId, [new RawTagImportRow(null, input)], Ct);
|
||||
(outcome.Errors.Count == 0).ShouldBe(row.Ok, $"{row.Name}: preview {row.Error ?? "OK"} vs commit {string.Join("; ", outcome.Errors)}");
|
||||
}
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Row_rules_are_driver_dispatched_not_named_at_call_sites()
|
||||
{
|
||||
RawTagRowRules.DriverTypesWithRules.ShouldContain(DriverTypeNames.Heidenhain);
|
||||
RawTagRowRules.Problem(DriverTypeNames.Modbus, TagAccessLevel.ReadWrite, "Float", "{}").ShouldBeNull();
|
||||
RawTagRowRules.Problem(DriverTypeNames.Heidenhain, TagAccessLevel.ReadWrite, "Int32", """{"address":"Status/ExecutionState"}""")
|
||||
.ShouldBe(HeidenhainTagRules.DescribeRowProblem(true, "Int32", """{"address":"Status/ExecutionState"}"""));
|
||||
RawTagRowRules.IsReadOnlyDriver(DriverTypeNames.Heidenhain).ShouldBeTrue();
|
||||
RawTagRowRules.IsReadOnlyDriver(DriverTypeNames.S7).ShouldBeFalse();
|
||||
}
|
||||
|
||||
// ---- (b) dictated data type is a lock ----
|
||||
|
||||
[Theory]
|
||||
[InlineData("""{"address":"Axes/Positions","isArray":true}""", "Double")]
|
||||
[InlineData("""{"address":"PLC:WORD:3","dataType":"Int16"}""", "Int16")]
|
||||
[InlineData("""{"address":"ALARM:*","alarm":{}}""", "Boolean")]
|
||||
public void The_dictated_data_type_is_what_the_grid_and_modal_lock_to(string config, string expected)
|
||||
{
|
||||
RawTagRowDefaults.DictatedDataType(DriverTypeNames.Heidenhain, config).ShouldBe(expected);
|
||||
// ...and the locked value is exactly what the save path accepts — nothing to rewrite on commit.
|
||||
RawTagRowRules.Problem(DriverTypeNames.Heidenhain, TagAccessLevel.Read, expected, config).ShouldBeNull();
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void An_unresolved_config_or_another_driver_leaves_the_data_type_to_the_operator()
|
||||
{
|
||||
RawTagRowDefaults.DictatedDataType(DriverTypeNames.Heidenhain, "{}").ShouldBeNull();
|
||||
RawTagRowDefaults.DictatedDataType(DriverTypeNames.Modbus, """{"address":"Axes/Positions","isArray":true}""").ShouldBeNull();
|
||||
}
|
||||
|
||||
// ---- (c) credential error shown once ----
|
||||
|
||||
[Fact]
|
||||
public void A_literal_password_is_reported_by_the_modal_save_gate_only_not_also_by_the_form()
|
||||
{
|
||||
var driver = HeidenhainDriverFormModel.FromJson("{}");
|
||||
driver.InspectPassword = "hunter2";
|
||||
var json = driver.ToJson();
|
||||
DriverConfigSaveGate.Validate(DriverTypeNames.Heidenhain, json).ShouldNotBeNull(); // the modal's one notice + Save disabled
|
||||
driver.Validate().ShouldBeNull(); // the form no longer repeats it
|
||||
driver.StatusMs = 10;
|
||||
driver.Validate()!.ShouldContain("StatusMs"); // non-credential problems still show in the form
|
||||
|
||||
var device = HeidenhainDeviceModel.FromJson("""{"Host":"cnc-7"}""");
|
||||
device.DncPassword = "hunter2";
|
||||
DriverConfigSaveGate.Validate(DriverTypeNames.Heidenhain, device.ToJson()).ShouldNotBeNull();
|
||||
device.Validate().ShouldBeNull();
|
||||
HeidenhainDeviceModel.FromJson("{}").Validate().ShouldNotBeNull(); // host still required in the form
|
||||
}
|
||||
|
||||
// ---- #831 authoring seams ----
|
||||
|
||||
[Fact]
|
||||
public void Picking_an_alarm_selector_seeds_the_alarm_object_and_leaving_it_drops_it()
|
||||
{
|
||||
var m = HeidenhainTagConfigModel.FromJson("{}");
|
||||
m.Address = "ALARM:CLASS=7";
|
||||
var json = m.ToJson();
|
||||
m.Validate().ShouldBeNull();
|
||||
TagConfigValidator.Validate(DriverTypeNames.Heidenhain, json).ShouldBeNull();
|
||||
NativeAlarmModel.FromJson(json).IsAlarm.ShouldBeTrue();
|
||||
HeidenhainTagDefinitionFactory.TryFromTagConfig("p", "d", json, out var def, out _).ShouldBeTrue();
|
||||
def!.Alarm!.Severity.ShouldBe(HeidenhainTagConfigModel.DefaultAlarmSeverity);
|
||||
|
||||
// An authored severity is never overwritten by a later edit.
|
||||
var edited = NativeAlarmModel.Edit(json, a => a.Severity = 950);
|
||||
var again = HeidenhainTagConfigModel.FromJson(edited);
|
||||
again.Address = "ALARM:*";
|
||||
HeidenhainTagDefinitionFactory.TryFromTagConfig("p", "d", again.ToJson(), out def, out _).ShouldBeTrue();
|
||||
def!.Alarm!.Severity.ShouldBe(950);
|
||||
|
||||
again.Address = "Status/ExecutionState";
|
||||
var plain = again.ToJson();
|
||||
NativeAlarmModel.FromJson(plain).IsAlarm.ShouldBeFalse();
|
||||
TagConfigValidator.Validate(DriverTypeNames.Heidenhain, plain).ShouldBeNull();
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Heidenhain_offers_the_native_alarm_editor_and_a_csv_alarm_row_imports()
|
||||
{
|
||||
NativeAlarmModel.SupportsNativeAlarms(DriverTypeNames.Heidenhain).ShouldBeTrue();
|
||||
var result = RawTagCsvMapper.Parse(DriverTypeNames.Heidenhain,
|
||||
"Name,DataType,AccessLevel,TagConfigJson,Alarm.AlarmType,Alarm.Severity\n" +
|
||||
$"Any,Boolean,Read,{Json("""{"address":"ALARM:*"}""")},AlarmCondition,800\n" +
|
||||
$"NoAlarm,Boolean,Read,{Json("""{"address":"ALARM:*"}""")},,\n");
|
||||
result.Rows[0].Ok.ShouldBeTrue(result.Rows[0].Error);
|
||||
result.Rows[1].Ok.ShouldBeFalse(); // a selector without the alarm object is refused in the preview
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void The_driver_form_round_trips_the_alarm_cadence()
|
||||
{
|
||||
var m = HeidenhainDriverFormModel.FromJson("{}");
|
||||
m.AlarmMs.ShouldBe(2000);
|
||||
m.AlarmMs = 500;
|
||||
var o = HeidenhainOptionsParser.Parse(m.ToJson());
|
||||
o.Polling.AlarmMs.ShouldBe(500);
|
||||
m.AlarmMs = 50;
|
||||
m.Validate()!.ShouldContain("AlarmMs");
|
||||
}
|
||||
}
|
||||
@@ -98,7 +98,7 @@ public sealed class NativeAlarmEditorModelTests
|
||||
public void SupportsNativeAlarms_covers_exactly_the_IAlarmSource_drivers()
|
||||
{
|
||||
foreach (var t in new[] { DriverTypeNames.MTConnect, DriverTypeNames.AbCip, DriverTypeNames.FOCAS,
|
||||
DriverTypeNames.OpcUaClient, DriverTypeNames.Galaxy })
|
||||
DriverTypeNames.OpcUaClient, DriverTypeNames.Galaxy, DriverTypeNames.Heidenhain })
|
||||
NativeAlarmModel.SupportsNativeAlarms(t).ShouldBeTrue(t);
|
||||
foreach (var t in new[] { DriverTypeNames.Modbus, DriverTypeNames.S7, DriverTypeNames.Mqtt, null })
|
||||
NativeAlarmModel.SupportsNativeAlarms(t).ShouldBeFalse(t);
|
||||
|
||||
@@ -47,6 +47,9 @@
|
||||
<ProjectReference Include="..\..\..\src\Drivers\ZB.MOM.WW.OtOpcUa.Driver.FOCAS\ZB.MOM.WW.OtOpcUa.Driver.FOCAS.csproj"/>
|
||||
<ProjectReference Include="..\..\..\src\Drivers\ZB.MOM.WW.OtOpcUa.Driver.OpcUaClient\ZB.MOM.WW.OtOpcUa.Driver.OpcUaClient.csproj"/>
|
||||
<ProjectReference Include="..\..\..\src\Drivers\ZB.MOM.WW.OtOpcUa.Driver.Galaxy\ZB.MOM.WW.OtOpcUa.Driver.Galaxy.csproj"/>
|
||||
<!-- #831: NativeAlarmDriverSetGuardTests discovers IAlarmSource implementers by scanning the driver DLLs
|
||||
deployed here, so a driver that raises native alarms must be referenced or the guard misses it. -->
|
||||
<ProjectReference Include="..\..\..\src\Drivers\ZB.MOM.WW.OtOpcUa.Driver.Heidenhain\ZB.MOM.WW.OtOpcUa.Driver.Heidenhain.csproj"/>
|
||||
</ItemGroup>
|
||||
|
||||
</Project>
|
||||
|
||||
Reference in New Issue
Block a user