ConstraintUsageTests.cs 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  1. namespace Jint.Tests.PublicInterface;
  2. [Collection("ConstraintUsageTests")]
  3. public class ConstraintUsageTests
  4. {
  5. // this test case is problematic due to nature of cancellation token source in old framework
  6. // in NET 6 it's better designed and signals more reliably
  7. // TODO NET 8 also has problems with this
  8. #if NET6_0
  9. [Fact]
  10. public void CanFindAndResetCancellationConstraint()
  11. {
  12. using var cts = new CancellationTokenSource(TimeSpan.FromMilliseconds(100));
  13. var engine = new Engine(new Options().CancellationToken(cts.Token));
  14. // expect constraint to abort execution due to timeout
  15. Assert.Throws<ExecutionCanceledException>(WaitAndCompute);
  16. // ensure constraint can be obtained publicly
  17. var cancellationConstraint = engine.FindConstraint<CancellationConstraint>();
  18. Assert.NotNull(cancellationConstraint);
  19. // reset constraint, expect computation to finish this time
  20. using var cts2 = new CancellationTokenSource(TimeSpan.FromMilliseconds(500));
  21. cancellationConstraint.Reset(cts2.Token);
  22. Assert.Equal("done", WaitAndCompute());
  23. string WaitAndCompute()
  24. {
  25. var result = engine.Evaluate(@"
  26. function sleep(millisecondsTimeout) {
  27. var totalMilliseconds = new Date().getTime() + millisecondsTimeout;
  28. var now = new Date().getTime();
  29. while (now < totalMilliseconds) {
  30. // simulate some work
  31. now = new Date().getTime();
  32. now = new Date().getTime();
  33. now = new Date().getTime();
  34. now = new Date().getTime();
  35. now = new Date().getTime();
  36. }
  37. }
  38. sleep(300);
  39. return 'done';
  40. ");
  41. return result.AsString();
  42. }
  43. }
  44. #endif
  45. [Fact]
  46. public void CanObserveConstraintsFromCustomCode()
  47. {
  48. var engine = new Engine(o => o.TimeoutInterval(TimeSpan.FromMilliseconds(100)));
  49. engine.SetValue("slowFunction", new Func<string>(() =>
  50. {
  51. for (var i = 0; i < 100; ++i)
  52. {
  53. Thread.Sleep(TimeSpan.FromMilliseconds(200));
  54. engine.Constraints.Check();
  55. }
  56. return "didn't throw!";
  57. }));
  58. Assert.Throws<TimeoutException>(() => engine.Execute("slowFunction()"));
  59. }
  60. }