src/vs/base/test/common/virtualScheduling/runWithFakedTimers.ts

104 LOC · 92 covered · 12 uncovered · 8 ranges · 2121 concepts · 4 introducers · 1304 tests

File neighbourhood

The centred file is linked to every concept that introduces one of its ranges, every test that runs code from the file, and the gray connector concepts standing between those tests and the file's own introducer concepts. Undirected links join concepts to every file where they introduce source and concepts to the tests they introduce; arrows show specialization between the displayed concepts and bridge only concepts omitted from this view. Concept colors match the source ranges below; connector concepts have no source color and are shown in gray.

Focused file, its introducer and connector concepts, their introduced files, and tests that run code from the file

In the embedded map, ordinary wheel input scrolls the page; use the visible controls to zoom and drag to pan. Open the full-screen map for canvas navigation: wheel pans, Ctrl/Command plus wheel zooms, and arrow keys pan when this region is focused. On touch screens, open the full-screen map to pan or pinch. If JavaScript or WebGL is unavailable, use the related-file, concept, and source links on this page.

Graph controls are ready.

Interactive rendering requires JavaScript and WebGL. Use the related-file, concept, and source links on this page while the interactive map is unavailable.

1 > /*--------------------------------------------------------------------------------------------- processor.ts ×17
2 > * Copyright (c) Microsoft Corporation. All rights reserved.
3 > * Licensed under the MIT License. See License.txt in the project root for license information.
4 > *--------------------------------------------------------------------------------------------*/
5 >
6 > import { CancellationTokenSource } from '../../../common/cancellation.js';
7 > import { drainMicrotasksEmbedding } from './embedding.js';
8 > import { pushGlobalTimeApi } from './globalTimeApi.js';
9 > import { realTimeApi } from './timeApi.js';
10 > import { untilToken, VirtualTimeProcessor } from './processor.js';
11 > import { createRecordingRealTimeApi, RecordedTimerEvent } from './recordingTimeApi.js';
12 > import { VirtualClock } from './virtualClock.js';
13 > import { createVirtualTimeApi } from './virtualTimeApi.js';
14 >
15 > export interface RunWithFakedTimersOptions {
16 > readonly startTime?: number;
17 > /** Default `true`. Set `false` to bypass virtual time entirely (for
18 > * cases where the same test is parameterised over real/virtual time). */
19 > readonly useFakeTimers?: boolean;
20 > /** No effect in the new processor; accepted for legacy compatibility.
21 > * The drain-microtasks embedding picks the fastest available macrotask
22 > * primitive automatically. */
23 > readonly useSetImmediate?: boolean;
24 > /** Maximum number of virtual events the run is allowed to execute
25 > * before being rejected. Default 100. */
26 > readonly maxTaskCount?: number;
27 > /**
28 > * If set, called once `fn` resolves with the recorded timer events.
29 > * In virtual mode the events come from the {@link VirtualTimeProcessor}'s
30 > * own history; in real mode a recording wrapper around the host time
31 > * API is installed for the duration of `fn`. Useful for swimlane
32 > * diagnostics.
33 > */
34 > readonly onHistory?: (history: readonly RecordedTimerEvent[]) => void;
35 > }
36 >
37 > /**
38 > * Run `fn` with a virtual clock installed as the global time API.
39 > *
40 > * After `fn` resolves, the virtual queue is drained (so any timers `fn`
41 > * scheduled and `await`ed for, transitively, complete deterministically).
42 > * If `fn` throws, the queue is *not* drained — the original error is
43 > * re-thrown immediately.
44 > */
45 > export async function runWithFakedTimers<T>( runWithFakedTimers.ts ×2
46 > options: RunWithFakedTimersOptions,
47 > fn: () => Promise<T>,
48 > ): Promise<T> {
49 > const useFakeTimers = options.useFakeTimers !== false;
50 > if (!useFakeTimers) {
51 > if (!options.onHistory) { return fn(); } runWithFakedTimers.ts ×2
52 const history: RecordedTimerEvent[] = [];
53 const restore = pushGlobalTimeApi(createRecordingRealTimeApi(history));
54 try {
55 return await fn();
56 } finally {
57 restore.dispose();
58 options.onHistory(history);
59 }
62 > const clock = new VirtualClock(options.startTime ?? 0); runWithFakedTimers.ts ×2
63 > const virtualApi = createVirtualTimeApi(clock);
64 > const restoreGlobals = pushGlobalTimeApi(virtualApi);
65 >
66 > const processor = new VirtualTimeProcessor(
67 > clock,
68 > drainMicrotasksEmbedding(realTimeApi),
69 > realTimeApi,
70 > { defaultMaxEvents: options.maxTaskCount ?? 100 },
71 > );
72 >
73 > const cts = new CancellationTokenSource();
74 > const runPromise = processor.run({ until: untilToken(cts.token) });
75 >
76 > let didThrow = true;
77 > let result: T;
78 > try {
79 > result = await fn();
80 > didThrow = false; runWithFakedTimers.ts ×3
81 > } finally {
82 > // Stop intercepting real-time scheduling before draining: any tasks
83 > // scheduled during the drain itself must not land back in the
84 > // virtual queue.
85 > restoreGlobals.dispose();
86 > cts.cancel();
87 >
88 > try {
89 > if (!didThrow) {
90 > await runPromise;
91 > } else {
92 // Avoid an unhandled rejection in case disposal rejects the
93 // run.
94 runPromise.catch(() => { /* swallowed: fn() already failed */ });
95 }
96 > } finally { runWithFakedTimers.ts ×3
97 > cts.dispose();
98 > options.onHistory?.(processor.history);
99 > processor.dispose();
100 > }
101 > }
102 >
103 > return result;
104 > }