using System.Text.RegularExpressions;
using Shouldly;
using Xunit;
namespace ZB.MOM.WW.OtOpcUa.Commons.Tests.Browsing;
///
/// Pins the layering rule for every bespoke driver browser in the tree: a *.Browser
/// project must not reach its runtime *.Driver project, by any path.
///
///
///
/// Why this exists rather than a per-driver test. Gitea #512 removed this violation from
/// the MQTT browser and pinned it with MqttBrowserLayeringTests. The identical violation was
/// sitting in Driver.Sql.Browser the whole time and no guard saw it, because the guard was
/// written for the driver that happened to have an issue filed (#526). This test enumerates the
/// browsers off disk, so a browser added later is covered on the day it is added.
///
///
/// Why it reads csproj files rather than loaded assemblies. The cost being prevented is a
/// build/deploy-graph cost: the AdminUI references these browsers, so a runtime driver reachable
/// from one lands in the AdminUI's output whether or not a single type is used. The compiler emits
/// no assembly reference for an unused ProjectReference, so an assembly-reference test —
/// which is what MqttBrowserLayeringTests does, and says so — cannot see that case. The two
/// are complementary: this one catches the reference, that one catches the usage.
///
///
/// The walk is transitive. Asserting only on direct references would pass a browser that
/// reached its runtime driver through a shared leaf, which is the same defect one hop further out
/// — the hazard MqttBrowserLayeringTests guards for .Transport by hand.
///
///
[Trait("Category", "Unit")]
public sealed class DriverBrowserLayeringTests
{
///
/// Browsers known to exist when this guard was written. Asserted as a MINIMUM, not an exact set —
/// a new browser must be covered automatically, so this list only defends against the discovery
/// itself silently finding nothing (a wrong repo root, a moved directory), which would make every
/// assertion below vacuously true.
///
private static readonly string[] KnownBrowsers =
[
"ZB.MOM.WW.OtOpcUa.Driver.Galaxy.Browser",
"ZB.MOM.WW.OtOpcUa.Driver.Mqtt.Browser",
"ZB.MOM.WW.OtOpcUa.Driver.OpcUaClient.Browser",
"ZB.MOM.WW.OtOpcUa.Driver.Sql.Browser",
];
[Fact]
public void Every_bespoke_browser_is_discovered()
{
// The positive control for the whole file. Every other test here is an ABSENCE assertion over a
// discovered set, so an empty set passes them all.
var discovered = DiscoverBrowsers().Select(p => Path.GetFileNameWithoutExtension(p)!).ToArray();
foreach (var known in KnownBrowsers)
discovered.ShouldContain(known);
}
[Fact]
public void Every_browser_declares_at_least_one_project_reference()
// The second half of the control: proves the csproj parse actually returns something, so a
// regex that silently stopped matching cannot turn the rule below into a no-op.
=> DiscoverBrowsers().ShouldAllBe(p => DirectReferences(p).Count > 0);
[Fact]
public void No_browser_reaches_its_runtime_driver_project()
{
var offenders = new List();
foreach (var browser in DiscoverBrowsers())
{
var browserName = Path.GetFileNameWithoutExtension(browser)!;
// "ZB…Driver.Sql.Browser" -> "ZB…Driver.Sql": the sibling runtime project.
var runtime = browserName[..^".Browser".Length];
var reached = TransitiveReferences(browser);
if (reached.Contains(runtime))
offenders.Add($"{browserName} -> {runtime}");
}
offenders.ShouldBeEmpty(
"a driver browser reaches its runtime driver project. The AdminUI references these browsers, "
+ "so the whole driver runtime lands in its build/deploy graph — the cost is invisible, which "
+ "is exactly why it needs a guard. If shared code is needed, put transport-free protocol or "
+ "contract types in .Contracts, and anything that must name a provider/vendor type in a leaf "
+ "project of its own (see Driver.Mqtt.Transport and Driver.Sql.Dialect). Do NOT resolve this "
+ "by copying the shared code into the browser: for anything touching credentials, TLS or "
+ "identifier quoting, a second copy is a silent security divergence rather than a build break.");
}
// ---- csproj graph ------------------------------------------------------------------------------
private static readonly Regex ProjectReferencePattern = new(
" DiscoverBrowsers() =>
[.. Directory
.EnumerateDirectories(Path.Combine(RepoRoot.Value, "src", "Drivers"), "*.Browser")
.Select(d => Path.Combine(d, Path.GetFileName(d) + ".csproj"))
.Where(File.Exists)
.OrderBy(p => p, StringComparer.Ordinal)];
/// Absolute paths of the csproj files one project references directly.
private static IReadOnlyList DirectReferences(string csprojPath)
{
var dir = Path.GetDirectoryName(csprojPath)!;
return
[
.. ProjectReferencePattern
.Matches(File.ReadAllText(csprojPath))
.Select(m => Path.GetFullPath(
Path.Combine(dir, m.Groups[1].Value.Replace('\\', Path.DirectorySeparatorChar))))
];
}
/// Assembly-ish names of every project reachable from .
private static HashSet TransitiveReferences(string csprojPath)
{
var reached = new HashSet(StringComparer.OrdinalIgnoreCase);
var pending = new Stack(DirectReferences(csprojPath));
while (pending.Count > 0)
{
var next = pending.Pop();
if (!reached.Add(Path.GetFileNameWithoutExtension(next)!) || !File.Exists(next)) continue;
foreach (var onward in DirectReferences(next)) pending.Push(onward);
}
return reached;
}
///
/// Walks up from the test binary until the solution file appears. The tests run out of
/// bin/Debug/net10.0, so no fixed relative depth is reliable across host layouts.
///
private static readonly Lazy RepoRoot = new(() =>
{
var dir = new DirectoryInfo(AppContext.BaseDirectory);
while (dir is not null && !File.Exists(Path.Combine(dir.FullName, "ZB.MOM.WW.OtOpcUa.slnx")))
dir = dir.Parent;
dir.ShouldNotBeNull("could not locate the repository root (no ZB.MOM.WW.OtOpcUa.slnx above the test binary)");
return dir.FullName;
});
}