ConstraintUsageTests.cs 2.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  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. #if NET6_0_OR_GREATER
  10. [Fact]
  11. public void CanFindAndResetCancellationConstraint()
  12. {
  13. using var cts = new CancellationTokenSource(TimeSpan.FromMilliseconds(100));
  14. var engine = new Engine(new Options().CancellationToken(cts.Token));
  15. // expect constraint to abort execution due to timeout
  16. Assert.Throws<ExecutionCanceledException>(WaitAndCompute);
  17. // ensure constraint can be obtained publicly
  18. var cancellationConstraint = engine.FindConstraint<CancellationConstraint>();
  19. Assert.NotNull(cancellationConstraint);
  20. // reset constraint, expect computation to finish this time
  21. using var cts2 = new CancellationTokenSource(TimeSpan.FromMilliseconds(500));
  22. cancellationConstraint.Reset(cts2.Token);
  23. Assert.Equal("done", WaitAndCompute());
  24. string WaitAndCompute()
  25. {
  26. var result = engine.Evaluate(@"
  27. function sleep(millisecondsTimeout) {
  28. var totalMilliseconds = new Date().getTime() + millisecondsTimeout;
  29. var now = new Date().getTime();
  30. while (now < totalMilliseconds) {
  31. // simulate some work
  32. now = new Date().getTime();
  33. now = new Date().getTime();
  34. now = new Date().getTime();
  35. now = new Date().getTime();
  36. now = new Date().getTime();
  37. }
  38. }
  39. sleep(300);
  40. return 'done';
  41. ");
  42. return result.AsString();
  43. }
  44. }
  45. #endif
  46. [Fact]
  47. public void CanObserveConstraintsFromCustomCode()
  48. {
  49. var engine = new Engine(o => o.TimeoutInterval(TimeSpan.FromMilliseconds(100)));
  50. engine.SetValue("slowFunction", new Func<string>(() =>
  51. {
  52. for (var i = 0; i < 100; ++i)
  53. {
  54. Thread.Sleep(TimeSpan.FromMilliseconds(200));
  55. engine.CheckConstraints();
  56. }
  57. return "didn't throw!";
  58. }));
  59. Assert.Throws<TimeoutException>(() => engine.Execute("slowFunction()"));
  60. }
  61. }