Files
lmxopcua/tests/Server/ZB.MOM.WW.OtOpcUa.AdminUI.Tests/Raw/RawCsvRenderingTests.cs
T
Joseph Doherty 0f1f8ad8fa fix(adminui): lane D-b review r0 fixes (I1, M1, M2, M5-M9, N1-N3, N5, H3)
I1: /hosts eviction keyed off the AUTHORED DriverInstances, so a driver
deleted in /raw but not yet deployed - still running, still publishing -
vanished every tick. The stores' sweep is now EvictUnconfiguredStale(set,
olderThanUtc): an entry goes only when unconfigured AND its PublishedUtc is
older than 60 s. Tests cover unconfigured+fresh kept (positive control),
unconfigured+stale evicted, configured+stale kept, and the deploy hand-off.

M1: Test Connect falls back to the driver's documented ProbeTimeoutSeconds
default (Galaxy 30, OpcUaClient 15, ...) when the key is absent.
M2: the budget never undercuts the config's root timeoutMs (+1 s).
M5: RawBrowseModal compares the open generation captured before the await,
so a close-then-reopen mid-open closes the stale session.
M6: /alarms-historian keeps a 30 s re-poll on 'not registered' (a driver
node may still be starting) instead of stopping for good.
M7: /scripts source fetch failure shows in the dialog, not the error boundary.
M8: the export modal maps only its preview rows; the endpoint writes via
Results.Text (no second byte[] copy).
M9: /hosts config queries are ordered, so SequenceEqual change detection holds.
N1 tooltip, N2 CRLF-safe regex, N3 throttled Warning for subscriber faults,
N5 equipment-import help text now describes RFC 4180 quoting.
H3: MonacoEditor documents that themes are page-global.

Refs #745
Claude-Session: https://claude.ai/code/session_01Ub9hGmYLQvn9XETzw7CMsT
2026-10-22 18:21:46 -04:00

123 lines
5.2 KiB
C#

