Code coverage report for src/TestRunner.js

Statements: 37.74% (60 / 159)      Branches: 25.4% (16 / 63)      Functions: 23.26% (10 / 43)      Lines: 37.74% (60 / 159)      Ignored: none     

All files » src/ » TestRunner.js
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                  10 10 10 10 10 10 10 10   10   10                                                                   20       10                   1 10 10 10 10               10       10         10 10             10               10                           10 22 22         22               10                                         10 6   6       6       6       6 6 6             6 6 6         6 6 18 18     18 13 12 12 12 6           6     6                                     10                                                                                                                       10       10                     10                                                                                                                                                                     10                                                                                                 10                   10                               10                                                                                                                           10  
/**
 * Copyright (c) 2014, Facebook, Inc. All rights reserved.
 *
 * This source code is licensed under the BSD-style license found in the
 * LICENSE file in the root directory of this source tree. An additional grant
 * of patent rights can be found in the PATENTS file in the same directory.
 */
'use strict';
 
var fs = require('graceful-fs');
var os = require('os');
var path = require('path');
var q = require('q');
var through = require('through');
var utils = require('./lib/utils');
var WorkerPool = require('node-worker-pool');
var Console = require('./Console');
 
var TEST_WORKER_PATH = require.resolve('./TestWorker');
 
var DEFAULT_OPTIONS = {
 
  /**
   * When true, runs all tests serially in the current process, rather than
   * creating a worker pool of child processes.
   *
   * This can be useful for debugging, or when the environment limits to a
   * single process.
   */
  runInBand: false,
 
  /**
   * The maximum number of workers to run tests concurrently with.
   *
   * It's probably good to keep this at something close to the number of cores
   * on the machine that's running the test.
   */
  maxWorkers: Math.max(os.cpus().length - 1, 1),
 
  /**
   * The path to the executable node binary.
   *
   * This is used in the process of booting each of the workers.
   */
  nodePath: process.execPath,
 
  /**
   * The args to be passed to the node binary executable.
   *
   * this is used in the process of booting each of the workers.
   */
  nodeArgv: process.execArgv.filter(function(arg) {
    // Passing --debug off to child processes can screw with socket connections
    // of the parent process.
    return arg !== '--debug';
  })
};
 
var HIDDEN_FILE_RE = /\/\.[^\/]*$/;
 
/**
 * A class that takes a project's test config and provides various utilities for
 * executing its tests.
 *
 * @param config The jest configuration
 * @param options See DEFAULT_OPTIONS for descriptions on the various options
 *                and their defaults.
 */
function TestRunner(config, options) {
  this._config = config;
  this._configDeps = null;
  this._moduleLoaderResourceMap = null;
  this._testPathDirsRegExp = new RegExp(
    config.testPathDirs
      .map(function(dir) {
        return utils.escapeStrForRegex(dir);
      })
      .join('|')
  );
 
  this._nodeHasteTestRegExp = new RegExp(
    '/' + utils.escapeStrForRegex(config.testDirectoryName) + '/' +
    '.*\\.(' +
      config.testFileExtensions.map(function(ext) {
        return utils.escapeStrForRegex(ext);
      })
      .join('|') +
    ')$'
  );
  this._opts = Object.create(DEFAULT_OPTIONS);
  Iif (options) {
    for (var key in options) {
      this._opts[key] = options[key];
    }
  }
}
 
TestRunner.prototype._constructModuleLoader = function(environment, customCfg) {
  var config = customCfg || this._config;
  var ModuleLoader = this._loadConfigDependencies().ModuleLoader;
  return this._getModuleLoaderResourceMap().then(function(resourceMap) {
    return new ModuleLoader(config, environment, resourceMap);
  });
};
 
TestRunner.prototype._getModuleLoaderResourceMap = function() {
  var ModuleLoader = this._loadConfigDependencies().ModuleLoader;
  if (this._moduleLoaderResourceMap === null) {
    if (this._opts.useCachedModuleLoaderResourceMap) {
      this._moduleLoaderResourceMap =
        ModuleLoader.loadResourceMapFromCacheFile(this._config);
    } else {
      this._moduleLoaderResourceMap =
        ModuleLoader.loadResourceMap(this._config);
    }
  }
  return this._moduleLoaderResourceMap;
};
 
