using Shouldly;
using Xunit;
using ZB.MOM.WW.OtOpcUa.Core.ScriptedAlarms;
using ZB.MOM.WW.OtOpcUa.Core.VirtualTags;
namespace ZB.MOM.WW.OtOpcUa.Core.Scripting.Tests;
///
/// lmxopcua#971 follow-up — the deploy-time script compile gate's Roslyn side. The gate must answer exactly as the
/// runtime seam would: same compile, same allow-list, per seam (a VirtualTag/Calculation compiles as
/// VirtualTagContext → object?, a scripted-alarm predicate as AlarmPredicateContext → bool after the
/// dependency extractor), and cached so a redeploy does not re-enter Roslyn.
///
[Trait("Category", "Unit")]
public sealed class RoslynDeployScriptCheckerTests
{
private const string Legit = "var v = ctx.GetTag(\"A\").Value; return v is null ? 0.0 : Convert.ToDouble(v) * 2;";
private const string Forbidden = "return System.IO.File.ReadAllText(\"/etc/passwd\");";
private const string Broken = "return undefinedThing + 1;";
private static DeployScriptCheckResult CheckOne(IDeployScriptChecker checker, ScriptContextKind kind, string source) =>
checker.Check([new DeployScriptCheckRequest(kind, source)], TestContext.Current.CancellationToken).Single();
[Fact]
public void A_legitimate_script_passes_positive_control()
{
var checker = new RoslynDeployScriptChecker();
CheckOne(checker, ScriptContextKind.VirtualTag, Legit).Passed.ShouldBeTrue();
CheckOne(checker, ScriptContextKind.Calculation, Legit).Passed.ShouldBeTrue();
CheckOne(checker, ScriptContextKind.AlarmPredicate, "return Convert.ToDouble(ctx.GetTag(\"A\").Value ?? 0.0) > 5;")
.Passed.ShouldBeTrue();
}
[Fact]
public void A_forbidden_api_is_a_sandbox_violation()
{
var result = CheckOne(new RoslynDeployScriptChecker(), ScriptContextKind.VirtualTag, Forbidden);
result.Passed.ShouldBeFalse();
result.Problems.Single().ShouldStartWith("sandbox violation: ");
result.Problems.Single().ShouldContain("File");
result.Problems.Single().ShouldNotContain("\n");
}
[Fact]
public void A_compile_error_is_reported_as_the_runtime_reports_it()
{
var result = CheckOne(new RoslynDeployScriptChecker(), ScriptContextKind.VirtualTag, Broken);
result.Problems.Single().ShouldStartWith("compile error: ");
result.Problems.Single().ShouldContain("undefinedThing");
}
[Fact]
public void The_seam_decides_the_compile_a_non_bool_result_fails_only_as_an_alarm_predicate()
{
var checker = new RoslynDeployScriptChecker();
const string returnsDouble = "return 1.5;";
CheckOne(checker, ScriptContextKind.VirtualTag, returnsDouble).Passed.ShouldBeTrue();
var asPredicate = CheckOne(checker, ScriptContextKind.AlarmPredicate, returnsDouble);
asPredicate.Passed.ShouldBeFalse();
asPredicate.Problems.Single().ShouldStartWith("compile error: ");
}
[Fact]
public void An_alarm_predicate_runs_the_dependency_extractor_first_a_virtual_tag_does_not()
{
// A non-literal tag path: the scripted-alarm load rejects it before compiling; the VirtualTag seam never
// runs the extractor, so the same source compiles there.
const string dynamicPath = "var p = \"A\"; return ctx.GetTag(p).Value is null;";
var checker = new RoslynDeployScriptChecker();
CheckOne(checker, ScriptContextKind.VirtualTag, dynamicPath).Passed.ShouldBeTrue();
CheckOne(checker, ScriptContextKind.AlarmPredicate, dynamicPath)
.Problems.Single().ShouldStartWith("dependency extraction rejected — ");
}
[Fact]
public void A_passthrough_mirror_never_reaches_roslyn_for_value_seams_but_does_for_a_predicate()
{
const string mirror = "return ctx.GetTag(\"Plant/Dev/Speed\").Value;";
var checker = new RoslynDeployScriptChecker();
CheckOne(checker, ScriptContextKind.VirtualTag, mirror).Passed.ShouldBeTrue();
CheckOne(checker, ScriptContextKind.Calculation, mirror).Passed.ShouldBeTrue();
checker.CompilesPerformed.ShouldBe(0);
// The alarm engine always compiles — and object is not bool.
CheckOne(checker, ScriptContextKind.AlarmPredicate, mirror).Passed.ShouldBeFalse();
checker.CompilesPerformed.ShouldBe(1);
}
[Fact]
public void Verdicts_are_cached_by_source_and_compile_identity()
{
var checker = new RoslynDeployScriptChecker();
CheckOne(checker, ScriptContextKind.VirtualTag, Forbidden).Passed.ShouldBeFalse();
checker.CompilesPerformed.ShouldBe(1);
// Cache hit: same source, same seam — and Calculation shares the VirtualTag compile.
CheckOne(checker, ScriptContextKind.VirtualTag, Forbidden).Passed.ShouldBeFalse();
CheckOne(checker, ScriptContextKind.Calculation, Forbidden).Passed.ShouldBeFalse();
checker.CompilesPerformed.ShouldBe(1);
// A different compile identity is a miss.
CheckOne(checker, ScriptContextKind.AlarmPredicate, Forbidden).Passed.ShouldBeFalse();
checker.CompilesPerformed.ShouldBe(2);
}
[Fact]
public void A_batch_compiles_each_distinct_source_once_and_answers_in_request_order()
{
var checker = new RoslynDeployScriptChecker(maxParallelism: 4);
var requests = new[]
{
new DeployScriptCheckRequest(ScriptContextKind.VirtualTag, Legit),
new DeployScriptCheckRequest(ScriptContextKind.VirtualTag, Forbidden),
new DeployScriptCheckRequest(ScriptContextKind.Calculation, Legit),
new DeployScriptCheckRequest(ScriptContextKind.VirtualTag, Broken),
new DeployScriptCheckRequest(ScriptContextKind.VirtualTag, Forbidden),
};
var results = checker.Check(requests, TestContext.Current.CancellationToken);
results.Select(r => r.Request).ShouldBe(requests);
results.Select(r => r.Passed).ShouldBe([true, false, true, false, false]);
checker.CompilesPerformed.ShouldBe(3);
}
[Fact]
public void A_full_cache_is_cleared_and_still_answers_correctly()
{
var checker = new RoslynDeployScriptChecker(capacity: 1);
CheckOne(checker, ScriptContextKind.VirtualTag, Legit).Passed.ShouldBeTrue();
CheckOne(checker, ScriptContextKind.VirtualTag, Forbidden).Passed.ShouldBeFalse();
CheckOne(checker, ScriptContextKind.VirtualTag, Legit).Passed.ShouldBeTrue();
checker.CompilesPerformed.ShouldBe(3);
}
///
/// Parity with the runtime compile: shares the
/// compilation factory with , so for every
/// sample the gate passes exactly when the runtime compile succeeds.
///
[Theory]
[InlineData(Legit)]
[InlineData(Forbidden)]
[InlineData(Broken)]
[InlineData("return 1.5;")]
[InlineData("return true;")]
[InlineData("return 0; } public static int Evil() { return 0;")]
[InlineData("var t = typeof(string).Assembly; return t.FullName;")]
[InlineData("return Environment.GetEnvironmentVariable(\"PATH\");")]
public void The_gate_accepts_exactly_what_the_runtime_compile_accepts(string source)
{
var checker = new RoslynDeployScriptChecker();
static bool RuntimeCompiles(string s) where TContext : ScriptContext
{
try { _ = ScriptEvaluator.CompileToImage(s); return true; }
catch (CompilationErrorException) { return false; }
catch (ScriptSandboxViolationException) { return false; }
}
CheckOne(checker, ScriptContextKind.VirtualTag, source).Passed
.ShouldBe(RuntimeCompiles(source));
var predicateRuntime = DependencyExtractor.Extract(source).IsValid && RuntimeCompiles(source);
CheckOne(checker, ScriptContextKind.AlarmPredicate, source).Passed.ShouldBe(predicateRuntime);
}
}