Debian Codegraph @

closure-library/closure/goog/module/modulemanager_test.js

raw
1 // Copyright 2008 The Closure Library Authors. All Rights Reserved.
2 //
3 // Licensed under the Apache License, Version 2.0 (the "License");
4 // you may not use this file except in compliance with the License.
5 // You may obtain a copy of the License at
6 //
7 // http://www.apache.org/licenses/LICENSE-2.0
8 //
9 // Unless required by applicable law or agreed to in writing, software
10 // distributed under the License is distributed on an "AS-IS" BASIS,
11 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 // See the License for the specific language governing permissions and
13 // limitations under the License.
14
15 goog.provide('goog.module.ModuleManagerTest');
16 goog.setTestOnly('goog.module.ModuleManagerTest');
17
18 goog.require('goog.array');
19 goog.require('goog.functions');
20 goog.require('goog.module.BaseModule');
21 goog.require('goog.module.ModuleManager');
22 goog.require('goog.testing');
23 goog.require('goog.testing.MockClock');
24 goog.require('goog.testing.jsunit');
25 goog.require('goog.testing.recordFunction');
26
27
28
29 var clock;
30 var requestCount = 0;
31
32
33 function tearDown() {
34 clock.dispose();
35 }
36
37 function setUp() {
38 clock = new goog.testing.MockClock(true);
39 requestCount = 0;
40 }
41
42 function getModuleManager(infoMap) {
43 var mm = new goog.module.ModuleManager();
44 mm.setAllModuleInfo(infoMap);
45
46 mm.isModuleLoaded = function(id) {
47 return this.getModuleInfo(id).isLoaded();
48 };
49 return mm;
50 }
51
52 function createSuccessfulBatchLoader(moduleMgr) {
53 return {
54 loadModules: function(
55 ids, moduleInfoMap, opt_successFn, opt_errFn, opt_timeoutFn) {
56 requestCount++;
57 setTimeout(goog.bind(this.onLoad, this, ids.concat(), 0), 5);
58 },
59 onLoad: function(ids, idxLoaded) {
60 moduleMgr.beforeLoadModuleCode(ids[idxLoaded]);
61 moduleMgr.setLoaded(ids[idxLoaded]);
62 moduleMgr.afterLoadModuleCode(ids[idxLoaded]);
63 var idx = idxLoaded + 1;
64 if (idx < ids.length) {
65 setTimeout(goog.bind(this.onLoad, this, ids, idx), 2);
66 }
67 }
68 };
69 }
70
71 function createSuccessfulNonBatchLoader(moduleMgr) {
72 return {
73 loadModules: function(
74 ids, moduleInfoMap, opt_successFn, opt_errFn, opt_timeoutFn) {
75 requestCount++;
76 setTimeout(function() {
77 moduleMgr.beforeLoadModuleCode(ids[0]);
78 moduleMgr.setLoaded(ids[0]);
79 moduleMgr.afterLoadModuleCode(ids[0]);
80 if (opt_successFn) {
81 opt_successFn();
82 }
83 }, 5);
84 }
85 };
86 }
87
88 function createUnsuccessfulLoader(moduleMgr, status) {
89 return {
90 loadModules: function(
91 ids, moduleInfoMap, opt_successFn, opt_errFn, opt_timeoutFn) {
92 moduleMgr.beforeLoadModuleCode(ids[0]);
93 setTimeout(function() { opt_errFn(status); }, 5);
94 }
95 };
96 }
97
98 function createUnsuccessfulBatchLoader(moduleMgr, status) {
99 return {
100 loadModules: function(
101 ids, moduleInfoMap, opt_successFn, opt_errFn, opt_timeoutFn) {
102 setTimeout(function() { opt_errFn(status); }, 5);
103 }
104 };
105 }
106
107 function createTimeoutLoader(moduleMgr, status) {
108 return {
109 loadModules: function(
110 ids, moduleInfoMap, opt_successFn, opt_errFn, opt_timeoutFn) {
111 setTimeout(function() { opt_timeoutFn(status); }, 5);
112 }
113 };
114 }
115
116
117 /**
118 * Tests loading a module under different conditions i.e. unloaded
119 * module, already loaded module, module loaded through user initiated
120 * actions, synchronous callback for a module that has been already
121 * loaded. Test both batch and non-batch loaders.
122 */
123 function testExecOnLoad() {
124 var mm = getModuleManager({'a': [], 'b': [], 'c': []});
125 mm.setLoader(createSuccessfulNonBatchLoader(mm));
126 execOnLoad_(mm);
127
128 mm = getModuleManager({'a': [], 'b': [], 'c': []});
129 mm.setLoader(createSuccessfulBatchLoader(mm));
130 mm.setBatchModeEnabled(true);
131 execOnLoad_(mm);
132 }
133
134
135 /**
136 * Tests execOnLoad with the specified module manager.
137 * @param {goog.module.ModuleManager} mm The module manager.
138 */
139 function execOnLoad_(mm) {
140 // When module is unloaded, execOnLoad is async.
141 var execCalled1 = false;
142 mm.execOnLoad('a', function() { execCalled1 = true; });
143 assertFalse('module "a" should not be loaded', mm.isModuleLoaded('a'));
144 assertTrue('module "a" should be loading', mm.isModuleLoading('a'));
145 assertFalse('execCalled1 should not be set yet', execCalled1);
146 assertTrue('ModuleManager should be active', mm.isActive());
147 assertFalse('ModuleManager should not be user active', mm.isUserActive());
148 clock.tick(5);
149 assertTrue('module "a" should be loaded', mm.isModuleLoaded('a'));
150 assertFalse('module "a" should not be loading', mm.isModuleLoading('a'));
151 assertTrue('execCalled1 should be set', execCalled1);
152 assertFalse('ModuleManager should not be active', mm.isActive());
153 assertFalse('ModuleManager should not be user active', mm.isUserActive());
154
155 // When module is already loaded, execOnLoad is still async unless
156 // specified otherwise.
157 var execCalled2 = false;
158 mm.execOnLoad('a', function() { execCalled2 = true; });
159 assertTrue('module "a" should be loaded', mm.isModuleLoaded('a'));
160 assertFalse('module "a" should not be loading', mm.isModuleLoading('a'));
161 assertFalse('execCalled2 should not be set yet', execCalled2);
162 clock.tick(5);
163 assertTrue('execCalled2 should be set', execCalled2);
164
165 // When module is unloaded, execOnLoad is async (user active).
166 var execCalled5 = false;
167 mm.execOnLoad('c', function() { execCalled5 = true; }, null, null, true);
168 assertFalse('module "c" should not be loaded', mm.isModuleLoaded('c'));
169 assertTrue('module "c" should be loading', mm.isModuleLoading('c'));
170 assertFalse('execCalled1 should not be set yet', execCalled5);
171 assertTrue('ModuleManager should be active', mm.isActive());
172 assertTrue('ModuleManager should be user active', mm.isUserActive());
173 clock.tick(5);
174 assertTrue('module "c" should be loaded', mm.isModuleLoaded('c'));
175 assertFalse('module "c" should not be loading', mm.isModuleLoading('c'));
176 assertTrue('execCalled1 should be set', execCalled5);
177 assertFalse('ModuleManager should not be active', mm.isActive());
178 assertFalse('ModuleManager should not be user active', mm.isUserActive());
179
180 // When module is already loaded, execOnLoad is still synchronous when
181 // so specified
182 var execCalled6 = false;
183 mm.execOnLoad('c', function() {
184 execCalled6 = true;
185 }, undefined, undefined, undefined, true);
186 assertTrue('module "c" should be loaded', mm.isModuleLoaded('c'));
187 assertFalse('module "c" should not be loading', mm.isModuleLoading('c'));
188 assertTrue('execCalled6 should be set', execCalled6);
189 clock.tick(5);
190 assertTrue('execCalled6 should still be set', execCalled6);
191 }
192
193
194 /**
195 * Test aborting the callback called on module load.
196 */
197 function testExecOnLoadAbort() {
198 var mm = getModuleManager({'a': [], 'b': [], 'c': []});
199 mm.setLoader(createSuccessfulNonBatchLoader(mm));
200
201 // When module is unloaded and abort is called, module still gets
202 // loaded, but callback is cancelled.
203 var execCalled1 = false;
204 var callback1 = mm.execOnLoad('b', function() { execCalled1 = true; });
205 callback1.abort();
206 clock.tick(5);
207 assertTrue('module "b" should be loaded', mm.isModuleLoaded('b'));
208 assertFalse('execCalled3 should not be set', execCalled1);
209
210 // When module is already loaded, execOnLoad is still async, so calling
211 // abort should still cancel the callback.
212 var execCalled2 = false;
213 var callback2 = mm.execOnLoad('a', function() { execCalled2 = true; });
214 callback2.abort();
215 clock.tick(5);
216 assertFalse('execCalled2 should not be set', execCalled2);
217 }
218
219
220 /**
221 * Test preloading modules and ensure that the before load, after load
222 * and set load called are called only once per module.
223 */
224 function testExecOnLoadWhilePreloadingAndViceVersa() {
225 var mm = getModuleManager({'c': [], 'd': []});
226 mm.setLoader(createSuccessfulNonBatchLoader(mm));
227 execOnLoadWhilePreloadingAndViceVersa_(mm);
228
229 mm = getModuleManager({'c': [], 'd': []});
230 mm.setLoader(createSuccessfulBatchLoader(mm));
231 mm.setBatchModeEnabled(true);
232 execOnLoadWhilePreloadingAndViceVersa_(mm);
233 }
234
235
236 /**
237 * Perform tests with the specified module manager.
238 * @param {goog.module.ModuleManager} mm The module manager.
239 */
240 function execOnLoadWhilePreloadingAndViceVersa_(mm) {
241 var mm = getModuleManager({'c': [], 'd': []});
242 mm.setLoader(createSuccessfulNonBatchLoader(mm));
243
244 var origSetLoaded = mm.setLoaded;
245 var calls = [0, 0, 0];
246 mm.beforeLoadModuleCode = function(id) { calls[0]++; };
247 mm.setLoaded = function(id) {
248 calls[1]++;
249 origSetLoaded.call(mm, id);
250 };
251 mm.afterLoadModuleCode = function(id) { calls[2]++; };
252
253 mm.preloadModule('c', 2);
254 assertFalse('module "c" should not be loading yet', mm.isModuleLoading('c'));
255 clock.tick(2);
256 assertTrue('module "c" should now be loading', mm.isModuleLoading('c'));
257 mm.execOnLoad('c', function() {});
258 assertTrue('module "c" should still be loading', mm.isModuleLoading('c'));
259 clock.tick(5);
260 assertFalse('module "c" should be done loading', mm.isModuleLoading('c'));
261 assertEquals('beforeLoad should only be called once for "c"', 1, calls[0]);
262 assertEquals('setLoaded should only be called once for "c"', 1, calls[1]);
263 assertEquals('afterLoad should only be called once for "c"', 1, calls[2]);
264
265 mm.execOnLoad('d', function() {});
266 assertTrue('module "d" should now be loading', mm.isModuleLoading('d'));
267 mm.preloadModule('d', 2);
268 clock.tick(5);
269 assertFalse('module "d" should be done loading', mm.isModuleLoading('d'));
270 assertTrue('module "d" should now be loaded', mm.isModuleLoaded('d'));
271 assertEquals('beforeLoad should only be called once for "d"', 2, calls[0]);
272 assertEquals('setLoaded should only be called once for "d"', 2, calls[1]);
273 assertEquals('afterLoad should only be called once for "d"', 2, calls[2]);
274 }
275
276
277 /**
278 * Tests that multiple callbacks on the same module don't cause
279 * confusion about the active state after the module is finally loaded.
280 */
281 function testUserInitiatedExecOnLoadEventuallyLeavesManagerIdle() {
282 var mm = getModuleManager({'c': [], 'd': []});
283 mm.setLoader(createSuccessfulNonBatchLoader(mm));
284
285 var calledBack1 = false;
286 var calledBack2 = false;
287
288 mm.execOnLoad(
289 'c', function() { calledBack1 = true; }, undefined, undefined, true);
290 mm.execOnLoad(
291 'c', function() { calledBack2 = true; }, undefined, undefined, true);
292 mm.load('c');
293
294 assertTrue(
295 'Manager should be active while waiting for load', mm.isUserActive());
296
297 clock.tick(5);
298
299 assertTrue('First callback should be called', calledBack1);
300 assertTrue('Second callback should be called', calledBack2);
301 assertFalse(
302 'Manager should be inactive after loading is complete',
303 mm.isUserActive());
304 }
305
306
307 /**
308 * Tests loading a module by requesting a Deferred object.
309 */
310 function testLoad() {
311 var mm = getModuleManager({'a': [], 'b': [], 'c': []});
312 mm.setLoader(createSuccessfulNonBatchLoader(mm));
313
314 var calledBack = false;
315 var error = null;
316
317 var d = mm.load('a');
318 d.addCallback(function(ctx) { calledBack = true; });
319 d.addErrback(function(err) { error = err; });
320
321 assertFalse(calledBack);
322 assertNull(error);
323 assertFalse(mm.isUserActive());
324
325 clock.tick(5);
326
327 assertTrue(calledBack);
328 assertNull(error);
329 }
330
331
332 /**
333 * Tests loading 2 modules asserting that the loads happen in parallel
334 * in one unit of time.
335 */
336 function testLoad_concurrent() {
337 var mm = getModuleManager({'a': [], 'b': [], 'c': []});
338 mm.setConcurrentLoadingEnabled(true);
339 mm.setLoader(createSuccessfulNonBatchLoader(mm));
340
341 var calledBack = false;
342 var error = null;
343
344 mm.load('a');
345 mm.load('b');
346 assertEquals(2, requestCount);
347 // Only time for one serialized download.
348 clock.tick(5);
349
350 assertTrue(mm.getModuleInfo('a').isLoaded());
351 assertTrue(mm.getModuleInfo('b').isLoaded());
352 }
353
354 function testLoad_concurrentSecondIsDepOfFist() {
355 var mm = getModuleManager({'a': [], 'b': [], 'c': []});
356 mm.setBatchModeEnabled(true);
357 mm.setConcurrentLoadingEnabled(true);
358 mm.setLoader(createSuccessfulBatchLoader(mm));
359
360 var calledBack = false;
361 var error = null;
362
363 mm.loadMultiple(['a', 'b']);
364 mm.load('b');
365 assertEquals('No 2nd request expected', 1, requestCount);
366 // Only time for one serialized download.
367 clock.tick(5);
368 clock.tick(2); // Makes second module come in from batch requst.
369
370 assertTrue(mm.getModuleInfo('a').isLoaded());
371 assertTrue(mm.getModuleInfo('b').isLoaded());
372 }
373
374 function testLoad_nonConcurrent() {
375 var mm = getModuleManager({'a': [], 'b': [], 'c': []});
376 mm.setLoader(createSuccessfulNonBatchLoader(mm));
377
378 var calledBack = false;
379 var error = null;
380
381 mm.load('a');
382 mm.load('b');
383 assertEquals(1, requestCount);
384 // Only time for one serialized download.
385 clock.tick(5);
386
387 assertTrue(mm.getModuleInfo('a').isLoaded());
388 assertFalse(mm.getModuleInfo('b').isLoaded());
389 }
390
391 function testLoadUnknown() {
392 var mm = getModuleManager({'a': [], 'b': [], 'c': []});
393 mm.setLoader(createSuccessfulNonBatchLoader(mm));
394 var e = assertThrows(function() { mm.load('DoesNotExist'); });
395 assertEquals('Unknown module: DoesNotExist', e.message);
396 }
397
398
399 /**
400 * Tests loading multiple modules by requesting a Deferred object.
401 */
402 function testLoadMultiple() {
403 var mm = getModuleManager({'a': [], 'b': [], 'c': []});
404 mm.setBatchModeEnabled(true);
405 mm.setLoader(createSuccessfulBatchLoader(mm));
406
407 var calledBack = false;
408 var error = null;
409 var calledBack2 = false;
410 var error2 = null;
411
412 var dMap = mm.loadMultiple(['a', 'b']);
413 dMap['a'].addCallback(function(ctx) { calledBack = true; });
414 dMap['a'].addErrback(function(err) { error = err; });
415 dMap['b'].addCallback(function(ctx) { calledBack2 = true; });
416 dMap['b'].addErrback(function(err) { error2 = err; });
417
418 assertFalse(calledBack);
419 assertFalse(calledBack2);
420
421 clock.tick(5);
422 assertTrue(calledBack);
423 assertFalse(calledBack2);
424 assertTrue('module "a" should be loaded', mm.isModuleLoaded('a'));
425 assertFalse('module "b" should not be loaded', mm.isModuleLoaded('b'));
426 assertFalse('module "c" should not be loaded', mm.isModuleLoaded('c'));
427
428 clock.tick(2);
429
430 assertTrue(calledBack);
431 assertTrue(calledBack2);
432 assertTrue('module "a" should be loaded', mm.isModuleLoaded('a'));
433 assertTrue('module "b" should be loaded', mm.isModuleLoaded('b'));
434 assertFalse('module "c" should not be loaded', mm.isModuleLoaded('c'));
435 assertNull(error);
436 assertNull(error2);
437 }
438
439
440 /**
441 * Tests loading multiple modules with deps by requesting a Deferred object.
442 */
443 function testLoadMultipleWithDeps() {
444 var mm = getModuleManager({'a': [], 'b': ['c'], 'c': []});
445 mm.setBatchModeEnabled(true);
446 mm.setLoader(createSuccessfulBatchLoader(mm));
447
448 var calledBack = false;
449 var error = null;
450 var calledBack2 = false;
451 var error2 = null;
452
453 var dMap = mm.loadMultiple(['a', 'b']);
454 dMap['a'].addCallback(function(ctx) { calledBack = true; });
455 dMap['a'].addErrback(function(err) { error = err; });
456 dMap['b'].addCallback(function(ctx) { calledBack2 = true; });
457 dMap['b'].addErrback(function(err) { error2 = err; });
458
459 assertFalse(calledBack);
460 assertFalse(calledBack2);
461
462 clock.tick(5);
463 assertTrue(calledBack);
464 assertFalse(calledBack2);
465 assertTrue('module "a" should be loaded', mm.isModuleLoaded('a'));
466 assertFalse('module "b" should not be loaded', mm.isModuleLoaded('b'));
467 assertFalse('module "c" should not be loaded', mm.isModuleLoaded('c'));
468
469 clock.tick(2);
470
471 assertFalse(calledBack2);
472 assertTrue('module "a" should be loaded', mm.isModuleLoaded('a'));
473 assertFalse('module "b" should not be loaded', mm.isModuleLoaded('b'));
474 assertTrue('module "c" should be loaded', mm.isModuleLoaded('c'));
475
476 clock.tick(2);
477
478 assertTrue(calledBack2);
479 assertTrue('module "a" should be loaded', mm.isModuleLoaded('a'));
480 assertTrue('module "b" should be loaded', mm.isModuleLoaded('b'));
481 assertTrue('module "c" should be loaded', mm.isModuleLoaded('c'));
482 assertNull(error);
483 assertNull(error2);
484 }
485
486
487 /**
488 * Tests loading multiple modules by requesting a Deferred object when
489 * a server error occurs.
490 */
491 function testLoadMultipleWithErrors() {
492 var mm = getModuleManager({'a': [], 'b': [], 'c': []});
493 mm.setBatchModeEnabled(true);
494 mm.setLoader(createUnsuccessfulLoader(mm, 500));
495
496 var calledBack = false;
497 var error = null;
498 var calledBack2 = false;
499 var error2 = null;
500 var calledBack3 = false;
501 var error3 = null;
502
503 var dMap = mm.loadMultiple(['a', 'b', 'c']);
504 dMap['a'].addCallback(function(ctx) { calledBack = true; });
505 dMap['a'].addErrback(function(err) { error = err; });
506 dMap['b'].addCallback(function(ctx) { calledBack2 = true; });
507 dMap['b'].addErrback(function(err) { error2 = err; });
508 dMap['c'].addCallback(function(ctx) { calledBack3 = true; });
509 dMap['c'].addErrback(function(err) { error3 = err; });
510
511 assertFalse(calledBack);
512 assertFalse(calledBack2);
513 assertFalse(calledBack3);
514
515 clock.tick(4);
516
517 // A module request is now underway using the unsuccessful loader.
518 // We substitute a successful loader for future module load requests.
519 mm.setLoader(createSuccessfulBatchLoader(mm));
520
521 clock.tick(1);
522
523 assertFalse(calledBack);
524 assertFalse(calledBack2);
525 assertFalse(calledBack3);
526 assertFalse('module "a" should not be loaded', mm.isModuleLoaded('a'));
527 assertFalse('module "b" should not be loaded', mm.isModuleLoaded('b'));
528 assertFalse('module "c" should not be loaded', mm.isModuleLoaded('c'));
529
530 // Retry should happen after a backoff
531 clock.tick(5 + mm.getBackOff_());
532
533 assertTrue(calledBack);
534 assertFalse(calledBack2);
535 assertFalse(calledBack3);
536 assertTrue('module "a" should be loaded', mm.isModuleLoaded('a'));
537 assertFalse('module "b" should not be loaded', mm.isModuleLoaded('b'));
538 assertFalse('module "c" should not be loaded', mm.isModuleLoaded('c'));
539
540 clock.tick(2);
541 assertTrue(calledBack2);
542 assertFalse(calledBack3);
543 assertTrue('module "b" should be loaded', mm.isModuleLoaded('b'));
544 assertFalse('module "c" should not be loaded', mm.isModuleLoaded('c'));
545
546 clock.tick(2);
547 assertTrue(calledBack3);
548 assertTrue('module "c" should be loaded', mm.isModuleLoaded('c'));
549
550 assertNull(error);
551 assertNull(error2);
552 assertNull(error3);
553 }
554
555
556 /**
557 * Tests loading multiple modules by requesting a Deferred object when
558 * consecutive server error occur and the loader falls back to serial
559 * loads.
560 */
561 function testLoadMultipleWithErrorsFallbackOnSerial() {
562 var mm = getModuleManager({'a': [], 'b': [], 'c': []});
563 mm.setBatchModeEnabled(true);
564 mm.setLoader(createUnsuccessfulLoader(mm, 500));
565
566 var calledBack = false;
567 var error = null;
568 var calledBack2 = false;
569 var error2 = null;
570 var calledBack3 = false;
571 var error3 = null;
572
573 var dMap = mm.loadMultiple(['a', 'b', 'c']);
574 dMap['a'].addCallback(function(ctx) { calledBack = true; });
575 dMap['a'].addErrback(function(err) { error = err; });
576 dMap['b'].addCallback(function(ctx) { calledBack2 = true; });
577 dMap['b'].addErrback(function(err) { error2 = err; });
578 dMap['c'].addCallback(function(ctx) { calledBack3 = true; });
579 dMap['c'].addErrback(function(err) { error3 = err; });
580
581 assertFalse(calledBack);
582 assertFalse(calledBack2);
583 assertFalse(calledBack3);
584
585 clock.tick(5);
586
587 assertFalse(calledBack);
588 assertFalse(calledBack2);
589 assertFalse(calledBack3);
590 assertFalse('module "a" should not be loaded', mm.isModuleLoaded('a'));
591 assertFalse('module "b" should not be loaded', mm.isModuleLoaded('b'));
592 assertFalse('module "c" should not be loaded', mm.isModuleLoaded('c'));
593
594 // Retry should happen and fail after a backoff
595 clock.tick(5 + mm.getBackOff_());
596 assertFalse(calledBack);
597 assertFalse(calledBack2);
598 assertFalse(calledBack3);
599 assertFalse('module "a" should not be loaded', mm.isModuleLoaded('a'));
600 assertFalse('module "b" should not be loaded', mm.isModuleLoaded('b'));
601 assertFalse('module "c" should not be loaded', mm.isModuleLoaded('c'));
602
603 // A second retry should happen after a backoff
604 clock.tick(4 + mm.getBackOff_());
605 // The second retry is now underway using the unsuccessful loader.
606 // We substitute a successful loader for future module load requests.
607 mm.setLoader(createSuccessfulBatchLoader(mm));
608
609 clock.tick(1);
610
611 // A second retry should fail now
612 assertFalse(calledBack);
613 assertFalse(calledBack2);
614 assertFalse(calledBack3);
615 assertFalse('module "a" should not be loaded', mm.isModuleLoaded('a'));
616 assertFalse('module "b" should not be loaded', mm.isModuleLoaded('b'));
617 assertFalse('module "c" should not be loaded', mm.isModuleLoaded('c'));
618
619 // Each module should be loaded individually now, each taking 5 ticks
620
621 clock.tick(5);
622 assertTrue(calledBack);
623 assertFalse(calledBack2);
624 assertFalse(calledBack3);
625 assertTrue('module "a" should be loaded', mm.isModuleLoaded('a'));
626 assertFalse('module "b" should not be loaded', mm.isModuleLoaded('b'));
627 assertFalse('module "c" should not be loaded', mm.isModuleLoaded('c'));
628
629 clock.tick(5);
630 assertTrue(calledBack2);
631 assertFalse(calledBack3);
632 assertTrue('module "b" should be loaded', mm.isModuleLoaded('b'));
633 assertFalse('module "c" should not be loaded', mm.isModuleLoaded('c'));
634
635 clock.tick(5);
636 assertTrue(calledBack3);
637 assertTrue('module "c" should be loaded', mm.isModuleLoaded('c'));
638
639 assertNull(error);
640 assertNull(error2);
641 assertNull(error3);
642 }
643
644
645 /**
646 * Tests loading a module by user action by requesting a Deferred object.
647 */
648 function testLoadForUser() {
649 var mm = getModuleManager({'a': [], 'b': [], 'c': []});
650 mm.setLoader(createSuccessfulNonBatchLoader(mm));
651
652 var calledBack = false;
653 var error = null;
654
655 var d = mm.load('a', true);
656 d.addCallback(function(ctx) { calledBack = true; });
657 d.addErrback(function(err) { error = err; });
658
659 assertFalse(calledBack);
660 assertNull(error);
661 assertTrue(mm.isUserActive());
662
663 clock.tick(5);
664
665 assertTrue(calledBack);
666 assertNull(error);
667 }
668
669
670 /**
671 * Tests that preloading a module calls back the deferred object.
672 */
673 function testPreloadDeferredWhenNotLoaded() {
674 var mm = getModuleManager({'a': []});
675 mm.setLoader(createSuccessfulNonBatchLoader(mm));
676
677 var calledBack = false;
678
679 var d = mm.preloadModule('a');
680 d.addCallback(function(ctx) { calledBack = true; });
681
682 // First load should take five ticks.
683 assertFalse('module "a" should not be loaded yet', calledBack);
684 clock.tick(5);
685 assertTrue('module "a" should be loaded', calledBack);
686 }
687
688
689 /**
690 * Tests preloading an already loaded module.
691 */
692 function testPreloadDeferredWhenLoaded() {
693 var mm = getModuleManager({'a': []});
694 mm.setLoader(createSuccessfulNonBatchLoader(mm));
695
696 var calledBack = false;
697
698 mm.preloadModule('a');
699 clock.tick(5);
700
701 var d = mm.preloadModule('a');
702 d.addCallback(function(ctx) { calledBack = true; });
703
704 // Module is already loaded, should be called back after the setTimeout
705 // in preloadModule.
706 assertFalse('deferred for module "a" should not be called yet', calledBack);
707 clock.tick(1);
708 assertTrue('module "a" should be loaded', calledBack);
709 }
710
711
712 /**
713 * Tests preloading a module that is currently loading.
714 */
715 function testPreloadDeferredWhenLoading() {
716 var mm = getModuleManager({'a': []});
717 mm.setLoader(createSuccessfulNonBatchLoader(mm));
718
719 mm.preloadModule('a');
720 clock.tick(1);
721
722 // 'b' is in the middle of loading, should get called back when it's done.
723 var calledBack = false;
724 var d = mm.preloadModule('a');
725 d.addCallback(function(ctx) { calledBack = true; });
726
727 assertFalse('module "a" should not be loaded yet', calledBack);
728 clock.tick(4);
729 assertTrue('module "a" should be loaded', calledBack);
730 }
731
732
733 /**
734 * Tests that load doesn't trigger another load if a module is already
735 * preloading.
736 */
737 function testLoadWhenPreloading() {
738 var mm = getModuleManager({'a': [], 'b': [], 'c': []});
739 mm.setLoader(createSuccessfulNonBatchLoader(mm));
740
741 var origSetLoaded = mm.setLoaded;
742 var calls = [0, 0, 0];
743 mm.beforeLoadModuleCode = function(id) { calls[0]++; };
744 mm.setLoaded = function(id) {
745 calls[1]++;
746 origSetLoaded.call(mm, id);
747 };
748 mm.afterLoadModuleCode = function(id) { calls[2]++; };
749
750 var calledBack = false;
751 var error = null;
752
753 mm.preloadModule('c', 2);
754 assertFalse('module "c" should not be loading yet', mm.isModuleLoading('c'));
755 clock.tick(2);
756 assertTrue('module "c" should now be loading', mm.isModuleLoading('c'));
757
758 var d = mm.load('c');
759 d.addCallback(function(ctx) { calledBack = true; });
760 d.addErrback(function(err) { error = err; });
761
762 assertTrue('module "c" should still be loading', mm.isModuleLoading('c'));
763 clock.tick(5);
764 assertFalse('module "c" should be done loading', mm.isModuleLoading('c'));
765 assertEquals('beforeLoad should only be called once for "c"', 1, calls[0]);
766 assertEquals('setLoaded should only be called once for "c"', 1, calls[1]);
767 assertEquals('afterLoad should only be called once for "c"', 1, calls[2]);
768
769 assertTrue(calledBack);
770 assertNull(error);
771 }
772
773
774 /**
775 * Tests that load doesn't trigger another load if a module is already
776 * preloading.
777 */
778 function testLoadMultipleWhenPreloading() {
779 var mm = getModuleManager({'a': [], 'b': ['d'], 'c': [], 'd': []});
780 mm.setLoader(createSuccessfulBatchLoader(mm));
781 mm.setBatchModeEnabled(true);
782
783 var origSetLoaded = mm.setLoaded;
784 var calls = {'a': [0, 0, 0], 'b': [0, 0, 0], 'c': [0, 0, 0], 'd': [0, 0, 0]};
785 mm.beforeLoadModuleCode = function(id) { calls[id][0]++; };
786 mm.setLoaded = function(id) {
787 calls[id][1]++;
788 origSetLoaded.call(mm, id);
789 };
790 mm.afterLoadModuleCode = function(id) { calls[id][2]++; };
791
792 var calledBack = false;
793 var error = null;
794 var calledBack2 = false;
795 var error2 = null;
796 var calledBack3 = false;
797 var error3 = null;
798
799 mm.preloadModule('c', 2);
800 mm.preloadModule('d', 3);
801 assertFalse('module "c" should not be loading yet', mm.isModuleLoading('c'));
802 assertFalse('module "d" should not be loading yet', mm.isModuleLoading('d'));
803 clock.tick(2);
804 assertTrue('module "c" should now be loading', mm.isModuleLoading('c'));
805 clock.tick(1);
806 assertTrue('module "d" should now be loading', mm.isModuleLoading('d'));
807
808 var dMap = mm.loadMultiple(['a', 'b', 'c']);
809 dMap['a'].addCallback(function(ctx) { calledBack = true; });
810 dMap['a'].addErrback(function(err) { error = err; });
811 dMap['b'].addCallback(function(ctx) { calledBack2 = true; });
812 dMap['b'].addErrback(function(err) { error2 = err; });
813 dMap['c'].addCallback(function(ctx) { calledBack3 = true; });
814 dMap['c'].addErrback(function(err) { error3 = err; });
815
816 assertTrue('module "a" should be loading', mm.isModuleLoading('a'));
817 assertTrue('module "b" should be loading', mm.isModuleLoading('b'));
818 assertTrue('module "c" should still be loading', mm.isModuleLoading('c'));
819 clock.tick(4);
820 assertTrue(calledBack3);
821
822 assertFalse('module "c" should be done loading', mm.isModuleLoading('c'));
823 assertTrue('module "d" should still be loading', mm.isModuleLoading('d'));
824 clock.tick(5);
825 assertFalse('module "d" should be done loading', mm.isModuleLoading('d'));
826
827 assertFalse(calledBack);
828 assertFalse(calledBack2);
829 assertTrue('module "a" should still be loading', mm.isModuleLoading('a'));
830 assertTrue('module "b" should still be loading', mm.isModuleLoading('b'));
831 clock.tick(7);
832
833 assertTrue(calledBack);
834 assertTrue(calledBack2);
835 assertFalse('module "a" should be done loading', mm.isModuleLoading('a'));
836 assertFalse('module "b" should be done loading', mm.isModuleLoading('b'));
837
838 assertEquals(
839 'beforeLoad should only be called once for "a"', 1, calls['a'][0]);
840 assertEquals(
841 'setLoaded should only be called once for "a"', 1, calls['a'][1]);
842 assertEquals(
843 'afterLoad should only be called once for "a"', 1, calls['a'][2]);
844 assertEquals(
845 'beforeLoad should only be called once for "b"', 1, calls['b'][0]);
846 assertEquals(
847 'setLoaded should only be called once for "b"', 1, calls['b'][1]);
848 assertEquals(
849 'afterLoad should only be called once for "b"', 1, calls['b'][2]);
850 assertEquals(
851 'beforeLoad should only be called once for "c"', 1, calls['c'][0]);
852 assertEquals(
853 'setLoaded should only be called once for "c"', 1, calls['c'][1]);
854 assertEquals(
855 'afterLoad should only be called once for "c"', 1, calls['c'][2]);
856 assertEquals(
857 'beforeLoad should only be called once for "d"', 1, calls['d'][0]);
858 assertEquals(
859 'setLoaded should only be called once for "d"', 1, calls['d'][1]);
860 assertEquals(
861 'afterLoad should only be called once for "d"', 1, calls['d'][2]);
862
863 assertNull(error);
864 assertNull(error2);
865 assertNull(error3);
866 }
867
868
869 /**
870 * Tests that the deferred is still called when loadMultiple loads modules
871 * that are already preloading.
872 */
873 function testLoadMultipleWhenPreloadingSameModules() {
874 var mm = getModuleManager({'a': [], 'b': ['d'], 'c': [], 'd': []});
875 mm.setLoader(createSuccessfulBatchLoader(mm));
876 mm.setBatchModeEnabled(true);
877
878 var origSetLoaded = mm.setLoaded;
879 var calls = {'c': [0, 0, 0], 'd': [0, 0, 0]};
880 mm.beforeLoadModuleCode = function(id) { calls[id][0]++; };
881 mm.setLoaded = function(id) {
882 calls[id][1]++;
883 origSetLoaded.call(mm, id);
884 };
885 mm.afterLoadModuleCode = function(id) { calls[id][2]++; };
886
887 var calledBack = false;
888 var error = null;
889 var calledBack2 = false;
890 var error2 = null;
891
892 mm.preloadModule('c', 2);
893 mm.preloadModule('d', 3);
894 assertFalse('module "c" should not be loading yet', mm.isModuleLoading('c'));
895 assertFalse('module "d" should not be loading yet', mm.isModuleLoading('d'));
896 clock.tick(2);
897 assertTrue('module "c" should now be loading', mm.isModuleLoading('c'));
898 clock.tick(1);
899 assertTrue('module "d" should now be loading', mm.isModuleLoading('d'));
900
901 var dMap = mm.loadMultiple(['c', 'd']);
902 dMap['c'].addCallback(function(ctx) { calledBack = true; });
903 dMap['c'].addErrback(function(err) { error = err; });
904 dMap['d'].addCallback(function(ctx) { calledBack2 = true; });
905 dMap['d'].addErrback(function(err) { error2 = err; });
906
907 assertTrue('module "c" should still be loading', mm.isModuleLoading('c'));
908 clock.tick(4);
909 assertFalse('module "c" should be done loading', mm.isModuleLoading('c'));
910 assertTrue('module "d" should still be loading', mm.isModuleLoading('d'));
911 clock.tick(5);
912 assertFalse('module "d" should be done loading', mm.isModuleLoading('d'));
913
914 assertTrue(calledBack);
915 assertTrue(calledBack2);
916
917 assertEquals(
918 'beforeLoad should only be called once for "c"', 1, calls['c'][0]);
919 assertEquals(
920 'setLoaded should only be called once for "c"', 1, calls['c'][1]);
921 assertEquals(
922 'afterLoad should only be called once for "c"', 1, calls['c'][2]);
923 assertEquals(
924 'beforeLoad should only be called once for "d"', 1, calls['d'][0]);
925 assertEquals(
926 'setLoaded should only be called once for "d"', 1, calls['d'][1]);
927 assertEquals(
928 'afterLoad should only be called once for "d"', 1, calls['d'][2]);
929
930 assertNull(error);
931 assertNull(error2);
932 }
933
934
935 /**
936 * Tests loading a module via load when the module is already
937 * loaded. The deferred's callback should be called immediately.
938 */
939 function testLoadWhenLoaded() {
940 var mm = getModuleManager({'a': [], 'b': [], 'c': []});
941 mm.setLoader(createSuccessfulNonBatchLoader(mm));
942
943 var calledBack = false;
944 var error = null;
945
946 mm.preloadModule('b', 2);
947 clock.tick(10);
948
949 assertFalse('module "b" should be done loading', mm.isModuleLoading('b'));
950
951 var d = mm.load('b');
952 d.addCallback(function(ctx) { calledBack = true; });
953 d.addErrback(function(err) { error = err; });
954
955 assertTrue(calledBack);
956 assertNull(error);
957 }
958
959
960 /**
961 * Tests that the deferred's errbacks are called if the module fails to load.
962 */
963 function testLoadWithFailingModule() {
964 var mm = getModuleManager({'a': [], 'b': [], 'c': []});
965 mm.setLoader(createUnsuccessfulLoader(mm, 401));
966 mm.registerCallback(
967 goog.module.ModuleManager.CallbackType.ERROR,
968 function(callbackType, id, cause) {
969 assertEquals(
970 'Failure cause was not as expected',
971 goog.module.ModuleManager.FailureType.UNAUTHORIZED, cause);
972 firedLoadFailed = true;
973 });
974 var calledBack = false;
975 var error = null;
976
977 var d = mm.load('a');
978 d.addCallback(function(ctx) { calledBack = true; });
979 d.addErrback(function(err) { error = err; });
980
981 assertFalse(calledBack);
982 assertNull(error);
983
984 clock.tick(500);
985
986 assertFalse(calledBack);
987
988 // NOTE: Deferred always calls errbacks with an Error object. For now the
989 // module manager just passes the FailureType which gets set as the Error
990 // object's message.
991 assertEquals(
992 'Failure cause was not as expected',
993 goog.module.ModuleManager.FailureType.UNAUTHORIZED,
994 Number(error.message));
995 }
996
997
998 /**
999 * Tests that the deferred's errbacks are called if a module fails to load.
1000 */
1001 function testLoadMultipleWithFailingModule() {
1002 var mm = getModuleManager({'a': [], 'b': [], 'c': []});
1003 mm.setLoader(createUnsuccessfulLoader(mm, 401));
1004 mm.setBatchModeEnabled(true);
1005 mm.registerCallback(
1006 goog.module.ModuleManager.CallbackType.ERROR,
1007 function(callbackType, id, cause) {
1008 assertEquals(
1009 'Failure cause was not as expected',
1010 goog.module.ModuleManager.FailureType.UNAUTHORIZED, cause);
1011 });
1012 var calledBack11 = false;
1013 var error11 = null;
1014 var calledBack12 = false;
1015 var error12 = null;
1016 var calledBack21 = false;
1017 var error21 = null;
1018 var calledBack22 = false;
1019 var error22 = null;
1020
1021 var dMap = mm.loadMultiple(['a', 'b']);
1022 dMap['a'].addCallback(function(ctx) { calledBack11 = true; });
1023 dMap['a'].addErrback(function(err) { error11 = err; });
1024 dMap['b'].addCallback(function(ctx) { calledBack12 = true; });
1025 dMap['b'].addErrback(function(err) { error12 = err; });
1026
1027 var dMap2 = mm.loadMultiple(['b', 'c']);
1028 dMap2['b'].addCallback(function(ctx) { calledBack21 = true; });
1029 dMap2['b'].addErrback(function(err) { error21 = err; });
1030 dMap2['c'].addCallback(function(ctx) { calledBack22 = true; });
1031 dMap2['c'].addErrback(function(err) { error22 = err; });
1032
1033 assertFalse(calledBack11);
1034 assertFalse(calledBack12);
1035 assertFalse(calledBack21);
1036 assertFalse(calledBack22);
1037 assertNull(error11);
1038 assertNull(error12);
1039 assertNull(error21);
1040 assertNull(error22);
1041
1042 clock.tick(5);
1043
1044 assertFalse(calledBack11);
1045 assertFalse(calledBack12);
1046 assertFalse(calledBack21);
1047 assertFalse(calledBack22);
1048
1049 // NOTE: Deferred always calls errbacks with an Error object. For now the
1050 // module manager just passes the FailureType which gets set as the Error
1051 // object's message.
1052 assertEquals(
1053 'Failure cause was not as expected',
1054 goog.module.ModuleManager.FailureType.UNAUTHORIZED,
1055 Number(error11.message));
1056 assertEquals(
1057 'Failure cause was not as expected',
1058 goog.module.ModuleManager.FailureType.UNAUTHORIZED,
1059 Number(error12.message));
1060
1061 // The first deferred of the second load should be called since it asks for
1062 // one of the failed modules.
1063 assertEquals(
1064 'Failure cause was not as expected',
1065 goog.module.ModuleManager.FailureType.UNAUTHORIZED,
1066 Number(error21.message));
1067
1068 // The last deferred should be dropped so it is neither called back nor an
1069 // error.
1070 assertFalse(calledBack22);
1071 assertNull(error22);
1072 }
1073
1074
1075 /**
1076 * Tests that the right dependencies are cancelled on a loadMultiple failure.
1077 */
1078 function testLoadMultipleWithFailingModuleDependencies() {
1079 var mm =
1080 getModuleManager({'a': [], 'b': [], 'c': ['b'], 'd': ['c'], 'e': []});
1081 mm.setLoader(createUnsuccessfulLoader(mm, 401));
1082 mm.setBatchModeEnabled(true);
1083 var cancelledIds = [];
1084
1085 mm.registerCallback(
1086 goog.module.ModuleManager.CallbackType.ERROR,
1087 function(callbackType, id, cause) {
1088 assertEquals(
1089 'Failure cause was not as expected',
1090 goog.module.ModuleManager.FailureType.UNAUTHORIZED, cause);
1091 cancelledIds.push(id);
1092 });
1093 var calledBack11 = false;
1094 var error11 = null;
1095 var calledBack12 = false;
1096 var error12 = null;
1097 var calledBack21 = false;
1098 var error21 = null;
1099 var calledBack22 = false;
1100 var error22 = null;
1101 var calledBack23 = false;
1102 var error23 = null;
1103
1104 var dMap = mm.loadMultiple(['a', 'b']);
1105 dMap['a'].addCallback(function(ctx) { calledBack11 = true; });
1106 dMap['a'].addErrback(function(err) { error11 = err; });
1107 dMap['b'].addCallback(function(ctx) { calledBack12 = true; });
1108 dMap['b'].addErrback(function(err) { error12 = err; });
1109
1110 var dMap2 = mm.loadMultiple(['c', 'd', 'e']);
1111 dMap2['c'].addCallback(function(ctx) { calledBack21 = true; });
1112 dMap2['c'].addErrback(function(err) { error21 = err; });
1113 dMap2['d'].addCallback(function(ctx) { calledBack22 = true; });
1114 dMap2['d'].addErrback(function(err) { error22 = err; });
1115 dMap2['e'].addCallback(function(ctx) { calledBack23 = true; });
1116 dMap2['e'].addErrback(function(err) { error23 = err; });
1117
1118 assertFalse(calledBack11);
1119 assertFalse(calledBack12);
1120 assertFalse(calledBack21);
1121 assertFalse(calledBack22);
1122 assertFalse(calledBack23);
1123 assertNull(error11);
1124 assertNull(error12);
1125 assertNull(error21);
1126 assertNull(error22);
1127 assertNull(error23);
1128
1129 clock.tick(5);
1130
1131 assertFalse(calledBack11);
1132 assertFalse(calledBack12);
1133 assertFalse(calledBack21);
1134 assertFalse(calledBack22);
1135 assertFalse(calledBack23);
1136
1137 // NOTE: Deferred always calls errbacks with an Error object. For now the
1138 // module manager just passes the FailureType which gets set as the Error
1139 // object's message.
1140 assertEquals(
1141 'Failure cause was not as expected',
1142 goog.module.ModuleManager.FailureType.UNAUTHORIZED,
1143 Number(error11.message));
1144 assertEquals(
1145 'Failure cause was not as expected',
1146 goog.module.ModuleManager.FailureType.UNAUTHORIZED,
1147 Number(error12.message));
1148
1149 // Check that among the failed modules, 'c' and 'd' are also cancelled
1150 // due to dependencies.
1151 assertTrue(goog.array.equals(['a', 'b', 'c', 'd'], cancelledIds.sort()));
1152 }
1153
1154
1155 /**
1156 * Tests that when loading multiple modules, the input array is not modified
1157 * when it has duplicates.
1158 */
1159 function testLoadMultipleWithDuplicates() {
1160 var mm = getModuleManager({'a': [], 'b': []});
1161 mm.setBatchModeEnabled(true);
1162 mm.setLoader(createSuccessfulBatchLoader(mm));
1163
1164 var listWithDuplicates = ['a', 'a', 'b'];
1165 mm.loadMultiple(listWithDuplicates);
1166 assertArrayEquals(
1167 'loadMultiple should not modify its input', ['a', 'a', 'b'],
1168 listWithDuplicates);
1169 }
1170
1171
1172 /**
1173 * Test loading dependencies transitively.
1174 */
1175 function testLoadingDepsInNonBatchMode1() {
1176 var mm =
1177 getModuleManager({'i': [], 'j': [], 'k': ['j'], 'l': ['i', 'j', 'k']});
1178 mm.setLoader(createSuccessfulNonBatchLoader(mm));
1179
1180 mm.preloadModule('j');
1181 clock.tick(5);
1182 assertTrue('module "j" should be loaded', mm.isModuleLoaded('j'));
1183 assertFalse('module "i" should not be loaded (1)', mm.isModuleLoaded('i'));
1184 assertFalse('module "k" should not be loaded (1)', mm.isModuleLoaded('k'));
1185 assertFalse('module "l" should not be loaded (1)', mm.isModuleLoaded('l'));
1186
1187 // When loading a module in non-batch mode, its dependencies should be
1188 // requested independently, and in dependency order.
1189 mm.preloadModule('l');
1190 clock.tick(5);
1191 assertTrue('module "i" should be loaded', mm.isModuleLoaded('i'));
1192 assertFalse('module "k" should not be loaded (2)', mm.isModuleLoaded('k'));
1193 assertFalse('module "l" should not be loaded (2)', mm.isModuleLoaded('l'));
1194 clock.tick(5);
1195 assertTrue('module "k" should be loaded', mm.isModuleLoaded('k'));
1196 assertFalse('module "l" should not be loaded (3)', mm.isModuleLoaded('l'));
1197 clock.tick(5);
1198 assertTrue('module "l" should be loaded', mm.isModuleLoaded('l'));
1199 }
1200
1201
1202 /**
1203 * Test loading dependencies transitively and in dependency order.
1204 */
1205 function testLoadingDepsInNonBatchMode2() {
1206 var mm = getModuleManager({
1207 'h': [],
1208 'i': ['h'],
1209 'j': ['i'],
1210 'k': ['j'],
1211 'l': ['i', 'j', 'k'],
1212 'm': ['l']
1213 });
1214 mm.setLoader(createSuccessfulNonBatchLoader(mm));
1215
1216 // When loading a module in non-batch mode, its dependencies should be
1217 // requested independently, and in dependency order. The order in this
1218 // case should be h,i,j,k,l,m.
1219 mm.preloadModule('m');
1220 clock.tick(5);
1221 assertTrue('module "h" should be loaded', mm.isModuleLoaded('h'));
1222 assertFalse('module "i" should not be loaded (1)', mm.isModuleLoaded('i'));
1223 assertFalse('module "j" should not be loaded (1)', mm.isModuleLoaded('j'));
1224 assertFalse('module "k" should not be loaded (1)', mm.isModuleLoaded('k'));
1225 assertFalse('module "l" should not be loaded (1)', mm.isModuleLoaded('l'));
1226 assertFalse('module "m" should not be loaded (1)', mm.isModuleLoaded('m'));
1227
1228 clock.tick(5);
1229 assertTrue('module "i" should be loaded', mm.isModuleLoaded('i'));
1230 assertFalse('module "j" should not be loaded (2)', mm.isModuleLoaded('j'));
1231 assertFalse('module "k" should not be loaded (2)', mm.isModuleLoaded('k'));
1232 assertFalse('module "l" should not be loaded (2)', mm.isModuleLoaded('l'));
1233 assertFalse('module "m" should not be loaded (2)', mm.isModuleLoaded('m'));
1234
1235 clock.tick(5);
1236 assertTrue('module "j" should be loaded', mm.isModuleLoaded('j'));
1237 assertFalse('module "k" should not be loaded (3)', mm.isModuleLoaded('k'));
1238 assertFalse('module "l" should not be loaded (3)', mm.isModuleLoaded('l'));
1239 assertFalse('module "m" should not be loaded (3)', mm.isModuleLoaded('m'));
1240
1241 clock.tick(5);
1242 assertTrue('module "k" should be loaded', mm.isModuleLoaded('k'));
1243 assertFalse('module "l" should not be loaded (4)', mm.isModuleLoaded('l'));
1244 assertFalse('module "m" should not be loaded (4)', mm.isModuleLoaded('m'));
1245
1246 clock.tick(5);
1247 assertTrue('module "l" should be loaded', mm.isModuleLoaded('l'));
1248 assertFalse('module "m" should not be loaded (5)', mm.isModuleLoaded('m'));
1249
1250 clock.tick(5);
1251 assertTrue('module "m" should be loaded', mm.isModuleLoaded('m'));
1252 }
1253
1254 function testLoadingDepsInBatchMode() {
1255 var mm =
1256 getModuleManager({'e': [], 'f': [], 'g': ['f'], 'h': ['e', 'f', 'g']});
1257 mm.setLoader(createSuccessfulBatchLoader(mm));
1258 mm.setBatchModeEnabled(true);
1259
1260 mm.preloadModule('f');
1261 clock.tick(5);
1262 assertTrue('module "f" should be loaded', mm.isModuleLoaded('f'));
1263 assertFalse('module "e" should not be loaded (1)', mm.isModuleLoaded('e'));
1264 assertFalse('module "g" should not be loaded (1)', mm.isModuleLoaded('g'));
1265 assertFalse('module "h" should not be loaded (1)', mm.isModuleLoaded('h'));
1266
1267 // When loading a module in batch mode, its not-yet-loaded dependencies
1268 // should be requested at the same time, and in dependency order.
1269 mm.preloadModule('h');
1270 clock.tick(5);
1271 assertTrue('module "e" should be loaded', mm.isModuleLoaded('e'));
1272 assertFalse('module "g" should not be loaded (2)', mm.isModuleLoaded('g'));
1273 assertFalse('module "h" should not be loaded (2)', mm.isModuleLoaded('h'));
1274 clock.tick(2);
1275 assertTrue('module "g" should be loaded', mm.isModuleLoaded('g'));
1276 assertFalse('module "h" should not be loaded (3)', mm.isModuleLoaded('h'));
1277 clock.tick(2);
1278 assertTrue('module "h" should be loaded', mm.isModuleLoaded('h'));
1279 }
1280
1281
1282 /**
1283 * Test unauthorized errors while loading modules.
1284 */
1285 function testUnauthorizedLoading() {
1286 var mm = getModuleManager({'m': [], 'n': [], 'o': ['n']});
1287 mm.setLoader(createUnsuccessfulLoader(mm, 401));
1288
1289 // Callback checks for an unauthorized error
1290 var firedLoadFailed = false;
1291 mm.registerCallback(
1292 goog.module.ModuleManager.CallbackType.ERROR,
1293 function(callbackType, id, cause) {
1294 assertEquals(
1295 'Failure cause was not as expected',
1296 goog.module.ModuleManager.FailureType.UNAUTHORIZED, cause);
1297 firedLoadFailed = true;
1298 });
1299 mm.execOnLoad('o', function() {});
1300 assertTrue('module "o" should be loading', mm.isModuleLoading('o'));
1301 assertTrue('module "n" should be loading', mm.isModuleLoading('n'));
1302 clock.tick(5);
1303 assertTrue(
1304 'should have called unauthorized module callback', firedLoadFailed);
1305 assertFalse('module "o" should not be loaded', mm.isModuleLoaded('o'));
1306 assertFalse('module "o" should not be loading', mm.isModuleLoading('o'));
1307 assertFalse('module "n" should not be loaded', mm.isModuleLoaded('n'));
1308 assertFalse('module "n" should not be loading', mm.isModuleLoading('n'));
1309 }
1310
1311
1312 /**
1313 * Test error loading modules which are retried.
1314 */
1315 function testErrorLoadingModule() {
1316 var mm = getModuleManager({'p': ['q'], 'q': [], 'r': ['q', 'p']});
1317 mm.setLoader(createUnsuccessfulLoader(mm, 500));
1318
1319 mm.preloadModule('r');
1320 clock.tick(4);
1321
1322 // A module request is now underway using the unsuccessful loader.
1323 // We substitute a successful loader for future module load requests.
1324 mm.setLoader(createSuccessfulNonBatchLoader(mm));
1325 clock.tick(1);
1326 assertFalse('module "q" should not be loaded (1)', mm.isModuleLoaded('q'));
1327 assertFalse('module "p" should not be loaded (1)', mm.isModuleLoaded('p'));
1328 assertFalse('module "r" should not be loaded (1)', mm.isModuleLoaded('r'));
1329
1330 // Failed loads are automatically retried after a backOff.
1331 clock.tick(5 + mm.getBackOff_());
1332 assertTrue('module "q" should be loaded', mm.isModuleLoaded('q'));
1333 assertFalse('module "p" should not be loaded (2)', mm.isModuleLoaded('p'));
1334 assertFalse('module "r" should not be loaded (2)', mm.isModuleLoaded('r'));
1335
1336 // A successful load decrements the backOff.
1337 clock.tick(5);
1338 assertTrue('module "p" should be loaded', mm.isModuleLoaded('p'));
1339 assertFalse('module "r" should not be loaded (3)', mm.isModuleLoaded('r'));
1340 clock.tick(5);
1341 assertTrue('module "r" should be loaded', mm.isModuleLoaded('r'));
1342 }
1343
1344
1345 /**
1346 * Tests error loading modules which are retried.
1347 */
1348 function testErrorLoadingModule_batchMode() {
1349 var mm = getModuleManager({'p': ['q'], 'q': [], 'r': ['q', 'p']});
1350 mm.setLoader(createUnsuccessfulBatchLoader(mm, 500));
1351 mm.setBatchModeEnabled(true);
1352
1353 mm.preloadModule('r');
1354 clock.tick(4);
1355
1356 // A module request is now underway using the unsuccessful loader.
1357 // We substitute a successful loader for future module load requests.
1358 mm.setLoader(createSuccessfulBatchLoader(mm));
1359 clock.tick(1);
1360 assertFalse('module "q" should not be loaded (1)', mm.isModuleLoaded('q'));
1361 assertFalse('module "p" should not be loaded (1)', mm.isModuleLoaded('p'));
1362 assertFalse('module "r" should not be loaded (1)', mm.isModuleLoaded('r'));
1363
1364 // Failed loads are automatically retried after a backOff.
1365 clock.tick(5 + mm.getBackOff_());
1366 assertTrue('module "q" should be loaded', mm.isModuleLoaded('q'));
1367 clock.tick(2);
1368 assertTrue('module "p" should not be loaded (2)', mm.isModuleLoaded('p'));
1369 clock.tick(2);
1370 assertTrue('module "r" should not be loaded (2)', mm.isModuleLoaded('r'));
1371 }
1372
1373
1374 /**
1375 * Test consecutive errors in loading modules.
1376 */
1377 function testConsecutiveErrors() {
1378 var mm = getModuleManager({'s': []});
1379 mm.setLoader(createUnsuccessfulLoader(mm, 500));
1380
1381 // Register an error callback for consecutive failures.
1382 var firedLoadFailed = false;
1383 mm.registerCallback(
1384 goog.module.ModuleManager.CallbackType.ERROR,
1385 function(callbackType, id, cause) {
1386 assertEquals(
1387 'Failure cause was not as expected',
1388 goog.module.ModuleManager.FailureType.CONSECUTIVE_FAILURES, cause);
1389 firedLoadFailed = true;
1390 });
1391
1392 mm.preloadModule('s');
1393 assertFalse('module "s" should not be loaded (0)', mm.isModuleLoaded('s'));
1394
1395 // Fail twice.
1396 for (var i = 0; i < 2; i++) {
1397 clock.tick(5 + mm.getBackOff_());
1398 assertFalse('module "s" should not be loaded (1)', mm.isModuleLoaded('s'));
1399 assertFalse('should not fire failed callback (1)', firedLoadFailed);
1400 }
1401
1402 // Fail a third time and check that the callback is fired.
1403 clock.tick(5 + mm.getBackOff_());
1404 assertFalse('module "s" should not be loaded (2)', mm.isModuleLoaded('s'));
1405 assertTrue('should have fired failed callback', firedLoadFailed);
1406
1407 // Check that it doesn't attempt to load the module anymore after it has
1408 // failed.
1409 var triedLoad = false;
1410 mm.setLoader({
1411 loadModules: function(ids, moduleInfoMap, opt_successFn, opt_errFn) {
1412 triedLoad = true;
1413 }
1414 });
1415
1416 // Also reset the failed callback flag and make sure it isn't called
1417 // again.
1418 firedLoadFailed = false;
1419 clock.tick(10 + mm.getBackOff_());
1420 assertFalse('module "s" should not be loaded (3)', mm.isModuleLoaded('s'));
1421 assertFalse('No more loads should have been tried', triedLoad);
1422 assertFalse(
1423 'The load failed callback should be fired only once', firedLoadFailed);
1424 }
1425
1426
1427 /**
1428 * Test loading errors due to old code.
1429 */
1430 function testOldCodeGoneError() {
1431 var mm = getModuleManager({'s': []});
1432 mm.setLoader(createUnsuccessfulLoader(mm, 410));
1433
1434 // Callback checks for an old code failure
1435 var firedLoadFailed = false;
1436 mm.registerCallback(
1437 goog.module.ModuleManager.CallbackType.ERROR,
1438 function(callbackType, id, cause) {
1439 assertEquals(
1440 'Failure cause was not as expected',
1441 goog.module.ModuleManager.FailureType.OLD_CODE_GONE, cause);
1442 firedLoadFailed = true;
1443 });
1444
1445 mm.preloadModule('s', 0);
1446 assertFalse('module "s" should not be loaded (0)', mm.isModuleLoaded('s'));
1447 clock.tick(5);
1448 assertFalse('module "s" should not be loaded (1)', mm.isModuleLoaded('s'));
1449 assertTrue('should have called old code gone callback', firedLoadFailed);
1450 }
1451
1452
1453 /**
1454 * Test timeout.
1455 */
1456 function testTimeout() {
1457 var mm = getModuleManager({'s': []});
1458 mm.setLoader(createTimeoutLoader(mm));
1459
1460 // Callback checks for timeout
1461 var firedTimeout = false;
1462 mm.registerCallback(
1463 goog.module.ModuleManager.CallbackType.ERROR,
1464 function(callbackType, id, cause) {
1465 assertEquals(
1466 'Failure cause was not as expected',
1467 goog.module.ModuleManager.FailureType.TIMEOUT, cause);
1468 firedTimeout = true;
1469 });
1470
1471 mm.preloadModule('s', 0);
1472 assertFalse('module "s" should not be loaded (0)', mm.isModuleLoaded('s'));
1473 clock.tick(5);
1474 assertFalse('module "s" should not be loaded (1)', mm.isModuleLoaded('s'));
1475 assertTrue('should have called timeout callback', firedTimeout);
1476 }
1477
1478
1479 /**
1480 * Tests that an error during execOnLoad will trigger the error callback.
1481 */
1482 function testExecOnLoadError() {
1483 // Expect two callbacks, each of which will be called with callback type
1484 // ERROR, the right module id and failure type INIT_ERROR.
1485 var errorCallback1 = goog.testing.createFunctionMock('callback1');
1486 errorCallback1(
1487 goog.module.ModuleManager.CallbackType.ERROR, 'b',
1488 goog.module.ModuleManager.FailureType.INIT_ERROR);
1489
1490 var errorCallback2 = goog.testing.createFunctionMock('callback2');
1491 errorCallback2(
1492 goog.module.ModuleManager.CallbackType.ERROR, 'b',
1493 goog.module.ModuleManager.FailureType.INIT_ERROR);
1494
1495 errorCallback1.$replay();
1496 errorCallback2.$replay();
1497
1498 var mm = new goog.module.ModuleManager();
1499 mm.setLoader(createSuccessfulNonBatchLoader(mm));
1500
1501 // Register the first callback before setting the module info map.
1502 mm.registerCallback(
1503 goog.module.ModuleManager.CallbackType.ERROR, errorCallback1);
1504
1505 mm.setAllModuleInfo({'a': [], 'b': [], 'c': []});
1506
1507 // Register the second callback after setting the module info map.
1508 mm.registerCallback(
1509 goog.module.ModuleManager.CallbackType.ERROR, errorCallback2);
1510
1511 var execOnLoadBCalled = false;
1512 mm.execOnLoad('b', function() {
1513 execOnLoadBCalled = true;
1514 throw new Error();
1515 });
1516
1517 assertThrows(function() { clock.tick(5); });
1518
1519 assertTrue(
1520 'execOnLoad should have been called on module b.', execOnLoadBCalled);
1521 errorCallback1.$verify();
1522 errorCallback2.$verify();
1523 }
1524
1525
1526 /**
1527 * Tests that an error during execOnLoad will trigger the error callback.
1528 * Uses setAllModuleInfoString rather than setAllModuleInfo.
1529 */
1530 function testExecOnLoadErrorModuleInfoString() {
1531 // Expect a callback to be called with callback type ERROR, the right module
1532 // id and failure type INIT_ERROR.
1533 var errorCallback = goog.testing.createFunctionMock('callback');
1534 errorCallback(
1535 goog.module.ModuleManager.CallbackType.ERROR, 'b',
1536 goog.module.ModuleManager.FailureType.INIT_ERROR);
1537
1538 errorCallback.$replay();
1539
1540 var mm = new goog.module.ModuleManager();
1541 mm.setLoader(createSuccessfulNonBatchLoader(mm));
1542
1543 // Register the first callback before setting the module info map.
1544 mm.registerCallback(
1545 goog.module.ModuleManager.CallbackType.ERROR, errorCallback);
1546
1547 mm.setAllModuleInfoString('a/b/c');
1548
1549 var execOnLoadBCalled = false;
1550 mm.execOnLoad('b', function() {
1551 execOnLoadBCalled = true;
1552 throw new Error();
1553 });
1554
1555 assertThrows(function() { clock.tick(5); });
1556
1557 assertTrue(
1558 'execOnLoad should have been called on module b.', execOnLoadBCalled);
1559 errorCallback.$verify();
1560 }
1561
1562
1563 /**
1564 * Make sure ModuleInfo objects in moduleInfoMap_ get disposed.
1565 */
1566 function testDispose() {
1567 var mm = getModuleManager({'a': [], 'b': [], 'c': []});
1568
1569 var moduleInfoA = mm.getModuleInfo('a');
1570 assertNotNull(moduleInfoA);
1571 var moduleInfoB = mm.getModuleInfo('b');
1572 assertNotNull(moduleInfoB);
1573 var moduleInfoC = mm.getModuleInfo('c');
1574 assertNotNull(moduleInfoC);
1575
1576 mm.dispose();
1577 assertTrue(moduleInfoA.isDisposed());
1578 assertTrue(moduleInfoB.isDisposed());
1579 assertTrue(moduleInfoC.isDisposed());
1580 }
1581
1582 function testDependencyOrderingWithSimpleDeps() {
1583 var mm = getModuleManager({
1584 'a': ['b', 'c'],
1585 'b': ['d'],
1586 'c': ['e', 'f'],
1587 'd': [],
1588 'e': [],
1589 'f': []
1590 });
1591 var ids = mm.getNotYetLoadedTransitiveDepIds_('a');
1592 assertDependencyOrder(ids, mm);
1593 assertArrayEquals(['d', 'e', 'f', 'b', 'c', 'a'], ids);
1594 }
1595
1596 function testDependencyOrderingWithCommonDepsInDeps() {
1597 // Tests to make sure that if dependencies of the root are loaded before
1598 // their common dependencies.
1599 var mm = getModuleManager({'a': ['b', 'c'], 'b': ['d'], 'c': ['d'], 'd': []});
1600 var ids = mm.getNotYetLoadedTransitiveDepIds_('a');
1601 assertDependencyOrder(ids, mm);
1602 assertArrayEquals(['d', 'b', 'c', 'a'], ids);
1603 }
1604
1605 function testDependencyOrderingWithCommonDepsInRoot1() {
1606 // Tests the case where a dependency of the root depends on another
1607 // dependency of the root. Regardless of ordering in the root's
1608 // deps.
1609 var mm = getModuleManager({'a': ['b', 'c'], 'b': ['c'], 'c': []});
1610 var ids = mm.getNotYetLoadedTransitiveDepIds_('a');
1611 assertDependencyOrder(ids, mm);
1612 assertArrayEquals(['c', 'b', 'a'], ids);
1613 }
1614
1615 function testDependencyOrderingWithCommonDepsInRoot2() {
1616 // Tests the case where a dependency of the root depends on another
1617 // dependency of the root. Regardless of ordering in the root's
1618 // deps.
1619 var mm = getModuleManager({'a': ['b', 'c'], 'b': [], 'c': ['b']});
1620 var ids = mm.getNotYetLoadedTransitiveDepIds_('a');
1621 assertDependencyOrder(ids, mm);
1622 assertArrayEquals(['b', 'c', 'a'], ids);
1623 }
1624
1625 function testDependencyOrderingWithGmailExample() {
1626 // Real dependency graph taken from gmail.
1627 var mm = getModuleManager({
1628 's': ['dp', 'ml', 'md'],
1629 'dp': ['a'],
1630 'ml': ['ld', 'm'],
1631 'ld': ['a'],
1632 'm': ['ad', 'mh', 'n'],
1633 'md': ['mh', 'ld'],
1634 'a': [],
1635 'mh': [],
1636 'ad': [],
1637 'n': []
1638 });
1639
1640 mm.setLoaded('a');
1641 mm.setLoaded('m');
1642 mm.setLoaded('n');
1643 mm.setLoaded('ad');
1644 mm.setLoaded('mh');
1645
1646 var ids = mm.getNotYetLoadedTransitiveDepIds_('s');
1647 assertDependencyOrder(ids, mm);
1648 assertArrayEquals(['ld', 'dp', 'ml', 'md', 's'], ids);
1649 }
1650
1651 function assertDependencyOrder(list, mm) {
1652 var seen = {};
1653 for (var i = 0; i < list.length; i++) {
1654 var id = list[i];
1655 seen[id] = true;
1656 var deps = mm.getModuleInfo(id).getDependencies();
1657 for (var j = 0; j < deps.length; j++) {
1658 var dep = deps[j];
1659 assertTrue(
1660 'Unresolved dependency [' + dep + '] for [' + id + '].',
1661 seen[dep] || mm.getModuleInfo(dep).isLoaded());
1662 }
1663 }
1664 }
1665
1666 function testRegisterInitializationCallback() {
1667 var initCalled = 0;
1668 var mm = getModuleManager({'a': [], 'b': [], 'c': []});
1669 mm.setLoader(
1670 createSuccessfulNonBatchLoaderWithRegisterInitCallback(
1671 mm, function() { ++initCalled; }));
1672 execOnLoad_(mm);
1673 // execOnLoad_ loads modules a and c
1674 assertTrue(initCalled == 2);
1675 }
1676
1677 function createSuccessfulNonBatchLoaderWithRegisterInitCallback(moduleMgr, fn) {
1678 return {
1679 loadModules: function(
1680 ids, moduleInfoMap, opt_successFn, opt_errFn, opt_timeoutFn) {
1681 moduleMgr.beforeLoadModuleCode(ids[0]);
1682 moduleMgr.registerInitializationCallback(fn);
1683 setTimeout(function() {
1684 moduleMgr.setLoaded(ids[0]);
1685 moduleMgr.afterLoadModuleCode(ids[0]);
1686 if (opt_successFn) {
1687 opt_successFn();
1688 }
1689 }, 5);
1690 }
1691 };
1692 }
1693
1694 function testSetModuleConstructor() {
1695 var initCalled = 0;
1696 var mm = getModuleManager({'a': [], 'b': [], 'c': []});
1697 var info = {
1698 'a': {ctor: AModule, count: 0},
1699 'b': {ctor: BModule, count: 0},
1700 'c': {ctor: CModule, count: 0}
1701 };
1702 function AModule() {
1703 ++info['a'].count;
1704 goog.module.BaseModule.call(this);
1705 }
1706 goog.inherits(AModule, goog.module.BaseModule);
1707 function BModule() {
1708 ++info['b'].count;
1709 goog.module.BaseModule.call(this);
1710 }
1711 goog.inherits(BModule, goog.module.BaseModule);
1712 function CModule() {
1713 ++info['c'].count;
1714 goog.module.BaseModule.call(this);
1715 }
1716 goog.inherits(CModule, goog.module.BaseModule);
1717
1718 mm.setLoader(createSuccessfulNonBatchLoaderWithConstructor(mm, info));
1719 execOnLoad_(mm);
1720 assertTrue(info['a'].count == 1);
1721 assertTrue(info['b'].count == 0);
1722 assertTrue(info['c'].count == 1);
1723 assertTrue(mm.getModuleInfo('a').getModule() instanceof AModule);
1724 assertTrue(mm.getModuleInfo('c').getModule() instanceof CModule);
1725 }
1726
1727
1728 /**
1729 * Tests that a call to load the loading module during module initialization
1730 * doesn't trigger a second load.
1731 */
1732 function testLoadWhenInitializing() {
1733 var mm = getModuleManager({'a': []});
1734 mm.setLoader(createSuccessfulNonBatchLoader(mm));
1735
1736 var info = {'a': {ctor: AModule, count: 0}};
1737 function AModule() {
1738 ++info['a'].count;
1739 goog.module.BaseModule.call(this);
1740 }
1741 goog.inherits(AModule, goog.module.BaseModule);
1742 AModule.prototype.initialize = function() { mm.load('a'); };
1743 mm.setLoader(createSuccessfulNonBatchLoaderWithConstructor(mm, info));
1744 mm.preloadModule('a');
1745 clock.tick(5);
1746 assertEquals(info['a'].count, 1);
1747 }
1748
1749 function testErrorInEarlyCallback() {
1750 var errback = goog.testing.recordFunction();
1751 var callback = goog.testing.recordFunction();
1752 var mm = getModuleManager({'a': [], 'b': ['a']});
1753 mm.getModuleInfo('a').registerEarlyCallback(goog.functions.error('error'));
1754 mm.getModuleInfo('a').registerCallback(callback);
1755 mm.getModuleInfo('a').registerErrback(errback);
1756
1757 mm.setLoader(
1758 createSuccessfulNonBatchLoaderWithConstructor(
1759 mm, createModulesFor('a', 'b')));
1760 mm.preloadModule('b');
1761 var e = assertThrows(function() { clock.tick(5); });
1762
1763 assertEquals('error', e.message);
1764 assertEquals(0, callback.getCallCount());
1765 assertEquals(1, errback.getCallCount());
1766 assertEquals(
1767 goog.module.ModuleManager.FailureType.INIT_ERROR,
1768 errback.getLastCall().getArguments()[0]);
1769 assertTrue(mm.getModuleInfo('a').isLoaded());
1770 assertFalse(mm.getModuleInfo('b').isLoaded());
1771
1772 clock.tick(5);
1773 assertTrue(mm.getModuleInfo('b').isLoaded());
1774 }
1775
1776 function testErrorInNormalCallback() {
1777 var earlyCallback = goog.testing.recordFunction();
1778 var errback = goog.testing.recordFunction();
1779 var mm = getModuleManager({'a': [], 'b': ['a']});
1780 mm.getModuleInfo('a').registerEarlyCallback(earlyCallback);
1781 mm.getModuleInfo('a').registerEarlyCallback(goog.functions.error('error'));
1782 mm.getModuleInfo('a').registerErrback(errback);
1783
1784 mm.setLoader(
1785 createSuccessfulNonBatchLoaderWithConstructor(
1786 mm, createModulesFor('a', 'b')));
1787 mm.preloadModule('b');
1788 var e = assertThrows(function() { clock.tick(10); });
1789 clock.tick(10);
1790
1791 assertEquals('error', e.message);
1792 assertEquals(1, errback.getCallCount());
1793 assertEquals(
1794 goog.module.ModuleManager.FailureType.INIT_ERROR,
1795 errback.getLastCall().getArguments()[0]);
1796 assertTrue(mm.getModuleInfo('a').isLoaded());
1797 assertTrue(mm.getModuleInfo('b').isLoaded());
1798 }
1799
1800 function testErrorInErrback() {
1801 var mm = getModuleManager({'a': [], 'b': ['a']});
1802 mm.getModuleInfo('a').registerCallback(goog.functions.error('error1'));
1803 mm.getModuleInfo('a').registerErrback(goog.functions.error('error2'));
1804
1805 mm.setLoader(
1806 createSuccessfulNonBatchLoaderWithConstructor(
1807 mm, createModulesFor('a', 'b')));
1808 mm.preloadModule('a');
1809 var e = assertThrows(function() { clock.tick(10); });
1810 assertEquals('error1', e.message);
1811 var e = assertThrows(function() { clock.tick(10); });
1812 assertEquals('error2', e.message);
1813 assertTrue(mm.getModuleInfo('a').isLoaded());
1814 }
1815
1816 function createModulesFor(var_args) {
1817 var result = {};
1818 for (var i = 0; i < arguments.length; i++) {
1819 var key = arguments[i];
1820 result[key] = {ctor: goog.module.BaseModule};
1821 }
1822 return result;
1823 }
1824
1825 function createSuccessfulNonBatchLoaderWithConstructor(moduleMgr, info) {
1826 return {
1827 loadModules: function(
1828 ids, moduleInfoMap, opt_successFn, opt_errFn, opt_timeoutFn) {
1829 setTimeout(function() {
1830 moduleMgr.beforeLoadModuleCode(ids[0]);
1831 moduleMgr.setModuleConstructor(info[ids[0]].ctor);
1832 moduleMgr.setLoaded(ids[0]);
1833 moduleMgr.afterLoadModuleCode(ids[0]);
1834 if (opt_successFn) {
1835 opt_successFn();
1836 }
1837 }, 5);
1838 }
1839 };
1840 }
1841
1842 function testInitCallbackInBaseModule() {
1843 var mm = new goog.module.ModuleManager();
1844 var called = false;
1845 var context;
1846 mm.registerInitializationCallback(function(mcontext) {
1847 called = true;
1848 context = mcontext;
1849 });
1850 mm.setAllModuleInfo({'a': [], 'b': ['a']});
1851 assertTrue('Base initialization not called', called);
1852 assertNull('Context should still be null', context);
1853
1854 var mm = new goog.module.ModuleManager();
1855 called = false;
1856 mm.registerInitializationCallback(function(mcontext) {
1857 called = true;
1858 context = mcontext;
1859 });
1860 var appContext = {};
1861 mm.setModuleContext(appContext);
1862 assertTrue('Base initialization not called after setModuleContext', called);
1863 assertEquals('Did not receive module context', appContext, context);
1864 }
1865
1866 function testSetAllModuleInfoString() {
1867 var info = 'base/one:0/two:0/three:0,1,2/four:0,3/five:';
1868 var mm = new goog.module.ModuleManager();
1869 mm.setAllModuleInfoString(info);
1870
1871 assertNotNull('Base should exist', mm.getModuleInfo('base'));
1872 assertNotNull('One should exist', mm.getModuleInfo('one'));
1873 assertNotNull('Two should exist', mm.getModuleInfo('two'));
1874 assertNotNull('Three should exist', mm.getModuleInfo('three'));
1875 assertNotNull('Four should exist', mm.getModuleInfo('four'));
1876 assertNotNull('Five should exist', mm.getModuleInfo('five'));
1877
1878 assertArrayEquals(
1879 ['base', 'one', 'two'], mm.getModuleInfo('three').getDependencies());
1880 assertArrayEquals(
1881 ['base', 'three'], mm.getModuleInfo('four').getDependencies());
1882 assertArrayEquals([], mm.getModuleInfo('five').getDependencies());
1883 }
1884
1885 function testSetAllModuleInfoStringWithEmptyString() {
1886 var mm = new goog.module.ModuleManager();
1887 var called = false;
1888 var context;
1889 mm.registerInitializationCallback(function(mcontext) {
1890 called = true;
1891 context = mcontext;
1892 });
1893 mm.setAllModuleInfoString('');
1894 assertTrue('Initialization not called', called);
1895 }
1896
1897 function testBackOffAmounts() {
1898 var mm = new goog.module.ModuleManager();
1899 assertEquals(0, mm.getBackOff_());
1900
1901 mm.consecutiveFailures_++;
1902 assertEquals(5000, mm.getBackOff_());
1903
1904 mm.consecutiveFailures_++;
1905 assertEquals(20000, mm.getBackOff_());
1906 }
1907
1908
1909 /**
1910 * Tests that the IDLE callbacks are executed for active->idle transitions
1911 * after setAllModuleInfoString with currently loading modules.
1912 */
1913 function testIdleCallbackWithInitialModules() {
1914 var callback = goog.testing.recordFunction();
1915
1916 var mm = new goog.module.ModuleManager();
1917 mm.setAllModuleInfoString('a', ['a']);
1918 mm.registerCallback(goog.module.ModuleManager.CallbackType.IDLE, callback);
1919
1920 assertTrue(mm.isActive());
1921
1922 mm.beforeLoadModuleCode('a');
1923
1924 assertEquals(0, callback.getCallCount());
1925
1926 mm.setLoaded('a');
1927 mm.afterLoadModuleCode('a');
1928
1929 assertFalse(mm.isActive());
1930
1931 assertEquals(1, callback.getCallCount());
1932 }