ソースを参照

PublicInterface test for CancellationConstraint.Reset (#1350)

ENZ 2 年 前
コミット
826bf4f788
2 ファイル変更46 行追加4 行削除
  1. 42 0
      Jint.Tests.PublicInterface/ConstraintUsageTests.cs
  2. 4 4
      README.md

+ 42 - 0
Jint.Tests.PublicInterface/ConstraintUsageTests.cs

@@ -0,0 +1,42 @@
+using Jint.Constraints;
+using Jint.Runtime;
+
+namespace Jint.Tests.PublicInterface
+{
+    public class ConstraintUsageTests
+    {
+        [Fact]
+        public void CanFindAndResetCancellationConstraint()
+        {
+            using var cts = new CancellationTokenSource(TimeSpan.FromMilliseconds(100));
+            var engine = new Engine(new Options().CancellationToken(cts.Token));
+
+            // expect constraint to abort execution due to timeout
+            Assert.Throws<ExecutionCanceledException>(WaitAndCompute);
+
+            // ensure constraint can be obtained publicly
+            var cancellationConstraint = engine.FindConstraint<CancellationConstraint>();
+            Assert.NotNull(cancellationConstraint);
+
+            // reset constraint, expect computation to finish this time
+            using var cts2 = new CancellationTokenSource(TimeSpan.FromMilliseconds(500));
+            cancellationConstraint.Reset(cts2.Token);
+            Assert.Equal("done", WaitAndCompute());
+
+            string WaitAndCompute()
+            {
+                var result = engine.Evaluate(@"
+                    function sleep(millisecondsTimeout) {
+                        var totalMilliseconds = new Date().getTime() + millisecondsTimeout;
+
+                        while (new Date() < totalMilliseconds) { }
+                    }
+
+                    sleep(200);
+                    return 'done';
+                ");
+                return result.AsString();
+            }
+        }
+    }
+}

+ 4 - 4
README.md

@@ -331,16 +331,16 @@ var engine = new Engine(options =>
 });
 ```
 
-When you reuse the engine you want to use cancellation tokens you have to reset the token before each call of `Execute`:
+When you reuse the engine and want to use cancellation tokens you have to reset the token before each call of `Execute`:
 
 ```c#
-var constraint = new CancellationConstraint();
-
 var engine = new Engine(options =>
 {
-    options.Constraint(constraint);
+    options.CancellationToken(new CancellationToken(true));
 });
 
+var constraint = engine.FindConstraint<CancellationConstraint>();
+
 for (var i = 0; i < 10; i++) 
 {
     using (var tcs = new CancellationTokenSource(TimeSpan.FromSeconds(10)))