summaryrefslogtreecommitdiffstats
path: root/toolkit/jetpack/sdk/deprecated/unit-test-finder.js
blob: e38629f45d7768b4da5a76c049a202d2a957b5f4 (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
/* 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";

module.metadata = {
  "stability": "deprecated"
};

const file = require("../io/file");
const { Loader } = require("../test/loader");

const { isNative } = require('@loader/options');

const cuddlefish = isNative ? require("toolkit/loader") : require("../loader/cuddlefish");

const { defer, resolve } = require("../core/promise");
const { getAddon } = require("../addon/installer");
const { id } = require("sdk/self");
const { newURI } = require('sdk/url/utils');
const { getZipReader } = require("../zip/utils");

const { Cc, Ci, Cu } = require("chrome");
const { AddonManager } = Cu.import("resource://gre/modules/AddonManager.jsm", {});
var ios = Cc['@mozilla.org/network/io-service;1']
          .getService(Ci.nsIIOService);

const CFX_TEST_REGEX = /(([^\/]+\/)(?:lib\/)?)?(tests?\/test-[^\.\/]+)\.js$/;
const JPM_TEST_REGEX = /^()(tests?\/test-[^\.\/]+)\.js$/;

const { mapcat, map, filter, fromEnumerator } = require("sdk/util/sequence");

const toFile = x => x.QueryInterface(Ci.nsIFile);
const isTestFile = ({leafName}) => leafName.substr(0, 5) == "test-" && leafName.substr(-3, 3) == ".js";
const getFileURI = x => ios.newFileURI(x).spec;

const getDirectoryEntries = file => map(toFile, fromEnumerator(_ => file.directoryEntries));
const getTestFiles = directory => filter(isTestFile, getDirectoryEntries(directory));
const getTestURIs = directory => map(getFileURI, getTestFiles(directory));

const isDirectory = x => x.isDirectory();
const getTestEntries = directory => mapcat(entry =>
  /^tests?$/.test(entry.leafName) ? getTestURIs(entry) : getTestEntries(entry),
  filter(isDirectory, getDirectoryEntries(directory)));

const removeDups = (array) => array.reduce((result, value) => {
  if (value != result[result.length - 1]) {
    result.push(value);
  }
  return result;
}, []);

const getSuites = function getSuites({ id, filter }) {
  const TEST_REGEX = isNative ? JPM_TEST_REGEX : CFX_TEST_REGEX;

  return getAddon(id).then(addon => {
    let fileURI = addon.getResourceURI("tests/");
    let isPacked = fileURI.scheme == "jar";
    let xpiURI = addon.getResourceURI();
    let file = xpiURI.QueryInterface(Ci.nsIFileURL).file;
    let suites = [];
    let addEntry = (entry) => {
      if (filter(entry) && TEST_REGEX.test(entry)) {
        let suite = (isNative ? "./" : "") + (RegExp.$2 || "") + RegExp.$3;
        suites.push(suite);
      }
    }

    if (isPacked) {
      return getZipReader(file).then(zip => {
        let entries = zip.findEntries(null);
        while (entries.hasMore()) {
          let entry = entries.getNext();
          addEntry(entry);
        }
        zip.close();

        // sort and remove dups
        suites = removeDups(suites.sort());
        return suites;
      })
    }
    else {
      let tests = [...getTestEntries(file)];
      let rootURI = addon.getResourceURI("/");
      tests.forEach((entry) => {
        addEntry(entry.replace(rootURI.spec, ""));
      });
    }

    // sort and remove dups
    suites = removeDups(suites.sort());
    return suites;
  });
}
exports.getSuites = getSuites;

const makeFilters = function makeFilters(options) {
  options = options || {};

  // A filter string is {fileNameRegex}[:{testNameRegex}] - ie, a colon
  // optionally separates a regex for the test fileName from a regex for the
  // testName.
  if (options.filter) {
    let colonPos = options.filter.indexOf(':');
    let filterFileRegex, filterNameRegex;

    if (colonPos === -1) {
      filterFileRegex = new RegExp(options.filter);
      filterNameRegex = { test: () => true }
    }
    else {
      filterFileRegex = new RegExp(options.filter.substr(0, colonPos));
      filterNameRegex = new RegExp(options.filter.substr(colonPos + 1));
    }

    return {
      fileFilter: (name) => filterFileRegex.test(name),
      testFilter: (name) => filterNameRegex.test(name)
    }
  }

  return {
    fileFilter: () => true,
    testFilter: () => true
  };
}
exports.makeFilters = makeFilters;

var loader = Loader(module);
const NOT_TESTS = ['setup', 'teardown'];

var TestFinder = exports.TestFinder = function TestFinder(options) {
  this.filter = options.filter;
  this.testInProcess = options.testInProcess === false ? false : true;
  this.testOutOfProcess = options.testOutOfProcess === true ? true : false;
};

TestFinder.prototype = {
  findTests: function findTests() {
    let { fileFilter, testFilter } = makeFilters({ filter: this.filter });

    return getSuites({ id: id, filter: fileFilter }).then(suites => {
      let testsRemaining = [];

      let getNextTest = () => {
        if (testsRemaining.length) {
          return testsRemaining.shift();
        }

        if (!suites.length) {
          return null;
        }

        let suite = suites.shift();

        // Load each test file as a main module in its own loader instance
        // `suite` is defined by cuddlefish/manifest.py:ManifestBuilder.build
        let suiteModule;

        try {
          suiteModule = cuddlefish.main(loader, suite);
        }
        catch (e) {
          if (/Unsupported Application/i.test(e.message)) {
            // If `Unsupported Application` error thrown during test,
            // skip the test suite
            suiteModule = {
              'test suite skipped': assert => assert.pass(e.message)
            };
          }
          else {
            console.exception(e);
            throw e;
          }
        }

        if (this.testInProcess) {
          for (let name of Object.keys(suiteModule).sort()) {
            if (NOT_TESTS.indexOf(name) === -1 && testFilter(name)) {
              testsRemaining.push({
                setup: suiteModule.setup,
                teardown: suiteModule.teardown,
                testFunction: suiteModule[name],
                name: suite + "." + name
              });
            }
          }
        }

        return getNextTest();
      };

      return {
        getNext: () => resolve(getNextTest())
      };
    });
  }
};