This commit is contained in:
MishaBagger
2023-10-25 09:15:21 +03:00
commit b6c10cc93f
9828 changed files with 1446743 additions and 0 deletions

View File

@@ -0,0 +1,61 @@
(function() {
var withoutAsync = {};
["it", "beforeEach", "afterEach"].forEach(function(jasmineFunction) {
withoutAsync[jasmineFunction] = jasmine.Env.prototype[jasmineFunction];
return jasmine.Env.prototype[jasmineFunction] = function() {
var args = Array.prototype.slice.call(arguments, 0);
var timeout = null;
if (isLastArgumentATimeout(args)) {
timeout = args.pop();
// The changes to the jasmine test runner causes undef to be passed when
// calling all it()'s now. If the last argument isn't a timeout and the
// last argument IS undefined, let's just pop it off. Since out of bounds
// items are undefined anyways, *hopefully* removing an undef item won't
// hurt.
} else if (args[args.length-1] == undefined) {
args.pop();
}
if (isLastArgumentAnAsyncSpecFunction(args))
{
var specFunction = args.pop();
args.push(function() {
return asyncSpec(specFunction, this, timeout);
});
}
return withoutAsync[jasmineFunction].apply(this, args);
};
});
function isLastArgumentATimeout(args)
{
return args.length > 0 && (typeof args[args.length-1]) === "number";
}
function isLastArgumentAnAsyncSpecFunction(args)
{
return args.length > 0 && (typeof args[args.length-1]) === "function" && args[args.length-1].length > 0;
}
function asyncSpec(specFunction, spec, timeout) {
if (timeout == null) timeout = jasmine.getEnv().defaultTimeoutInterval || 1000;
var done = false;
spec.runs(function() {
try {
return specFunction.call(spec, function(error) {
done = true;
if (error != null) return spec.fail(error);
});
} catch (e) {
done = true;
throw e;
}
});
return spec.waitsFor(function() {
if (done === true) {
return true;
}
}, "spec to complete", timeout);
};
}).call(this);

View File

@@ -0,0 +1,118 @@
var walkdir = require('walkdir');
var collection = require('./spec-collection');
var path = require('path');
var fs = require('fs');
var child_process = require('child_process');
var gaze = require('gaze');
var _ = require('underscore');
var baseArgv = [];
for(var i = 0; i < process.argv.length; i++) {
if(process.argv[i] !== '--autotest') {
baseArgv.push(process.argv[i]);
}
}
var run_external = function(command, args, callback) {
var child = child_process.spawn(command, args);
child.stdout.on('data', function(data) {
process.stdout.write(data);
});
child.stderr.on('data', function(data) {
process.stderr.write(data);
});
if(typeof callback == 'function') {
child.on('exit', callback);
}
}
var last_run_successful = false;
var run_everything = function() {
// run the suite when it starts
var argv = [].concat(baseArgv);
run_external(argv.shift(), argv, function (code) {
last_run_successful = code === 0
});
}
exports.start = function(loadpaths, watchFolders, patterns) {
var watchPatterns;
loadpaths.forEach(function(loadpath){
// If loadpath is just a single file, we should just watch that file
stats = fs.statSync(loadpath);
if (stats.isFile()) {
watchPatterns = loadpath;
} else {
watchPatterns = patterns.map(function(p) {
return path.join(loadpath, p);
});
}
changedFunc = function(event, file) {
console.log(file + ' was changed');
var match = path.basename(file, path.extname(file)) + ".*";
match = match.replace(new RegExp("spec", "i"), "");
var argv = [].concat(baseArgv, ["--match", match]);
run_external(argv.shift(), argv, function(code) {
// run everything if we fixed some bugs
if(code == 0) {
if(!last_run_successful) {
run_everything();
}
} else {
last_run_successful = false;
}
});
}
// Vim seems to change a file multiple times, with non-scientific testing
// the only time we didn't duplicate the call to onChanged was at 2.5s
// Passing true to have onChanged run on the leading edge of the timeout
var onChanged = _.debounce(changedFunc, 2500, true);
gaze(watchPatterns, function(err, watcher) {
// Get all watched files
console.log("Watching for changes in " + loadpath);
// On file changed
this.on('all', onChanged);
});
});
watchFolders.forEach(function(watchPath) {
// If watchPath is just a single file, we should just watch that file
stats = fs.statSync(watchPath);
if (stats.isFile()) {
watchPatterns = watchPath;
} else {
watchPatterns = patterns.map(function(p) {
return path.join(watchPath, p);
});
}
// We debounce run_everything here due to the Vim issue described above.
var onChanged = _.debounce(run_everything, 2500, true);
gaze(watchPatterns, function(err, watcher) {
console.log("Watching for changes in " + watchPath);
this.on('all', onChanged);
});
});
run_everything();
};

