Files
lmxopcua/tests/Server/ZB.MOM.WW.OtOpcUa.AdminUI.Tests/ScriptAnalysis/EditorGateParityTests.cs
T
Joseph Doherty 73f49eaf32 fix(scripting): #1063 one compile-refusal authority for editor and deploy gate (ScriptCompileRules + the runtime's own wrapper text) — CS0161 and wrapper injection are now flagged in the editor; #1065 {{equip}} in a Calculation script is refused by the gate and by a new Calculation editor mode
#1063: the Monaco diagnostics dropped every Roslyn error located in the synthesized
wrapper as 'phantom', so CS0161 (not all code paths return a value, pinned on Run)
passed the editor and failed the deploy gate. ScriptCompileRules (Core.Scripting) now
states which diagnostics refuse (every Error, wherever located; LMX001/002 injection)
and which sources skip the compile (blank/passthrough value scripts); ScriptEvaluator
and the editor both use it, and the editor wraps with ScriptEvaluator.WrapperPreamble/
WrapperSuffix instead of its own copy. Wrapper-located refusals are drawn on the
script's last line. EditorGateParityTests runs one corpus through editor and gate in
all three modes.

#1065: a Calculation tag is raw/device-level with no equipment and its seam never
substitutes {{equip}}, so such a script deployed clean and read Bad forever. Refused
rather than substituted: EquipTokenLiteralScanner.FindInCalculation is run by
RoslynDeployScriptChecker for every Calculation use (before the passthrough shortcut,
outside the shared VT/Calc cache) and by the editor in the new 'calculation' mode
(Calculation tag editor; ScriptEdit defaults to it when a Calculation tag uses the
script).
2026-12-03 16:47:14 -05:00

117 lines
6.6 KiB
C#

