Files
lmxopcua/tests/Server/ZB.MOM.WW.OtOpcUa.Host.IntegrationTests/PubSubTopicCoverageGuardTests.cs
T

98 lines
5.2 KiB
C#

using System.Text.RegularExpressions;
using Shouldly;
using Xunit;
namespace ZB.MOM.WW.OtOpcUa.Host.IntegrationTests;
/// <summary>
/// lmxopcua#1111: guards <see cref="TwoNodeClusterHarness.AllHostTopics"/> (hand-kept, #1108) against drift. A host
/// DistributedPubSub topic missing from it means <c>StartAsync</c>/<c>WaitForPubSubConvergedAsync</c> cannot wait for it
/// and a test publishing on it has the #1106 lost-publish window.
/// </summary>
/// <remarks>
/// Approach (source scan, no reflection - topics live in many assemblies and some are instance constants):
/// (1) scan every <c>src/**/*.cs</c> for <c>new Subscribe(&lt;first-arg&gt;, </c>; the first argument is the topic. Calls whose
/// first argument is not topic-shaped (a string literal, or a PascalCase identifier / dotted path such as
/// <c>DeploymentsTopic</c>, <c>Foo.BarTopic</c>) are skipped - this excludes the unrelated
/// <c>new Subscribe(_desiredRefs, ...)</c> driver message. (2) Resolve the argument to its string value by parsing
/// every <c>const string X = "lit" | Other.Y;</c> in src (keyed by enclosing class + name, chased transitively;
/// a bare name resolves in the file's first type, a dotted <c>A.B.X</c> via class <c>B</c>). (3) Compare the values with
/// <c>AllHostTopics</c> names. An unresolvable argument FAILS the test (so a new spelling cannot silently pass).
/// Non-DPS <c>new Subscribe(</c> uses with a topic-shaped first arg would need adding to the allowlist below.
/// </remarks>
public sealed class PubSubTopicCoverageGuardTests
{
private static readonly Regex ClassRx = new(@"\b(?:class|record|struct)\s+(\w+)", RegexOptions.Compiled);
private static readonly Regex ConstRx = new(
@"\bconst\s+string\s+(\w+)\s*=\s*(""[^""]*""|[\w.]+)\s*;", RegexOptions.Compiled);
private static readonly Regex SubscribeRx = new(
@"new\s+Subscribe\(\s*(""[^""]*""|[A-Z][\w.]*)\s*,", RegexOptions.Compiled);
[Fact]
public void EveryDistributedPubSubSubscribeTopic_IsInHarnessAllHostTopics()
{
var srcRoot = Path.Combine(SolutionRoot(), "src");
var files = Directory.EnumerateFiles(srcRoot, "*.cs", SearchOption.AllDirectories)
.Where(f => !f.Contains($"{Path.DirectorySeparatorChar}obj{Path.DirectorySeparatorChar}")
&& !f.Contains($"{Path.DirectorySeparatorChar}bin{Path.DirectorySeparatorChar}"))
.ToList();
// (class, const) -> raw RHS ; also const-name -> RHS list for fallbacks is deliberately NOT used (ambiguous).
var consts = new Dictionary<(string Cls, string Name), string>();
var calls = new List<(string File, string Cls, string Arg)>();
foreach (var file in files)
{
var cls = "";
foreach (var line in File.ReadLines(file))
{
var cm = ClassRx.Match(line);
// First type in the file only: later (nested) types must not hijack the owner of a const / call site.
if (cls.Length == 0 && cm.Success && !line.TrimStart().StartsWith("//")) cls = cm.Groups[1].Value;
var k = ConstRx.Match(line);
if (k.Success) consts[(cls, k.Groups[1].Value)] = k.Groups[2].Value;
var sm = SubscribeRx.Match(line);
if (sm.Success) calls.Add((Path.GetFileName(file), cls, sm.Groups[1].Value));
}
}
calls.ShouldNotBeEmpty("scan found no `new Subscribe(` call sites - the regex or src root is wrong");
string? Resolve(string cls, string arg, int depth = 0)
{
if (depth > 8) return null;
if (arg.StartsWith('"')) return arg.Trim('"');
var parts = arg.Split('.');
var name = parts[^1];
var owner = parts.Length >= 2 ? parts[^2] : cls;
return consts.TryGetValue((owner, name), out var rhs) ? Resolve(owner, rhs, depth + 1) : null;
}
var unresolved = new List<string>();
var subscribed = new SortedDictionary<string, string>();
foreach (var (file, cls, arg) in calls)
{
var value = Resolve(cls, arg);
if (value is null) unresolved.Add($"{file}: Subscribe({arg}, ...)");
else subscribed.TryAdd(value, $"{file}: Subscribe({arg}, ...)");
}
unresolved.ShouldBeEmpty("could not resolve these topic arguments to a const string; teach the guard");
var known = TwoNodeClusterHarness.AllHostTopics.Select(t => t.Name).ToHashSet();
var missing = subscribed.Where(kv => !known.Contains(kv.Key))
.Select(kv => $"\"{kv.Key}\" ({kv.Value})").ToList();
missing.ShouldBeEmpty(
"host DistributedPubSub topics subscribed in src/ but absent from TwoNodeClusterHarness.AllHostTopics "
+ "(#1108/#1111): add them with the right MinNodes/AtBoot");
}
private static string SolutionRoot()
{
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 find solution root (ZB.MOM.WW.OtOpcUa.slnx).");
return dir!.FullName;
}
}