287
6/node_modules/jasmine-node/lib/jasmine-node/cli.js generated vendored Normal file
View File

@@ -0,0 +1,287 @@
var util,
Path= require('path'),
fs = require('fs');
var jasmine = require('./index');
try {
util = require('util')
} catch(e) {
util = require('sys')
}
var helperCollection = require('./spec-collection');
var specFolders = [];
var watchFolders = [];
// The following line keeps the jasmine setTimeout in the proper scope
jasmine.setTimeout = jasmine.getGlobal().setTimeout;
jasmine.setInterval = jasmine.getGlobal().setInterval;
for (var key in jasmine)
global[key] = jasmine[key];
var isVerbose = false;
var showColors = true;
// Disable if we're not on a TTY
if (!process.stdout.isTTY) {
showColors = false;
}
var teamcity = process.env.TEAMCITY_PROJECT_NAME || false;
var useRequireJs = false;
var extensions = "js";
var match = '.';
var matchall = false;
var autotest = false;
var useHelpers = true;
var forceExit = false;
var captureExceptions = false;
var includeStackTrace = true;
var growl = false;
var junitreport = {
report: false,
savePath : "./reports/",
useDotNotation: true,
consolidate: true
}
var args = process.argv.slice(2);
var existsSync = fs.existsSync || Path.existsSync;
while(args.length) {
var arg = args.shift();
switch(arg)
{
case '--version':
printVersion();
case '--color':
showColors = true;
break;
case '--noColor':
case '--nocolor':
showColors = false;
break;
case '--verbose':
isVerbose = true;
break;
case '--coffee':
try {
require('coffeescript/register'); // support CoffeeScript >=1.7.0
} catch ( e ) {
require('coffeescript'); // support CoffeeScript <=1.6.3
}
extensions = "js|coffee|litcoffee";
break;
case '-m':
case '--match':
match = args.shift();
break;
case '--matchall':
matchall = true;
break;
case '--junitreport':
junitreport.report = true;
break;
case '--output':
junitreport.savePath = args.shift();
break;
case '--teamcity':
teamcity = true;
break;
case '--requireJsSetup':
var setup = args.shift();
if(!existsSync(setup))
throw new Error("RequireJS setup '" + setup + "' doesn't exist!");
useRequireJs = setup;
break;
case '--runWithRequireJs':
useRequireJs = useRequireJs || true;
break;
case '--nohelpers':
useHelpers = false;
break;
case '--test-dir':
var dir = args.shift();
if(!existsSync(dir))
throw new Error("Test root path '" + dir + "' doesn't exist!");
specFolders.push(dir); // NOTE: Does not look from current working directory.
break;
case '--autotest':
autotest = true;
break;
case '--watch':
var nextWatchDir;
// Add the following arguments, until we see another argument starting with '-'
while (args[0] && args[0][0] !== '-') {
nextWatchDir = args.shift();
watchFolders.push(nextWatchDir);
if (!existsSync(nextWatchDir))
throw new Error("Watch path '" + nextWatchDir + "' doesn't exist!");
}
break;
case '--forceexit':
forceExit = true;
break;
case '--captureExceptions':
captureExceptions = true;
break;
case '--noStack':
includeStackTrace = false;
break;
case '--growl':
growl = true;
break;
case '--config':
var configKey = args.shift();
var configValue = args.shift();
process.env[configKey]=configValue;
break;
case '-h':
help();
default:
if (arg.match(/^--params=.*/)) {
break;
}
if (arg.match(/^--/)) help();
if (arg.match(/^\/.*/)) {
specFolders.push(arg);
} else {
specFolders.push(Path.join(process.cwd(), arg));
}
break;
}
}
if (specFolders.length === 0) {
help();
} else {
// Check to see if all our files exist
for (var idx = 0; idx < specFolders.length; idx++) {
if (!existsSync(specFolders[idx])) {
console.log("File: " + specFolders[idx] + " is missing.");
return;
}
}
}
if (autotest) {
var patterns = ['**/*.js'];
if (extensions.indexOf("coffee") !== -1) {
patterns.push('**/*.coffee');
}
require('./autotest').start(specFolders, watchFolders, patterns);
return;
}
var exitCode = 0;
if (captureExceptions) {
process.on('uncaughtException', function(e) {
console.error(e.stack || e);
exitCode = 1;
process.exit(exitCode);
});
}
process.on("exit", onExit);
function onExit() {
process.removeListener("exit", onExit);
process.exit(exitCode);
}
var onComplete = function(runner, log) {
process.stdout.write('\n');
if (runner.results().failedCount == 0) {
exitCode = 0;
} else {
exitCode = 1;
}
if (forceExit) {
process.exit(exitCode);
}
};
if(useHelpers){
specFolders.forEach(function(path){
jasmine.loadHelpersInFolder(path,
new RegExp("helpers?\\.(" + extensions + ")$", 'i'));
})
}
try {
var regExpSpec = new RegExp(match + (matchall ? "" : "spec\\.") + "(" + extensions + ")$", 'i')
} catch (error) {
console.error("Failed to build spec-matching regex: " + error);
process.exit(2);
}
var options = {
specFolders: specFolders,
onComplete: onComplete,
isVerbose: isVerbose,
showColors: showColors,
teamcity: teamcity,
useRequireJs: useRequireJs,
regExpSpec: regExpSpec,
junitreport: junitreport,
includeStackTrace: includeStackTrace,
growl: growl
}
jasmine.executeSpecsInFolder(options);
function help(){
process.stdout.write([
'USAGE: jasmine-node [--color|--noColor] [--verbose] [--coffee] directory'
, ''
, 'Options:'
, ' --autotest - rerun automatically the specs when a file changes'
, ' --watch PATH - when used with --autotest, watches the given path(s) and runs all tests if a change is detected'
, ' --color - use color coding for output'
, ' --noColor - do not use color coding for output'
, ' -m, --match REGEXP - load only specs containing "REGEXPspec"'
, ' --matchall - relax requirement of "spec" in spec file names'
, ' --verbose - print extra information per each test run'
, ' --coffee - load coffeescript which allows execution .coffee files'
, ' --junitreport - export tests results as junitreport xml format'
, ' --output - defines the output folder for junitreport files'
, ' --teamcity - converts all console output to teamcity custom test runner commands. (Normally auto detected.)'
, ' --growl - display test run summary in a growl notification (in addition to other outputs)'
, ' --runWithRequireJs - loads all specs using requirejs instead of node\'s native require method'
, ' --requireJsSetup - file run before specs to include and configure RequireJS'
, ' --test-dir - the absolute root directory path where tests are located'
, ' --nohelpers - does not load helpers.'
, ' --forceexit - force exit once tests complete.'
, ' --captureExceptions- listen to global exceptions, report them and exit (interferes with Domains)'
, ' --config NAME VALUE- set a global variable in process.env'
, ' --noStack - suppress the stack trace generated from a test failure'
, ' --version - show the current version'
, ' -h, --help - display this help and exit'
, ''
].join("\n"));
process.exit(-1);
}
function printVersion(){
const package = require(__dirname + '/../../package.json')
console.log(package.version);
process.exit(0);
}