TestRunner.prototype._isTestFilePath = function(filePath) {
  filePath = utils.pathNormalize(filePath);
  var testPathIgnorePattern =
    this._config.testPathIgnorePatterns
    ? new RegExp(this._config.testPathIgnorePatterns.join('|'))
    : null;
 
  return (
    this._nodeHasteTestRegExp.test(filePath)
    && !HIDDEN_FILE_RE.test(filePath)
    && (!testPathIgnorePattern || !testPathIgnorePattern.test(filePath))
    && this._testPathDirsRegExp.test(filePath)
  );
};
 
TestRunner.prototype._loadConfigDependencies = function() {
  var config = this._config;
  if (this._configDeps === null) {
    this._configDeps = {
      ModuleLoader: require(config.moduleLoader),
      testEnvironment: require(config.testEnvironment),
      testRunner: require(config.testRunner).bind(null)
    };
  }
  return this._configDeps;
};
 
/**
 * Given a list of paths to modules or tests, find all tests that are related to
 * any of those paths. For a test to be considered "related" to a path, the test
 * must depend on that path (either directly, or indirectly through one of its
 * direct dependencies).
 *
 * @param {Array<String>} paths A list of path strings to find related tests for
 * @return {Stream<String>} Stream of testPath strings
 */
TestRunner.prototype.streamTestPathsRelatedTo = function(paths) {
  var pathStream = through(
    function write(data) {
      Iif (data.isError) {
        this.emit('error', data);
        this.emit('end');
      } else {
        this.emit('data', data);
      }
    },
    function end() {
      this.emit('end');
    }
  );
 
  var testRunner = this;
  this._constructModuleLoader().done(function(moduleLoader) {
    var discoveredModules = {};
 
    // If a path to a test file is given, make sure we consider that test as
    // related to itself...
    //
    // (If any of the supplied paths aren't tests, it's ok because we filter
    //  non-tests out at the end)
    paths.forEach(function(path) {
      discoveredModules[path] = true;
      Iif (testRunner._isTestFilePath(path) && fs.existsSync(path)) {
        pathStream.write(path);
      }
    });
 
    var modulesToSearch = [].concat(paths);
    while (modulesToSearch.length > 0) {
      var modulePath = modulesToSearch.shift();
      var depPaths = moduleLoader.getDependentsFromPath(modulePath);
 
      /* jshint loopfunc:true */
      depPaths.forEach(function(depPath) {
        if (!discoveredModules.hasOwnProperty(depPath)) {
          discoveredModules[depPath] = true;
          modulesToSearch.push(depPath);
          if (testRunner._isTestFilePath(depPath) && fs.existsSync(depPath)) {
            pathStream.write(depPath);
          }
        }
      });
    }
 
    pathStream.end();
  });
 
  return pathStream;
};
 
/**
 * Given a path pattern, return a stream of absolute paths for all tests that
 * match the pattern.
 *
 * @param {RegExp} pathPattern
 * @param {Function} onTestFound Callback called immediately when a test is
 *                               found.
 *
 *                               Ideally this function should return a
 *                               stream, but I don't personally understand all
 *                               the variations of "node streams" that exist in
 *                               the world (and their various compatibilities
 *                               with various node versions), so I've opted to
 *                               forgo that for now.
 * @return {Stream<String>} Stream of test-path strings
 */
TestRunner.prototype.streamTestPathsMatching = function(pathPattern) {
  var pathStream = through(
    function write(data) {
      if (data.isError) {
        this.emit('error', data);
        this.emit('end');
      } else {
        this.emit('data', data);
      }
    },
    function end() {
      this.emit('end');
    }
  );
 
  this._getModuleLoaderResourceMap().then(function(resourceMap) {
    var resourcePathMap = resourceMap.resourcePathMap;
    for (var i in resourcePathMap) {
      // Sometimes the loader finds a path with no resource. This typically
      // happens if a file is recently deleted.
      if (!resourcePathMap[i]) {
        continue;
      }
 
      var pathStr = resourcePathMap[i].path;
      if (
        this._isTestFilePath(pathStr) &&
        pathPattern.test(pathStr)
      ) {
        pathStream.write(pathStr);
      }
    }
    pathStream.end();
  }.bind(this));
 
 
  return pathStream;
};
 
