Debian Codegraph @

node/rxjs/dist/cjs/internal/testing/TestScheduler.js

raw
1 "use strict";
2 var __extends = (this && this.__extends) || (function () {
3 var extendStatics = function (d, b) {
4 extendStatics = Object.setPrototypeOf ||
5 ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
6 function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; };
7 return extendStatics(d, b);
8 };
9 return function (d, b) {
10 if (typeof b !== "function" && b !== null)
11 throw new TypeError("Class extends value " + String(b) + " is not a constructor or null");
12 extendStatics(d, b);
13 function __() { this.constructor = d; }
14 d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
15 };
16 })();
17 var __read = (this && this.__read) || function (o, n) {
18 var m = typeof Symbol === "function" && o[Symbol.iterator];
19 if (!m) return o;
20 var i = m.call(o), r, ar = [], e;
21 try {
22 while ((n === void 0 || n-- > 0) && !(r = i.next()).done) ar.push(r.value);
23 }
24 catch (error) { e = { error: error }; }
25 finally {
26 try {
27 if (r && !r.done && (m = i["return"])) m.call(i);
28 }
29 finally { if (e) throw e.error; }
30 }
31 return ar;
32 };
33 var __spreadArray = (this && this.__spreadArray) || function (to, from) {
34 for (var i = 0, il = from.length, j = to.length; i < il; i++, j++)
35 to[j] = from[i];
36 return to;
37 };
38 var __values = (this && this.__values) || function(o) {
39 var s = typeof Symbol === "function" && Symbol.iterator, m = s && o[s], i = 0;
40 if (m) return m.call(o);
41 if (o && typeof o.length === "number") return {
42 next: function () {
43 if (o && i >= o.length) o = void 0;
44 return { value: o && o[i++], done: !o };
45 }
46 };
47 throw new TypeError(s ? "Object is not iterable." : "Symbol.iterator is not defined.");
48 };
49 Object.defineProperty(exports, "__esModule", { value: true });
50 exports.TestScheduler = void 0;
51 var Observable_1 = require("../Observable");
52 var ColdObservable_1 = require("./ColdObservable");
53 var HotObservable_1 = require("./HotObservable");
54 var SubscriptionLog_1 = require("./SubscriptionLog");
55 var VirtualTimeScheduler_1 = require("../scheduler/VirtualTimeScheduler");
56 var NotificationFactories_1 = require("../NotificationFactories");
57 var dateTimestampProvider_1 = require("../scheduler/dateTimestampProvider");
58 var performanceTimestampProvider_1 = require("../scheduler/performanceTimestampProvider");
59 var animationFrameProvider_1 = require("../scheduler/animationFrameProvider");
60 var immediateProvider_1 = require("../scheduler/immediateProvider");
61 var intervalProvider_1 = require("../scheduler/intervalProvider");
62 var timeoutProvider_1 = require("../scheduler/timeoutProvider");
63 var defaultMaxFrame = 750;
64 var TestScheduler = (function (_super) {
65 __extends(TestScheduler, _super);
66 function TestScheduler(assertDeepEqual) {
67 var _this = _super.call(this, VirtualTimeScheduler_1.VirtualAction, defaultMaxFrame) || this;
68 _this.assertDeepEqual = assertDeepEqual;
69 _this.hotObservables = [];
70 _this.coldObservables = [];
71 _this.flushTests = [];
72 _this.runMode = false;
73 return _this;
74 }
75 TestScheduler.prototype.createTime = function (marbles) {
76 var indexOf = this.runMode ? marbles.trim().indexOf('|') : marbles.indexOf('|');
77 if (indexOf === -1) {
78 throw new Error('marble diagram for time should have a completion marker "|"');
79 }
80 return indexOf * TestScheduler.frameTimeFactor;
81 };
82 TestScheduler.prototype.createColdObservable = function (marbles, values, error) {
83 if (marbles.indexOf('^') !== -1) {
84 throw new Error('cold observable cannot have subscription offset "^"');
85 }
86 if (marbles.indexOf('!') !== -1) {
87 throw new Error('cold observable cannot have unsubscription marker "!"');
88 }
89 var messages = TestScheduler.parseMarbles(marbles, values, error, undefined, this.runMode);
90 var cold = new ColdObservable_1.ColdObservable(messages, this);
91 this.coldObservables.push(cold);
92 return cold;
93 };
94 TestScheduler.prototype.createHotObservable = function (marbles, values, error) {
95 if (marbles.indexOf('!') !== -1) {
96 throw new Error('hot observable cannot have unsubscription marker "!"');
97 }
98 var messages = TestScheduler.parseMarbles(marbles, values, error, undefined, this.runMode);
99 var subject = new HotObservable_1.HotObservable(messages, this);
100 this.hotObservables.push(subject);
101 return subject;
102 };
103 TestScheduler.prototype.materializeInnerObservable = function (observable, outerFrame) {
104 var _this = this;
105 var messages = [];
106 observable.subscribe({
107 next: function (value) {
108 messages.push({ frame: _this.frame - outerFrame, notification: NotificationFactories_1.nextNotification(value) });
109 },
110 error: function (error) {
111 messages.push({ frame: _this.frame - outerFrame, notification: NotificationFactories_1.errorNotification(error) });
112 },
113 complete: function () {
114 messages.push({ frame: _this.frame - outerFrame, notification: NotificationFactories_1.COMPLETE_NOTIFICATION });
115 },
116 });
117 return messages;
118 };
119 TestScheduler.prototype.expectObservable = function (observable, subscriptionMarbles) {
120 var _this = this;
121 if (subscriptionMarbles === void 0) { subscriptionMarbles = null; }
122 var actual = [];
123 var flushTest = { actual: actual, ready: false };
124 var subscriptionParsed = TestScheduler.parseMarblesAsSubscriptions(subscriptionMarbles, this.runMode);
125 var subscriptionFrame = subscriptionParsed.subscribedFrame === Infinity ? 0 : subscriptionParsed.subscribedFrame;
126 var unsubscriptionFrame = subscriptionParsed.unsubscribedFrame;
127 var subscription;
128 this.schedule(function () {
129 subscription = observable.subscribe({
130 next: function (x) {
131 var value = x instanceof Observable_1.Observable ? _this.materializeInnerObservable(x, _this.frame) : x;
132 actual.push({ frame: _this.frame, notification: NotificationFactories_1.nextNotification(value) });
133 },
134 error: function (error) {
135 actual.push({ frame: _this.frame, notification: NotificationFactories_1.errorNotification(error) });
136 },
137 complete: function () {
138 actual.push({ frame: _this.frame, notification: NotificationFactories_1.COMPLETE_NOTIFICATION });
139 },
140 });
141 }, subscriptionFrame);
142 if (unsubscriptionFrame !== Infinity) {
143 this.schedule(function () { return subscription.unsubscribe(); }, unsubscriptionFrame);
144 }
145 this.flushTests.push(flushTest);
146 var runMode = this.runMode;
147 return {
148 toBe: function (marbles, values, errorValue) {
149 flushTest.ready = true;
150 flushTest.expected = TestScheduler.parseMarbles(marbles, values, errorValue, true, runMode);
151 },
152 toEqual: function (other) {
153 flushTest.ready = true;
154 flushTest.expected = [];
155 _this.schedule(function () {
156 subscription = other.subscribe({
157 next: function (x) {
158 var value = x instanceof Observable_1.Observable ? _this.materializeInnerObservable(x, _this.frame) : x;
159 flushTest.expected.push({ frame: _this.frame, notification: NotificationFactories_1.nextNotification(value) });
160 },
161 error: function (error) {
162 flushTest.expected.push({ frame: _this.frame, notification: NotificationFactories_1.errorNotification(error) });
163 },
164 complete: function () {
165 flushTest.expected.push({ frame: _this.frame, notification: NotificationFactories_1.COMPLETE_NOTIFICATION });
166 },
167 });
168 }, subscriptionFrame);
169 },
170 };
171 };
172 TestScheduler.prototype.expectSubscriptions = function (actualSubscriptionLogs) {
173 var flushTest = { actual: actualSubscriptionLogs, ready: false };
174 this.flushTests.push(flushTest);
175 var runMode = this.runMode;
176 return {
177 toBe: function (marblesOrMarblesArray) {
178 var marblesArray = typeof marblesOrMarblesArray === 'string' ? [marblesOrMarblesArray] : marblesOrMarblesArray;
179 flushTest.ready = true;
180 flushTest.expected = marblesArray
181 .map(function (marbles) { return TestScheduler.parseMarblesAsSubscriptions(marbles, runMode); })
182 .filter(function (marbles) { return marbles.subscribedFrame !== Infinity; });
183 },
184 };
185 };
186 TestScheduler.prototype.flush = function () {
187 var _this = this;
188 var hotObservables = this.hotObservables;
189 while (hotObservables.length > 0) {
190 hotObservables.shift().setup();
191 }
192 _super.prototype.flush.call(this);
193 this.flushTests = this.flushTests.filter(function (test) {
194 if (test.ready) {
195 _this.assertDeepEqual(test.actual, test.expected);
196 return false;
197 }
198 return true;
199 });
200 };
201 TestScheduler.parseMarblesAsSubscriptions = function (marbles, runMode) {
202 var _this = this;
203 if (runMode === void 0) { runMode = false; }
204 if (typeof marbles !== 'string') {
205 return new SubscriptionLog_1.SubscriptionLog(Infinity);
206 }
207 var characters = __spreadArray([], __read(marbles));
208 var len = characters.length;
209 var groupStart = -1;
210 var subscriptionFrame = Infinity;
211 var unsubscriptionFrame = Infinity;
212 var frame = 0;
213 var _loop_1 = function (i) {
214 var nextFrame = frame;
215 var advanceFrameBy = function (count) {
216 nextFrame += count * _this.frameTimeFactor;
217 };
218 var c = characters[i];
219 switch (c) {
220 case ' ':
221 if (!runMode) {
222 advanceFrameBy(1);
223 }
224 break;
225 case '-':
226 advanceFrameBy(1);
227 break;
228 case '(':
229 groupStart = frame;
230 advanceFrameBy(1);
231 break;
232 case ')':
233 groupStart = -1;
234 advanceFrameBy(1);
235 break;
236 case '^':
237 if (subscriptionFrame !== Infinity) {
238 throw new Error("found a second subscription point '^' in a " + 'subscription marble diagram. There can only be one.');
239 }
240 subscriptionFrame = groupStart > -1 ? groupStart : frame;
241 advanceFrameBy(1);
242 break;
243 case '!':
244 if (unsubscriptionFrame !== Infinity) {
245 throw new Error("found a second unsubscription point '!' in a " + 'subscription marble diagram. There can only be one.');
246 }
247 unsubscriptionFrame = groupStart > -1 ? groupStart : frame;
248 break;
249 default:
250 if (runMode && c.match(/^[0-9]$/)) {
251 if (i === 0 || characters[i - 1] === ' ') {
252 var buffer = characters.slice(i).join('');
253 var match = buffer.match(/^([0-9]+(?:\.[0-9]+)?)(ms|s|m) /);
254 if (match) {
255 i += match[0].length - 1;
256 var duration = parseFloat(match[1]);
257 var unit = match[2];
258 var durationInMs = void 0;
259 switch (unit) {
260 case 'ms':
261 durationInMs = duration;
262 break;
263 case 's':
264 durationInMs = duration * 1000;
265 break;
266 case 'm':
267 durationInMs = duration * 1000 * 60;
268 break;
269 default:
270 break;
271 }
272 advanceFrameBy(durationInMs / this_1.frameTimeFactor);
273 break;
274 }
275 }
276 }
277 throw new Error("there can only be '^' and '!' markers in a " + "subscription marble diagram. Found instead '" + c + "'.");
278 }
279 frame = nextFrame;
280 out_i_1 = i;
281 };
282 var this_1 = this, out_i_1;
283 for (var i = 0; i < len; i++) {
284 _loop_1(i);
285 i = out_i_1;
286 }
287 if (unsubscriptionFrame < 0) {
288 return new SubscriptionLog_1.SubscriptionLog(subscriptionFrame);
289 }
290 else {
291 return new SubscriptionLog_1.SubscriptionLog(subscriptionFrame, unsubscriptionFrame);
292 }
293 };
294 TestScheduler.parseMarbles = function (marbles, values, errorValue, materializeInnerObservables, runMode) {
295 var _this = this;
296 if (materializeInnerObservables === void 0) { materializeInnerObservables = false; }
297 if (runMode === void 0) { runMode = false; }
298 if (marbles.indexOf('!') !== -1) {
299 throw new Error('conventional marble diagrams cannot have the ' + 'unsubscription marker "!"');
300 }
301 var characters = __spreadArray([], __read(marbles));
302 var len = characters.length;
303 var testMessages = [];
304 var subIndex = runMode ? marbles.replace(/^[ ]+/, '').indexOf('^') : marbles.indexOf('^');
305 var frame = subIndex === -1 ? 0 : subIndex * -this.frameTimeFactor;
306 var getValue = typeof values !== 'object'
307 ? function (x) { return x; }
308 : function (x) {
309 if (materializeInnerObservables && values[x] instanceof ColdObservable_1.ColdObservable) {
310 return values[x].messages;
311 }
312 return values[x];
313 };
314 var groupStart = -1;
315 var _loop_2 = function (i) {
316 var nextFrame = frame;
317 var advanceFrameBy = function (count) {
318 nextFrame += count * _this.frameTimeFactor;
319 };
320 var notification = void 0;
321 var c = characters[i];
322 switch (c) {
323 case ' ':
324 if (!runMode) {
325 advanceFrameBy(1);
326 }
327 break;
328 case '-':
329 advanceFrameBy(1);
330 break;
331 case '(':
332 groupStart = frame;
333 advanceFrameBy(1);
334 break;
335 case ')':
336 groupStart = -1;
337 advanceFrameBy(1);
338 break;
339 case '|':
340 notification = NotificationFactories_1.COMPLETE_NOTIFICATION;
341 advanceFrameBy(1);
342 break;
343 case '^':
344 advanceFrameBy(1);
345 break;
346 case '#':
347 notification = NotificationFactories_1.errorNotification(errorValue || 'error');
348 advanceFrameBy(1);
349 break;
350 default:
351 if (runMode && c.match(/^[0-9]$/)) {
352 if (i === 0 || characters[i - 1] === ' ') {
353 var buffer = characters.slice(i).join('');
354 var match = buffer.match(/^([0-9]+(?:\.[0-9]+)?)(ms|s|m) /);
355 if (match) {
356 i += match[0].length - 1;
357 var duration = parseFloat(match[1]);
358 var unit = match[2];
359 var durationInMs = void 0;
360 switch (unit) {
361 case 'ms':
362 durationInMs = duration;
363 break;
364 case 's':
365 durationInMs = duration * 1000;
366 break;
367 case 'm':
368 durationInMs = duration * 1000 * 60;
369 break;
370 default:
371 break;
372 }
373 advanceFrameBy(durationInMs / this_2.frameTimeFactor);
374 break;
375 }
376 }
377 }
378 notification = NotificationFactories_1.nextNotification(getValue(c));
379 advanceFrameBy(1);
380 break;
381 }
382 if (notification) {
383 testMessages.push({ frame: groupStart > -1 ? groupStart : frame, notification: notification });
384 }
385 frame = nextFrame;
386 out_i_2 = i;
387 };
388 var this_2 = this, out_i_2;
389 for (var i = 0; i < len; i++) {
390 _loop_2(i);
391 i = out_i_2;
392 }
393 return testMessages;
394 };
395 TestScheduler.prototype.createAnimator = function () {
396 var _this = this;
397 if (!this.runMode) {
398 throw new Error('animate() must only be used in run mode');
399 }
400 var lastHandle = 0;
401 var map;
402 var delegate = {
403 requestAnimationFrame: function (callback) {
404 if (!map) {
405 throw new Error('animate() was not called within run()');
406 }
407 var handle = ++lastHandle;
408 map.set(handle, callback);
409 return handle;
410 },
411 cancelAnimationFrame: function (handle) {
412 if (!map) {
413 throw new Error('animate() was not called within run()');
414 }
415 map.delete(handle);
416 },
417 };
418 var animate = function (marbles) {
419 var e_1, _a;
420 if (map) {
421 throw new Error('animate() must not be called more than once within run()');
422 }
423 if (/[|#]/.test(marbles)) {
424 throw new Error('animate() must not complete or error');
425 }
426 map = new Map();
427 var messages = TestScheduler.parseMarbles(marbles, undefined, undefined, undefined, true);
428 try {
429 for (var messages_1 = __values(messages), messages_1_1 = messages_1.next(); !messages_1_1.done; messages_1_1 = messages_1.next()) {
430 var message = messages_1_1.value;
431 _this.schedule(function () {
432 var e_2, _a;
433 var now = _this.now();
434 var callbacks = Array.from(map.values());
435 map.clear();
436 try {
437 for (var callbacks_1 = (e_2 = void 0, __values(callbacks)), callbacks_1_1 = callbacks_1.next(); !callbacks_1_1.done; callbacks_1_1 = callbacks_1.next()) {
438 var callback = callbacks_1_1.value;
439 callback(now);
440 }
441 }
442 catch (e_2_1) { e_2 = { error: e_2_1 }; }
443 finally {
444 try {
445 if (callbacks_1_1 && !callbacks_1_1.done && (_a = callbacks_1.return)) _a.call(callbacks_1);
446 }
447 finally { if (e_2) throw e_2.error; }
448 }
449 }, message.frame);
450 }
451 }
452 catch (e_1_1) { e_1 = { error: e_1_1 }; }
453 finally {
454 try {
455 if (messages_1_1 && !messages_1_1.done && (_a = messages_1.return)) _a.call(messages_1);
456 }
457 finally { if (e_1) throw e_1.error; }
458 }
459 };
460 return { animate: animate, delegate: delegate };
461 };
462 TestScheduler.prototype.createDelegates = function () {
463 var _this = this;
464 var lastHandle = 0;
465 var scheduleLookup = new Map();
466 var run = function () {
467 var now = _this.now();
468 var scheduledRecords = Array.from(scheduleLookup.values());
469 var scheduledRecordsDue = scheduledRecords.filter(function (_a) {
470 var due = _a.due;
471 return due <= now;
472 });
473 var dueImmediates = scheduledRecordsDue.filter(function (_a) {
474 var type = _a.type;
475 return type === 'immediate';
476 });
477 if (dueImmediates.length > 0) {
478 var _a = dueImmediates[0], handle = _a.handle, handler = _a.handler;
479 scheduleLookup.delete(handle);
480 handler();
481 return;
482 }
483 var dueIntervals = scheduledRecordsDue.filter(function (_a) {
484 var type = _a.type;
485 return type === 'interval';
486 });
487 if (dueIntervals.length > 0) {
488 var firstDueInterval = dueIntervals[0];
489 var duration = firstDueInterval.duration, handler = firstDueInterval.handler;
490 firstDueInterval.due = now + duration;
491 firstDueInterval.subscription = _this.schedule(run, duration);
492 handler();
493 return;
494 }
495 var dueTimeouts = scheduledRecordsDue.filter(function (_a) {
496 var type = _a.type;
497 return type === 'timeout';
498 });
499 if (dueTimeouts.length > 0) {
500 var _b = dueTimeouts[0], handle = _b.handle, handler = _b.handler;
501 scheduleLookup.delete(handle);
502 handler();
503 return;
504 }
505 throw new Error('Expected a due immediate or interval');
506 };
507 var immediate = {
508 setImmediate: function (handler) {
509 var handle = ++lastHandle;
510 scheduleLookup.set(handle, {
511 due: _this.now(),
512 duration: 0,
513 handle: handle,
514 handler: handler,
515 subscription: _this.schedule(run, 0),
516 type: 'immediate',
517 });
518 return handle;
519 },
520 clearImmediate: function (handle) {
521 var value = scheduleLookup.get(handle);
522 if (value) {
523 value.subscription.unsubscribe();
524 scheduleLookup.delete(handle);
525 }
526 },
527 };
528 var interval = {
529 setInterval: function (handler, duration) {
530 if (duration === void 0) { duration = 0; }
531 var handle = ++lastHandle;
532 scheduleLookup.set(handle, {
533 due: _this.now() + duration,
534 duration: duration,
535 handle: handle,
536 handler: handler,
537 subscription: _this.schedule(run, duration),
538 type: 'interval',
539 });
540 return handle;
541 },
542 clearInterval: function (handle) {
543 var value = scheduleLookup.get(handle);
544 if (value) {
545 value.subscription.unsubscribe();
546 scheduleLookup.delete(handle);
547 }
548 },
549 };
550 var timeout = {
551 setTimeout: function (handler, duration) {
552 if (duration === void 0) { duration = 0; }
553 var handle = ++lastHandle;
554 scheduleLookup.set(handle, {
555 due: _this.now() + duration,
556 duration: duration,
557 handle: handle,
558 handler: handler,
559 subscription: _this.schedule(run, duration),
560 type: 'timeout',
561 });
562 return handle;
563 },
564 clearTimeout: function (handle) {
565 var value = scheduleLookup.get(handle);
566 if (value) {
567 value.subscription.unsubscribe();
568 scheduleLookup.delete(handle);
569 }
570 },
571 };
572 return { immediate: immediate, interval: interval, timeout: timeout };
573 };
574 TestScheduler.prototype.run = function (callback) {
575 var prevFrameTimeFactor = TestScheduler.frameTimeFactor;
576 var prevMaxFrames = this.maxFrames;
577 TestScheduler.frameTimeFactor = 1;
578 this.maxFrames = Infinity;
579 this.runMode = true;
580 var animator = this.createAnimator();
581 var delegates = this.createDelegates();
582 animationFrameProvider_1.animationFrameProvider.delegate = animator.delegate;
583 dateTimestampProvider_1.dateTimestampProvider.delegate = this;
584 immediateProvider_1.immediateProvider.delegate = delegates.immediate;
585 intervalProvider_1.intervalProvider.delegate = delegates.interval;
586 timeoutProvider_1.timeoutProvider.delegate = delegates.timeout;
587 performanceTimestampProvider_1.performanceTimestampProvider.delegate = this;
588 var helpers = {
589 cold: this.createColdObservable.bind(this),
590 hot: this.createHotObservable.bind(this),
591 flush: this.flush.bind(this),
592 time: this.createTime.bind(this),
593 expectObservable: this.expectObservable.bind(this),
594 expectSubscriptions: this.expectSubscriptions.bind(this),
595 animate: animator.animate,
596 };
597 try {
598 var ret = callback(helpers);
599 this.flush();
600 return ret;
601 }
602 finally {
603 TestScheduler.frameTimeFactor = prevFrameTimeFactor;
604 this.maxFrames = prevMaxFrames;
605 this.runMode = false;
606 animationFrameProvider_1.animationFrameProvider.delegate = undefined;
607 dateTimestampProvider_1.dateTimestampProvider.delegate = undefined;
608 immediateProvider_1.immediateProvider.delegate = undefined;
609 intervalProvider_1.intervalProvider.delegate = undefined;
610 timeoutProvider_1.timeoutProvider.delegate = undefined;
611 performanceTimestampProvider_1.performanceTimestampProvider.delegate = undefined;
612 }
613 };
614 TestScheduler.frameTimeFactor = 10;
615 return TestScheduler;
616 }(VirtualTimeScheduler_1.VirtualTimeScheduler));
617 exports.TestScheduler = TestScheduler;
618 //# sourceMappingURL=TestScheduler.js.map