summaryrefslogtreecommitdiffstats
path: root/services/sync/tps/extensions/mozmill/resource/modules/frame.js
blob: 799e81d5553258c7d25b182bb46303e27e8967f7 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
/* This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, you can obtain one at http://mozilla.org/MPL/2.0/. */

var EXPORTED_SYMBOLS = ['Collector','Runner','events', 'runTestFile', 'log',
                        'timers', 'persisted', 'shutdownApplication'];

const Cc = Components.classes;
const Ci = Components.interfaces;
const Cu = Components.utils;

const TIMEOUT_SHUTDOWN_HTTPD = 15000;

Cu.import("resource://gre/modules/Services.jsm");

Cu.import('resource://mozmill/stdlib/httpd.js');

var broker = {};  Cu.import('resource://mozmill/driver/msgbroker.js', broker);
var assertions = {}; Cu.import('resource://mozmill/modules/assertions.js', assertions);
var errors = {}; Cu.import('resource://mozmill/modules/errors.js', errors);
var os = {};      Cu.import('resource://mozmill/stdlib/os.js', os);
var strings = {}; Cu.import('resource://mozmill/stdlib/strings.js', strings);
var arrays = {};  Cu.import('resource://mozmill/stdlib/arrays.js', arrays);
var withs = {};   Cu.import('resource://mozmill/stdlib/withs.js', withs);
var utils = {};   Cu.import('resource://mozmill/stdlib/utils.js', utils);

var securableModule = {};
Cu.import('resource://mozmill/stdlib/securable-module.js', securableModule);

var uuidgen = Cc["@mozilla.org/uuid-generator;1"].getService(Ci.nsIUUIDGenerator);

var httpd = null;
var persisted = {};

var assert = new assertions.Assert();
var expect = new assertions.Expect();

var mozmill = undefined;
var mozelement = undefined;
var modules = undefined;

var timers = [];


/**
 * Shutdown or restart the application
 *
 * @param {boolean} [aFlags=undefined]
 *        Additional flags how to handle the shutdown or restart. The attributes
 *        eRestarti386 and eRestartx86_64 have not been documented yet.
 * @see https://developer.mozilla.org/nsIAppStartup#Attributes
 */
function shutdownApplication(aFlags) {
  var flags = Ci.nsIAppStartup.eForceQuit;

  if (aFlags) {
    flags |= aFlags;
  }

  // Send a request to shutdown the application. That will allow us and other
  // components to finish up with any shutdown code. Please note that we don't
  // care if other components or add-ons want to prevent this via cancelQuit,
  // we really force the shutdown.
  let cancelQuit = Components.classes["@mozilla.org/supports-PRBool;1"].
                   createInstance(Components.interfaces.nsISupportsPRBool);
  Services.obs.notifyObservers(cancelQuit, "quit-application-requested", null);

  // Use a timer to trigger the application restart, which will allow us to
  // send an ACK packet via jsbridge if the method has been called via Python.
  var event = {
    notify: function(timer) {
      Services.startup.quit(flags);
    }
  }

  var timer = Cc["@mozilla.org/timer;1"].createInstance(Ci.nsITimer);
  timer.initWithCallback(event, 100, Ci.nsITimer.TYPE_ONE_SHOT);
}

function stateChangeBase(possibilties, restrictions, target, cmeta, v) {
  if (possibilties) {
    if (!arrays.inArray(possibilties, v)) {
      // TODO Error value not in this.poss
      return;
    }
  }

  if (restrictions) {
    for (var i in restrictions) {
      var r = restrictions[i];
      if (!r(v)) {
        // TODO error value did not pass restriction
        return;
      }
    }
  }

  // Fire jsbridge notification, logging notification, listener notifications
  events[target] = v;
  events.fireEvent(cmeta, target);
}


var events = {
  appQuit           : false,
  currentModule     : null,
  currentState      : null,
  currentTest       : null,
  shutdownRequested : false,
  userShutdown      : null,
  userShutdownTimer : null,

  listeners       : {},
  globalListeners : []
}

events.setState = function (v) {
  return stateChangeBase(['dependencies', 'setupModule', 'teardownModule',
                          'test', 'setupTest', 'teardownTest', 'collection'],
                          null, 'currentState', 'setState', v);
}