using Shouldly;
using Xunit;
using ZB.MOM.WW.OtOpcUa.AdminUI.ScriptAnalysis;
using ZB.MOM.WW.OtOpcUa.Core.Scripting;
namespace ZB.MOM.WW.OtOpcUa.AdminUI.Tests.ScriptAnalysis;
/// <summary>
/// lmxopcua#1063 / #1065 — "the editor accepts ⇔ publish accepts", checked over one corpus in all three editor modes
/// against the deploy gate's own checker (<see cref="RoslynDeployScriptChecker"/>, the seam the mode names). The
/// editor used to drop wrapper-located errors, so a script with a path that does not return (CS0161) was clean in the
/// editor and refused at deploy; and a Calculation script carrying <c>{{equip}}</c> was accepted by both and read Bad
/// forever. Both sides now share <see cref="ScriptCompileRules"/> and <see cref="EquipTokenLiteralScanner"/>.
/// </summary>
/// <remarks>
/// Excluded on purpose: a DYNAMIC tag path (<c>ctx.GetTag(variable)</c>) in a value or Calculation script. The editor
/// marks it an error in every mode while the gate refuses it only for a scripted-alarm predicate — a known,
/// editor-stricter divergence tracked separately (it is not a compile rule, and either fix changes behaviour).
/// </remarks>
public sealed class EditorGateParityTests
{
private static readonly ScriptAnalysisService Svc = new();
private static readonly RoslynDeployScriptChecker Gate = new();
public static TheoryData<string, string> Corpus()
{
string[] sources =
[
// CS0161 family (#1063): a path that falls off the end, no return at all, blank, whitespace-only.
"var x = 1;",
"""if (ctx.GetTag("A").Value is null) return 1;""",
"""if (ctx.GetTag("A").Value is null) return true;""",
"",
" \n ",
"while (true) { }",
"throw new System.InvalidOperationException(\"x\");",
// Well-formed returns: value and bool.
"""if (ctx.GetTag("A").Value is null) return 1; return 2;""",
"""return ctx.GetTag("A").Value;""",
"""return Convert.ToDouble(ctx.GetTag("A").Value ?? 0.0) > 5;""",
"return true;",
"return null;",
"return;",
// Ordinary compile errors, sandbox, injection (LMX001/002).
"var x = ; return 1;",
"return ctx.Nope();",
"""var f = new System.IO.FileInfo("/x"); return 1;""",
"return 0; } public static int Evil() { return 0;",
"return 0; } } class Evil { ",
"return 1; }",
"{ return 1;",
// {{equip}} (#1056 / #1065): substituted regular literal, passthrough shape, verbatim, interpolated, mid-path.
"""return ctx.GetTag("{{equip}}/Speed").Value;""",
"""return (double)ctx.GetTag("{{equip}}/Speed").Value * 2;""",
"""return ctx.GetTag(@"{{equip}}/Speed").Value;""",
"""return ctx.GetTag($"{{equip}}/Speed").Value;""",
"""return ctx.GetTag("Plant/{{equip}}/Speed").Value;""",
"""ctx.SetVirtualTag("{{equip}}/Out", 1); return 1;""",
"""ctx.Logger.Information("{{equip}} is only a log string"); return 1;""",
];
string[] modes = [ScriptAnalysisModes.Value, ScriptAnalysisModes.Calculation, ScriptAnalysisModes.AlarmPredicate];
var data = new TheoryData<string, string>();
foreach (var mode in modes)
foreach (var source in sources)
data.Add(mode, source);
return data;
}
[Theory]
[MemberData(nameof(Corpus))]
public void Editor_and_gate_agree(string mode, string source)
{
var markers = Svc.Diagnose(new DiagnoseRequest(source, Mode: mode), TestContext.Current.CancellationToken).Markers;
var editorRejects = markers.Any(m => m.Severity == 8);
var verdict = Gate.Check(
[new DeployScriptCheckRequest(ScriptAnalysisModes.KindOf(mode), source)], TestContext.Current.CancellationToken)[0];
editorRejects.ShouldBe(!verdict.Passed,
$"mode {mode}, source <{source}>: editor [{string.Join(" | ", markers.Select(m => m.Code + " " + m.Message))}] " +
$"vs gate [{string.Join(" | ", verdict.Problems)}]");
}
[Fact]
public void A_missing_return_is_refused_by_both_positive_control_for_the_parity_theory()
{
// Pins that the corpus really exercises #1063 — both sides REFUSE it (a parity theory where both accepted
// everything would pass vacuously).
const string source = """if (ctx.GetTag("A").Value is null) return 1;""";
Svc.Diagnose(new DiagnoseRequest(source), TestContext.Current.CancellationToken).Markers.ShouldContain(m => m.Code == "CS0161" && m.Severity == 8);
Gate.Check([new DeployScriptCheckRequest(ScriptContextKind.VirtualTag, source)], TestContext.Current.CancellationToken)[0]
.Problems.ShouldContain(p => p.Contains("CS0161"));
}
[Fact]
public void Equip_in_a_calculation_is_refused_by_both_but_accepted_by_both_for_a_virtual_tag()
{
const string source = """return ctx.GetTag("{{equip}}/Speed").Value;""";
var ct = TestContext.Current.CancellationToken;
Svc.Diagnose(new DiagnoseRequest(source, Mode: ScriptAnalysisModes.Calculation), TestContext.Current.CancellationToken).Markers
.ShouldContain(m => m.Code == "OTSCRIPT_EQUIPCALC" && m.Severity == 8);
Gate.Check([new DeployScriptCheckRequest(ScriptContextKind.Calculation, source)], ct)[0].Passed.ShouldBeFalse();
// Positive control: the same text is the normal VirtualTag template form.
Svc.Diagnose(new DiagnoseRequest(source, Mode: ScriptAnalysisModes.Value), TestContext.Current.CancellationToken).Markers.ShouldBeEmpty();
Gate.Check([new DeployScriptCheckRequest(ScriptContextKind.VirtualTag, source)], ct)[0].Passed.ShouldBeTrue();
}
[Fact]
public void The_editor_wraps_scripts_in_the_runtimes_own_wrapper_text()
{
var tree = Svc.CompilationFor("return 1;").SyntaxTrees.Single().ToString();
tree.ShouldBe(ScriptEvaluator<ZB.MOM.WW.OtOpcUa.Core.VirtualTags.VirtualTagContext, object?>.WrapperPreamble
+ "return 1;" + ScriptEvaluator<ZB.MOM.WW.OtOpcUa.Core.VirtualTags.VirtualTagContext, object?>.WrapperSuffix);
var predicate = Svc.CompilationFor("return true;", ScriptAnalysisModes.AlarmPredicate).SyntaxTrees.Single().ToString();
predicate.ShouldBe(ScriptEvaluator<ZB.MOM.WW.OtOpcUa.Core.ScriptedAlarms.AlarmPredicateContext, bool>.WrapperPreamble
+ "return true;" + ScriptEvaluator<ZB.MOM.WW.OtOpcUa.Core.ScriptedAlarms.AlarmPredicateContext, bool>.WrapperSuffix);
}
}