Skip to content

Commit ccfc404

Browse files
committed
Added tests for MacrotaskExecutor
1 parent 63d35b3 commit ccfc404

File tree

2 files changed

+58
-1
lines changed

2 files changed

+58
-1
lines changed

core/src/main/scala/org/scalajs/macrotaskexecutor/MacrotaskExecutor.scala

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -150,4 +150,8 @@ object MacrotaskExecutor extends ExecutionContext {
150150
}
151151
}
152152
}
153+
154+
object Implicits {
155+
implicit def global: ExecutionContext = MacrotaskExecutor
156+
}
153157
}

core/src/test/scala/org/scalajs/macrotaskexecutor/MacrotaskExecutorSuite.scala

Lines changed: 54 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -18,6 +18,59 @@ package org.scalajs.macrotaskexecutor
1818

1919
import munit.FunSuite
2020

21+
import scala.concurrent.Future
22+
import scala.concurrent.duration._
23+
import scala.scalajs.js
24+
2125
class MacrotaskExecutorSuite extends FunSuite {
22-
26+
import MacrotaskExecutor.Implicits._
27+
28+
test("sequence a series of 10,000 recursive executions without clamping") {
29+
def loop(n: Int): Future[Int] =
30+
if (n <= 0)
31+
Future(0)
32+
else
33+
Future.unit.flatMap(_ => loop(n - 1)).map(_ + 1)
34+
35+
val start = System.currentTimeMillis()
36+
val MinimumClamp = 10000 * 2 * 4 // HTML5 specifies a 4ms clamp (https://developer.mozilla.org/en-US/docs/Web/API/WindowTimers.setTimeout#Minimum.2F_maximum_delay_and_timeout_nesting)
37+
38+
loop(10000) flatMap { res =>
39+
Future {
40+
val end = System.currentTimeMillis()
41+
42+
assert(res == 10000)
43+
assert((end - start).toDouble / MinimumClamp < 0.25) // we should beat the clamping by at least 4x even on slow environments
44+
}
45+
}
46+
}
47+
48+
// this test fails to terminate with a Promise-based executor
49+
test("preserve fairness with setTimeout") {
50+
var cancel = false
51+
52+
def loop(): Future[Unit] =
53+
Future(cancel) flatMap { canceled =>
54+
if (canceled)
55+
Future.unit
56+
else
57+
loop()
58+
}
59+
60+
js.timers.setTimeout(100.millis) {
61+
cancel = true
62+
}
63+
64+
loop()
65+
}
66+
67+
test("execute a bunch of stuff in 'parallel' and ensure it all runs") {
68+
var i = 0
69+
70+
Future.sequence(List.fill(10000)(Future { i += 1 })) flatMap { _ =>
71+
Future {
72+
assert(i == 10000)
73+
}
74+
}
75+
}
2376
}

0 commit comments

Comments
 (0)