events.toggleUserShutdown = function (obj){
  if (!this.userShutdown) {
    this.userShutdown = obj;

    var event = {
      notify: function(timer) {
       events.toggleUserShutdown(obj);
      }
    }

    this.userShutdownTimer = Cc["@mozilla.org/timer;1"].createInstance(Ci.nsITimer);
    this.userShutdownTimer.initWithCallback(event, obj.timeout, Ci.nsITimer.TYPE_ONE_SHOT);

  } else {
    this.userShutdownTimer.cancel();

    // If the application is not going to shutdown, the user shutdown failed and
    // we have to force a shutdown.
    if (!events.appQuit) {
      this.fail({'function':'events.toggleUserShutdown',
                 'message':'Shutdown expected but none detected before timeout',
                 'userShutdown': obj});

      var flags = Ci.nsIAppStartup.eAttemptQuit;
      if (events.isRestartShutdown()) {
        flags |= Ci.nsIAppStartup.eRestart;
      }

      shutdownApplication(flags);
    }
  }
}

events.isUserShutdown = function () {
  return this.userShutdown ? this.userShutdown["user"] : false;
}

events.isRestartShutdown = function () {
  return this.userShutdown.restart;
}

events.startShutdown = function (obj) {
  events.fireEvent('shutdown', obj);

  if (obj["user"]) {
    events.toggleUserShutdown(obj);
  } else {
    shutdownApplication(obj.flags);
  }
}

events.setTest = function (test) {
  test.__start__ = Date.now();
  test.__passes__ = [];
  test.__fails__ = [];

  events.currentTest = test;

  var obj = {'filename': events.currentModule.__file__,
             'name': test.__name__}
  events.fireEvent('setTest', obj);
}

events.endTest = function (test) {
  // use the current test unless specified
  if (test === undefined) {
    test = events.currentTest;
  }

  // If no test is set it has already been reported. Beside that we don't want
  // to report it a second time.
  if (!test || test.status === 'done')
    return;

  // report the end of a test
  test.__end__ = Date.now();
  test.status = 'done';

  var obj = {'filename': events.currentModule.__file__,
             'passed': test.__passes__.length,
             'failed': test.__fails__.length,
             'passes': test.__passes__,
             'fails' : test.__fails__,
             'name'  : test.__name__,
             'time_start': test.__start__,
             'time_end': test.__end__}

  if (test.skipped) {
    obj['skipped'] = true;
    obj.skipped_reason = test.skipped_reason;
  }

  if (test.meta) {
    obj.meta = test.meta;
  }

  // Report the test result only if the test is a true test or if it is failing
  if (withs.startsWith(test.__name__, "test") || test.__fails__.length > 0) {
    events.fireEvent('endTest', obj);
  }
}

events.setModule = function (aModule) {
  aModule.__start__ = Date.now();
  aModule.__status__ = 'running';

  var result = stateChangeBase(null,
                               [function (aModule) {return (aModule.__file__ != undefined)}],
                               'currentModule', 'setModule', aModule);

  return result;
}

events.endModule = function (aModule) {
  // It should only reported once, so check if it already has been done
  if (aModule.__status__ === 'done')
    return;

  aModule.__end__ = Date.now();
  aModule.__status__ = 'done';

  var obj = {
    'filename': aModule.__file__,
    'time_start': aModule.__start__,
    'time_end': aModule.__end__
  }

  events.fireEvent('endModule', obj);
}

events.pass = function (obj) {
  // a low level event, such as a keystroke, succeeds
  if (events.currentTest) {
    events.currentTest.__passes__.push(obj);
  }

  for each (var timer in timers) {
    timer.actions.push(
      {"currentTest": events.currentModule.__file__ + "::" + events.currentTest.__name__,
       "obj": obj,
       "result": "pass"}
    );
  }

  events.fireEvent('pass', obj);
}

events.fail = function (obj) {
  var error = obj.exception;

  if (error) {
    // Error objects aren't enumerable https://bugzilla.mozilla.org/show_bug.cgi?id=637207
    obj.exception = {
      name: error.name,
      message: error.message,
      lineNumber: error.lineNumber,
      fileName: error.fileName,
      stack: error.stack
    };
  }

  // a low level event, such as a keystroke, fails
  if (events.currentTest) {
    events.currentTest.__fails__.push(obj);
  }

  for each (var time in timers) {
    timer.actions.push(
      {"currentTest": events.currentModule.__file__ + "::" + events.currentTest.__name__,
       "obj": obj,
       "result": "fail"}
    );
  }

  events.fireEvent('fail', obj);
}

