ConstraintUsageTests.cs 1.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142
  1. using Jint.Constraints;
  2. using Jint.Runtime;
  3. namespace Jint.Tests.PublicInterface;
  4. public class ConstraintUsageTests
  5. {
  6. [Fact]
  7. public void CanFindAndResetCancellationConstraint()
  8. {
  9. using var cts = new CancellationTokenSource(TimeSpan.FromMilliseconds(100));
  10. var engine = new Engine(new Options().CancellationToken(cts.Token));
  11. // expect constraint to abort execution due to timeout
  12. Assert.Throws<ExecutionCanceledException>(WaitAndCompute);
  13. // ensure constraint can be obtained publicly
  14. var cancellationConstraint = engine.FindConstraint<CancellationConstraint>();
  15. Assert.NotNull(cancellationConstraint);
  16. // reset constraint, expect computation to finish this time
  17. using var cts2 = new CancellationTokenSource(TimeSpan.FromMilliseconds(500));
  18. cancellationConstraint.Reset(cts2.Token);
  19. Assert.Equal("done", WaitAndCompute());
  20. string WaitAndCompute()
  21. {
  22. var result = engine.Evaluate(@"
  23. function sleep(millisecondsTimeout) {
  24. var x = 0;
  25. var totalMilliseconds = new Date().getTime() + millisecondsTimeout;
  26. while (new Date().getTime() < totalMilliseconds) {
  27. x++;
  28. }
  29. }
  30. sleep(200);
  31. return 'done';
  32. ");
  33. return result.AsString();
  34. }
  35. }
  36. }