160
6/node_modules/jasmine-node/lib/jasmine-node/cs.js generated vendored Normal file
View File

@@ -0,0 +1,160 @@
/**
* @license cs 0.4.2 Copyright (c) 2010-2011, The Dojo Foundation All Rights Reserved.
* Available via the MIT or new BSD license.
* see: http://github.com/jrburke/require-cs for details
*/
/*jslint */
/*global define, window, XMLHttpRequest, importScripts, Packages, java,
ActiveXObject, process, require */
define(['coffeescript'], function (CoffeeScript) {
'use strict';
var fs, getXhr,
progIds = ['Msxml2.XMLHTTP', 'Microsoft.XMLHTTP', 'Msxml2.XMLHTTP.4.0'],
fetchText = function () {
throw new Error('Environment unsupported.');
},
buildMap = {};
if (typeof process !== "undefined" &&
process.versions &&
!!process.versions.node) {
//Using special require.nodeRequire, something added by r.js.
fs = require.nodeRequire('fs');
fetchText = function (path, callback) {
callback(fs.readFileSync(path, 'utf8'));
};
} else if ((typeof window !== "undefined" && window.navigator && window.document) || typeof importScripts !== "undefined") {
// Browser action
getXhr = function () {
//Would love to dump the ActiveX crap in here. Need IE 6 to die first.
var xhr, i, progId;
if (typeof XMLHttpRequest !== "undefined") {
return new XMLHttpRequest();
} else {
for (i = 0; i < 3; i++) {
progId = progIds[i];
try {
xhr = new ActiveXObject(progId);
} catch (e) {}
if (xhr) {
progIds = [progId]; // so faster next time
break;
}
}
}
if (!xhr) {
throw new Error("getXhr(): XMLHttpRequest not available");
}
return xhr;
};
fetchText = function (url, callback) {
var xhr = getXhr();
xhr.open('GET', url, true);
xhr.onreadystatechange = function (evt) {
//Do not explicitly handle errors, those should be
//visible via console output in the browser.
if (xhr.readyState === 4) {
callback(xhr.responseText);
}
};
xhr.send(null);
};
// end browser.js adapters
} else if (typeof Packages !== 'undefined') {
//Why Java, why is this so awkward?
fetchText = function (path, callback) {
var encoding = "utf-8",
file = new java.io.File(path),
lineSeparator = java.lang.System.getProperty("line.separator"),
input = new java.io.BufferedReader(new java.io.InputStreamReader(new java.io.FileInputStream(file), encoding)),
stringBuffer, line,
content = '';
try {
stringBuffer = new java.lang.StringBuffer();
line = input.readLine();
// Byte Order Mark (BOM) - The Unicode Standard, version 3.0, page 324
// http://www.unicode.org/faq/utf_bom.html
// Note that when we use utf-8, the BOM should appear as "EF BB BF", but it doesn't due to this bug in the JDK:
// http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=4508058
if (line && line.length() && line.charAt(0) === 0xfeff) {
// Eat the BOM, since we've already found the encoding on this file,
// and we plan to concatenating this buffer with others; the BOM should
// only appear at the top of a file.
line = line.substring(1);
}
stringBuffer.append(line);
while ((line = input.readLine()) !== null) {
stringBuffer.append(lineSeparator);
stringBuffer.append(line);
}
//Make sure we return a JavaScript string and not a Java string.
content = String(stringBuffer.toString()); //String
} finally {
input.close();
}
callback(content);
};
}
return {
get: function () {
return CoffeeScript;
},
write: function (pluginName, name, write) {
if (buildMap.hasOwnProperty(name)) {
var text = buildMap[name];
write.asModule(pluginName + "!" + name, text);
}
},
version: '0.4.2',
load: function (name, parentRequire, load, config) {
var path = parentRequire.toUrl(name + '.coffee');
fetchText(path, function (text) {
//Do CoffeeScript transform.
try {
text = CoffeeScript.compile(text, config.CoffeeScript);
}
catch (err) {
err.message = "In " + path + ", " + err.message;
throw(err);
}
//Hold on to the transformed text if a build.
if (config.isBuild) {
buildMap[name] = text;
}
//IE with conditional comments on cannot handle the
//sourceURL trick, so skip it if enabled.
/*@if (@_jscript) @else @*/
if (!config.isBuild) {
text += "\r\n//@ sourceURL=" + path;
}
/*@end@*/
load.fromText(name, text);
//Give result to load. Need to wait until the module
//is fully parse, which will happen after this
//execution.
parentRequire([name], function (value) {
load(value);
});
});
}
};
});