events.skip = function (reason) {
  // this is used to report skips associated with setupModule and nothing else
  events.currentTest.skipped = true;
  events.currentTest.skipped_reason = reason;

  for (var timer of timers) {
    timer.actions.push(
      {"currentTest": events.currentModule.__file__ + "::" + events.currentTest.__name__,
       "obj": reason,
       "result": "skip"}
    );
  }

  events.fireEvent('skip', reason);
}

events.fireEvent = function (name, obj) {
  if (events.appQuit) {
    // dump('* Event discarded: ' + name + ' ' + JSON.stringify(obj) + '\n');
    return;
  }

  if (this.listeners[name]) {
    for (var i in this.listeners[name]) {
      this.listeners[name][i](obj);
    }
  }

  for each(var listener in this.globalListeners) {
    listener(name, obj);
  }
}

events.addListener = function (name, listener) {
  if (this.listeners[name]) {
    this.listeners[name].push(listener);
  } else if (name == '') {
    this.globalListeners.push(listener)
  } else {
    this.listeners[name] = [listener];
  }
}

events.removeListener = function (listener) {
  for (var listenerIndex in this.listeners) {
    var e = this.listeners[listenerIndex];

    for (var i in e){
      if (e[i] == listener) {
        this.listeners[listenerIndex] = arrays.remove(e, i);
      }
    }
  }

  for (var i in this.globalListeners) {
    if (this.globalListeners[i] == listener) {
      this.globalListeners = arrays.remove(this.globalListeners, i);
    }
  }
}

events.persist = function () {
  try {
    events.fireEvent('persist', persisted);
  } catch (e) {
    events.fireEvent('error', "persist serialization failed.")
  }
}

events.firePythonCallback = function (obj) {
  obj['test'] = events.currentModule.__file__;
  events.fireEvent('firePythonCallback', obj);
}

events.screenshot = function (obj) {
  // Find the name of the test function
  for (var attr in events.currentModule) {
    if (events.currentModule[attr] == events.currentTest) {
      var testName = attr;
      break;
    }
  }

  obj['test_file'] = events.currentModule.__file__;
  obj['test_name'] = testName;
  events.fireEvent('screenshot', obj);
}

var log = function (obj) {
  events.fireEvent('log', obj);
}

// Register the listeners
broker.addObject({'endTest': events.endTest,
                  'fail': events.fail,
                  'firePythonCallback': events.firePythonCallback,
                  'log': log,
                  'pass': events.pass,
                  'persist': events.persist,
                  'screenshot': events.screenshot,
                  'shutdown': events.startShutdown,
                 });

try {
  Cu.import('resource://jsbridge/modules/Events.jsm');

  events.addListener('', function (name, obj) {
    Events.fireEvent('mozmill.' + name, obj);
  });
} catch (e) {
  Services.console.logStringMessage("Event module of JSBridge not available.");
}


/**
 * Observer for notifications when the application is going to shutdown
 */
function AppQuitObserver() {
  this.runner = null;

  Services.obs.addObserver(this, "quit-application-requested", false);
}

AppQuitObserver.prototype = {
  observe: function (aSubject, aTopic, aData) {
    switch (aTopic) {
      case "quit-application-requested":
        Services.obs.removeObserver(this, "quit-application-requested");

        // If we observe a quit notification make sure to send the
        // results of the current test. In those cases we don't reach
        // the equivalent code in runTestModule()
        events.pass({'message': 'AppQuitObserver: ' + JSON.stringify(aData),
                     'userShutdown': events.userShutdown});

        if (this.runner) {
          this.runner.end();
        }

        if (httpd) {
          httpd.stop();
        }

        events.appQuit = true;

        break;
    }
  }
}

var appQuitObserver = new AppQuitObserver();

/**
 * The collector handles HTTPd.js and initilizing the module
 */
function Collector() {
  this.test_modules_by_filename = {};
  this.testing = [];
}

Collector.prototype.addHttpResource = function (aDirectory, aPath) {
  var fp = Cc["@mozilla.org/file/local;1"].createInstance(Ci.nsILocalFile);
  fp.initWithPath(os.abspath(aDirectory, this.current_file));

  return httpd.addHttpResource(fp, aPath);
}

