Files
ScadaBridge/tests/ZB.MOM.WW.ScadaBridge.CLI.Tests/ManagementSurfaceParityTests.cs
T
Joseph Doherty 513fa1aa16 docs(tests): fix CommentChecker findings across tests/ — 13,392 → 0 (repo-wide scan clean)
Comment/XML-doc changes only:
- add summaries to ~10k test methods, fixtures, fakes and helpers
  (+ <param> on theories, <returns> on async Task methods,
  <inheritdoc/> on interface implementations the checker can resolve)
- strip ~2.6k project-tracking references (WP*, P*-*, row-NN, Task N,
  #NN, Component-0NN) from comments, keeping the explanatory text;
  reword false positives in comments only
- real docs on fakes implementing BCL/library interfaces
  (IDisposable, ILogger, IOptionsMonitor, IAsyncLifetime)
- reword the last 5 src/ false positives (CWE-1236, failures-1,
  year-0001, M365)

Only non-comment edits: four one-line nested classes split across lines
so members can carry docs. Build 0 errors / 0 warnings.
2026-10-07 15:05:49 -04:00

173 lines
8.4 KiB
C#

using System.Collections.Concurrent;
using System.CommandLine;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Text.Json;
using ZB.MOM.WW.ScadaBridge.CLI;
using ZB.MOM.WW.ScadaBridge.Commons.Messages.Management;
namespace ZB.MOM.WW.ScadaBridge.CLI.Tests;
/// <summary>
/// Drives the production command tree against a loopback recorder. Every public
/// management contract must actually cross HTTP from a CLI action. A constructor
/// reference, an unregistered group, or a help-only leaf cannot satisfy this gate.
/// Server replies are deliberate errors so no local success handlers write exports.
/// </summary>
[Collection("Console")]
public class ManagementSurfaceParityTests
{
/// <summary>Verifies that every HTTP management contract is sent by the production CLI.</summary>
/// <returns>A task that represents the asynchronous operation.</returns>
[Fact]
public async Task EveryHttpManagementContract_IsSentByTheProductionCli()
{
var sent = await ProbeProductionTree();
var registered = typeof(ManagementEnvelope).Assembly.GetTypes()
.Where(t => t.Namespace == typeof(ManagementEnvelope).Namespace && !t.IsAbstract
&& t.Name.EndsWith("Command", StringComparison.Ordinal))
.Where(t => ManagementCommandRegistry.Resolve(t.Name[..^7]) == t)
.Select(ManagementCommandRegistry.GetCommandName).ToHashSet();
var missing = registered.Except(sent.Keys).Order().ToArray();
Assert.True(missing.Length == 0, "No CLI dispatch for: " + string.Join(", ", missing));
Assert.Empty(sent.Keys.Except(registered));
}
/// <summary>Verifies that removing a production schema group is detected by the parity probe.</summary>
/// <returns>A task that represents the asynchronous operation.</returns>
[Fact]
public async Task RemovingProductionSchemaGroup_IsDetectedByParityProbe()
{
var sent = await ProbeProductionTree(omitGroup: "shared-schema");
Assert.DoesNotContain("ListSharedSchemas", sent.Keys);
Assert.Contains("ListSharedScripts", sent.Keys);
}
private static async Task<ConcurrentDictionary<string, string>> ProbeProductionTree(string? omitGroup = null)
{
var root = CliApplication.BuildRoot();
var recorded = new ConcurrentDictionary<string, string>();
var directory = Directory.CreateTempSubdirectory("cli-parity-");
var file = Path.Combine(directory.FullName, "input.json");
await File.WriteAllTextAsync(file, "{}");
var csv = Path.Combine(directory.FullName, "native.csv");
await File.WriteAllTextAsync(csv, "SourceName,Connection,SourceReference,Filter\nSource,Connection,Path,\n");
using var stop = new CancellationTokenSource(TimeSpan.FromSeconds(30));
var listener = new TcpListener(IPAddress.Loopback, 0);
listener.Start();
var url = $"http://127.0.0.1:{((IPEndPoint)listener.LocalEndpoint).Port}";
var currentPath = "";
var server = Task.Run(async () =>
{
try
{
while (!stop.IsCancellationRequested)
{
using var client = await listener.AcceptTcpClientAsync(stop.Token);
await using var stream = client.GetStream();
using var reader = new StreamReader(stream, Encoding.UTF8, leaveOpen: true);
var length = 0;
while (await reader.ReadLineAsync(stop.Token) is { Length: > 0 } line)
if (line.StartsWith("Content-Length:", StringComparison.OrdinalIgnoreCase))
length = int.Parse(line[15..].Trim());
var buffer = new char[length];
var read = 0;
while (read < length)
{
var count = await reader.ReadAsync(buffer.AsMemory(read), stop.Token);
if (count == 0) throw new EndOfStreamException();
read += count;
}
using var body = JsonDocument.Parse(new string(buffer));
recorded[body.RootElement.GetProperty("command").GetString()!] = currentPath;
const string response = "{\"error\":\"parity probe\",\"code\":\"PROBE\"}";
var bytes = Encoding.UTF8.GetBytes($"HTTP/1.1 400 Bad Request\r\nContent-Type: application/json\r\nContent-Length: {response.Length}\r\nConnection: close\r\n\r\n{response}");
await stream.WriteAsync(bytes, stop.Token);
}
}
catch (OperationCanceledException) when (stop.IsCancellationRequested) { }
}, stop.Token);
try
{
foreach (var (leaf, path) in Leaves(root, []))
{
// Separate REST and persistent SignalR surfaces, not management contracts.
if (path.Length == 0 || path[0] == "audit" || path[0] == omitGroup
|| string.Join(' ', path) == "debug stream") continue;
currentPath = string.Join(' ', path);
var args = new List<string>(path);
foreach (var option in leaf.Options.Where(o => o.Required))
{
args.Add(option.Name);
args.Add(ValueFor(option, currentPath, file, csv));
}
AddConditionalOptions(args, currentPath);
args.AddRange(["--url", url, "--username", "probe", "--password", "probe", "--format", "json"]);
var parse = root.Parse(args.ToArray());
// Some convenience aliases require richer local files/preflight replies;
// other leaves must still emit every contract. Missing coverage fails above.
if (parse.Errors.Count > 0) continue;
await parse.InvokeAsync().WaitAsync(stop.Token);
}
}
finally
{
await stop.CancelAsync();
listener.Stop();
await server;
directory.Delete(recursive: true);
}
return recorded;
}
private static IEnumerable<(Command Leaf, string[] Path)> Leaves(Command command, string[] path)
{
if (command.Subcommands.Count == 0) yield return (command, path);
foreach (var child in command.Subcommands)
foreach (var entry in Leaves(child, [.. path, child.Name])) yield return entry;
}
private static string ValueFor(Option option, string path, string file, string csv)
{
var type = option.GetType().GetGenericArguments().FirstOrDefault();
type = Nullable.GetUnderlyingType(type ?? typeof(string)) ?? type;
if (type == typeof(int) || type == typeof(long) || type == typeof(double)) return "1";
if (type == typeof(Guid)) return "aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa";
if (type == typeof(bool)) return "true";
if (type?.IsEnum == true) return Enum.GetNames(type)[0];
return option.Name switch
{
"--schema-file" or "--input" or "--config-file" or "--der-file" => file,
"--output" => file + ".out",
"--file" => csv,
"--bindings" => "[[\"Value\",1]]",
"--direction" => "up",
"--overrides" or "--config" => "{}",
"--value-json" => "1",
"--data-type" or "--value-type" => "Int32",
"--trigger-type" => "Periodic",
"--auth-type" or "--auth-mode" => "None",
"--http-method" => "GET",
"--type" => "OpcUa",
"--endpoint-url" => "http://localhost",
"--account-sid" => "AC" + new string('a', 32),
"--from-address" => "sender@example.test",
"--thumbprint" => new string('A', 40),
"--role" => "Designer",
"--code" or "--script" => "return null;",
_ => "fixture"
};
}
private static void AddConditionalOptions(List<string> args, string path)
{
if (path is "notification create" or "notification update")
args.AddRange(["--emails", "recipient@example.test"]);
if (path is "notification sms create" or "notification sms update")
args.AddRange(["--from-number", "+15551234567"]);
if (path == "notification sms create") args.AddRange(["--auth-token", "test-token"]);
if (path == "notification recipient add") args.AddRange(["--email", "recipient@example.test"]);
}
}