204
6/node_modules/jasmine-node/lib/jasmine-node/index.js generated vendored Normal file
View File

@@ -0,0 +1,204 @@
var fs = require('fs');
var mkdirp = require('mkdirp');
var util;
try {
util = require('util')
} catch(e) {
util = require('sys')
}
var path = require('path');
var filename = __dirname + '/jasmine-1.3.1.js';
var isWindowUndefined = typeof global.window === 'undefined';
if (isWindowUndefined) {
global.window = {
setTimeout: setTimeout,
clearTimeout: clearTimeout,
setInterval: setInterval,
clearInterval: clearInterval
};
}
var src = fs.readFileSync(filename);
// Put jasmine in the global context, this is somewhat like running in a
// browser where every file will have access to `jasmine`
var jasmine = require('vm').runInThisContext(src + "\njasmine;", filename);
if (isWindowUndefined) {
delete global.window;
}
require("./async-callback");
require("jasmine-reporters");
var nodeReporters = require('./reporter').jasmineNode;
jasmine.TerminalVerboseReporter = nodeReporters.TerminalVerboseReporter;
jasmine.TerminalReporter = nodeReporters.TerminalReporter;
jasmine.TeamcityReporter = nodeReporters.TeamcityReporter;
jasmine.GrowlReporter = require('jasmine-growl-reporter');
jasmine.loadHelpersInFolder = function(folder, matcher) {
// Check to see if the folder is actually a file, if so, back up to the
// parent directory and find some helpers
folderStats = fs.statSync(folder);
if (folderStats.isFile()) {
folder = path.dirname(folder);
}
var helpers = [],
helperCollection = require('./spec-collection');
helperCollection.load([folder], matcher);
helpers = helperCollection.getSpecs();
for (var i = 0, len = helpers.length; i < len; ++i) {
var file = helpers[i].path();
try {
var helper = require(file.replace(/\.*$/, ""));
} catch (e) {
console.log("Exception loading helper: " + file)
console.log(e);
throw e; // If any of the helpers fail to load, fail everything
}
for (var key in helper) {
global[key]= helper[key];
}
}
};
function removeJasmineFrames(text) {
if (!text) {
return text;
}
var lines = [];
text.split(/\n/).forEach(function(line){
if (line.indexOf(filename) == -1) {
lines.push(line);
}
});
return lines.join('\n');
}
jasmine.executeSpecsInFolder = function(options){
var folders = options['specFolders'];
var done = options['onComplete'];
var isVerbose = options['isVerbose'];
var showColors = options['showColors'];
var teamcity = options['teamcity'];
var useRequireJs = options['useRequireJs'];
var matcher = options['regExpSpec'];
var junitreport = options['junitreport'];
var includeStackTrace = options['includeStackTrace'];
var growl = options['growl'];
// Overwriting it allows us to handle custom async specs
it = function(desc, func, timeout) {
return jasmine.getEnv().it(desc, func, timeout);
}
beforeEach = function(func, timeout) {
return jasmine.getEnv().beforeEach(func, timeout);
}
afterEach = function(func, timeout) {
return jasmine.getEnv().afterEach(func, timeout);
}
var fileMatcher = matcher || new RegExp(".(js)$", "i"),
colors = showColors || false,
specs = require('./spec-collection'),
jasmineEnv = jasmine.getEnv();
specs.load(folders, fileMatcher);
if(junitreport && junitreport.report) {
var existsSync = fs.existsSync || path.existsSync;
if(!existsSync(junitreport.savePath)) {
console.log('creating junit xml report save path: ' + junitreport.savePath);
mkdirp.sync(junitreport.savePath, "0755");
}
jasmineEnv.addReporter(new jasmine.JUnitXmlReporter(junitreport.savePath,
junitreport.consolidate,
junitreport.useDotNotation));
}
if(teamcity){
jasmineEnv.addReporter(new jasmine.TeamcityReporter({onComplete: done}));
} else if(isVerbose) {
jasmineEnv.addReporter(new jasmine.TerminalVerboseReporter({ print: print,
color: showColors,
onComplete: done,
stackFilter: removeJasmineFrames}));
} else {
jasmineEnv.addReporter(new jasmine.TerminalReporter({print: print,
color: showColors,
includeStackTrace: includeStackTrace,
onComplete: done,
stackFilter: removeJasmineFrames}));
}
if (growl) {
jasmineEnv.addReporter(new jasmine.GrowlReporter());
}
if (useRequireJs) {
require('./requirejs-runner').executeJsRunner(
specs,
done,
jasmineEnv,
typeof useRequireJs === 'string' ? useRequireJs : null
);
} else {
var specsList = specs.getSpecs();
for (var i = 0, len = specsList.length; i < len; ++i) {
var filename = specsList[i];
delete require.cache[filename.path()];
// Catch exceptions in loading the spec
try {
require(filename.path().replace(/\.\w+$/, ""));
} catch (e) {
console.log("Exception loading: " + filename.path());
console.log(e);
throw e;
}
}
jasmineEnv.execute();
}
};
function now(){
return new Date().getTime();
}
jasmine.asyncSpecWait = function(){
var wait = jasmine.asyncSpecWait;
wait.start = now();
wait.done = false;
(function innerWait(){
waits(10);
runs(function() {
if (wait.start + wait.timeout < now()) {
expect('timeout waiting for spec').toBeNull();
} else if (wait.done) {
wait.done = false;
} else {
innerWait();
}
});
})();
};
jasmine.asyncSpecWait.timeout = 4 * 1000;
jasmine.asyncSpecDone = function(){
jasmine.asyncSpecWait.done = true;
};
function print(str) {
process.stdout.write(util.format(str));
}
for ( var key in jasmine) {
exports[key] = jasmine[key];
}

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,342 @@
(function() {
//
// Imports
//
var util;
try {
util = require('util')
} catch(e) {
util = require('sys')
}
var jasmineNode = {};
//
// Helpers
//
function noop() {}
jasmineNode.TerminalReporter = function(config) {
this.print_ = config.print || function (str) { process.stdout.write(util.format(str)); };
this.color_ = config.color ? this.ANSIColors : this.NoColors;
this.started_ = false;
this.finished_ = false;
this.callback_ = config.onComplete || false
this.suites_ = [];
this.specResults_ = {};
this.failures_ = [];
this.includeStackTrace_ = config.includeStackTrace === false ? false : true;
this.stackFilter_ = config.stackFilter || function(t) { return t; };
}
jasmineNode.TerminalReporter.prototype = {
reportRunnerStarting: function(runner) {
this.started_ = true;
this.startedAt = new Date();
var suites = runner.topLevelSuites();
for (var i = 0; i < suites.length; i++) {
var suite = suites[i];
this.suites_.push(this.summarize_(suite));
}
},
ANSIColors: {
pass: function() { return '\033[32m'; }, // Green
fail: function() { return '\033[31m'; }, // Red
specTiming: function() { return '\033[34m'; }, // Blue
suiteTiming: function() { return '\033[33m'; }, // Yelow
ignore: function() { return '\033[37m'; }, // Light Gray
neutral: function() { return '\033[0m'; } // Normal
},
NoColors: {
pass: function() { return ''; },
fail: function() { return ''; },
specTiming: function() { return ''; },
suiteTiming: function() { return ''; },
ignore: function() { return ''; },
neutral: function() { return ''; }
},
summarize_: function(suiteOrSpec) {
var isSuite = suiteOrSpec instanceof jasmine.Suite;
// We could use a separate object for suite and spec
var summary = {
id: suiteOrSpec.id,
name: suiteOrSpec.description,
type: isSuite? 'suite' : 'spec',
suiteNestingLevel: 0,
children: []
};
if (isSuite) {
var calculateNestingLevel = function(examinedSuite) {
var nestingLevel = 0;
while (examinedSuite.parentSuite !== null) {
nestingLevel += 1;
examinedSuite = examinedSuite.parentSuite;
}
return nestingLevel;
};
summary.suiteNestingLevel = calculateNestingLevel(suiteOrSpec);
var children = suiteOrSpec.children();
for (var i = 0; i < children.length; i++) {
summary.children.push(this.summarize_(children[i]));
}
}
return summary;
},
// This is heavily influenced by Jasmine's Html/Trivial Reporter
reportRunnerResults: function(runner) {
this.reportFailures_();
var results = runner.results();
var resultColor = (results.failedCount > 0) ? this.color_.fail() : this.color_.pass();
var specs = runner.specs();
var specCount = specs.length;
var message = "\n\nFinished in " + ((new Date().getTime() - this.startedAt.getTime()) / 1000) + " seconds";
this.printLine_(message);
// This is what jasmine-html.js has
//message = "" + specCount + " spec" + ( specCount === 1 ? "" : "s" ) + ", " + results.failedCount + " failure" + ((results.failedCount === 1) ? "" : "s");
this.printLine_(this.stringWithColor_(this.printRunnerResults_(runner), resultColor));
this.finished_ = true;
if(this.callback_) { this.callback_(runner); }
},
reportFailures_: function() {
if (this.failures_.length === 0) {
return;
}
var indent = ' ', failure;
this.printLine_('\n');
this.print_('Failures:');
for (var i = 0; i < this.failures_.length; i++) {
failure = this.failures_[i];
this.printLine_('\n');
this.printLine_(' ' + (i + 1) + ') ' + failure.spec);
this.printLine_(' Message:');
this.printLine_(' ' + this.stringWithColor_(failure.message, this.color_.fail()));
if (this.includeStackTrace_) {
this.printLine_(' Stacktrace:');
this.print_(' ' + this.stackFilter_(failure.stackTrace));
}
}
},
reportSuiteResults: function(suite) {
// Not used in this context
},
reportSpecResults: function(spec) {
var result = spec.results();
var msg = '';
if (result.skipped) {
msg = this.stringWithColor_('-', this.color_.ignore());
} else if (result.passed()) {
msg = this.stringWithColor_('.', this.color_.pass());
} else {
msg = this.stringWithColor_('F', this.color_.fail());
this.addFailureToFailures_(spec);
}
this.spec_results += msg;
this.print_(msg);
},
addFailureToFailures_: function(spec) {
var result = spec.results();
var failureItem = null;
var items_length = result.items_.length;
for (var i = 0; i < items_length; i++) {
if (result.items_[i].passed_ === false) {
failureItem = result.items_[i];
var failure = {
spec: spec.suite.getFullName() + " " + spec.description,
message: failureItem.message,
stackTrace: failureItem.trace.stack
}
this.failures_.push(failure);
}
}
},
printRunnerResults_: function(runner){
var results = runner.results();
var specs = runner.specs();
var msg = '';
var skippedCount = 0;
specs.forEach(function(spec) {
if (spec.results().skipped) {
skippedCount++;
}
});
var passedCount = specs.length - skippedCount;
msg += passedCount + ' test' + ((passedCount === 1) ? '' : 's') + ', ';
msg += results.totalCount + ' assertion' + ((results.totalCount === 1) ? '' : 's') + ', ';
msg += results.failedCount + ' failure' + ((results.failedCount === 1) ? '' : 's') + ', ';
msg += skippedCount + ' skipped' + '\n';
return msg;
},
// Helper Methods //
stringWithColor_: function(stringValue, color) {
return (color || this.color_.neutral()) + stringValue + this.color_.neutral();
},
printLine_: function(stringValue) {
this.print_(stringValue);
this.print_('\n');
}
};
// ***************************************************************
// TerminalVerboseReporter uses the TerminalReporter's constructor
// ***************************************************************
jasmineNode.TerminalVerboseReporter = function(config) {
jasmineNode.TerminalReporter.call(this, config);
// The extra field in this object
this.indent_ = 0;
this.specTimes_ = {};
this.suiteTimes_ = {};
this.suiteResults_ = {};
}
jasmineNode.TerminalVerboseReporter.prototype = {
reportSpecStarting: function(spec) {
now = new Date().getTime();
this.specTimes_[spec.id] = now;
var suite = spec.suite;
while (suite) {
if (!this.suiteTimes_[suite.id]) {
this.suiteTimes_[suite.id] = now;
}
suite = suite.parentSuite;
}
},
reportSpecResults: function(spec) {
var elapsed = new Date().getTime() - this.specTimes_[spec.id];
if (spec.results().failedCount > 0) {
this.addFailureToFailures_(spec);
}
this.specResults_[spec.id] = {
messages: spec.results().getItems(),
result: spec.results().failedCount > 0 ? 'failed' : 'passed',
runtime: elapsed
};
},
reportSuiteResults: function(suite) {
var startTime = this.suiteTimes_[suite.id];
if (startTime) {
var elapsed = new Date().getTime() - startTime;
this.suiteResults_[suite.id] = {
runtime: elapsed
};
}
},
reportRunnerResults: function(runner) {
var messages = new Array();
this.buildMessagesFromResults_(messages, this.suites_);
var messages_length = messages.length;
for (var i = 0; i < messages_length-1; i++) {
this.printLine_(messages[i]);
}
this.print_(messages[messages_length-1]);
// Call the parent object's method
jasmineNode.TerminalReporter.prototype.reportRunnerResults.call(this, runner);
},
buildMessagesFromResults_: function(messages, results, depth) {
var element, specResult, specIndentSpaces, msg = '';
depth = (depth === undefined) ? 0 : depth;
var results_length = results.length;
for (var i = 0; i < results_length; i++) {
element = results[i];
if (element.type === 'spec') {
specResult = this.specResults_[element.id.toString()];
if (specResult.result === 'passed') {
msg = this.stringWithColor_(this.indentMessage_(element.name, depth), this.color_.pass());
} else {
msg = this.stringWithColor_(this.indentMessage_(element.name, depth), this.color_.fail());
}
msg += this.stringWithColor_(" - " + specResult.runtime + " ms",
this.color_.specTiming());
messages.push(msg);
} else {
messages.push('');
msg = this.indentMessage_(element.name, depth)
if (element.id != null) {
suiteResult = this.suiteResults_[element.id.toString()];
if (suiteResult) {
msg += this.stringWithColor_(" - " + suiteResult.runtime + " ms", this.color_.suiteTiming());
}
}
messages.push(msg);
}
this.buildMessagesFromResults_(messages, element.children, depth + 2);
}
},
indentMessage_: function(message, indentCount) {
var _indent = '';
for (var i = 0; i < indentCount; i++) {
_indent += ' ';
}
return (_indent + message);
}
};
// Inherit from TerminalReporter
jasmineNode.TerminalVerboseReporter.prototype.__proto__ = jasmineNode.TerminalReporter.prototype;
// Extend Teamcity Reporter
jasmineNode.TeamcityReporter = function(config) {
var callback_ = config.onComplete || false;
(function(superFn) {
jasmineNode.TeamcityReporter.prototype.reportRunnerResults = function(runner) {
superFn.call(this, runner);
if (callback_) {callback_(runner)}
}
}(jasmine.TeamcityReporter.prototype.reportRunnerResults));
};
jasmineNode.TeamcityReporter.prototype = new jasmine.TeamcityReporter;
//
// Exports
//
exports.jasmineNode = jasmineNode;
})();

