ConstraintUsageTests.cs 2.5 KB

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