Collector.prototype.initTestModule = function (filename, testname) {
  var test_module = this.loadFile(filename, this);
  var has_restarted = !(testname == null);
  test_module.__tests__ = [];

  for (var i in test_module) {
    if (typeof(test_module[i]) == "function") {
      test_module[i].__name__ = i;

      // Only run setupModule if we are a single test OR if we are the first
      // test of a restart chain (don't run it prior to members in a restart
      // chain)
      if (i == "setupModule" && !has_restarted) {
        test_module.__setupModule__ = test_module[i];
      } else if (i == "setupTest") {
        test_module.__setupTest__ = test_module[i];
      } else if (i == "teardownTest") {
        test_module.__teardownTest__ = test_module[i];
      } else if (i == "teardownModule") {
        test_module.__teardownModule__ = test_module[i];
      } else if (withs.startsWith(i, "test")) {
        if (testname && (i != testname)) {
          continue;
        }

        testname = null;
        test_module.__tests__.push(test_module[i]);
      }
    }
  }

  test_module.collector = this;
  test_module.status = 'loaded';

  this.test_modules_by_filename[filename] = test_module;

  return test_module;
}

Collector.prototype.loadFile = function (path, collector) {
  var moduleLoader = new securableModule.Loader({
    rootPaths: ["resource://mozmill/modules/"],
    defaultPrincipal: "system",
    globals : { Cc: Cc,
                Ci: Ci,
                Cu: Cu,
                Cr: Components.results}
  });

  // load a test module from a file and add some candy
  var file = Cc["@mozilla.org/file/local;1"].createInstance(Ci.nsILocalFile);
  file.initWithPath(path);
  var uri = Services.io.newFileURI(file).spec;

  this.loadTestResources();

  var systemPrincipal = Services.scriptSecurityManager.getSystemPrincipal();
  var module = new Components.utils.Sandbox(systemPrincipal);
  module.assert = assert;
  module.Cc = Cc;
  module.Ci = Ci;
  module.Cr = Components.results;
  module.Cu = Cu;
  module.collector = collector;
  module.driver = moduleLoader.require("driver");
  module.elementslib = mozelement;
  module.errors = errors;
  module.expect = expect;
  module.findElement = mozelement;
  module.log = log;
  module.mozmill = mozmill;
  module.persisted = persisted;

  module.require = function (mod) {
    var loader = new securableModule.Loader({
      rootPaths: [Services.io.newFileURI(file.parent).spec,
                  "resource://mozmill/modules/"],
      defaultPrincipal: "system",
      globals : { assert: assert,
                  expect: expect,
                  mozmill: mozmill,
                  elementslib: mozelement,      // This a quick hack to maintain backwards compatibility with 1.5.x
                  findElement: mozelement,
                  persisted: persisted,
                  Cc: Cc,
                  Ci: Ci,
                  Cu: Cu,
                  log: log }
    });

    if (modules != undefined) {
      loader.modules = modules;
    }

    var retval = loader.require(mod);
    modules = loader.modules;

    return retval;
  }

  if (collector != undefined) {
    collector.current_file = file;
    collector.current_path = path;
  }

  try {
    Services.scriptloader.loadSubScript(uri, module, "UTF-8");
  } catch (e) {
    var obj = {
      'filename': path,
      'passed': 0,
      'failed': 1,
      'passes': [],
      'fails' : [{'exception' : {
                    message: e.message,
                    filename: e.filename,
                    lineNumber: e.lineNumber}}],
      'name'  :'<TOP_LEVEL>'
    };

    events.fail({'exception': e});
    events.fireEvent('endTest', obj);
  }

  module.__file__ = path;
  module.__uri__ = uri;

  return module;
}

Collector.prototype.loadTestResources = function () {
  // load resources we want in our tests
  if (mozmill === undefined) {
    mozmill = {};
    Cu.import("resource://mozmill/driver/mozmill.js", mozmill);
  }
  if (mozelement === undefined) {
    mozelement = {};
    Cu.import("resource://mozmill/driver/mozelement.js", mozelement);
  }
}


/**
 *
 */