/**
 * For use by external users of TestRunner as a means of optimization.
 *
 * Imagine the following scenario executing in a child worker process:
 *
 * var runner = new TestRunner(config, {
 *   moduleLoaderResourceMap: serializedResourceMap
 * });
 * someOtherAyncProcess.then(function() {
 *   runner.runTestsParallel();
 * });
 *
 * Here we wouldn't start deserializing the resource map (passed to us from the
 * parent) until runner.runTestsParallel() is called. At the time of this
 * writing, resource map deserialization is slow and a bottleneck on running the
 * first test in a child.
 *
 * So this API gives scenarios such as the one above an optimization path to
 * potentially start deserializing the resource map while we wait on the
 * someOtherAsyncProcess to resolve (rather that doing it after it's resolved).
 */
TestRunner.prototype.preloadResourceMap = function() {
  this._getModuleLoaderResourceMap().done();
};
 
TestRunner.prototype.preloadConfigDependencies = function() {
  this._loadConfigDependencies();
};
 
/**
 * Run the given single test file path.
 * This just contains logic for running a single test given it's file path.
 *
 * @param {String} testFilePath
 * @return {Promise<Object>} Results of the test
 */
TestRunner.prototype.runTest = function(testFilePath) {
  // Using Object.create() lets us adjust the config object locally without
  // worrying about the external consequences of changing the config object for
  // needs that are local to this particular function call
  var config = Object.create(this._config);
  var configDeps = this._loadConfigDependencies();
 
  var env = new configDeps.testEnvironment(config);
  var testRunner = configDeps.testRunner;
 
  // Capture and serialize console.{log|warning|error}s so they can be passed
  // around (such as through some channel back to a parent process)
  var consoleMessages = [];
  env.global.console = new Console(consoleMessages);
 
  return this._constructModuleLoader(env, config).then(function(moduleLoader) {
    // This is a kind of janky way to ensure that we only collect coverage
    // information on modules that are immediate dependencies of the test file.
    //
    // Collecting coverage info on more than that is often not useful as
    // *usually*, when one is looking for coverage info, one is only looking
    // for coverage info on the files under test. Since a test file is just a
    // regular old module that can depend on whatever other modules it likes,
    // it's usually pretty hard to tell which of those dependencies is/are the
    // "module(s)" under test.
    //
    // I'm not super happy with having to inject stuff into the config object
    // mid-stream here, but it gets the job done.
    if (config.collectCoverage && !config.collectCoverageOnlyFrom) {
      config.collectCoverageOnlyFrom = {};
      moduleLoader.getDependenciesFromPath(testFilePath)
        .filter(function(depPath) {
          // Skip over built-in and node modules
          return /^\//.test(depPath);
        }).forEach(function(depPath) {
          config.collectCoverageOnlyFrom[depPath] = true;
        });
    }
 
    if (config.setupEnvScriptFile) {
      utils.runContentWithLocalBindings(
        env.runSourceText.bind(env),
        utils.readAndPreprocessFileContent(config.setupEnvScriptFile, config),
        config.setupEnvScriptFile,
        {
          __dirname: path.dirname(config.setupEnvScriptFile),
          __filename: config.setupEnvScriptFile,
          global: env.global,
          require: moduleLoader.constructBoundRequire(
            config.setupEnvScriptFile
          )
        }
      );
    }
 
    var testExecStats = {start: Date.now()};
    return testRunner(config, env, moduleLoader, testFilePath)
      .then(function(results) {
        testExecStats.end = Date.now();
 
        results.logMessages = consoleMessages;
        results.perfStats = testExecStats;
        results.testFilePath = testFilePath;
        results.coverage =
          config.collectCoverage
          ? moduleLoader.getAllCoverageInfo()
          : {};
 
        return results;
      });
  }).finally(function() {
    env.dispose();
  });
};
 
/**
 * Run all given test paths.
 *
 * @param {Array<String>} testPaths Array of paths to test files
 * @param {Object} reporter Collection of callbacks called on test events
 * @return {Promise<Object>} Fulfilled with aggregate pass/fail information
 *                           about all tests that were run
 */