View File

@@ -0,0 +1,86 @@
exports.executeJsRunner = function(specCollection, done, jasmineEnv, setupFile) {
var specs,
specLoader = require('./requirejs-spec-loader'),
requirejs = require('requirejs'),
vm = require('vm'),
fs = require('fs'),
coffeescript = require('coffeescript'),
template = fs.readFileSync(
setupFile || (__dirname + '/requirejs-wrapper-template.js'),
'utf8'
),
ensureUnixPath = function(path){
return path.replace(/^(.):/, '/$1').replace(/\\/g, '/');
},
buildNewContext = function(spec){
var context = {
describe: describe,
it: it,
xdescribe: xdescribe,
xit: xit,
beforeEach: beforeEach,
afterEach: afterEach,
spyOn: spyOn,
waitsFor: waitsFor,
waits: waits,
runs: runs,
jasmine: jasmine,
expect: expect,
require: require,
console: console,
process: process,
module: module,
specLoader: specLoader,
__dirname: spec.directory(),
__filename: spec.path(),
baseUrl: buildRelativeDirName(spec.directory()),
csPath: __dirname + '/cs'
};
context.global = context;
return context;
},
buildRelativeDirName = function(dir){
var retVal = "",
thisDir = ensureUnixPath(process.cwd()),
toDir = ensureUnixPath(dir).split('/'),
index = 0;
thisDir = thisDir.split('/');
for(; index < thisDir.length || index < toDir.length; index++) {
if(thisDir[index] != toDir[index]){
for(var i = index; i < thisDir.length-1; i++){
retVal += '../';
}
for(var i = index; i < toDir.length; i++){
retVal += toDir[i] + '/';
}
break;
}
}
return retVal.trim('/');
};
specCollection.getSpecs().forEach(function(s){
var script = fs.readFileSync(s.path(), 'utf8');
if (s.filename().substr(-6).toLowerCase() == 'coffee') {
script = coffeescript.compile(script);
}
var newContext = buildNewContext(s);
newContext.setTimeout = jasmine.getGlobal().setTimeout;
newContext.setInterval = jasmine.getGlobal().setInterval;
var vmContext = vm.createContext(newContext);
vm.runInContext(template, vmContext);
vm.runInContext(script, vmContext, s.path());
});
specLoader.executeWhenAllSpecsAreComplete(jasmineEnv);
};

