Files
lmxopcua/tests/Drivers/ZB.MOM.WW.OtOpcUa.Driver.Mqtt.Tests/MqttInspectAcceptGateTests.cs
T
Joseph Doherty f5475868f7 fix(inspect): trim before the framing check; stop advisories swallowing the backstop (#556); pin the MQTT payloadFormat mode contract (#557 item 2)
#556 item 1 — leading whitespace defeated every Inspect's pre-filter. Seven
factories (Modbus/S7/AbCip/AbLegacy/TwinCAT/FOCAS/Mqtt) tested
`reference[0] != '{'`, so a padded blob returned EMPTY and a tag the driver
refuses deployed clean. The check now trims first, matching the idiom
Sql/Calculation/MTConnect/OpcUaClient already used. The raw reference is still
what is handed to the mapper — the driver reads the stored blob, not a trimmed
copy — so the gate keeps mirroring the runtime rather than becoming lenient.
Both directions are pinned: a padded blob the mapper accepts still draws
nothing, and one that is not object-framed AFTER trimming still draws nothing
(it is not an equipment-tag TagConfig at all).

Six of the seven mappers hand the blob to a whitespace-tolerant
JsonDocument.Parse, so their verdict is unchanged by padding. MQTT is the
exception: both its readers carry the same framing gate, so a padded blob is
genuinely refused — which is why the untrimmed pre-filter was a real defect
there and not a cosmetic mismatch.

#556 item 2 — FOCAS and MQTT appended advisories unconditionally and then gated
the catch-all rejection message on `warnings.Count == 0`, so an advisory (which
fires on ACCEPTED blobs too, and says nothing about a refusal) silently
swallowed the only message naming a refusal nothing else can. The two classes
now accumulate in SEPARATE lists and the backstop gates on the rejection count
alone — structural, not string matching. MQTT's swallow was reachable in
production (a padded blob its readers refuse while every describe branch finds
the parsed document well-formed); FOCAS's backstop is currently unreachable by
audit, so its guard is protective.

#557 item 2 — decided and pinned: KEEP the union verdict. Evidence:
FromSparkplugTagConfig hard-codes PayloadFormat=Json and never consults the key;
only MqttSubscriptionManager (the Plain ingest path) decodes by it; and
MqttTagConfigModel.ToJson deliberately omits the key entirely in Sparkplug mode
(#513). So a Sparkplug driver genuinely serves the tag and rejecting it would be
stricter than the runtime. The cost — served behaviour depends on the driver's
MqttMode, which no tag row records — is paid by an ADVISORY naming the key and
the mode dependency, not by changing the verdict, so both gates keep agreeing.
The same invalid value on a blob the union REFUSES stays a rejection; the class
is decided by the accept gate, never by the key.

Falsified: reverting Modbus's trim reddens the padded-rejection theory;
neutering MQTT's backstop guard to the pre-#556 shape reddens the
advisory-plus-unnameable-rejection test; disabling the #557 advisory reddens the
contract pin; and for FOCAS, removing a describe branch alone stays green (the
backstop covers it) while additionally neutering the guard goes red.
2026-08-10 03:07:18 -04:00

219 lines
12 KiB
C#

using Shouldly;
using Xunit;
namespace ZB.MOM.WW.OtOpcUa.Driver.Mqtt.Tests;
/// <summary>
/// Gitea #551: <see cref="MqttTagDefinitionFactory.Inspect"/> gained an accept gate — see
/// <c>ModbusInspectAcceptGateTests</c>'s remarks for why both directions (never stricter, never silent)
/// are pinned.
/// <para>
/// MQTT's gate is the <b>UNION</b> of its two mappers, because <c>Inspect</c> is handed a blob with
/// no mode: the driver's <c>MqttMode</c> decides whether
/// <see cref="MqttTagDefinitionFactory.FromTagConfig"/> or
/// <see cref="MqttTagDefinitionFactory.FromSparkplugTagConfig"/> reads it, and nothing on a tag row
/// says which. Gating on the Plain mapper alone would warn that every correctly-authored Sparkplug
/// tag has no topic — the falsification control below is exactly that case.
/// </para>
/// </summary>
public sealed class MqttInspectAcceptGateTests
{
private const string RawPath = "cell/mqtt/dev1/T1";
private static bool EitherModeAccepts(string tagConfig)
=> MqttTagDefinitionFactory.FromTagConfig(tagConfig, RawPath, out _)
|| MqttTagDefinitionFactory.FromSparkplugTagConfig(tagConfig, RawPath, out _);
/// <summary>Blobs at least one mapper ACCEPTS, with no wildcard advisory — the gate must be silent.</summary>
public static TheoryData<string> Accepted() =>
[
"""{"topic":"plant/line1/temp"}""",
"""{"topic":"plant/line1/temp","payloadFormat":"Json","dataType":"Float64","qos":1}""",
// Sparkplug: no topic at all, and that is CORRECT — the control this whole union exists for.
"""{"groupId":"OtOpcUaSim","edgeNodeId":"EdgeA","metricName":"Temp"}""",
"""{"groupId":"OtOpcUaSim","edgeNodeId":"EdgeA","deviceId":"Filler1","metricName":"Node Control/Rebirth"}""",
];
/// <summary>Blobs NEITHER mapper accepts — the gate must produce at least one warning for each.</summary>
public static TheoryData<string> Rejected() =>
[
"{}", // no address of either shape
"""{"payloadFormat":"Json","dataType":"String"}""", // still no address
"""{"groupId":"G","edgeNodeId":"E"}""", // incomplete Sparkplug tuple
"""{"topic":"a/b","payloadFormat":"Jsonn"}""", // typo'd payloadFormat
"""{"topic":"a/b","dataType":"Flooat64"}""", // typo'd dataType
"""{"topic":"a/b","qos":5}""", // out-of-range qos
"""{"groupId":"G","edgeNodeId":"E","metricName":"M","qos":"high"}""", // non-numeric qos, both modes
];
[Theory]
[MemberData(nameof(Accepted))]
public void A_config_a_mapper_accepts_draws_no_warning(string tagConfig)
{
EitherModeAccepts(tagConfig).ShouldBeTrue("fixture must be accepted by at least one mode");
MqttTagDefinitionFactory.Inspect(tagConfig).ShouldBeEmpty();
}
[Theory]
[MemberData(nameof(Rejected))]
public void A_config_neither_mapper_accepts_is_never_passed_over_in_silence(string tagConfig)
{
EitherModeAccepts(tagConfig).ShouldBeFalse("fixture must be rejected by both modes");
MqttTagDefinitionFactory.Inspect(tagConfig).ShouldNotBeEmpty();
}
[Fact]
public void A_blob_with_no_address_of_either_shape_names_both()
{
var warnings = MqttTagDefinitionFactory.Inspect("{}");
warnings.ShouldContain(w => w.Contains("topic") && w.Contains("metricName"));
}
/// <summary>The wildcard advisory is about an ACCEPTED blob, so the accept gate must not swallow it.</summary>
[Fact]
public void A_wildcard_topic_still_warns_even_though_the_mapper_accepts_it()
{
const string Blob = """{"topic":"plant/+/temp"}""";
MqttTagDefinitionFactory.FromTagConfig(Blob, RawPath, out _).ShouldBeTrue("a wildcard topic is accepted on purpose");
MqttTagDefinitionFactory.Inspect(Blob).ShouldContain(w => w.Contains("wildcard"));
}
[Fact]
public void A_blank_reference_draws_nothing()
=> MqttTagDefinitionFactory.Inspect(" ").ShouldBeEmpty();
[Fact]
public void Unparseable_json_names_the_json()
=> MqttTagDefinitionFactory.Inspect("{oops").ShouldContain(w => w.Contains("not valid JSON"));
// ---- Gitea #556 item 1: leading whitespace no longer defeats the framing pre-filter ----
/// <summary>Padding a blob with leading whitespace.</summary>
private const string Pad = " \t\r\n ";
/// <summary>
/// MQTT is the one factory of the seven whose RUNTIME mappers carry the same <c>[0] != '{'</c>
/// framing gate the inspector did, so a padded blob is genuinely REFUSED by this driver — which is
/// precisely why the untrimmed pre-filter was a defect rather than a cosmetic mismatch: the tag
/// read <c>BadNodeIdUnknown</c> forever and the deploy gate said nothing at all. Its siblings hand
/// the blob to a whitespace-tolerant <c>JsonDocument.Parse</c> and so keep accepting it; both
/// behaviours are correct, because each inspector mirrors its own mapper.
/// </summary>
/// <param name="tagConfig">A fixture that is accepted unpadded.</param>
[Theory]
[MemberData(nameof(Accepted))]
public void A_padded_config_the_readers_refuse_is_no_longer_passed_over_in_silence(string tagConfig)
{
var padded = Pad + tagConfig;
EitherModeAccepts(tagConfig).ShouldBeTrue("the unpadded fixture must be accepted");
EitherModeAccepts(padded).ShouldBeFalse("both MQTT readers carry their own framing gate");
MqttTagDefinitionFactory.Inspect(padded).ShouldNotBeEmpty();
}
/// <summary>
/// Trimming widens the gate ONLY for JSON objects — a reference still not object-framed after the
/// trim is not an equipment-tag TagConfig at all and keeps drawing nothing.
/// </summary>
/// <param name="reference">A padded, non-object reference.</param>
[Theory]
[InlineData(" just a string")]
[InlineData(" [1,2,3]")]
[InlineData(" \t\r\n 42")]
[InlineData(" \"a\"")]
[InlineData(" ")]
public void A_non_object_reference_still_draws_nothing_after_trimming(string reference)
{
EitherModeAccepts(reference).ShouldBeFalse();
MqttTagDefinitionFactory.Inspect(reference).ShouldBeEmpty();
}
// ---- Gitea #556 item 2: an advisory can no longer swallow the catch-all rejection ----
/// <summary>
/// The advisory-plus-unnameable-rejection shape, and for MQTT it is REACHABLE in production rather
/// than theoretical: a padded blob is refused by both readers' own framing gates, while every
/// <c>DescribeRejection</c> branch — which walks the PARSED document — finds it perfectly
/// well-formed and names nothing. The wildcard advisory fires regardless. Before #556 the backstop
/// was gated on <c>warnings.Count == 0</c>, so that advisory satisfied the guard and the operator
/// was told only that the topic had a wildcard — never that the tag would not resolve at all.
/// </summary>
[Fact]
public void A_refusal_nothing_can_name_still_reports_the_backstop_when_an_advisory_is_present()
{
var padded = Pad + """{"topic":"plant/+/temp"}""";
EitherModeAccepts(padded).ShouldBeFalse("the framing gate in both readers refuses a padded blob");
var warnings = MqttTagDefinitionFactory.Inspect(padded);
warnings.ShouldContain(w => w.Contains("wildcard"), "the advisory still fires");
warnings.ShouldContain(
w => w.Contains("rejected by the driver's tag reader"),
"the backstop must survive the advisory — it is the only message naming the refusal");
}
// ---- Gitea #557 item 2: the payloadFormat mode-asymmetry contract ----
/// <summary>
/// The decided contract. An invalid <c>payloadFormat</c> is fatal to the Plain reader and invisible
/// to the Sparkplug one (which hard-codes <c>Json</c> and never consults the key), so the UNION
/// verdict both gates use ADMITS a Sparkplug-shaped blob carrying one. That is intended: in
/// Sparkplug mode the driver genuinely serves the tag, and a gate that rejected it would be
/// stricter than the runtime. The cost — the served behaviour depends on the driver's
/// <c>MqttMode</c>, which no tag row records — is paid by an ADVISORY, not by changing the verdict.
/// </summary>
[Fact]
public void An_invalid_payloadFormat_on_a_Sparkplug_blob_is_accepted_and_advised_not_rejected()
{
const string Blob =
"""{"groupId":"OtOpcUaSim","edgeNodeId":"EdgeA","metricName":"Temp","payloadFormat":"Jsonn"}""";
MqttTagDefinitionFactory.FromSparkplugTagConfig(Blob, RawPath, out _)
.ShouldBeTrue("the Sparkplug reader never consults payloadFormat");
MqttTagDefinitionFactory.FromTagConfig(Blob, RawPath, out _)
.ShouldBeFalse("the Plain reader reads payloadFormat strictly (and this blob has no topic)");
var warnings = MqttTagDefinitionFactory.Inspect(Blob);
warnings.ShouldContain(w => w.Contains("payloadFormat") && w.Contains("Jsonn"));
warnings.ShouldContain(w => w.Contains("Plain mode"), "the advisory must name the mode dependency");
// The verdict itself is unchanged — this is an advisory, not a rejection. A rejection would name
// the tag as unresolvable, which is false for every Sparkplug deployment.
warnings.ShouldNotContain(w => w.Contains("rejected by the driver's tag reader"));
}
/// <summary>
/// The falsification control for the rule above: the SAME invalid <c>payloadFormat</c> on a blob
/// the union REFUSES is a rejection, not an advisory — so the advisory branch cannot be a blanket
/// "payloadFormat is always advisory", which would under-report a Plain tag that is dead in every
/// mode. The class a key lands in is decided by the accept gate, never by the key.
/// </summary>
[Fact]
public void The_same_invalid_payloadFormat_on_a_rejected_blob_is_a_rejection()
{
const string Blob = """{"topic":"plant/line1/temp","payloadFormat":"Jsonn"}""";
EitherModeAccepts(Blob).ShouldBeFalse("Plain refuses the enum, Sparkplug has no binding tuple");
var warnings = MqttTagDefinitionFactory.Inspect(Blob);
warnings.ShouldContain(w => w.Contains("payloadFormat") && w.Contains("Jsonn"));
warnings.ShouldNotContain(w => w.Contains("Plain mode"), "an unserved tag is not a mode-dependent case");
}
/// <summary>
/// Both gates must keep agreeing on the VERDICT (Gitea #557 item 2). The #554 authoring consult in
/// <c>MqttTagConfigModel</c> asks the identical union and only words a REFUSAL, so an advisory can
/// never leak into the modal as a blocking error. Re-stated here as the union itself, since the
/// AdminUI model is not referenced from this project.
/// </summary>
[Fact]
public void The_authoring_consults_union_is_the_same_union_the_deploy_gate_uses()
{
const string Blob =
"""{"groupId":"OtOpcUaSim","edgeNodeId":"EdgeA","metricName":"Temp","payloadFormat":"Jsonn"}""";
// Both gates read this verdict; the deploy gate's non-empty inspection above does not change it.
EitherModeAccepts(Blob).ShouldBeTrue();
MqttTagDefinitionFactory.Inspect(Blob).ShouldNotBeEmpty("advisories are allowed on an accepted blob");
}
}