TestRunner.prototype.runTests = function(testPaths, reporter) {
  if (!reporter) {
    reporter = require('./defaultTestReporter');
  }
  var config = this._config;
 
  var aggregatedResults = {
    numFailedTests: 0,
    numPassedTests: 0,
    numTotalTests: testPaths.length,
    startTime: Date.now(),
    endTime: null
  };
 
  reporter.onRunStart && reporter.onRunStart(config, aggregatedResults);
 
  var onTestResult = function (testPath, testResult) {
    if (testResult.numFailingTests > 0) {
      aggregatedResults.numFailedTests++;
    } else {
      aggregatedResults.numPassedTests++;
    }
    reporter.onTestResult && reporter.onTestResult(
      config,
      testResult,
      aggregatedResults
    );
  };
 
  var onRunFailure = function (testPath, err) {
    aggregatedResults.numFailedTests++;
    reporter.onTestResult && reporter.onTestResult(config, {
      testFilePath: testPath,
      testExecError: err,
      suites: {},
      tests: {},
      logMessages: []
    }, aggregatedResults);
  };
 
  var testRun = this._createTestRun(testPaths, onTestResult, onRunFailure);
 
  return testRun.then(function() {
    aggregatedResults.endTime = Date.now();
    reporter.onRunComplete && reporter.onRunComplete(config, aggregatedResults);
    return aggregatedResults.numFailedTests === 0;
  });
};
 
TestRunner.prototype._createTestRun = function(
  testPaths, onTestResult, onRunFailure
) {
  if (this._opts.runInBand) {
    return this._createInBandTestRun(testPaths, onTestResult, onRunFailure);
  } else {
    return this._createParallelTestRun(testPaths, onTestResult, onRunFailure);
  }
};
 
TestRunner.prototype._createInBandTestRun = function(
  testPaths, onTestResult, onRunFailure
) {
  var testSequence = q();
  testPaths.forEach(function(testPath) {
    testSequence = testSequence.then(this.runTest.bind(this, testPath))
      .then(function(testResult) {
        onTestResult(testPath, testResult);
      })
      .catch(function(err) {
        onRunFailure(testPath, err);
      });
  }, this);
  return testSequence;
};
 
TestRunner.prototype._createParallelTestRun = function(
  testPaths, onTestResult, onRunFailure
) {
  var workerPool = new WorkerPool(
    this._opts.maxWorkers,
    this._opts.nodePath,
    this._opts.nodeArgv.concat([
      '--harmony',
      TEST_WORKER_PATH,
      '--config=' + JSON.stringify(this._config)
    ])
  );
 
  return this._getModuleLoaderResourceMap()
    .then(function() {
      // Tell all workers that it's now safe to read the resource map from disk.
      return workerPool.sendMessageToAllWorkers({
        resourceMapWrittenToDisk: true
      });
    })
    .then(function() {
      return q.all(testPaths.map(function(testPath) {
        return workerPool.sendMessage({testFilePath: testPath})
          .then(function(testResult) {
            onTestResult(testPath, testResult);
          })
          .catch(function(err) {
            onRunFailure(testPath, err);
 
            // Jest uses regular worker messages to initialize workers, so
            // there's no way for node-worker-pool to understand how to
            // recover/re-initialize a child worker that needs to be restarted.
            // (node-worker-pool can't distinguish between initialization
            // messages and ephemeral "normal" messages in order to replay the
            // initialization message upon booting the new, replacement worker
            // process).
            //
            // This is mostly a limitation of node-worker-pool's initialization
            // features, and ideally it would be possible to recover from a
            // test that causes a worker process to exit unexpectedly. However,
            // for now Jest will just fail hard if any child process exits
            // unexpectedly.
            //
            // This will likely bite me in the ass as an unbreak now if we hit
            // this issue again -- but I guess that's a faster failure than
            // having Jest just hang forever without any indication as to why.
            if (err.message
                && /Worker process exited before /.test(err.message)) {
              console.error(
                'A worker process has quit unexpectedly! This is bad news, ' +
                'shutting down now!'
              );
              process.exit(1);
            }
          });
      }));
    })
    .then(function() {
      return workerPool.destroy();
    });
};
 
module.exports = TestRunner;