function Httpd(aPort) {
  this.http_port = aPort;

  while (true) {
    try {
      var srv = new HttpServer();
      srv.registerContentType("sjs", "sjs");
      srv.identity.setPrimary("http", "localhost", this.http_port);
      srv.start(this.http_port);

      this._httpd = srv;
      break;
    }
    catch (e) {
      // Failure most likely due to port conflict
      this.http_port++;
    }
  }
}

Httpd.prototype.addHttpResource = function (aDir, aPath) {
  var path = aPath ? ("/" + aPath + "/") : "/";

  try {
    this._httpd.registerDirectory(path, aDir);
    return 'http://localhost:' + this.http_port + path;
  }
  catch (e) {
    throw Error("Failure to register directory: " + aDir.path);
  }
};

Httpd.prototype.stop = function () {
  if (!this._httpd) {
    return;
  }

  var shutdown = false;
  this._httpd.stop(function () { shutdown = true; });

  assert.waitFor(function () {
    return shutdown;
  }, "Local HTTP server has been stopped", TIMEOUT_SHUTDOWN_HTTPD);

  this._httpd = null;
};

function startHTTPd() {
  if (!httpd) {
    // Ensure that we start the HTTP server only once during a session
    httpd = new Httpd(43336);
  }
}


function Runner() {
  this.collector = new Collector();
  this.ended = false;

  var m = {}; Cu.import('resource://mozmill/driver/mozmill.js', m);
  this.platform = m.platform;

  events.fireEvent('startRunner', true);
}

Runner.prototype.end = function () {
  if (!this.ended) {
    this.ended = true;

    appQuitObserver.runner = null;

    events.endTest();
    events.endModule(events.currentModule);
    events.fireEvent('endRunner', true);
    events.persist();
  }
};

Runner.prototype.runTestFile = function (filename, name) {
  var module = this.collector.initTestModule(filename, name);
  this.runTestModule(module);
};

Runner.prototype.runTestModule = function (module) {
  appQuitObserver.runner = this;
  events.setModule(module);

  // If setupModule passes, run all the tests. Otherwise mark them as skipped.
  if (this.execFunction(module.__setupModule__, module)) {
    for (var test of module.__tests__) {
      if (events.shutdownRequested) {
        break;
      }

      // If setupTest passes, run the test. Otherwise mark it as skipped.
      if (this.execFunction(module.__setupTest__, module)) {
        this.execFunction(test);
      } else {
        this.skipFunction(test, module.__setupTest__.__name__ + " failed");
      }

      this.execFunction(module.__teardownTest__, module);
    }

  } else {
    for (var test of module.__tests__) {
      this.skipFunction(test, module.__setupModule__.__name__ + " failed");
    }
  }

  this.execFunction(module.__teardownModule__, module);
  events.endModule(module);
};

Runner.prototype.execFunction = function (func, arg) {
  if (typeof func !== "function" || events.shutdownRequested) {
    return true;
  }

  var isTest = withs.startsWith(func.__name__, "test");

  events.setState(isTest ? "test" : func.__name);
  events.setTest(func);

  // skip excluded platforms
  if (func.EXCLUDED_PLATFORMS != undefined) {
    if (arrays.inArray(func.EXCLUDED_PLATFORMS, this.platform)) {
      events.skip("Platform exclusion");
      events.endTest(func);
      return false;
    }
  }

  // skip function if requested
  if (func.__force_skip__ != undefined) {
    events.skip(func.__force_skip__);
    events.endTest(func);
    return false;
  }

  // execute the test function
  try {
    func(arg);
  } catch (e) {
    if (e instanceof errors.ApplicationQuitError) {
      events.shutdownRequested = true;
    } else {
      events.fail({'exception': e, 'test': func})
    }
  }

  // If a user shutdown has been requested and the function already returned,
  // we can assume that a shutdown will not happen anymore. We should force a
  // shutdown then, to prevent the next test from being executed.
  if (events.isUserShutdown()) {
    events.shutdownRequested = true;
    events.toggleUserShutdown(events.userShutdown);
  }

  events.endTest(func);
  return events.currentTest.__fails__.length == 0;
};

function runTestFile(filename, name) {
  var runner = new Runner();
  runner.runTestFile(filename, name);
  runner.end();

  return true;
}

Runner.prototype.skipFunction = function (func, message) {
  events.setTest(func);
  events.skip(message);
  events.endTest(func);
};