View File

@@ -0,0 +1,48 @@
var _ = require('underscore'),
registry = {},
timeout = 120000,
now = function() {
return new Date().getTime();
},
loader = {
register: function(name) {
registry[name] = false;
},
completed: function(name){
registry[name] = true;
}
},
specLoader = {
defineLoader: function(requirejs) {
requirejs.define('jasmine-spec-loader', function() {
return loader;
});
},
executeWhenAllSpecsAreComplete: function(jasmineEnv) {
var allComplete = false,
wait = now(),
timeoutCallback = function() {
allComplete = _.all(registry, function(value) {
return value;
});
if(!allComplete && wait + timeout > now()) {
setTimeout(timeoutCallback, 100);
} else if (!allComplete) {
console.log('Failed to load all specs within timeout window.');
process.exit(-1);
} else {
jasmineEnv.execute();
}
};
setTimeout(timeoutCallback, 100);
},
setTimeoutInterval: function(value) {
timeout = value;
},
};
for(var key in specLoader) {
exports[key] = specLoader[key];
}

View File

@@ -0,0 +1,78 @@
/* Setup file run before spec files to setup the context (and RequireJS
* specifically) to execute the spec file.
*
* Defined by caller:
* - Jasmine predefines
* - require (Node require)
* - __dirname, __filename
* - baseUrl (Relative path to the directory containing this file)
* - csPath (Path to require-cs module)
*
* See requirejs-runner source for full invocation details.
*/
var define,
requirejsOrig = require('requirejs'),
ostring = Object.prototype.toString,
path = require('path'),
isArray = function(it){
return ostring.call(it) === '[object Array]';
},
isFunction = function(it){
return ostring.call(it) === '[object Function]';
},
requirejs = function(deps, callback){
var retVal;
if(!isArray(deps) && typeof deps !== 'string'){
if(isArray(callback)){
retVal = requirejsOrig(deps, callback, arguments[2]);
} else {
retVal = requirejsOrig(deps, [], callback);
}
} else {
retVal = requirejsOrig(deps, callback);
}
return retVal;
};
requirejsOrig.config({
baseUrl: baseUrl,
nodeRequire: require,
paths: {
cs: csPath
}
});
for(var key in requirejsOrig) {
requirejs[key] = requirejsOrig[key];
}
requirejs.config = function(config){
var alteredConfig = {};
for(var key in config) {
alteredConfig[key] = config[key];
}
if(alteredConfig.baseUrl){
var base = baseUrl.replace(/\\/g, '/'),
splitUrl = alteredConfig.baseUrl.replace(/\\/g, '/').split('/'),
index = 0;
for(; index < splitUrl.length; index++){
if(splitUrl[index] === '..'){
base = path.dirname(base);
} else {
base += '/' + splitUrl[index];
}
}
alteredConfig.baseUrl = base;
}
return requirejsOrig.config(alteredConfig);
};
require = requirejs;
define = requirejs.define;

