285 lines
16 KiB
C#
285 lines
16 KiB
C#
using System.Reflection;
|
|
using System.Text;
|
|
using Bunit;
|
|
using Microsoft.AspNetCore.Components;
|
|
using Microsoft.AspNetCore.Components.Forms;
|
|
using Microsoft.Extensions.DependencyInjection;
|
|
using Microsoft.EntityFrameworkCore;
|
|
using ZB.MOM.WW.OtOpcUa.Configuration;
|
|
using Shouldly;
|
|
using Xunit;
|
|
using ZB.MOM.WW.OtOpcUa.AdminUI.Components.Shared.Raw;
|
|
using ZB.MOM.WW.OtOpcUa.AdminUI.Tests.Uns;
|
|
using ZB.MOM.WW.OtOpcUa.AdminUI.Uns;
|
|
|
|
namespace ZB.MOM.WW.OtOpcUa.AdminUI.Tests.Pages;
|
|
|
|
/// <summary>Staged CSV import keeps names, pending work and successful refresh bound to its target.</summary>
|
|
[Trait("Category", "Unit")]
|
|
public sealed class RawCsvImportModalAccessibilityTests : BunitContext
|
|
{
|
|
private const string ValidCsv = "Name,DataType,TagConfigJson\nalpha,Float,\"{\"\"region\"\":\"\"HoldingRegisters\"\",\"\"address\"\":1,\"\"unknown\"\":7}\"";
|
|
private readonly ImportProxy _import;
|
|
public RawCsvImportModalAccessibilityTests()
|
|
{
|
|
JSInterop.Mode = JSRuntimeMode.Loose;
|
|
JSInterop.Setup<bool>("otDialog.activate", _ => true).SetResult(true);
|
|
var service = DispatchProxy.Create<IRawTreeService, ImportProxy>();
|
|
_import = (ImportProxy)(object)service;
|
|
Services.AddSingleton(service);
|
|
Services.AddSingleton(new RawTagCsvExportReader(RawTreeTestDb.Factory("csv-modal-" + Guid.NewGuid().ToString("N"))));
|
|
}
|
|
private IRenderedComponent<RawCsvImportModal> Open(string device = "A") => Render<RawCsvImportModal>(p => p
|
|
.Add(x => x.Visible, true).Add(x => x.DeviceId, device).Add(x => x.DriverType, "Modbus"));
|
|
private static void Upload<T>(IRenderedComponent<T> cut, string text = ValidCsv) where T : class, IComponent =>
|
|
cut.FindComponent<InputFile>().UploadFiles(InputFileContent.CreateFromText(text, "synthetic.csv"));
|
|
private static AngleSharp.Dom.IElement Commit(IRenderedComponent<RawCsvImportModal> cut) => cut.Find(".modal-footer .btn-primary");
|
|
private static Task Submit(IRenderedComponent<RawCsvImportModal> cut) => Commit(cut).TriggerEventAsync("onclick", new Microsoft.AspNetCore.Components.Web.MouseEventArgs());
|
|
|
|
[Fact]
|
|
public void UploadHasVisibleNameHintAndModalHasResolvedTitle()
|
|
{
|
|
var cut = Open();
|
|
var dialog = cut.Find("[role=dialog]");
|
|
var title = dialog.GetAttribute("aria-labelledby");
|
|
title.ShouldNotBeNullOrWhiteSpace();
|
|
cut.Find("#" + title).TextContent.ShouldContain("Import tags");
|
|
var file = cut.Find("input[type=file]");
|
|
cut.FindAll("label").ShouldContain(label => label.GetAttribute("for") == file.Id);
|
|
file.GetAttribute("aria-describedby").ShouldNotBeNullOrWhiteSpace();
|
|
cut.Find(".modal-footer [data-initial-focus]").TextContent.ShouldContain("Cancel");
|
|
}
|
|
|
|
[Theory]
|
|
[InlineData("success")]
|
|
[InlineData("failure")]
|
|
[InlineData("exception")]
|
|
public async Task PendingCommitRejectsRepeatResetCloseAndKeepsCapturedTargetCallback(string outcome)
|
|
{
|
|
var savedA = 0; var savedB = 0; var closedB = 0;
|
|
var cut = Open();
|
|
cut.Render(p => p.Add(x => x.OnSaved, () => savedA++));
|
|
Upload(cut);
|
|
var saving = Submit(cut);
|
|
await _import.Entered.Task.WaitAsync(TimeSpan.FromSeconds(10), Xunit.TestContext.Current.CancellationToken);
|
|
try
|
|
{
|
|
var repeated = Submit(cut);
|
|
_import.Calls.ShouldBe(1);
|
|
await repeated;
|
|
await cut.FindAll("button").Single(b => b.TextContent.Contains("Choose another")).TriggerEventAsync("onclick", new Microsoft.AspNetCore.Components.Web.MouseEventArgs());
|
|
await cut.Find(".modal-footer .btn-outline-secondary").TriggerEventAsync("onclick", new Microsoft.AspNetCore.Components.Web.MouseEventArgs());
|
|
_import.Calls.ShouldBe(1);
|
|
cut.Find("[role=dialog]").GetAttribute("aria-busy").ShouldBe("true");
|
|
cut.Render(p => p.Add(x => x.DeviceId, "B").Add(x => x.OnSaved, () => savedB++)
|
|
.Add(x => x.VisibleChanged, _ => closedB++));
|
|
}
|
|
finally
|
|
{
|
|
if (outcome == "exception") _import.Pending.TrySetException(new IOException("retired A exception"));
|
|
else _import.Pending.TrySetResult(new(outcome == "success" ? 1 : 0, outcome == "failure" ? ["retired A rejection"] : []));
|
|
await saving;
|
|
}
|
|
_import.Device.ShouldBe("A");
|
|
_import.Rows.Single().Tag.Name.ShouldBe("alpha");
|
|
_import.Rows.Single().Tag.TagConfig.ShouldContain("unknown");
|
|
savedA.ShouldBe(outcome == "success" ? 1 : 0); savedB.ShouldBe(0); closedB.ShouldBe(0);
|
|
cut.Find("[role=dialog]").TextContent.ShouldContain("B");
|
|
cut.Markup.ShouldNotContain("retired A rejection"); cut.Markup.ShouldNotContain("retired A exception");
|
|
cut.FindAll("input[type=file]").Count.ShouldBe(1);
|
|
}
|
|
|
|
[Fact]
|
|
public async Task DisposalDoesNotCancelCommittedImportOrInvokeUiCallbacks()
|
|
{
|
|
var saved = 0; var closed = 0;
|
|
var cut = Open();cut.Render(p => p.Add(x => x.OnSaved, () => saved++).Add(x => x.VisibleChanged, _ => closed++));Upload(cut);
|
|
var saving = Submit(cut);
|
|
await _import.Entered.Task.WaitAsync(TimeSpan.FromSeconds(10), Xunit.TestContext.Current.CancellationToken);
|
|
await DisposeComponentsAsync();_import.Pending.TrySetResult(new(1, []));await saving;
|
|
_import.Calls.ShouldBe(1); _import.Token.CanBeCanceled.ShouldBeFalse(); saved.ShouldBe(0); closed.ShouldBe(0);
|
|
}
|
|
|
|
[Theory]
|
|
[InlineData(false)]
|
|
[InlineData(true)]
|
|
public async Task RetiredUploadSuccessOrFailureCannotOverwriteReplacementReview(bool fail)
|
|
{
|
|
var cut = Open();
|
|
var callback = cut.FindComponent<InputFile>().Instance.OnChange;
|
|
var file = new DeferredFile();
|
|
var reading = cut.InvokeAsync(() => callback.InvokeAsync(new InputFileChangeEventArgs([file])));
|
|
await file.Entered.Task.WaitAsync(TimeSpan.FromSeconds(10), Xunit.TestContext.Current.CancellationToken);
|
|
cut.Render(p => p.Add(x => x.DeviceId, "B"));
|
|
Upload(cut, ValidCsv.Replace("alpha", "beta"));
|
|
if (fail) file.Release.TrySetException(new IOException("retired upload failure"));else file.Release.TrySetResult();
|
|
await reading;
|
|
cut.Markup.ShouldNotContain("retired upload failure");
|
|
var result = (RawCsvParseResult)typeof(RawCsvImportModal).GetField("_result", BindingFlags.NonPublic | BindingFlags.Instance)!.GetValue(cut.Instance)!;
|
|
result.Rows.Single().Name.ShouldBe("beta");
|
|
_import.Calls.ShouldBe(0);
|
|
}
|
|
|
|
[Fact]
|
|
public async Task RetiredInputFileCallbackCannotStartAnotherReadForReplacement()
|
|
{
|
|
var cut = Open();var callback = cut.FindComponent<InputFile>().Instance.OnChange;
|
|
cut.Render(p => p.Add(x => x.DeviceId, "B"));
|
|
var file = new DeferredFile();file.Release.TrySetResult();
|
|
await cut.InvokeAsync(() => callback.InvokeAsync(new InputFileChangeEventArgs([file])));
|
|
file.Opens.ShouldBe(0);cut.FindAll("input[type=file]").Count.ShouldBe(1);_import.Calls.ShouldBe(0);
|
|
}
|
|
|
|
[Fact]
|
|
public async Task InvalidRowsBlockAllOrNothingCommitAndResetReturnsToNamedUpload()
|
|
{
|
|
var cut = Open();
|
|
Upload(cut, ValidCsv + "\n/bad,Float,{}\n");
|
|
Commit(cut).HasAttribute("disabled").ShouldBeTrue();
|
|
cut.Markup.ShouldContain("1 invalid");
|
|
await Submit(cut);
|
|
_import.Calls.ShouldBe(0);
|
|
cut.FindAll("button").Single(b => b.TextContent.Contains("Choose another")).Click();
|
|
var file = cut.Find("input[type=file]");
|
|
cut.FindAll("label").ShouldContain(label => label.GetAttribute("for") == file.Id);
|
|
Upload(cut);
|
|
Commit(cut).HasAttribute("disabled").ShouldBeFalse();
|
|
_import.Calls.ShouldBe(0);
|
|
}
|
|
|
|
[Fact]
|
|
public async Task PendingUploadIsSingleFlightAndClosingDiscardsLateReadFailure()
|
|
{
|
|
var cut = Open(); var callback = cut.FindComponent<InputFile>().Instance.OnChange;
|
|
var first = new DeferredFile();
|
|
var reading = cut.InvokeAsync(() => callback.InvokeAsync(new InputFileChangeEventArgs([first])));
|
|
await first.Entered.Task.WaitAsync(TimeSpan.FromSeconds(10), Xunit.TestContext.Current.CancellationToken);
|
|
var repeated = new DeferredFile(); repeated.Release.TrySetResult();
|
|
await cut.InvokeAsync(() => callback.InvokeAsync(new InputFileChangeEventArgs([repeated])));
|
|
repeated.Opens.ShouldBe(0);
|
|
await cut.Find(".modal-footer .btn-outline-secondary").TriggerEventAsync("onclick", new Microsoft.AspNetCore.Components.Web.MouseEventArgs());
|
|
first.Release.TrySetException(new IOException("retired closed upload"));
|
|
await reading;
|
|
cut.FindAll("[role=dialog]").ShouldBeEmpty();
|
|
_import.Calls.ShouldBe(0);
|
|
}
|
|
|
|
[Theory]
|
|
[InlineData(false)]
|
|
[InlineData(true)]
|
|
public async Task DirectTargetReplacementRejectsRetiredGroupResolution(bool fail)
|
|
{
|
|
var factory = new GroupFactory { HoldFirst = true };
|
|
Services.AddSingleton(new RawTagCsvExportReader(factory));
|
|
var cut = Render<ObservedImport>(p => p.Add(x => x.Visible, true).Add(x => x.TagGroupId, "group-A").Add(x => x.DriverType, "Modbus"));
|
|
await factory.Entered.Task.WaitAsync(TimeSpan.FromSeconds(10), Xunit.TestContext.Current.CancellationToken);
|
|
var blockedFile = new DeferredFile(); blockedFile.Release.TrySetResult();
|
|
await cut.InvokeAsync(() => cut.FindComponent<InputFile>().Instance.OnChange.InvokeAsync(new InputFileChangeEventArgs([blockedFile])));
|
|
blockedFile.Opens.ShouldBe(0);
|
|
cut.Render(p => p.Add(x => x.DeviceId, "B").Add(x => x.TagGroupId, (string?)null));
|
|
Upload(cut, ValidCsv.Replace("alpha", "beta"));
|
|
if (fail) factory.Release.TrySetException(new IOException("retired group resolution")); else factory.Release.TrySetResult();
|
|
await cut.Instance.FirstParametersFinished.Task.WaitAsync(TimeSpan.FromSeconds(10), Xunit.TestContext.Current.CancellationToken);
|
|
cut.WaitForAssertion(() =>
|
|
{
|
|
var result = (RawCsvParseResult)typeof(RawCsvImportModal).GetField("_result", BindingFlags.NonPublic | BindingFlags.Instance)!.GetValue(cut.Instance)!;
|
|
result.Rows.Single().Name.ShouldBe("beta");
|
|
cut.Markup.ShouldNotContain("retired group resolution");
|
|
});
|
|
_import.Calls.ShouldBe(0);
|
|
}
|
|
|
|
[Fact]
|
|
public async Task FailedGroupResolutionRequiresReadOnlyRetryBeforeUploadAndKeepsItsPrefix()
|
|
{
|
|
var factory = new GroupFactory { Fail = true };
|
|
Services.AddSingleton(new RawTagCsvExportReader(factory));
|
|
var cut = Render<RawCsvImportModal>(p => p.Add(x => x.Visible, true).Add(x => x.TagGroupId, "group-A").Add(x => x.DriverType, "Modbus"));
|
|
cut.Find("[role=alert]").TextContent.ShouldContain("target could not be read");
|
|
var file = new DeferredFile(); file.Release.TrySetResult();
|
|
await cut.InvokeAsync(() => cut.FindComponent<InputFile>().Instance.OnChange.InvokeAsync(new InputFileChangeEventArgs([file])));
|
|
file.Opens.ShouldBe(0);
|
|
factory.Fail = false;
|
|
cut.FindAll("button").Single(b => b.TextContent == "Retry target").Click();
|
|
cut.WaitForAssertion(() => cut.FindAll("[role=alert]").ShouldBeEmpty());
|
|
Upload(cut);
|
|
var parsed = (RawCsvParseResult)typeof(RawCsvImportModal).GetField("_result", BindingFlags.NonPublic | BindingFlags.Instance)!.GetValue(cut.Instance)!;
|
|
parsed.Rows.Single().EffectiveGroupPath.ShouldBe("GroupA");
|
|
_import.Calls.ShouldBe(0);
|
|
}
|
|
|
|
[Fact]
|
|
public void OversizeUploadIsRejectedBeforeAnyImportAndAllowsChoosingAnotherFile()
|
|
{
|
|
var cut = Open();
|
|
cut.FindComponent<InputFile>().UploadFiles(InputFileContent.CreateFromBinary(new byte[16 * 1024 * 1024 + 1], "oversize.csv"));
|
|
cut.WaitForAssertion(() => cut.Find("[role=alert]").TextContent.ShouldContain("Could not read the file"));
|
|
Commit(cut).HasAttribute("disabled").ShouldBeTrue();_import.Calls.ShouldBe(0);
|
|
Upload(cut);
|
|
Commit(cut).HasAttribute("disabled").ShouldBeFalse();
|
|
}
|
|
|
|
private sealed class ObservedImport : RawCsvImportModal
|
|
{
|
|
private int _visits;
|
|
public TaskCompletionSource FirstParametersFinished { get; } = new(TaskCreationOptions.RunContinuationsAsynchronously);
|
|
protected override async Task OnParametersSetAsync()
|
|
{
|
|
var first = _visits++ == 0;
|
|
try { await base.OnParametersSetAsync(); }
|
|
finally { if (first) FirstParametersFinished.TrySetResult(); }
|
|
}
|
|
}
|
|
|
|
private sealed class GroupFactory : IDbContextFactory<OtOpcUaConfigDbContext>
|
|
{
|
|
private readonly string _database = "csv-groups-" + Guid.NewGuid().ToString("N");
|
|
private int _calls;
|
|
public bool HoldFirst { get; init; }
|
|
public bool Fail { get; set; }
|
|
public TaskCompletionSource Entered { get; } = new(TaskCreationOptions.RunContinuationsAsynchronously);
|
|
public TaskCompletionSource Release { get; } = new(TaskCreationOptions.RunContinuationsAsynchronously);
|
|
public GroupFactory()
|
|
{
|
|
using var db = CreateDbContext();
|
|
db.TagGroups.Add(new() { TagGroupId = "group-A", DeviceId = "A", Name = "GroupA" });db.SaveChanges();
|
|
}
|
|
public OtOpcUaConfigDbContext CreateDbContext() => RawTreeTestDb.CreateNamed(_database);
|
|
public async Task<OtOpcUaConfigDbContext> CreateDbContextAsync(CancellationToken ct = default)
|
|
{
|
|
var first = ++_calls == 1;
|
|
if (first && HoldFirst) { Entered.TrySetResult(); await Release.Task.WaitAsync(ct); }
|
|
if (Fail) throw new IOException("Synthetic target read failure");
|
|
return CreateDbContext();
|
|
}
|
|
}
|
|
|
|
public class ImportProxy : DispatchProxy
|
|
{
|
|
public int Calls; public string? Device; public IReadOnlyList<RawTagImportRow> Rows = [];
|
|
public CancellationToken Token;
|
|
public TaskCompletionSource Entered { get; } = new(TaskCreationOptions.RunContinuationsAsynchronously);
|
|
public TaskCompletionSource<RawTagImportResult> Pending { get; } = new(TaskCreationOptions.RunContinuationsAsynchronously);
|
|
protected override object? Invoke(MethodInfo? method, object?[]? args)
|
|
{
|
|
if (method?.Name != nameof(IRawTreeService.ImportTagsAsync)) throw new InvalidOperationException("Synthetic import fixture refuses " + method?.Name);
|
|
Calls++; Device = (string)args![0]!; Rows = (IReadOnlyList<RawTagImportRow>)args[1]!; Token = (CancellationToken)args[2]!;
|
|
Entered.TrySetResult(); return Pending.Task;
|
|
}
|
|
}
|
|
private sealed class DeferredFile : IBrowserFile
|
|
{
|
|
public string Name => "synthetic.csv"; public DateTimeOffset LastModified => DateTimeOffset.UnixEpoch;
|
|
public long Size => Encoding.UTF8.GetByteCount(ValidCsv); public string ContentType => "text/csv";public int Opens;
|
|
public TaskCompletionSource Entered { get; } = new(TaskCreationOptions.RunContinuationsAsynchronously);
|
|
public TaskCompletionSource Release { get; } = new(TaskCreationOptions.RunContinuationsAsynchronously);
|
|
public Stream OpenReadStream(long maxAllowedSize = 512000, CancellationToken cancellationToken = default)
|
|
{ Opens++;return new DelayedStream(this); }
|
|
private sealed class DelayedStream(DeferredFile owner) : MemoryStream(Encoding.UTF8.GetBytes(ValidCsv))
|
|
{
|
|
public override async ValueTask<int> ReadAsync(Memory<byte> buffer, CancellationToken cancellationToken = default)
|
|
{ owner.Entered.TrySetResult();await owner.Release.Task;return await base.ReadAsync(buffer,cancellationToken); }
|
|
}
|
|
}
|
|
}
|