Debian Codegraph @

node/rxjs/src/internal/testing/TestScheduler.ts

raw
1 import { Observable } from '../Observable';
2 import { ColdObservable } from './ColdObservable';
3 import { HotObservable } from './HotObservable';
4 import { TestMessage } from './TestMessage';
5 import { SubscriptionLog } from './SubscriptionLog';
6 import { Subscription } from '../Subscription';
7 import { VirtualTimeScheduler, VirtualAction } from '../scheduler/VirtualTimeScheduler';
8 import { ObservableNotification } from '../types';
9 import { COMPLETE_NOTIFICATION, errorNotification, nextNotification } from '../NotificationFactories';
10 import { dateTimestampProvider } from '../scheduler/dateTimestampProvider';
11 import { performanceTimestampProvider } from '../scheduler/performanceTimestampProvider';
12 import { animationFrameProvider } from '../scheduler/animationFrameProvider';
13 import type { TimerHandle } from '../scheduler/timerHandle';
14 import { immediateProvider } from '../scheduler/immediateProvider';
15 import { intervalProvider } from '../scheduler/intervalProvider';
16 import { timeoutProvider } from '../scheduler/timeoutProvider';
17
18 const defaultMaxFrame: number = 750;
19
20 export interface RunHelpers {
21 cold: typeof TestScheduler.prototype.createColdObservable;
22 hot: typeof TestScheduler.prototype.createHotObservable;
23 flush: typeof TestScheduler.prototype.flush;
24 time: typeof TestScheduler.prototype.createTime;
25 expectObservable: typeof TestScheduler.prototype.expectObservable;
26 expectSubscriptions: typeof TestScheduler.prototype.expectSubscriptions;
27 animate: (marbles: string) => void;
28 }
29
30 interface FlushableTest {
31 ready: boolean;
32 actual?: any[];
33 expected?: any[];
34 }
35
36 export type observableToBeFn = (marbles: string, values?: any, errorValue?: any) => void;
37 export type subscriptionLogsToBeFn = (marbles: string | string[]) => void;
38
39 export class TestScheduler extends VirtualTimeScheduler {
40 /**
41 * The number of virtual time units each character in a marble diagram represents. If
42 * the test scheduler is being used in "run mode", via the `run` method, this is temporarily
43 * set to `1` for the duration of the `run` block, then set back to whatever value it was.
44 */
45 static frameTimeFactor = 10;
46
47 /**
48 * @deprecated Internal implementation detail, do not use directly. Will be made internal in v8.
49 */
50 public readonly hotObservables: HotObservable<any>[] = [];
51
52 /**
53 * @deprecated Internal implementation detail, do not use directly. Will be made internal in v8.
54 */
55 public readonly coldObservables: ColdObservable<any>[] = [];
56
57 /**
58 * Test meta data to be processed during `flush()`
59 */
60 private flushTests: FlushableTest[] = [];
61
62 /**
63 * Indicates whether the TestScheduler instance is operating in "run mode",
64 * meaning it's processing a call to `run()`
65 */
66 private runMode = false;
67
68 /**
69 *
70 * @param assertDeepEqual A function to set up your assertion for your test harness
71 */
72 constructor(public assertDeepEqual: (actual: any, expected: any) => boolean | void) {
73 super(VirtualAction, defaultMaxFrame);
74 }
75
76 createTime(marbles: string): number {
77 const indexOf = this.runMode ? marbles.trim().indexOf('|') : marbles.indexOf('|');
78 if (indexOf === -1) {
79 throw new Error('marble diagram for time should have a completion marker "|"');
80 }
81 return indexOf * TestScheduler.frameTimeFactor;
82 }
83
84 /**
85 * @param marbles A diagram in the marble DSL. Letters map to keys in `values` if provided.
86 * @param values Values to use for the letters in `marbles`. If omitted, the letters themselves are used.
87 * @param error The error to use for the `#` marble (if present).
88 */
89 createColdObservable<T = string>(marbles: string, values?: { [marble: string]: T }, error?: any): ColdObservable<T> {
90 if (marbles.indexOf('^') !== -1) {
91 throw new Error('cold observable cannot have subscription offset "^"');
92 }
93 if (marbles.indexOf('!') !== -1) {
94 throw new Error('cold observable cannot have unsubscription marker "!"');
95 }
96 const messages = TestScheduler.parseMarbles(marbles, values, error, undefined, this.runMode);
97 const cold = new ColdObservable<T>(messages, this);
98 this.coldObservables.push(cold);
99 return cold;
100 }
101
102 /**
103 * @param marbles A diagram in the marble DSL. Letters map to keys in `values` if provided.
104 * @param values Values to use for the letters in `marbles`. If omitted, the letters themselves are used.
105 * @param error The error to use for the `#` marble (if present).
106 */
107 createHotObservable<T = string>(marbles: string, values?: { [marble: string]: T }, error?: any): HotObservable<T> {
108 if (marbles.indexOf('!') !== -1) {
109 throw new Error('hot observable cannot have unsubscription marker "!"');
110 }
111 const messages = TestScheduler.parseMarbles(marbles, values, error, undefined, this.runMode);
112 const subject = new HotObservable<T>(messages, this);
113 this.hotObservables.push(subject);
114 return subject;
115 }
116
117 private materializeInnerObservable(observable: Observable<any>, outerFrame: number): TestMessage[] {
118 const messages: TestMessage[] = [];
119 observable.subscribe({
120 next: (value) => {
121 messages.push({ frame: this.frame - outerFrame, notification: nextNotification(value) });
122 },
123 error: (error) => {
124 messages.push({ frame: this.frame - outerFrame, notification: errorNotification(error) });
125 },
126 complete: () => {
127 messages.push({ frame: this.frame - outerFrame, notification: COMPLETE_NOTIFICATION });
128 },
129 });
130 return messages;
131 }
132
133 expectObservable<T>(observable: Observable<T>, subscriptionMarbles: string | null = null) {
134 const actual: TestMessage[] = [];
135 const flushTest: FlushableTest = { actual, ready: false };
136 const subscriptionParsed = TestScheduler.parseMarblesAsSubscriptions(subscriptionMarbles, this.runMode);
137 const subscriptionFrame = subscriptionParsed.subscribedFrame === Infinity ? 0 : subscriptionParsed.subscribedFrame;
138 const unsubscriptionFrame = subscriptionParsed.unsubscribedFrame;
139 let subscription: Subscription;
140
141 this.schedule(() => {
142 subscription = observable.subscribe({
143 next: (x) => {
144 // Support Observable-of-Observables
145 const value = x instanceof Observable ? this.materializeInnerObservable(x, this.frame) : x;
146 actual.push({ frame: this.frame, notification: nextNotification(value) });
147 },
148 error: (error) => {
149 actual.push({ frame: this.frame, notification: errorNotification(error) });
150 },
151 complete: () => {
152 actual.push({ frame: this.frame, notification: COMPLETE_NOTIFICATION });
153 },
154 });
155 }, subscriptionFrame);
156
157 if (unsubscriptionFrame !== Infinity) {
158 this.schedule(() => subscription.unsubscribe(), unsubscriptionFrame);
159 }
160
161 this.flushTests.push(flushTest);
162 const { runMode } = this;
163
164 return {
165 toBe(marbles: string, values?: any, errorValue?: any) {
166 flushTest.ready = true;
167 flushTest.expected = TestScheduler.parseMarbles(marbles, values, errorValue, true, runMode);
168 },
169 toEqual: (other: Observable<T>) => {
170 flushTest.ready = true;
171 flushTest.expected = [];
172 this.schedule(() => {
173 subscription = other.subscribe({
174 next: (x) => {
175 // Support Observable-of-Observables
176 const value = x instanceof Observable ? this.materializeInnerObservable(x, this.frame) : x;
177 flushTest.expected!.push({ frame: this.frame, notification: nextNotification(value) });
178 },
179 error: (error) => {
180 flushTest.expected!.push({ frame: this.frame, notification: errorNotification(error) });
181 },
182 complete: () => {
183 flushTest.expected!.push({ frame: this.frame, notification: COMPLETE_NOTIFICATION });
184 },
185 });
186 }, subscriptionFrame);
187 },
188 };
189 }
190
191 expectSubscriptions(actualSubscriptionLogs: SubscriptionLog[]): { toBe: subscriptionLogsToBeFn } {
192 const flushTest: FlushableTest = { actual: actualSubscriptionLogs, ready: false };
193 this.flushTests.push(flushTest);
194 const { runMode } = this;
195 return {
196 toBe(marblesOrMarblesArray: string | string[]) {
197 const marblesArray: string[] = typeof marblesOrMarblesArray === 'string' ? [marblesOrMarblesArray] : marblesOrMarblesArray;
198 flushTest.ready = true;
199 flushTest.expected = marblesArray
200 .map((marbles) => TestScheduler.parseMarblesAsSubscriptions(marbles, runMode))
201 .filter((marbles) => marbles.subscribedFrame !== Infinity);
202 },
203 };
204 }
205
206 flush() {
207 const hotObservables = this.hotObservables;
208 while (hotObservables.length > 0) {
209 hotObservables.shift()!.setup();
210 }
211
212 super.flush();
213
214 this.flushTests = this.flushTests.filter((test) => {
215 if (test.ready) {
216 this.assertDeepEqual(test.actual, test.expected);
217 return false;
218 }
219 return true;
220 });
221 }
222
223 static parseMarblesAsSubscriptions(marbles: string | null, runMode = false): SubscriptionLog {
224 if (typeof marbles !== 'string') {
225 return new SubscriptionLog(Infinity);
226 }
227 // Spreading the marbles into an array leverages ES2015's support for emoji
228 // characters when iterating strings.
229 const characters = [...marbles];
230 const len = characters.length;
231 let groupStart = -1;
232 let subscriptionFrame = Infinity;
233 let unsubscriptionFrame = Infinity;
234 let frame = 0;
235
236 for (let i = 0; i < len; i++) {
237 let nextFrame = frame;
238 const advanceFrameBy = (count: number) => {
239 nextFrame += count * this.frameTimeFactor;
240 };
241 const c = characters[i];
242 switch (c) {
243 case ' ':
244 // Whitespace no longer advances time
245 if (!runMode) {
246 advanceFrameBy(1);
247 }
248 break;
249 case '-':
250 advanceFrameBy(1);
251 break;
252 case '(':
253 groupStart = frame;
254 advanceFrameBy(1);
255 break;
256 case ')':
257 groupStart = -1;
258 advanceFrameBy(1);
259 break;
260 case '^':
261 if (subscriptionFrame !== Infinity) {
262 throw new Error("found a second subscription point '^' in a " + 'subscription marble diagram. There can only be one.');
263 }
264 subscriptionFrame = groupStart > -1 ? groupStart : frame;
265 advanceFrameBy(1);
266 break;
267 case '!':
268 if (unsubscriptionFrame !== Infinity) {
269 throw new Error("found a second unsubscription point '!' in a " + 'subscription marble diagram. There can only be one.');
270 }
271 unsubscriptionFrame = groupStart > -1 ? groupStart : frame;
272 break;
273 default:
274 // time progression syntax
275 if (runMode && c.match(/^[0-9]$/)) {
276 // Time progression must be preceded by at least one space
277 // if it's not at the beginning of the diagram
278 if (i === 0 || characters[i - 1] === ' ') {
279 const buffer = characters.slice(i).join('');
280 const match = buffer.match(/^([0-9]+(?:\.[0-9]+)?)(ms|s|m) /);
281 if (match) {
282 i += match[0].length - 1;
283 const duration = parseFloat(match[1]);
284 const unit = match[2];
285 let durationInMs: number;
286
287 switch (unit) {
288 case 'ms':
289 durationInMs = duration;
290 break;
291 case 's':
292 durationInMs = duration * 1000;
293 break;
294 case 'm':
295 durationInMs = duration * 1000 * 60;
296 break;
297 default:
298 break;
299 }
300
301 advanceFrameBy(durationInMs! / this.frameTimeFactor);
302 break;
303 }
304 }
305 }
306
307 throw new Error("there can only be '^' and '!' markers in a " + "subscription marble diagram. Found instead '" + c + "'.");
308 }
309
310 frame = nextFrame;
311 }
312
313 if (unsubscriptionFrame < 0) {
314 return new SubscriptionLog(subscriptionFrame);
315 } else {
316 return new SubscriptionLog(subscriptionFrame, unsubscriptionFrame);
317 }
318 }
319
320 static parseMarbles(
321 marbles: string,
322 values?: any,
323 errorValue?: any,
324 materializeInnerObservables: boolean = false,
325 runMode = false
326 ): TestMessage[] {
327 if (marbles.indexOf('!') !== -1) {
328 throw new Error('conventional marble diagrams cannot have the ' + 'unsubscription marker "!"');
329 }
330 // Spreading the marbles into an array leverages ES2015's support for emoji
331 // characters when iterating strings.
332 const characters = [...marbles];
333 const len = characters.length;
334 const testMessages: TestMessage[] = [];
335 const subIndex = runMode ? marbles.replace(/^[ ]+/, '').indexOf('^') : marbles.indexOf('^');
336 let frame = subIndex === -1 ? 0 : subIndex * -this.frameTimeFactor;
337 const getValue =
338 typeof values !== 'object'
339 ? (x: any) => x
340 : (x: any) => {
341 // Support Observable-of-Observables
342 if (materializeInnerObservables && values[x] instanceof ColdObservable) {
343 return values[x].messages;
344 }
345 return values[x];
346 };
347 let groupStart = -1;
348
349 for (let i = 0; i < len; i++) {
350 let nextFrame = frame;
351 const advanceFrameBy = (count: number) => {
352 nextFrame += count * this.frameTimeFactor;
353 };
354
355 let notification: ObservableNotification<any> | undefined;
356 const c = characters[i];
357 switch (c) {
358 case ' ':
359 // Whitespace no longer advances time
360 if (!runMode) {
361 advanceFrameBy(1);
362 }
363 break;
364 case '-':
365 advanceFrameBy(1);
366 break;
367 case '(':
368 groupStart = frame;
369 advanceFrameBy(1);
370 break;
371 case ')':
372 groupStart = -1;
373 advanceFrameBy(1);
374 break;
375 case '|':
376 notification = COMPLETE_NOTIFICATION;
377 advanceFrameBy(1);
378 break;
379 case '^':
380 advanceFrameBy(1);
381 break;
382 case '#':
383 notification = errorNotification(errorValue || 'error');
384 advanceFrameBy(1);
385 break;
386 default:
387 // Might be time progression syntax, or a value literal
388 if (runMode && c.match(/^[0-9]$/)) {
389 // Time progression must be preceded by at least one space
390 // if it's not at the beginning of the diagram
391 if (i === 0 || characters[i - 1] === ' ') {
392 const buffer = characters.slice(i).join('');
393 const match = buffer.match(/^([0-9]+(?:\.[0-9]+)?)(ms|s|m) /);
394 if (match) {
395 i += match[0].length - 1;
396 const duration = parseFloat(match[1]);
397 const unit = match[2];
398 let durationInMs: number;
399
400 switch (unit) {
401 case 'ms':
402 durationInMs = duration;
403 break;
404 case 's':
405 durationInMs = duration * 1000;
406 break;
407 case 'm':
408 durationInMs = duration * 1000 * 60;
409 break;
410 default:
411 break;
412 }
413
414 advanceFrameBy(durationInMs! / this.frameTimeFactor);
415 break;
416 }
417 }
418 }
419
420 notification = nextNotification(getValue(c));
421 advanceFrameBy(1);
422 break;
423 }
424
425 if (notification) {
426 testMessages.push({ frame: groupStart > -1 ? groupStart : frame, notification });
427 }
428
429 frame = nextFrame;
430 }
431 return testMessages;
432 }
433
434 private createAnimator() {
435 if (!this.runMode) {
436 throw new Error('animate() must only be used in run mode');
437 }
438
439 // The TestScheduler assigns a delegate to the provider that's used for
440 // requestAnimationFrame (rAF). The delegate works in conjunction with the
441 // animate run helper to coordinate the invocation of any rAF callbacks,
442 // that are effected within tests, with the animation frames specified by
443 // the test's author - in the marbles that are passed to the animate run
444 // helper. This allows the test's author to write deterministic tests and
445 // gives the author full control over when - or if - animation frames are
446 // 'painted'.
447
448 let lastHandle = 0;
449 let map: Map<number, FrameRequestCallback> | undefined;
450
451 const delegate = {
452 requestAnimationFrame(callback: FrameRequestCallback) {
453 if (!map) {
454 throw new Error('animate() was not called within run()');
455 }
456 const handle = ++lastHandle;
457 map.set(handle, callback);
458 return handle;
459 },
460 cancelAnimationFrame(handle: number) {
461 if (!map) {
462 throw new Error('animate() was not called within run()');
463 }
464 map.delete(handle);
465 },
466 };
467
468 const animate = (marbles: string) => {
469 if (map) {
470 throw new Error('animate() must not be called more than once within run()');
471 }
472 if (/[|#]/.test(marbles)) {
473 throw new Error('animate() must not complete or error');
474 }
475 map = new Map<number, FrameRequestCallback>();
476 const messages = TestScheduler.parseMarbles(marbles, undefined, undefined, undefined, true);
477 for (const message of messages) {
478 this.schedule(() => {
479 const now = this.now();
480 // Capture the callbacks within the queue and clear the queue
481 // before enumerating the callbacks, as callbacks might
482 // reschedule themselves. (And, yeah, we're using a Map to represent
483 // the queue, but the values are guaranteed to be returned in
484 // insertion order, so it's all good. Trust me, I've read the docs.)
485 const callbacks = Array.from(map!.values());
486 map!.clear();
487 for (const callback of callbacks) {
488 callback(now);
489 }
490 }, message.frame);
491 }
492 };
493
494 return { animate, delegate };
495 }
496
497 private createDelegates() {
498 // When in run mode, the TestScheduler provides alternate implementations
499 // of set/clearImmediate and set/clearInterval. These implementations are
500 // consumed by the scheduler implementations via the providers. This is
501 // done to effect deterministic asap and async scheduler behavior so that
502 // all of the schedulers are testable in 'run mode'. Prior to v7,
503 // delegation occurred at the scheduler level. That is, the asap and
504 // animation frame schedulers were identical in behavior to the async
505 // scheduler. Now, when in run mode, asap actions are prioritized over
506 // async actions and animation frame actions are coordinated using the
507 // animate run helper.
508
509 let lastHandle = 0;
510 const scheduleLookup = new Map<
511 TimerHandle,
512 {
513 due: number;
514 duration: number;
515 handle: TimerHandle;
516 handler: () => void;
517 subscription: Subscription;
518 type: 'immediate' | 'interval' | 'timeout';
519 }
520 >();
521
522 const run = () => {
523 // Whenever a scheduled run is executed, it must run a single immediate
524 // or interval action - with immediate actions being prioritized over
525 // interval and timeout actions.
526 const now = this.now();
527 const scheduledRecords = Array.from(scheduleLookup.values());
528 const scheduledRecordsDue = scheduledRecords.filter(({ due }) => due <= now);
529 const dueImmediates = scheduledRecordsDue.filter(({ type }) => type === 'immediate');
530 if (dueImmediates.length > 0) {
531 const { handle, handler } = dueImmediates[0];
532 scheduleLookup.delete(handle);
533 handler();
534 return;
535 }
536 const dueIntervals = scheduledRecordsDue.filter(({ type }) => type === 'interval');
537 if (dueIntervals.length > 0) {
538 const firstDueInterval = dueIntervals[0];
539 const { duration, handler } = firstDueInterval;
540 firstDueInterval.due = now + duration;
541 // The interval delegate must behave like setInterval, so run needs to
542 // be rescheduled. This will continue until the clearInterval delegate
543 // unsubscribes and deletes the handle from the map.
544 firstDueInterval.subscription = this.schedule(run, duration);
545 handler();
546 return;
547 }
548 const dueTimeouts = scheduledRecordsDue.filter(({ type }) => type === 'timeout');
549 if (dueTimeouts.length > 0) {
550 const { handle, handler } = dueTimeouts[0];
551 scheduleLookup.delete(handle);
552 handler();
553 return;
554 }
555 throw new Error('Expected a due immediate or interval');
556 };
557
558 // The following objects are the delegates that replace conventional
559 // runtime implementations with TestScheduler implementations.
560 //
561 // The immediate delegate is depended upon by the asapScheduler.
562 //
563 // The interval delegate is depended upon by the asyncScheduler.
564 //
565 // The timeout delegate is not depended upon by any scheduler, but it's
566 // included here because the onUnhandledError and onStoppedNotification
567 // configuration points use setTimeout to avoid producer interference. It's
568 // inclusion allows for the testing of these configuration points.
569
570 const immediate = {
571 setImmediate: (handler: () => void) => {
572 const handle = ++lastHandle;
573 scheduleLookup.set(handle, {
574 due: this.now(),
575 duration: 0,
576 handle,
577 handler,
578 subscription: this.schedule(run, 0),
579 type: 'immediate',
580 });
581 return handle;
582 },
583 clearImmediate: (handle: TimerHandle) => {
584 const value = scheduleLookup.get(handle);
585 if (value) {
586 value.subscription.unsubscribe();
587 scheduleLookup.delete(handle);
588 }
589 },
590 };
591
592 const interval = {
593 setInterval: (handler: () => void, duration = 0) => {
594 const handle = ++lastHandle;
595 scheduleLookup.set(handle, {
596 due: this.now() + duration,
597 duration,
598 handle,
599 handler,
600 subscription: this.schedule(run, duration),
601 type: 'interval',
602 });
603 return handle;
604 },
605 clearInterval: (handle: TimerHandle) => {
606 const value = scheduleLookup.get(handle);
607 if (value) {
608 value.subscription.unsubscribe();
609 scheduleLookup.delete(handle);
610 }
611 },
612 };
613
614 const timeout = {
615 setTimeout: (handler: () => void, duration = 0) => {
616 const handle = ++lastHandle;
617 scheduleLookup.set(handle, {
618 due: this.now() + duration,
619 duration,
620 handle,
621 handler,
622 subscription: this.schedule(run, duration),
623 type: 'timeout',
624 });
625 return handle;
626 },
627 clearTimeout: (handle: TimerHandle) => {
628 const value = scheduleLookup.get(handle);
629 if (value) {
630 value.subscription.unsubscribe();
631 scheduleLookup.delete(handle);
632 }
633 },
634 };
635
636 return { immediate, interval, timeout };
637 }
638
639 /**
640 * The `run` method performs the test in 'run mode' - in which schedulers
641 * used within the test automatically delegate to the `TestScheduler`. That
642 * is, in 'run mode' there is no need to explicitly pass a `TestScheduler`
643 * instance to observable creators or operators.
644 *
645 * @see {@link /guide/testing/marble-testing}
646 */
647 run<T>(callback: (helpers: RunHelpers) => T): T {
648 const prevFrameTimeFactor = TestScheduler.frameTimeFactor;
649 const prevMaxFrames = this.maxFrames;
650
651 TestScheduler.frameTimeFactor = 1;
652 this.maxFrames = Infinity;
653 this.runMode = true;
654
655 const animator = this.createAnimator();
656 const delegates = this.createDelegates();
657
658 animationFrameProvider.delegate = animator.delegate;
659 dateTimestampProvider.delegate = this;
660 immediateProvider.delegate = delegates.immediate;
661 intervalProvider.delegate = delegates.interval;
662 timeoutProvider.delegate = delegates.timeout;
663 performanceTimestampProvider.delegate = this;
664
665 const helpers: RunHelpers = {
666 cold: this.createColdObservable.bind(this),
667 hot: this.createHotObservable.bind(this),
668 flush: this.flush.bind(this),
669 time: this.createTime.bind(this),
670 expectObservable: this.expectObservable.bind(this),
671 expectSubscriptions: this.expectSubscriptions.bind(this),
672 animate: animator.animate,
673 };
674 try {
675 const ret = callback(helpers);
676 this.flush();
677 return ret;
678 } finally {
679 TestScheduler.frameTimeFactor = prevFrameTimeFactor;
680 this.maxFrames = prevMaxFrames;
681 this.runMode = false;
682 animationFrameProvider.delegate = undefined;
683 dateTimestampProvider.delegate = undefined;
684 immediateProvider.delegate = undefined;
685 intervalProvider.delegate = undefined;
686 timeoutProvider.delegate = undefined;
687 performanceTimestampProvider.delegate = undefined;
688 }
689 }
690 }