Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

PublicInterface test for CancellationConstraint.Reset #1350

Merged
merged 1 commit into from
Nov 8, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
42 changes: 42 additions & 0 deletions Jint.Tests.PublicInterface/ConstraintUsageTests.cs
Original file line number Diff line number Diff line change
@@ -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();
}
}
}
}
8 changes: 4 additions & 4 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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)))
Expand Down