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;
///
/// lmxopcua#1063 / #1065 — "the editor accepts ⇔ publish accepts", checked over one corpus in all three editor modes
/// against the deploy gate's own checker (, 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 {{equip}} was accepted by both and read Bad
/// forever. Both sides now share and .
///
///
/// A DYNAMIC tag path (ctx.GetTag(variable), OTSCRIPT_DYNPATH) is in the corpus since lmxopcua#1083: the
/// editor used to mark it an error in every mode while the gate refuses it only for a scripted-alarm predicate. The
/// split is now 's — an error where the gate refuses, a warning
/// elsewhere — so it gets the same verdict per mode.
///
public sealed class EditorGateParityTests
{
private static readonly ScriptAnalysisService Svc = new();
private static readonly RoslynDeployScriptChecker Gate = new();
public static TheoryData 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;""",
// Dynamic / empty tag paths (#1083): refused for a predicate only. Bool-returning forms too, so the predicate's
// refusal is the path's, not a non-bool return.
"""var p = "A"; return ctx.GetTag(p).Value;""",
"""var p = "A"; return ctx.GetTag(p).Value is null;""",
"""return ctx.GetTag("A" + "B").Value is null;""",
"""return ctx.GetTag($"A{1}").Value is null;""",
"""return ctx.GetTag("").Value is null;""",
"""var p = "Out"; ctx.SetVirtualTag(p, 1); return true;""",
"""var p = "A"; return ctx.GetTag(p).Value is null && ctx.GetTag("A").Value is null;""",
];
string[] modes = [ScriptAnalysisModes.Value, ScriptAnalysisModes.Calculation, ScriptAnalysisModes.AlarmPredicate];
var data = new TheoryData();
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();
}
///
/// lmxopcua#1083: a dynamic tag path is an editor ERROR exactly where the gate refuses it (a predicate) and a
/// WARNING where the gate accepts it (value, Calculation) — and the warning still shows, so the author learns the
/// path is not a declared input. Positive control for the corpus rows: the predicate really is refused by both.
///
[Theory]
[InlineData(ScriptAnalysisModes.Value, 4, true)]
[InlineData(ScriptAnalysisModes.Calculation, 4, true)]
[InlineData(ScriptAnalysisModes.AlarmPredicate, 8, false)]
public void A_dynamic_tag_path_is_an_error_only_where_the_gate_refuses_it(string mode, int severity, bool gatePasses)
{
const string source = """var p = "A"; return ctx.GetTag(p).Value is null;""";
var ct = TestContext.Current.CancellationToken;
var dynpath = Svc.Diagnose(new DiagnoseRequest(source, Mode: mode), ct).Markers.Single(m => m.Code == "OTSCRIPT_DYNPATH");
dynpath.Severity.ShouldBe(severity);
(dynpath.StartLineNumber, dynpath.StartColumn).ShouldBe((1, 32)); // on the `p` argument
if (severity == 4) dynpath.Message.ShouldContain("not a declared input");
Gate.Check([new DeployScriptCheckRequest(ScriptAnalysisModes.KindOf(mode), source)], ct)[0].Passed.ShouldBe(gatePasses);
ScriptCompileRules.RefusesNonLiteralTagPaths(ScriptAnalysisModes.KindOf(mode)).ShouldBe(!gatePasses);
}
[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.WrapperPreamble
+ "return 1;" + ScriptEvaluator.WrapperSuffix);
var predicate = Svc.CompilationFor("return true;", ScriptAnalysisModes.AlarmPredicate).SyntaxTrees.Single().ToString();
predicate.ShouldBe(ScriptEvaluator.WrapperPreamble
+ "return true;" + ScriptEvaluator.WrapperSuffix);
}
}