summaryrefslogtreecommitdiffstats
path: root/addon-sdk/source/test/util.js
blob: af6a6f564f3f311e5f43ec9cb993922d13277899 (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
/* 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/. */
"use strict";

const {Cc, Ci} = require("chrome");
const {getMostRecentBrowserWindow, open} = require("sdk/window/utils");
const tabUtils = require("sdk/tabs/utils");
const {when} = require("sdk/dom/events");


var observerService = Cc["@mozilla.org/observer-service;1"]
                      .getService(Ci.nsIObserverService);

const { ShimWaiver } = Cu.import("resource://gre/modules/ShimWaiver.jsm");
const addObserver = ShimWaiver.getProperty(observerService, "addObserver");
const removeObserver = ShimWaiver.getProperty(observerService, "removeObserver");

const getActiveTab = (window=getMostRecentBrowserWindow()) =>
  tabUtils.getActiveTab(window)

const openWindow = () => {
  const window = open();
  return new Promise((resolve) => {
    addObserver({
      observe(subject, topic) {
        if (subject === window) {
          removeObserver(this, topic);
          resolve(subject);
        }
      }
    }, "browser-delayed-startup-finished", false);
  });
};
exports.openWindow = openWindow;

const closeWindow = (window) => {
  const closed = when(window, "unload", true).then(_ => window);
  window.close();
  return closed;
};
exports.closeWindow = closeWindow;

const openTab = (url, window=getMostRecentBrowserWindow()) => {
  const tab = tabUtils.openTab(window, url);
  const browser = tabUtils.getBrowserForTab(tab);

  return when(browser, "load", true).then(_ => tab);
};
exports.openTab = openTab;

const closeTab = (tab) => {
  const result = when(tab, "TabClose").then(_ => tab);
  tabUtils.closeTab(tab);

  return result;
};
exports.closeTab = closeTab;

const withTab = (test, uri="about:blank") => function*(assert) {
  const tab = yield openTab(uri);
  try {
    yield* test(assert, tab);
  }
  finally {
    yield closeTab(tab);
  }
};
exports.withTab = withTab;

const withWindow = () => function*(assert) {
  const window = yield openWindow();
  try {
    yield* test(assert, window);
  }
  finally {
    yield closeWindow(window);
  }
};
exports.withWindow = withWindow;

const receiveMessage = (manager, name) => new Promise((resolve) => {
  manager.addMessageListener(name, {
    receiveMessage(message) {
      manager.removeMessageListener(name, this);
      resolve(message);
    }
  });
});
exports.receiveMessage = receiveMessage;