using System.Security.Claims;
using Bunit;
using Microsoft.AspNetCore.Components.Authorization;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Logging.Abstractions;
using Microsoft.Extensions.Options;
using NSubstitute;
using ScadaLink.Commons.Entities.Instances;
using ScadaLink.Commons.Entities.Sites;
using ScadaLink.Commons.Entities.Templates;
using ScadaLink.Commons.Interfaces.Repositories;
using ScadaLink.Commons.Interfaces.Services;
using ScadaLink.Commons.Types.Enums;
using ScadaLink.Communication;
using ScadaLink.DeploymentManager;
using ScadaLink.CentralUI.Components.Shared;
using ScadaLink.TemplateEngine.Services;
using TopologyPage = ScadaLink.CentralUI.Components.Pages.Deployment.Topology;
namespace ScadaLink.CentralUI.Tests;
///
/// bUnit rendering tests for the Topology page (Site → Area → Instance tree).
/// Focuses on the behavior that's specific to this page:
/// always-visible empty containers, search dimming, F2 area rename, and the
/// move-dialog destination lists.
///
public class TopologyPageTests : BunitContext
{
private readonly ITemplateEngineRepository _repo = Substitute.For();
private readonly ISiteRepository _siteRepo = Substitute.For();
private readonly IDeploymentManagerRepository _deployRepo = Substitute.For();
private readonly IFlatteningPipeline _pipeline = Substitute.For();
private readonly IAuditService _audit = Substitute.For();
public TopologyPageTests()
{
Services.AddSingleton(_repo);
Services.AddSingleton(_siteRepo);
Services.AddSingleton(_deployRepo);
Services.AddSingleton(_pipeline);
Services.AddSingleton(_audit);
// DeploymentService has non-mockable concrete deps; instantiate them directly.
var comms = new CommunicationService(
Options.Create(new CommunicationOptions()),
NullLogger.Instance);
Services.AddSingleton(comms);
Services.AddSingleton(new OperationLockManager());
Services.AddSingleton(Options.Create(new DeploymentManagerOptions
{
OperationLockTimeout = TimeSpan.FromSeconds(5)
}));
Services.AddSingleton>(NullLogger.Instance);
Services.AddScoped();
Services.AddScoped();
Services.AddScoped();
AddTestAuth();
// The page injects IDialogService for delete confirmations; the host
// (rendered globally in MainLayout) is not present in bUnit, but the
// DI registration still has to satisfy the [Inject].
Services.AddScoped();
// Site scoping (CentralUI-002): Topology injects SiteScopeService to
// filter the tree by the user's permitted sites.
Services.AddScoped();
// TreeView persists expansion state via JS interop. Stub the calls so render doesn't throw.
JSInterop.Setup("treeviewStorage.load", _ => true).SetResult(null);
JSInterop.SetupVoid("treeviewStorage.save", _ => true);
}
private void AddTestAuth()
{
var claims = new[]
{
new Claim("Username", "tester"),
new Claim(ClaimTypes.Role, "Deployment")
};
var user = new ClaimsPrincipal(new ClaimsIdentity(claims, "TestAuth"));
Services.AddSingleton(new TestAuthStateProvider(user));
Services.AddAuthorizationCore();
}
private void SeedRepos(
IEnumerable? sites = null,
IEnumerable? templates = null,
IEnumerable? instances = null,
Dictionary>? areasBySite = null)
{
_siteRepo.GetAllSitesAsync(Arg.Any())
.Returns(Task.FromResult>(sites?.ToList() ?? new List()));
_repo.GetAllTemplatesAsync(Arg.Any())
.Returns(Task.FromResult>(templates?.ToList() ?? new List()));
_repo.GetAllInstancesAsync(Arg.Any())
.Returns(Task.FromResult>(instances?.ToList() ?? new List()));
areasBySite ??= new();
_repo.GetAreasBySiteIdAsync(Arg.Any(), Arg.Any())
.Returns(call =>
{
var sid = call.Arg();
return Task.FromResult(areasBySite.TryGetValue(sid, out var list)
? list
: (IReadOnlyList)new List());
});
}
[Fact]
public void Renders_EmptyState_WhenNoSites()
{
SeedRepos();
var cut = Render();
Assert.Contains("No sites configured", cut.Markup);
}
[Fact]
public void Renders_EmptySite_AsTopLevelNode()
{
// An always-show-empty container is a hard requirement: a site with nothing
// under it must still appear so users can move/create into it.
SeedRepos(sites: new[] { new Site("Plant-A", "plant-a") { Id = 1 } });
var cut = Render();
Assert.Contains("Plant-A", cut.Markup);
Assert.Contains("bi-building", cut.Markup);
}
private static AngleSharp.Dom.IElement? FindToggleForLabel(IRenderedComponent cut, string label) =>
cut.FindAll(".tv-row")
.FirstOrDefault(row => row.QuerySelector(".tv-label")?.TextContent == label)
?.QuerySelector(".tv-toggle");
[Fact]
public void Renders_SiteAreaInstance_Nesting()
{
var areasBySite = new Dictionary>
{
[1] = new List
{
new("Line-1") { Id = 10, SiteId = 1, ParentAreaId = null }
}
};
SeedRepos(
sites: new[] { new Site("Plant-A", "plant-a") { Id = 1 } },
instances: new[]
{
new Instance("Pump-001") { Id = 100, SiteId = 1, AreaId = 10, State = InstanceState.NotDeployed }
},
areasBySite: areasBySite);
var cut = Render();
// Expand the site, then the area, to render the instance leaf. The
// helper scopes by the row's own label so we don't match outer rows
// whose TextContent transitively contains the inner label.
FindToggleForLabel(cut, "Plant-A")!.Click();
FindToggleForLabel(cut, "Line-1")!.Click();
Assert.Contains("Pump-001", cut.Markup);
Assert.Contains("bi-diagram-3", cut.Markup);
Assert.Contains("bi-box", cut.Markup);
Assert.Contains("NotDeployed", cut.Markup);
}
[Fact]
public void Search_DimsNonMatches_PreservesShape()
{
var areasBySite = new Dictionary>
{
[1] = new List
{
new("Line-1") { Id = 10, SiteId = 1 },
new("Boilers") { Id = 11, SiteId = 1 }
}
};
SeedRepos(
sites: new[] { new Site("Plant-A", "plant-a") { Id = 1 } },
areasBySite: areasBySite);
var cut = Render();
FindToggleForLabel(cut, "Plant-A")!.Click();
var search = cut.Find("input[type='text']");
search.Input("Line");
// Both areas remain in the DOM (shape preserved). 'Boilers' gets the dim style.
Assert.Contains("Line-1", cut.Markup);
Assert.Contains("Boilers", cut.Markup);
var dimmedNodes = cut.FindAll("span.tv-label[style*='opacity']");
Assert.Contains(dimmedNodes, n => n.TextContent.Contains("Boilers"));
}
[Fact]
public void SiteScoping_ScopedDeploymentUser_OnlySeesPermittedSites()
{
// Regression test for CentralUI-002. The SiteId claims issued at login were
// never read, so a Deployment user scoped to one site could view (and act
// on) every site's topology. Topology now filters the tree by the user's
// permitted sites via SiteScopeService.
var scopedUser = new ClaimsPrincipal(new ClaimsIdentity(new[]
{
new Claim("Username", "scoped-tester"),
new Claim(ScadaLink.Security.JwtTokenService.RoleClaimType, "Deployment"),
// Permitted on site 1 only.
new Claim(ScadaLink.Security.JwtTokenService.SiteIdClaimType, "1"),
}, "TestAuth"));
// Last AuthenticationStateProvider registration wins on resolution.
Services.AddSingleton(new TestAuthStateProvider(scopedUser));
SeedRepos(sites: new[]
{
new Site("Plant-A", "plant-a") { Id = 1 },
new Site("Plant-B", "plant-b") { Id = 2 },
});
var cut = Render();
// The permitted site is rendered; the non-permitted site is not.
Assert.Contains("Plant-A", cut.Markup);
Assert.DoesNotContain("Plant-B", cut.Markup);
}
[Fact]
public void SiteScoping_SystemWideDeploymentUser_SeesAllSites()
{
// A Deployment user with no SiteId claims is system-wide and sees every site.
SeedRepos(sites: new[]
{
new Site("Plant-A", "plant-a") { Id = 1 },
new Site("Plant-B", "plant-b") { Id = 2 },
});
var cut = Render();
Assert.Contains("Plant-A", cut.Markup);
Assert.Contains("Plant-B", cut.Markup);
}
[Fact]
public void DoubleClick_OnAreaLabel_EntersRenameMode()
{
var areasBySite = new Dictionary>
{
[1] = new List { new("Line-1") { Id = 10, SiteId = 1 } }
};
SeedRepos(sites: new[] { new Site("Plant-A", "plant-a") { Id = 1 } }, areasBySite: areasBySite);
var cut = Render();
FindToggleForLabel(cut, "Plant-A")!.Click();
var areaLabel = cut.FindAll("span.tv-label").First(s => s.TextContent == "Line-1");
areaLabel.DoubleClick();
// Inline rename input replaces the label.
Assert.NotNull(cut.Find("input.form-control-sm.d-inline-block"));
}
[Fact]
public void InstanceRows_DoNotHaveDoubleClickRename()
{
// Instance rename is out of scope; the label should not have @ondblclick wired.
// bUnit throws MissingEventHandlerException when dispatching to an element
// that has no handler — that's the assertion: the dblclick event is not bound.
SeedRepos(
sites: new[] { new Site("Plant-A", "plant-a") { Id = 1 } },
instances: new[]
{
new Instance("Pump-001") { Id = 100, SiteId = 1, State = InstanceState.NotDeployed }
});
var cut = Render();
FindToggleForLabel(cut, "Plant-A")!.Click();
var instanceLabel = cut.FindAll("span.tv-label").First(s => s.TextContent == "Pump-001");
Assert.Throws(() => instanceLabel.DoubleClick());
}
[Fact]
public void LegacyInstancesRoute_IsDeclaredOnTopologyPage()
{
// Old bookmarks to /deployment/instances must still resolve. Reflection
// check: the Topology component carries both @page directives.
var pageAttrs = typeof(TopologyPage).GetCustomAttributes(
typeof(Microsoft.AspNetCore.Components.RouteAttribute), inherit: false)
.Cast()
.Select(a => a.Template)
.ToList();
Assert.Contains("/deployment/topology", pageAttrs);
Assert.Contains("/deployment/instances", pageAttrs);
}
}