using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Routing;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.DependencyInjection;
using Shouldly;
using Xunit;
using ZB.MOM.WW.OtOpcUa.AdminUI.Uns;
using ZB.MOM.WW.OtOpcUa.Configuration;
using ZB.MOM.WW.OtOpcUa.Security.Auth;
namespace ZB.MOM.WW.OtOpcUa.AdminUI.Tests.Raw;
/// <summary>
/// R04 P6: the CSV import grid renders through Virtualize from a precomputed view, and the export is
/// downloaded from an endpoint (bounded preview in the modal) instead of being embedded in the circuit.
/// </summary>
[Trait("Category", "Unit")]
public sealed class RawCsvRenderingTests
{
private static RawCsvParseResult Result(params (int Row, bool Ok)[] rows) =>
new(["Name"], rows.Select(r => new RawCsvReviewRow
{
RowNumber = r.Row, Name = $"t{r.Row}", Error = r.Ok ? null : "bad",
ImportRow = r.Ok ? new RawTagImportRow(null, new RawTagInput($"t{r.Row}", "Int32", Configuration.Enums.TagAccessLevel.Read, false, null, "{}")) : null,
}).ToList(), null);
[Fact]
public void Review_view_counts_and_filters_once_per_change()
{
var view = new RawCsvReviewView();
view.Set(Result((1, true), (2, false), (3, true)));
view.OkCount.ShouldBe(2);
view.ErrorCount.ShouldBe(1);
view.RemainingCount.ShouldBe(3);
view.Remove(2);
view.ErrorCount.ShouldBe(0);
view.VisibleRows.Select(r => r.RowNumber).ShouldBe([1, 3]);
view.CommitRows().Select(r => r.Tag.Name).ShouldBe(["t1", "t3"]);
view.Set(null);
view.RemainingCount.ShouldBe(0);
// Positive control: a fresh set after a clear shows every row again (removals are forgotten).
view.Set(Result((1, true), (2, false)));
view.RemainingCount.ShouldBe(2);
}
[Fact]
public void Preview_is_bounded_and_flags_truncation()
{
var csv = string.Concat(Enumerable.Range(0, 200).Select(i => $"row{i}\n"));
var (preview, truncated) = RawTagCsvExport.Preview(csv, maxLines: 50);
truncated.ShouldBeTrue();
preview.Split('\n', StringSplitOptions.RemoveEmptyEntries).Length.ShouldBe(50);
var (all, cut) = RawTagCsvExport.Preview("a\nb\n", maxLines: 50);
cut.ShouldBeFalse();
all.ShouldBe("a\nb\n");
}
[Fact]
public async Task Preview_build_maps_only_the_first_rows_but_counts_all()
{
// Review r0 M8: the modal maps only its preview's rows; the full count still comes back.
var dbName = Uns.RawTreeTestDb.SeedFresh();
var reader = new RawTagCsvExportReader(Uns.RawTreeTestDb.Factory(dbName));
var full = await RawTagCsvExport.BuildAsync(reader, Uns.RawTreeTestDb.FolderedDeviceId, null, "Modbus");
var preview = await RawTagCsvExport.BuildAsync(reader, Uns.RawTreeTestDb.FolderedDeviceId, null, "Modbus", maxRows: 1);
full!.RowCount.ShouldBe(2);
Commons.Csv.CsvParser.Parse(full.Csv).Count.ShouldBe(3); // header + 2 (positive control)
preview!.RowCount.ShouldBe(2);
Commons.Csv.CsvParser.Parse(preview.Csv).Count.ShouldBe(2); // header + 1
}
[Fact]
public void Download_url_escapes_its_query_values()
{
RawTagCsvExport.DownloadUrl("dev 1&x", null, "Modbus")
.ShouldBe("/api/raw/tags.csv?deviceId=dev%201%26x&driverType=Modbus");
RawTagCsvExport.DownloadUrl("", "TG/1", null).ShouldBe("/api/raw/tags.csv?tagGroupId=TG%2F1");
}
[Fact]
public void Download_endpoint_requires_the_same_ConfigEditor_policy_as_the_raw_page()
{
var builder = WebApplication.CreateBuilder();
builder.Services.AddDbContextFactory<OtOpcUaConfigDbContext>(o => o.UseInMemoryDatabase("csv-export-metadata"));
builder.Services.AddScoped<RawTagCsvExportReader>();
var app = builder.Build();
app.MapRawTagCsvExport();
var endpoint = ((IEndpointRouteBuilder)app).DataSources.SelectMany(d => d.Endpoints).OfType<RouteEndpoint>()
.Single(e => e.RoutePattern.RawText == RawTagCsvExport.DownloadPath);
endpoint.Metadata.GetMetadata<IAllowAnonymous>().ShouldBeNull();
endpoint.Metadata.GetOrderedMetadata<IAuthorizeData>().Select(a => a.Policy)
.ShouldContain(AdminUiPolicies.ConfigEditor);
// Parity with the page that links to it.
typeof(ZB.MOM.WW.OtOpcUa.AdminUI.Components.Pages.Raw.GlobalRaw)
.GetCustomAttributes(typeof(AuthorizeAttribute), false).Cast<AuthorizeAttribute>()
.Single().Policy.ShouldBe(AdminUiPolicies.ConfigEditor);
}
[Fact]
public void Modals_no_longer_embed_the_csv_or_render_every_row()
{
var export = AdminUiSource.Read("Components", "Shared", "Raw", "RawCsvExportModal.razor");
export.ShouldNotContain("data:text/csv");
export.ShouldContain("RawTagCsvExport.Preview(");
var import = AdminUiSource.Read("Components", "Shared", "Raw", "RawCsvImportModal.razor");
import.ShouldContain("<Virtualize Items=\"@_view.VisibleRows\"");
import.ShouldNotContain("@foreach (var row in _result.Rows)");
AdminUiSource.Read("EndpointRouteBuilderExtensions.cs").ShouldContain("app.MapRawTagCsvExport();");
}
}