Open History to see the last commit
1/**
2 * Controllable `Clock` service for tests.
3 *
4 * Instead of waiting for real time to pass, effects that use `Effect.sleep`,
5 * timeouts, schedules, retries, and other time-based operators can be driven by
6 * advancing the test clock. This makes time-based tests deterministic and fast.
7 * The module also includes helpers for moving test time, temporarily using the
8 * live clock, and warning when a test appears to be waiting on time without
9 * advancing it.
10 *
11 * @since 2.0.0
12 */
13import * as Arr from "../Array.ts"
14import * as Clock from "../Clock.ts"
15import * as Data from "../Data.ts"
16import * as Duration from "../Duration.ts"
17import * as Effect from "../Effect.ts"
18import * as Fiber from "../Fiber.ts"
19import { flow } from "../Function.ts"
20import * as Latch from "../Latch.ts"
21import * as Layer from "../Layer.ts"
22import * as Order from "../Order.ts"
23import * as Semaphore from "../Semaphore.ts"
24
25/**
26 * A `TestClock` simplifies deterministic and efficient testing of effects that
27 * involve the passage of time.
28 *
29 * **Details**
30 *
31 * Instead of waiting for actual time to pass, `sleep` and methods implemented
32 * in terms of it schedule effects to take place at a given clock time. Use
33 * `adjust` and `setTime` to move clock time, and all effects scheduled to take
34 * place on or before that time will automatically run in order.
35 *
36 * **Gotchas**
37 *
38 * Calls to `sleep` and methods derived from it will semantically block until
39 * the time is set to on or after the time they are scheduled to run. Fork the
40 * effect being tested, then adjust the clock time, and finally verify that the
41 * expected effects have been performed.
42 *
43 * **Example** (Testing timeouts deterministically)
44 *
45 * Tests `Effect.timeout` using `TestClock`.
46 *
47 * ```ts
48 * import { Effect, Fiber, Option, pipe } from "effect"
49 * import { TestClock } from "effect/testing"
50 * import * as assert from "node:assert"
51 *
52 * Effect.gen(function*() {
53 * const fiber = yield* pipe(
54 * Effect.sleep("5 minutes"),
55 * Effect.timeout("1 minute"),
56 * Effect.forkChild
57 * )
58 * yield* TestClock.adjust("1 minute")
59 * const result = yield* Fiber.join(fiber)
60 * assert.deepStrictEqual(result, Option.none())
61 * })
62 * ```
63 *
64 * **Example** (Advancing time deterministically)
65 *
66 * ```ts
67 * import { Effect } from "effect"
68 * import { TestClock } from "effect/testing"
69 *
70 * const program = Effect.gen(function*() {
71 * let executed = false
72 *
73 * // Fork an effect that sleeps for 1 hour
74 * const fiber = yield* Effect.gen(function*() {
75 * yield* Effect.sleep("1 hour")
76 * executed = true
77 * }).pipe(Effect.forkChild)
78 *
79 * // Advance the test clock by 1 hour
80 * yield* TestClock.adjust("1 hour")
81 *
82 * // The effect should now be executed
83 * console.log(executed) // true
84 * })
85 * ```
86 *
87 * @category models
88 * @since 2.0.0
89 */
90export interface TestClock extends Clock.Clock {
91 /**
92 * Increments the current clock time by the specified duration. Any effects
93 * that were scheduled to occur on or before the new time will be run in
94 * order.
95 */
96 adjust(duration: Duration.Input): Effect.Effect<void>
97 /**
98 * Sets the current clock time to the specified `timestamp`. Any effects that
99 * were scheduled to occur on or before the new time will be run in order.
100 */
101 setTime(timestamp: number): Effect.Effect<void>
102 /**
103 * Executes the specified effect with the live `Clock` instead of the
104 * `TestClock`.
105 */
106 withLive<A, E, R>(effect: Effect.Effect<A, E, R>): Effect.Effect<A, E, R>
107}
108
109/**
110 * Namespace containing `TestClock` configuration and state types.
111 *
112 * **Example** (Configuring a test clock)
113 *
114 * ```ts
115 * import { Effect } from "effect"
116 * import { TestClock } from "effect/testing"
117 *
118 * const program = Effect.gen(function*() {
119 * // Create a TestClock with custom options
120 * const testClock = yield* TestClock.make({
121 * warningDelay: "5 seconds"
122 * })
123 *
124 * // Access the current state
125 * const currentTime = testClock.currentTimeMillisUnsafe()
126 * console.log(currentTime) // 0 (starts at epoch)
127 * })
128 * ```
129 *
130 * @since 2.0.0
131 */
132export declare namespace TestClock {
133 /**
134 * Options used when constructing a `TestClock`. `warningDelay` controls how
135 * long the live clock waits before logging a warning when a test uses time
136 * without advancing the test clock.
137 *
138 * **Example** (Configuring the warning delay)
139 *
140 * ```ts
141 * import { Effect } from "effect"
142 * import { TestClock } from "effect/testing"
143 *
144 * const program = Effect.gen(function*() {
145 * // Create a TestClock with custom warning delay
146 * const testClock = yield* TestClock.make({
147 * warningDelay: "30 seconds"
148 * })
149 *
150 * // Use the TestClock in your test
151 * yield* testClock.adjust("1 hour")
152 * })
153 * ```
154 *
155 * @category options
156 * @since 4.0.0
157 */
158 export interface Options {
159 /**
160 * The amount of time to wait before displaying a warning message when a
161 * test is using time but is not advancing the `TestClock`.
162 */
163 readonly warningDelay?: Duration.Input
164 }
165
166 /**
167 * Represents the state tracked by a `TestClock`, including the current
168 * millisecond timestamp and the sleeps scheduled to resume when the clock
169 * reaches their target time.
170 *
171 * @category models
172 * @since 4.0.0
173 */
174 export interface State {
175 readonly timestamp: number
176 readonly sleeps: ReadonlyArray<[number, Latch.Latch]>
177 }
178}
179
180/**
181 * The warning message that will be displayed if a test is using time but is
182 * not advancing the `TestClock`.
183 */
184const warningMessage = "A test is using time, but is not advancing the test " +
185 "clock, which may result in the test hanging. Use TestClock.adjust to " +
186 "manually advance the time."
187
188const defaultOptions: Required<TestClock.Options> = {
189 warningDelay: "1 second"
190}
191
192const SleepOrder = Order.flip(Order.Struct({
193 timestamp: Order.Number,
194 sequence: Order.Number
195}))
196
197/**
198 * Creates a `TestClock` with optional configuration.
199 *
200 * **Example** (Creating a test clock)
201 *
202 * ```ts
203 * import { Effect } from "effect"
204 * import { TestClock } from "effect/testing"
205 *
206 * const program = Effect.gen(function*() {
207 * // Create a TestClock with default settings
208 * const testClock = yield* TestClock.make()
209 *
210 * // Create a TestClock with custom warning delay
211 * const customTestClock = yield* TestClock.make({
212 * warningDelay: "10 seconds"
213 * })
214 *
215 * // Use the TestClock to control time in tests
216 * yield* testClock.adjust("1 hour")
217 * const currentTime = testClock.currentTimeMillisUnsafe()
218 * console.log(currentTime) // Time advanced by 1 hour
219 * })
220 * ```
221 *
222 * @category constructors
223 * @since 4.0.0
224 */
225export const make = Effect.fnUntraced(function*(
226 options?: TestClock.Options
227) {
228 const config = { ...defaultOptions, ...options }
229 let sequence = 0
230 const sleeps: Array<{
231 readonly sequence: number
232 readonly timestamp: number
233 readonly latch: Latch.Latch
234 }> = []
235 const liveClock = yield* Clock.clockWith(Effect.succeed)
236 const warningSemaphore = yield* Semaphore.make(1)
237
238 let currentTimestamp: number = new Date(0).getTime()
239 let warningState: WarningState = WarningState.Start()
240
241 function currentTimeMillisUnsafe(): number {
242 return currentTimestamp
243 }
244
245 function currentTimeNanosUnsafe(): bigint {
246 return BigInt(Math.floor(currentTimestamp * 1000000))
247 }
248
249 const currentTimeMillis = Effect.sync(currentTimeMillisUnsafe)
250 const currentTimeNanos = Effect.sync(currentTimeNanosUnsafe)
251
252 function withLive<A, E, R>(effect: Effect.Effect<A, E, R>) {
253 return Effect.provideService(effect, Clock.Clock, liveClock)
254 }
255
256 /**
257 * Forks a fiber that will display a warning message if a test is using time
258 * but is not advancing the `TestClock`.
259 */
260 const warningStart = warningSemaphore.withPermits(1)(
261 Effect.suspend(() => {
262 if (warningState._tag === "Start") {
263 return Effect.logWarning(warningMessage).pipe(
264 Effect.delay(config.warningDelay),
265 withLive,
266 Effect.forkChild,
267 Effect.interruptible,
268 Effect.flatMap((fiber) =>
269 Effect.sync(() => {
270 warningState = WarningState.Pending({ fiber })
271 })
272 )
273 )
274 }
275 return Effect.void
276 })
277 )
278 /**
279 * Cancels the warning message that is displayed if a test is using time but
280 * is not advancing the `TestClock`.
281 */
282 const warningDone = warningSemaphore.withPermits(1)(
283 Effect.suspend(() => {
284 switch (warningState._tag) {
285 case "Pending": {
286 return Fiber.interrupt(warningState.fiber).pipe(
287 Effect.andThen(Effect.sync(() => {
288 warningState = WarningState.Done()
289 }))
290 )
291 }
292 case "Start":
293 case "Done": {
294 warningState = WarningState.Done()
295 return Effect.void
296 }
297 }
298 })
299 )
300
301 const sleep = Effect.fnUntraced(function*(duration: Duration.Duration) {
302 const millis = Duration.toMillis(duration)
303 const end = currentTimestamp + millis
304 if (end <= currentTimestamp) return
305 const latch = Latch.makeUnsafe()
306 sleeps.push({
307 sequence: sequence++,
308 timestamp: end,
309 latch
310 })
311 sleeps.sort(SleepOrder)
312 yield* warningStart
313 yield* latch.await
314 })
315
316 const runSemaphore = yield* Semaphore.make(1)
317 const run = Effect.fnUntraced(function*(step: (currentTimestamp: number) => number) {
318 yield* Fiber.await(yield* Effect.forkChild(Effect.yieldNow))
319 const endTimestamp = step(currentTimestamp)
320 while (Arr.isArrayNonEmpty(sleeps)) {
321 if (Arr.lastNonEmpty(sleeps).timestamp > endTimestamp) break
322 const entry = sleeps.pop()!
323 currentTimestamp = entry.timestamp
324 entry.latch.openUnsafe()
325 yield* Effect.yieldNow
326 }
327 currentTimestamp = endTimestamp
328 }, runSemaphore.withPermits(1))
329
330 function adjust(duration: Duration.Input) {
331 const millis = Duration.toMillis(Duration.fromInputUnsafe(duration))
332 return warningDone.pipe(Effect.andThen(run((timestamp) => timestamp + millis)))
333 }
334
335 function setTime(timestamp: number) {
336 return warningDone.pipe(Effect.andThen(run(() => timestamp)))
337 }
338
339 yield* Effect.addFinalizer(() => warningDone)
340
341 return {
342 currentTimeMillisUnsafe,
343 currentTimeNanosUnsafe,
344 currentTimeMillis,
345 currentTimeNanos,
346 adjust,
347 setTime,
348 sleep,
349 withLive
350 }
351})
352
353/**
354 * Creates a `Layer` which constructs a `TestClock`.
355 *
356 * **Example** (Providing a test clock layer)
357 *
358 * ```ts
359 * import { Effect } from "effect"
360 * import { TestClock } from "effect/testing"
361 *
362 * // Create a TestClock layer
363 * const testClockLayer = TestClock.layer()
364 *
365 * // Create a TestClock layer with custom options
366 * const customTestClockLayer = TestClock.layer({
367 * warningDelay: "5 seconds"
368 * })
369 *
370 * const program = Effect.gen(function*() {
371 * // Use the layer in your program
372 * yield* TestClock.adjust("1 hour")
373 * }).pipe(Effect.provide(testClockLayer))
374 * ```
375 *
376 * @category layers
377 * @since 4.0.0
378 */
379export const layer: (options?: TestClock.Options) => Layer.Layer<TestClock> = flow(
380 make,
381 Layer.effect(Clock.Clock)
382) as any
383
384/**
385 * Retrieves the `TestClock` service for this test and uses it to run the
386 * specified workflow.
387 *
388 * **Example** (Accessing the test clock)
389 *
390 * ```ts
391 * import { Effect } from "effect"
392 * import { TestClock } from "effect/testing"
393 *
394 * const program = Effect.gen(function*() {
395 * // Use testClockWith to access the TestClock instance
396 * const currentTime = yield* TestClock.testClockWith((testClock) =>
397 * Effect.succeed(testClock.currentTimeMillisUnsafe())
398 * )
399 *
400 * // Adjust time using the TestClock instance
401 * yield* TestClock.testClockWith((testClock) => testClock.adjust("2 hours"))
402 *
403 * console.log(currentTime) // Initial time
404 * })
405 * ```
406 *
407 * @category testing
408 * @since 2.0.0
409 */
410export const testClockWith = <A, E, R>(
411 f: (testClock: TestClock) => Effect.Effect<A, E, R>
412): Effect.Effect<A, E, R> => Effect.withFiber((fiber) => f(fiber.getRef(Clock.Clock) as TestClock))
413
414/**
415 * Accesses a `TestClock` instance in the context and increments the time
416 * by the specified duration, running any actions scheduled for on or before
417 * the new time in order.
418 *
419 * **Example** (Advancing the test clock)
420 *
421 * ```ts
422 * import { Effect } from "effect"
423 * import { TestClock } from "effect/testing"
424 *
425 * const program = Effect.gen(function*() {
426 * let executed = false
427 *
428 * // Fork an effect that sleeps for 30 minutes
429 * const fiber = yield* Effect.gen(function*() {
430 * yield* Effect.sleep("30 minutes")
431 * executed = true
432 * }).pipe(Effect.forkChild)
433 *
434 * // Advance the clock by 30 minutes
435 * yield* TestClock.adjust("30 minutes")
436 *
437 * // The effect should now be executed
438 * console.log(executed) // true
439 * })
440 * ```
441 *
442 * @category testing
443 * @since 2.0.0
444 */
445export const adjust = (duration: Duration.Input): Effect.Effect<void> =>
446 testClockWith((testClock) => testClock.adjust(duration))
447
448/**
449 * Sets the current clock time to the specified `timestamp`. Any effects that
450 * were scheduled to occur on or before the new time will be run in order.
451 *
452 * **Example** (Setting the test clock time)
453 *
454 * ```ts
455 * import { Duration, Effect } from "effect"
456 * import { TestClock } from "effect/testing"
457 *
458 * const program = Effect.gen(function*() {
459 * let executed = false
460 *
461 * // Fork an effect that sleeps for 2 hours
462 * const fiber = yield* Effect.gen(function*() {
463 * yield* Effect.sleep("2 hours")
464 * executed = true
465 * }).pipe(Effect.forkChild)
466 *
467 * // Set the clock to a specific timestamp (2 hours from epoch)
468 * const targetTime = Duration.toMillis(Duration.hours(2))
469 * yield* TestClock.setTime(targetTime)
470 *
471 * // The effect should now be executed
472 * console.log(executed) // true
473 * })
474 * ```
475 *
476 * @category testing
477 * @since 2.0.0
478 */
479export const setTime = (timestamp: number): Effect.Effect<void> =>
480 testClockWith((testClock) => testClock.setTime(timestamp))
481
482/**
483 * Executes the specified effect with the live `Clock` instead of the
484 * `TestClock`.
485 *
486 * **Example** (Running with the live clock)
487 *
488 * ```ts
489 * import { Clock, Effect } from "effect"
490 * import { TestClock } from "effect/testing"
491 *
492 * const program = Effect.gen(function*() {
493 * // Get the current test time (starts at epoch)
494 * const testTime = yield* Clock.currentTimeMillis
495 * console.log(testTime) // 0
496 *
497 * // Get the actual system time using withLive
498 * const realTime = yield* TestClock.withLive(Clock.currentTimeMillis)
499 * console.log(realTime) // Actual system timestamp
500 *
501 * // Advance test time
502 * yield* TestClock.adjust("1 hour")
503 *
504 * // Test time is now 1 hour ahead
505 * const newTestTime = yield* Clock.currentTimeMillis
506 * console.log(newTestTime) // 3600000 (1 hour in milliseconds)
507 * })
508 * ```
509 *
510 * @category testing
511 * @since 4.0.0
512 */
513export const withLive = <A, E, R>(effect: Effect.Effect<A, E, R>): Effect.Effect<A, E, R> =>
514 testClockWith((testClock) => testClock.withLive(effect))
515
516/**
517 * `WarningState` describes the state of the warning message that is displayed
518 * if a test is using time but is not advancing the `TestClock`.
519 *
520 * The possible states are:
521 * - `Start` if a test has not used time yet
522 * - `Pending` if a test has used time but has not adjusted the `TestClock`
523 * - `Done` if a test has adjusted the `TestClock` or the warning message
524 * has already been displayed.
525 */
526type WarningState = Data.TaggedEnum<{
527 /**
528 * The `WarningState` which indicates that a test has not yet used time.
529 */
530 readonly Start: {}
531 /**
532 * The `WarningState` which indicates that a test has used time but has not
533 * adjusted the `TestClock`.
534 *
535 * The `Pending` state also includes a reference to the fiber that will
536 * display the warning message.
537 */
538 readonly Pending: {
539 readonly fiber: Fiber.Fiber<void, unknown>
540 }
541 /**
542 * The `WarningState` which indicates that a test has used time, or that the
543 * warning message has already been displayed.
544 */
545 readonly Done: {}
546}>
547const WarningState = Data.taggedEnum<WarningState>()