View File

@@ -0,0 +1,44 @@
var walkdir = require('walkdir');
var path = require('path');
var fs = require('fs');
var specs;
var createSpecObj = function(path, root) {
return {
path: function() { return path; },
relativePath: function() { return path.replace(root, '').replace(/^[\/\\]/, '').replace(/\\/g, '/'); },
directory: function() { return path.replace(/[\/\\][\s\w\.-]*$/, "").replace(/\\/g, '/'); },
relativeDirectory: function() { return relativePath().replace(/[\/\\][\s\w\.-]*$/, "").replace(/\\/g, '/'); },
filename: function() { return path.replace(/^.*[\\\/]/, ''); }
};
};
exports.load = function(loadpaths, matcher) {
var wannaBeSpecs = []
specs = [];
loadpaths.forEach(function(loadpath){
wannaBeSpecs = walkdir.sync(loadpath, { follow_symlinks: true });
for (var i = 0; i < wannaBeSpecs.length; i++) {
var file = wannaBeSpecs[i];
try {
if (fs.statSync(file).isFile()) {
if (!/.*node_modules.*/.test(path.relative(loadpath, file)) &
matcher.test(path.basename(file))) {
specs.push(createSpecObj(file));
}
}
} catch(e) {
// nothing to do here
}
}
});
};
exports.getSpecs = function() {
// Sorts spec paths in ascending alphabetical order to be able to
// run tests in a deterministic order.
specs.sort(function(a, b) {
return a.path().localeCompare(b.path());
});
return specs;
};