using Shouldly;
using Xunit;
namespace ZB.MOM.WW.OtOpcUa.Core.Scripting.Tests;
///
/// lmxopcua#1059 — a script that returns an iterator or an unfinished LINQ query used to hand the host a sequence
/// nothing had run yet; the host then enumerated it on its own thread, outside the guard's timeout / allocation sample
/// and with no element bound. The guard now materialises the result inside the guarded run, bounded.
///
[Trait("Category", "Unit")]
public sealed class ScriptResultMaterializerTests
{
private static IEnumerable Endless() { var i = 0.0; while (true) yield return i++; }
[Fact]
public void A_lazy_sequence_becomes_a_typed_array_and_runs_now()
{
var ran = 0;
var lazy = Enumerable.Range(0, 4).Select(i => { ran++; return (double)i; });
ran.ShouldBe(0);
var result = ScriptResultMaterializer.Materialize(lazy, 100).ShouldBeOfType();
result.ShouldBe([0.0, 1.0, 2.0, 3.0]);
ran.ShouldBe(4);
}
[Fact]
public void A_sequence_past_the_cap_is_cut_off_not_enumerated_forever()
{
var ex = Should.Throw(() => ScriptResultMaterializer.Materialize(Endless(), 1000));
ex.Message.ShouldContain("1000");
}
[Fact]
public void A_sequence_of_exactly_the_cap_is_accepted_boundary()
=> ScriptResultMaterializer.Materialize(Enumerable.Range(0, 5).Select(i => (long)i), 5)
.ShouldBeOfType().Length.ShouldBe(5);
[Fact]
public void A_lazy_sequence_of_an_open_slot_type_is_refused()
{
Should.Throw(() => ScriptResultMaterializer.Materialize(Enumerable.Range(0, 3).Select(i => (object)i), 100));
Should.Throw(() => ScriptResultMaterializer.Materialize(Enumerable.Range(0, 3).Select(i => new List { i }), 100));
Should.Throw(() => ScriptResultMaterializer.Materialize(Enumerable.Range(0, 3).Select(i => (IComparable)i), 100));
}
[Fact]
public void Arrays_strings_scalars_and_null_pass_through_unchanged_positive_controls()
{
var array = new[] { 1.0, 2.0 };
ScriptResultMaterializer.Materialize(array, 100).ShouldBeSameAs(array);
ScriptResultMaterializer.Materialize("abc", 100).ShouldBe("abc");
ScriptResultMaterializer.Materialize(42, 100).ShouldBe(42);
ScriptResultMaterializer.Materialize(null, 100).ShouldBeNull();
}
///
/// lmxopcua#1092: a concrete collection becomes the same typed array a lazy sequence does — the out-of-process
/// worker's wire has no collection type, so returning the collection as-is made the two runners disagree.
///
[Fact]
public void A_concrete_collection_becomes_a_typed_array()
{
ScriptResultMaterializer.Materialize(new List { 1, 2 }, 100).ShouldBeOfType().ShouldBe([1, 2]);
ScriptResultMaterializer.Materialize(new HashSet { "a" }, 100).ShouldBeOfType().ShouldBe(["a"]);
ScriptResultMaterializer.Materialize(new Queue([1.5]), 100).ShouldBeOfType().ShouldBe([1.5]);
ScriptResultMaterializer.Materialize(new List(new int[100]), 100).ShouldBeOfType().Length.ShouldBe(100);
}
[Fact]
public void A_collection_of_an_open_or_unknown_element_type_is_refused_like_a_lazy_one()
{
Should.Throw(() => ScriptResultMaterializer.Materialize(new List