using Shouldly; using Xunit; using ZB.MOM.WW.OtOpcUa.Core.Scripting; namespace ZB.MOM.WW.OtOpcUa.Core.Scripting.Tests; /// /// lmxopcua#1052 (#999 review K-11 remainder): every evaluation through the in-process, shadow and out-of-process runners /// used to build its runner-internal {kind}:{key} string afresh, although the key is constant for a script. /// hands back the same cached string with no allocation once warm. /// public sealed class ScopedKeyCacheTests { private const int Evaluations = 10_000; [Fact] public void Warm_lookups_do_not_allocate_while_the_uncached_form_allocates_per_call() { var keys = Enumerable.Range(0, 100).Select(i => $"Plant/Line{i}/Equipment/Speed-{Guid.NewGuid():N}").ToArray(); foreach (var key in keys) ScopedKeys.For(ScriptContextKind.VirtualTag, key); // warm // Positive control: the measurement sees the per-call string of the old form. var before = GC.GetAllocatedBytesForCurrentThread(); for (var i = 0; i < Evaluations; i++) _ = InProcessScriptRunner.ScopedKey(ScriptContextKind.VirtualTag, keys[i % keys.Length]); var uncached = GC.GetAllocatedBytesForCurrentThread() - before; before = GC.GetAllocatedBytesForCurrentThread(); for (var i = 0; i < Evaluations; i++) _ = ScopedKeys.For(ScriptContextKind.VirtualTag, keys[i % keys.Length]); var cached = GC.GetAllocatedBytesForCurrentThread() - before; TestContext.Current.TestOutputHelper?.WriteLine($"{Evaluations} scoped keys: uncached {uncached} B, cached {cached} B"); uncached.ShouldBeGreaterThan(Evaluations * 64L, "positive control: the old form allocates a string per call"); cached.ShouldBeLessThan(1024, "a warm scoped-key lookup must not allocate"); } [Theory] [InlineData(ScriptContextKind.VirtualTag, "vt-1")] [InlineData(ScriptContextKind.Calculation, "Plant/Modbus/dev1/Speed")] [InlineData(ScriptContextKind.AlarmPredicate, "")] public void Cached_key_is_the_scoped_key_and_the_same_instance_each_time(ScriptContextKind kind, string key) { var first = ScopedKeys.For(kind, key); first.ShouldBe(InProcessScriptRunner.ScopedKey(kind, key)); ReferenceEquals(first, ScopedKeys.For(kind, key)).ShouldBeTrue(); } [Fact] public void Kinds_do_not_share_entries() { var key = Guid.NewGuid().ToString("N"); ScopedKeys.For(ScriptContextKind.VirtualTag, key).ShouldNotBe(ScopedKeys.For(ScriptContextKind.Calculation, key)); } [Fact] public void An_unknown_kind_still_answers_the_scoped_key() { ScopedKeys.For((ScriptContextKind)99, "x").ShouldBe("99:x"); } [Fact] public void The_cache_is_bounded() { for (var i = 0; i < ScopedKeys.CapacityPerKind + 50; i++) ScopedKeys.For(ScriptContextKind.AlarmPredicate, $"bounded-{i}"); ScopedKeys.CountFor(ScriptContextKind.AlarmPredicate).ShouldBeLessThanOrEqualTo(ScopedKeys.CapacityPerKind); // Still correct after a reset. ScopedKeys.For(ScriptContextKind.AlarmPredicate, "after").ShouldBe("3:after"); } }