<commit_before>window.WebSQL_driver = function () {

	var db = null;
	var ddl = [];

	var nativeSQLite = (window.openDatabase !== undefined);

	var splitStatement = function (statements)
	{
		return statements ? statements.split(/;\s*\r?\n|$/) : [];
	}

	this.buildSchema = function (args) {
		try {

			if (nativeSQLite)
			{
				db = openDatabase(args["short_code"], '1.0', args["short_code"], args["ddl"].length * 1024);

				db.transaction(function(tx){

					var statements = splitStatement(args["ddl"]);
					ddl = statements;

					// $.each(splitStatement(args["ddl"]), function (i, stmt) { statements.push(stmt); });

					var currentStatement = 0;
					var statement = statements[currentStatement];

					var sequentiallyExecute = function(tx2, result){
						if (currentStatement < statements.length-1)
						{
							currentStatement++;
							statement = statements[currentStatement];

							tx.executeSql(statement, [], sequentiallyExecute, handleFailure);

						}
						else
						{
							tx.executeSql("intentional failure used to rollback transaction");
							args["success"]();
						}
					};

					var handleFailure = function (tx2, result) {
						args["error"](result.message);

					};

					tx.executeSql(statement, [],
						sequentiallyExecute,
						handleFailure
					);

				});

			}
			else
			{
				args["error"]("SQLite (WebSQL) not available in your browser. Try either using a webkit-based browser (such as Safari or Chrome) or using the SQLite (SQL.js) database type.")
			}

		}
		catch (e)
		{
			args["error"](e);
		}

	}

	this.executeQuery = function (args) {

		try {

			if (!db) {
				throw ("Database Schema not available!");
			}

			var returnSets = [];

			db.transaction(function(tx){

				var sequentiallyExecute = function(tx2, result) {

					var thisSet = {
						"SUCCEEDED": true,
						"EXECUTIONTIME": (new Date()) - startTime,
						"RESULTS": {
							"COLUMNS": [],
							"DATA": []
						},
						"EXECUTIONPLAN": {
							"COLUMNS": [],
							"DATA": []
						}

					};

					for (var i = 0; i < result.rows.length; i++) {
						var rowVals = [];
						var item = result.rows.item(i);

						/* We can't be sure about the order of the columns returned, since they are returned as
						 * a simple unordered structure. So, we'll just take the order returned the from the first
						 * request, then just use that order for each row.
						 */
						if (i == 0) {
							for (col in item) {
								thisSet["RESULTS"]["COLUMNS"].push(col);
							}
						}

						for (var j = 0; j < thisSet["RESULTS"]["COLUMNS"].length; j++) {
							rowVals.push(item[thisSet["RESULTS"]["COLUMNS"][j]]);
						}

						thisSet["RESULTS"]["DATA"].push(rowVals);
					}

					tx.executeSql("EXPLAIN QUERY PLAN " + statement, [], function (tx3, executionPlanResult) {

						for (var l = 0; l < executionPlanResult.rows.length; l++) {
							var rowVals = [];
							var item = executionPlanResult.rows.item(l);

							/* We can't be sure about the order of the columns returned, since they are returned as
							 * a simple unordered structure. So, we'll just take the order returned the from the first
							 * request, then just use that order for each row.
							 */
							if (l == 0) {
								for (col in item) {
									thisSet["EXECUTIONPLAN"]["COLUMNS"].push(col);
								}
							}

							for (var j = 0; j < thisSet["EXECUTIONPLAN"]["COLUMNS"].length; j++) {
								rowVals.push(item[thisSet["EXECUTIONPLAN"]["COLUMNS"][j]]);
							}

							thisSet["EXECUTIONPLAN"]["DATA"].push(rowVals);
						}

						if (currentStatement > ddl.length-1)
							returnSets.push(thisSet);

						// executeSQL runs asynchronously, so we have to make recursive calls to handle subsequent queries in order.
						if (currentStatement < (statements.length - 1))
						{
							currentStatement++;
							statement = statements[currentStatement];

							tx.executeSql(statement, [], sequentiallyExecute, handleFailure);
						}
						else
						{
							tx.executeSql("intentional failure used to rollback transaction");
							args["success"](returnSets);
						}

					},
					function(tx3, executionPlanResult){
						// if the explain failed, then just append the base set to the result and move on....

						if (currentStatement > ddl.length-1)
							returnSets.push(thisSet);

						// executeSQL runs asynchronously, so we have to make recursive calls to handle subsequent queries in order.
						if (currentStatement < (statements.length - 1))
						{
							currentStatement++;
							statement = statements[currentStatement];

							tx.executeSql(statement, [], sequentiallyExecute, handleFailure);
						}
						else
						{
							tx.executeSql("intentional failure used to rollback transaction");
							args["success"](returnSets);
						}

					});

				}

				var handleFailure = function (tx, result) {

					var thisSet = {
						"SUCCEEDED": false,
						"EXECUTIONTIME": (new Date()) - startTime,
						"ERRORMESSAGE": result.message
					};
					returnSets.push(thisSet);
					args["success"](returnSets); // 'success' - slightly confusing here, but in this context a failed query is still a valid result from the database
				}

				var setArray = [], k, stop = false;

				// $.each(splitStatement(args["ddl"]), function (i, stmt) { statements.push(stmt); });

				var statements = ddl.slice(0);

				$.each(splitStatement(args["sql"]), function (i, stmt) { statements.push(stmt); });

				var currentStatement = 0;
				var statement = statements[currentStatement];

				var startTime = new Date();

				/*
				 * executeSql runs asynchronously, so I impose a semblance of synchronous-ness via recusive calls
				 */
				tx.executeSql(statement, [], sequentiallyExecute, handleFailure);

			});

		}
		catch (e)
		{
			args["error"](e);
		}

	}

	return this;

}
<commit_msg>fixing bugs that cropped up when exceptions were thrown<commit_after>window.WebSQL_driver = function () {

	var db = null;
	var ddl = [];

	var nativeSQLite = (window.openDatabase !== undefined);

	var splitStatement = function (statements)
	{
		return statements ? statements.split(/;\s*\r?\n|$/) : [];
	}

	this.buildSchema = function (args) {
		try {

			if (nativeSQLite)
			{
				db = openDatabase(args["short_code"], '1.0', args["short_code"], args["ddl"].length * 1024);

				db.transaction(function(tx){

					var statements = splitStatement(args["ddl"]);
					ddl = statements;

					// $.each(splitStatement(args["ddl"]), function (i, stmt) { statements.push(stmt); });

					var currentStatement = 0;
					var statement = statements[currentStatement];

					var sequentiallyExecute = function(tx2, result){
						if (currentStatement < statements.length-1)
						{
							currentStatement++;
							statement = statements[currentStatement];

							tx.executeSql(statement, [], sequentiallyExecute, handleFailure);

						}
						else
						{
							tx.executeSql("intentional failure used to rollback transaction");
							args["success"]();
						}
					};

					var handleFailure = function (tx2, result) {
						args["error"](result.message);
						return true; // roll back transaction
					};

					tx.executeSql(statement, [],
						sequentiallyExecute,
						handleFailure
					);

				});

			}
			else
			{
				args["error"]("SQLite (WebSQL) not available in your browser. Try either using a webkit-based browser (such as Safari or Chrome) or using the SQLite (SQL.js) database type.")
			}

		}
		catch (e)
		{
			args["error"](e);
		}

	}

	this.executeQuery = function (args) {

		try {

			if (!db) {
				throw ("Database Schema not available!");
			}

			var returnSets = [];

			db.transaction(function(tx){

				var sequentiallyExecute = function(tx2, result) {

					var thisSet = {
						"SUCCEEDED": true,
						"EXECUTIONTIME": (new Date()) - startTime,
						"RESULTS": {
							"COLUMNS": [],
							"DATA": []
						},
						"EXECUTIONPLAN": {
							"COLUMNS": [],
							"DATA": []
						}

					};

					for (var i = 0; i < result.rows.length; i++) {
						var rowVals = [];
						var item = result.rows.item(i);

						/* We can't be sure about the order of the columns returned, since they are returned as
						 * a simple unordered structure. So, we'll just take the order returned the from the first
						 * request, then just use that order for each row.
						 */
						if (i == 0) {
							for (col in item) {
								thisSet["RESULTS"]["COLUMNS"].push(col);
							}
						}

						for (var j = 0; j < thisSet["RESULTS"]["COLUMNS"].length; j++) {
							rowVals.push(item[thisSet["RESULTS"]["COLUMNS"][j]]);
						}

						thisSet["RESULTS"]["DATA"].push(rowVals);
					}

					tx.executeSql("EXPLAIN QUERY PLAN " + statement, [], function (tx3, executionPlanResult) {

						for (var l = 0; l < executionPlanResult.rows.length; l++) {
							var rowVals = [];
							var item = executionPlanResult.rows.item(l);

							/* We can't be sure about the order of the columns returned, since they are returned as
							 * a simple unordered structure. So, we'll just take the order returned the from the first
							 * request, then just use that order for each row.
							 */
							if (l == 0) {
								for (col in item) {
									thisSet["EXECUTIONPLAN"]["COLUMNS"].push(col);
								}
							}

							for (var j = 0; j < thisSet["EXECUTIONPLAN"]["COLUMNS"].length; j++) {
								rowVals.push(item[thisSet["EXECUTIONPLAN"]["COLUMNS"][j]]);
							}

							thisSet["EXECUTIONPLAN"]["DATA"].push(rowVals);
						}

						if (currentStatement > ddl.length-1)
							returnSets.push(thisSet);

						// executeSQL runs asynchronously, so we have to make recursive calls to handle subsequent queries in order.
						if (currentStatement < (statements.length - 1))
						{
							currentStatement++;
							statement = statements[currentStatement];

							tx.executeSql(statement, [], sequentiallyExecute, handleFailure);
						}
						else
						{
							tx.executeSql("intentional failure used to rollback transaction");
							args["success"](returnSets);
						}

					},
					function(tx3, executionPlanResult){
						// if the explain failed, then just append the base set to the result and move on....

						if (currentStatement > ddl.length-1)
							returnSets.push(thisSet);

						// executeSQL runs asynchronously, so we have to make recursive calls to handle subsequent queries in order.
						if (currentStatement < (statements.length - 1))
						{
							currentStatement++;
							statement = statements[currentStatement];

							tx.executeSql(statement, [], sequentiallyExecute, handleFailure);
						}
						else
						{
							tx.executeSql("intentional failure used to rollback transaction");
							args["success"](returnSets);
						}

					});

				}

				var handleFailure = function (tx, result) {

					var thisSet = {
						"SUCCEEDED": false,
						"EXECUTIONTIME": (new Date()) - startTime,
						"ERRORMESSAGE": result.message
					};
					returnSets.push(thisSet);
					args["success"](returnSets); // 'success' - slightly confusing here, but in this context a failed query is still a valid result from the database

					return true; // roll back transaction
				}

				var setArray = [], k, stop = false;

				// $.each(splitStatement(args["ddl"]), function (i, stmt) { statements.push(stmt); });

				var statements = ddl.slice(0);

				$.each(splitStatement(args["sql"]), function (i, stmt) { statements.push(stmt); });

				var currentStatement = 0;
				var statement = statements[currentStatement];

				var startTime = new Date();

				/*
				 * executeSql runs asynchronously, so I impose a semblance of synchronous-ness via recusive calls
				 */
				tx.executeSql(statement, [], sequentiallyExecute, handleFailure);

			});

		}
		catch (e)
		{
			args["error"](e);
		}

	}

	return this;

}
<|endoftext|>


<commit_before>// TODO: Test multiple tasks executing synchronously. I think, only the first of them will be executed.

var rush = require('./../index.js');
var stackParser = require('stack-parser');

var check = function(condition, message) {
	if (condition)
		return;

	if (typeof message === 'undefined')
		message = '';
	else
		message += ' ';

	var where = stackParser.here()[1].format('(%f, line %l)');
	console.log('FAILED: ' + message + where);
};

// Calls cb(err, param). Error is set if param === false.
var asyncAction = function(param, cb) {
	setTimeout(function() {
		if (param !== false)
			cb(null, param);
		else
			cb(new Error('An error in asyncAction() occurred.'));
	}, Math.random() * 100 | 0);
};

// Calls cb(param, err). Error is set if param === false.
var weirdAsyncAction = function(param, cb) {
	setTimeout(function() {
		if (param !== false)
			cb(param, null);
		else
			cb(null, new Error('An error in weirdAsyncAction() occurred.'));
	}, 0);
};

console.log('Running tests...\n');

var finalizers = {};

// Test initialization errors.

try {
	rush();
	check(false);
} catch(err) {
	check(err instanceof Error);
	check(err.message === 'An attempt to execute an too short Rush chain. A chain must have one or more blocks and a finalizer.');
}

try {
	rush(function() {})();
	check(false);
} catch(err) {
	check(err instanceof Error);
	check(err.message === 'An attempt to execute an too short Rush chain. A chain must have one or more blocks and a finalizer.');
}

try {
	rush(function() {})(function(err) {})()();
	check(false);
} catch(err) {
	check(err instanceof Error);
	check(err.message === 'An attempt to execute a Rush chain twice or alter it after execution.');
}

try {
	rush(1);
	check(false);
} catch(err) {
	check(err instanceof TypeError);
	check(err.message === 'Single argument passed to Rush should be either a function or an object.');
}

try {
	rush(function() {}, 1);
	check(false);
} catch(err) {
	check(err instanceof TypeError);
	check(err.message === 'When two arguments are passed to Rush, each of them should be a function.');
}

try {
	rush(1, function() {});
	check(false);
} catch(err) {
	check(err instanceof TypeError);
	check(err.message === 'When two arguments are passed to Rush, each of them should be a function.');
}

try {
	rush(1, 1);
	check(false);
} catch(err) {
	check(err instanceof TypeError);
	check(err.message === 'When two arguments are passed to Rush, each of them should be a function.');
}

try {
	rush(1, 1, 1);
	check(false);
} catch(err) {
	check(err instanceof Error);
	check(err.message === 'Invalid number of arguments passed to Rush.');
}

try {
	rush(function() {})(function() {}, function() {})();
	check(false);
} catch(err) {
	check(err instanceof Error);
	check(err.message === 'Finalizer should be passed as a single argument.');
}

// Test initializers.

rush({ x: 2, y: 3 })(function() {
	check(this.x === 2);
	check(this.y === 3);
})(function(err) {
	check(!err);
})();

rush({
	x: 2
})(function() {
	// TODO: This should actually be "=== 2", but currently such behaviour is not implemented.
	check(this.x === 3);
})({
	x: 3
})(function() {
	check(this.x === 3);
})(function(err) {
	check(!err);
	check(this.x === 3);
	finalizers.a1 = true;
})();

// Test proper context application.

rush({ z: 1 })(function() {
	this.n = 1;
	check(this.z === 1);

	asyncAction(1, this(function(v) {
		this.n++;
		check(this.z === 1);
	}));

	asyncAction(false, this(function(v) {
		// Never called.
	}, function(err) {
		this.n++;
		check(this.z === 1);
	}));
})(function() {
	this.n++;
	throw new Error(); // Force block error handler to be executed.
}, function(err) {
	this.n++;
	check(this.z === 1);
})(function(err) {
	check(this.z === 1);
	check(this.n === 5);
	finalizers.a2 = true;
})();

// Test this() errors.

rush(function() {
	try {
		this();
	} catch(err) {
		check(err instanceof TypeError);
		check(err.message === 'A callback function should be passed.');
	}

	try {
		this(1);
	} catch(err) {
		check(err instanceof TypeError);
		check(err.message === 'A callback passed to be wrapped should be a function.');
	}

	try {
		this(function() {}, 1);
	} catch(err) {
		check(err instanceof TypeError);
		check(err.message === 'An error handler passed with the callback should be a function.');
	}

	var f = this(function() {}, function(err) {});
	f(); // Otherwise the finalizer won't be called.
})(function(err) {
	check(!err);
	finalizers.a3 = true;
})();

rush({
	value1: 'v1',
	n: 100
})(function() {
	check(this.value1 === 'v1');

	asyncAction(1, this(function(result) {
		check(result === 1);
		this.n++;
	}));

	asyncAction(2, this(function(result) {
		check(result === 2);
		this.n++;
	}));

	asyncAction(3, this(function(result) {
		check(result === 3);
		this.n++;
	}));

	check(this.n === 100);
})(function(err) {
	finalizers.a4 = true;
	check(!err);
	check(this.value1 === 'v1');
	check(this.n === 103);
})();

rush({
	n: 1
})(function() {
	check(this.n === 1);
	this.n++;
})(function() {
	check(this.n === 2);
	this.n++;
})(function(err) {
	finalizers.a5 = true;
	check(!err);
	check(this.n === 3);
})();

rush(function() {
	this.n = 1;
	asyncAction(3, this(function(result) {
		check(result === 3);
		this.n++;
	}));
})(function() {
	check(this.n === 2);
	this.n++;
})(function() {
	check(this.n === 3);
	this.n++;
	asyncAction(3, this(function(result) {
		check(result === 3);
		this.n++;
	}));
})(function() {
	check(this.n === 5);
	this.n++;
})(function(err) {
	finalizers.a6 = true;
	check(!err);
	check(this.n === 6);
})();

// Test exceptions in blocks.

rush(function() {
	throw new Error('Test exception.');
})(function(err) {
	finalizers.b1 = true;
	check(err instanceof Error);
	check(err && err.message === 'Test exception.');
})();

// Check task failing, and sealing of callbacks.

rush(function() {
	this.n = 1;

	setTimeout(this(function() {
		this.a = 1;
		throw new Error('Test exception.');
	}), 100);

	setTimeout(this(function() {
		this.b = 1;
		check(false);
	}), 500);

	setTimeout(this(function() {
		this.c = 1;
		check(false);
	}), 500);
})(function() {
	this.n++;
})(function(err) {
	finalizers.b2 = true;
	check(err && err.message === 'Test exception.');
	check(this.n === 1);
	check(this.a && !this.b && !this.c);
})();

// Test task error handler suppressing errors.

rush(function() {
	this.n = 1;

	asyncAction(false, this(function() {
		this.n++; // This should not be called.
		check(false);
	}, function(err) {
		check(err && err.message === 'An error in asyncAction() occurred.');
		this.e = 1;
	}));
})(function() {
	this.n2 = 1;
})(function(err) {
	finalizers.b3 = true;
	check(!err);
	check(this.n === 1);
	check(this.e === 1);
	check(this.n2 === 1);
})();

// Check task error handler throwing.

rush(function() {
	this.n = 1;

	asyncAction(false, this(function() {
		this.n++; // This should not be called.
		check(false);
	}, function(err) {
		throw new Error('Another error.');
	}));
})(function() {
	this.n2 = 1;
})(function(err) {
	finalizers.b4 = true;
	check(err)
	check(err && err.message === 'Another error.');
	check(this.n === 1);
	check(this.n2 !== 1);
})();

// Test block error handler catching and suppressing errors.

rush({
	n: 0
})(function() {
	this.n++;
	throw new Error('Error in block.');
}, function(err) {
	check(err && err.message === 'Error in block.');
	this.a = 1;
})(function() {
	this.n++;
	asyncAction(1, this(function() {
		throw new Error('Error in async callback.');
	}));
}, function(err) {
	check(err && err.message === 'Error in async callback.');
	this.b = 1;
})(function() {
	this.n++;
	asyncAction(false, this(function() {}));
}, function(err) {
	check(err && err.message === 'An error in asyncAction() occurred.');
	this.c = 1;
})(function() {
	this.n++;
	asyncAction(false, this(function() {
	}, function(err) {
		throw new Error('Error in task error handler.');
	}));
}, function(err) {
	check(err && err.message === 'Error in task error handler.');
	this.d = 1;
})(function(err) {
	finalizers.b5 = true;
	check(!err);
	check(this.n === 4);
	check(this.a === 1);
	check(this.b === 1);
	check(this.c === 1);
	check(this.d === 1);
})();

// Test block error handler throwing errors.

rush(function() {
	setTimeout(this(function() {}), 100);
})(function() {
	throw new Error('Some error.');
}, function(err) {
	throw new Error('Another error.');
})(function(err) {
	finalizers.b6 = true;
	check(err && err.message === 'Another error.');
})();

setTimeout(function() {
	check(finalizers.a1);
	check(finalizers.a2);
	check(finalizers.a3);
	check(finalizers.a4);
	check(finalizers.a5);
	check(finalizers.a6);

	check(finalizers.b1);
	check(finalizers.b2);
	check(finalizers.b3);
	check(finalizers.b4);
	check(finalizers.b5);
	check(finalizers.b6);

	console.log('\nTesting completed.');
}, 2000);
<commit_msg>One more test.<commit_after>// TODO: Test multiple tasks executing synchronously. I think, only the first of them will be executed.

var rush = require('./../index.js');
var stackParser = require('stack-parser');

var check = function(condition, message) {
	if (condition)
		return;

	if (typeof message === 'undefined')
		message = '';
	else
		message += ' ';

	var where = stackParser.here()[1].format('(%f, line %l)');
	console.log('FAILED: ' + message + where);
};

// Calls cb(err, param). Error is set if param === false.
var asyncAction = function(param, cb) {
	setTimeout(function() {
		if (param !== false)
			cb(null, param);
		else
			cb(new Error('An error in asyncAction() occurred.'));
	}, Math.random() * 100 | 0);
};

// Calls cb(param, err). Error is set if param === false.
var weirdAsyncAction = function(param, cb) {
	setTimeout(function() {
		if (param !== false)
			cb(param, null);
		else
			cb(null, new Error('An error in weirdAsyncAction() occurred.'));
	}, 0);
};

console.log('Running tests...\n');

var finalizers = {};

// Test initialization errors.

try {
	rush();
	check(false);
} catch(err) {
	check(err instanceof Error);
	check(err.message === 'An attempt to execute an too short Rush chain. A chain must have one or more blocks and a finalizer.');
}

try {
	rush(function() {})();
	check(false);
} catch(err) {
	check(err instanceof Error);
	check(err.message === 'An attempt to execute an too short Rush chain. A chain must have one or more blocks and a finalizer.');
}

try {
	rush(function() {})(function(err) {})()();
	check(false);
} catch(err) {
	check(err instanceof Error);
	check(err.message === 'An attempt to execute a Rush chain twice or alter it after execution.');
}

try {
	rush(1);
	check(false);
} catch(err) {
	check(err instanceof TypeError);
	check(err.message === 'Single argument passed to Rush should be either a function or an object.');
}

try {
	rush(function() {}, 1);
	check(false);
} catch(err) {
	check(err instanceof TypeError);
	check(err.message === 'When two arguments are passed to Rush, each of them should be a function.');
}

try {
	rush(1, function() {});
	check(false);
} catch(err) {
	check(err instanceof TypeError);
	check(err.message === 'When two arguments are passed to Rush, each of them should be a function.');
}

try {
	rush(1, 1);
	check(false);
} catch(err) {
	check(err instanceof TypeError);
	check(err.message === 'When two arguments are passed to Rush, each of them should be a function.');
}

try {
	rush(1, 1, 1);
	check(false);
} catch(err) {
	check(err instanceof Error);
	check(err.message === 'Invalid number of arguments passed to Rush.');
}

try {
	rush(function() {})(function() {}, function() {})();
	check(false);
} catch(err) {
	check(err instanceof Error);
	check(err.message === 'Finalizer should be passed as a single argument.');
}

// Test initializers.

rush({ x: 2, y: 3 })(function() {
	check(this.x === 2);
	check(this.y === 3);
})(function(err) {
	check(!err);
})();

rush({
	x: 2
})(function() {
	// TODO: This should actually be "=== 2", but currently such behaviour is not implemented.
	check(this.x === 3);
})({
	x: 3
})(function() {
	check(this.x === 3);
})(function(err) {
	check(!err);
	check(this.x === 3);
	finalizers.a1 = true;
})();

// Test proper context application.

rush({ z: 1 })(function() {
	this.n = 1;
	check(this.z === 1);

	asyncAction(1, this(function(v) {
		this.n++;
		check(this.z === 1);
	}));

	asyncAction(false, this(function(v) {
		// Never called.
	}, function(err) {
		this.n++;
		check(this.z === 1);
	}));
})(function() {
	this.n++;
	throw new Error(); // Force block error handler to be executed.
}, function(err) {
	this.n++;
	check(this.z === 1);
})(function(err) {
	check(this.z === 1);
	check(this.n === 5);
	finalizers.a2 = true;
})();

// Test this() errors.

rush(function() {
	try {
		this();
	} catch(err) {
		check(err instanceof TypeError);
		check(err.message === 'A callback function should be passed.');
	}

	try {
		this(1);
	} catch(err) {
		check(err instanceof TypeError);
		check(err.message === 'A callback passed to be wrapped should be a function.');
	}

	try {
		this(function() {}, 1);
	} catch(err) {
		check(err instanceof TypeError);
		check(err.message === 'An error handler passed with the callback should be a function.');
	}

	var f = this(function() {}, function(err) {});
	f(); // Otherwise the finalizer won't be called.
})(function(err) {
	check(!err);
	finalizers.a3 = true;
})();

// Test an async action with multiple arguments for its callback.

rush(function() {
	this.n = 1;

	var action = function(a, b, c, d, cb) {
		setTimeout(function() {
			cb.call(null, null, a, b, c, d);
		}, 0);
	};

	action(1, 2, 3, 4, this(function(x, y, z, w) {
		this.n++;
		check(x === 1);
		check(y === 2);
		check(z === 3);
		check(w === 4);
	}));

	action(7, 11, 17, 19, this(function(x, y, z, w) {
		this.n++;
		check(x === 7);
		check(y === 11);
		check(z === 17);
		check(w === 19);
	}));
})(function(err) {
	check(!err);
	check(this.n === 3);
	finalizers.a35 = true;
})();

// Test multiple async actions in a block.

rush({
	value1: 'v1',
	n: 100
})(function() {
	check(this.value1 === 'v1');

	asyncAction(1, this(function(result) {
		check(result === 1);
		this.n++;
	}));

	asyncAction(2, this(function(result) {
		check(result === 2);
		this.n++;
	}));

	asyncAction(3, this(function(result) {
		check(result === 3);
		this.n++;
	}));

	check(this.n === 100);
})(function(err) {
	finalizers.a4 = true;
	check(!err);
	check(this.value1 === 'v1');
	check(this.n === 103);
})();

// Check no async actions in blocks.

rush({
	n: 1
})(function() {
	check(this.n === 1);
	this.n++;
})(function() {
	check(this.n === 2);
	this.n++;
})(function(err) {
	finalizers.a5 = true;
	check(!err);
	check(this.n === 3);
})();

// Check mixed chain of blocks with and without async actions.

rush(function() {
	this.n = 1;
	asyncAction(3, this(function(result) {
		check(result === 3);
		this.n++;
	}));
})(function() {
	check(this.n === 2);
	this.n++;
})(function() {
	check(this.n === 3);
	this.n++;
	asyncAction(3, this(function(result) {
		check(result === 3);
		this.n++;
	}));
})(function() {
	check(this.n === 5);
	this.n++;
})(function(err) {
	finalizers.a6 = true;
	check(!err);
	check(this.n === 6);
})();

// Test exceptions in blocks.

rush(function() {
	throw new Error('Test exception.');
})(function(err) {
	finalizers.b1 = true;
	check(err instanceof Error);
	check(err && err.message === 'Test exception.');
})();

// Check task failing, and sealing of callbacks.

for (var i = 0; i < 1000; i++) {
	rush(function() {
		this.n = 1;

		setTimeout(this(function() {
			this.a = 1;
			throw new Error('Test exception.');
		}), 100);

		setTimeout(this(function() {
			this.b = 1;
			check(false);
		}), 1000);

		setTimeout(this(function() {
			this.c = 1;
			check(false);
		}), 1000);
	})(function() {
		this.n++;
	})(function(err) {
		finalizers.b2 = true;
		check(err && err.message === 'Test exception.');
		check(this.n === 1);
		check(this.a && !this.b && !this.c);
	})();
}

// Test task error handler suppressing errors.

rush(function() {
	this.n = 1;

	asyncAction(false, this(function() {
		this.n++; // This should not be called.
		check(false);
	}, function(err) {
		check(err && err.message === 'An error in asyncAction() occurred.');
		this.e = 1;
	}));
})(function() {
	this.n2 = 1;
})(function(err) {
	finalizers.b3 = true;
	check(!err);
	check(this.n === 1);
	check(this.e === 1);
	check(this.n2 === 1);
})();

// Check task error handler throwing.

rush(function() {
	this.n = 1;

	asyncAction(false, this(function() {
		this.n++; // This should not be called.
		check(false);
	}, function(err) {
		throw new Error('Another error.');
	}));
})(function() {
	this.n2 = 1;
})(function(err) {
	finalizers.b4 = true;
	check(err)
	check(err && err.message === 'Another error.');
	check(this.n === 1);
	check(this.n2 !== 1);
})();

// Test block error handler catching and suppressing errors.

rush({
	n: 0
})(function() {
	this.n++;
	throw new Error('Error in block.');
}, function(err) {
	check(err && err.message === 'Error in block.');
	this.a = 1;
})(function() {
	this.n++;
	asyncAction(1, this(function() {
		throw new Error('Error in async callback.');
	}));
}, function(err) {
	check(err && err.message === 'Error in async callback.');
	this.b = 1;
})(function() {
	this.n++;
	asyncAction(false, this(function() {}));
}, function(err) {
	check(err && err.message === 'An error in asyncAction() occurred.');
	this.c = 1;
})(function() {
	this.n++;
	asyncAction(false, this(function() {
	}, function(err) {
		throw new Error('Error in task error handler.');
	}));
}, function(err) {
	check(err && err.message === 'Error in task error handler.');
	this.d = 1;
})(function(err) {
	finalizers.b5 = true;
	check(!err);
	check(this.n === 4);
	check(this.a === 1);
	check(this.b === 1);
	check(this.c === 1);
	check(this.d === 1);
})();

// Test block error handler throwing errors.

rush(function() {
	setTimeout(this(function() {}), 100);
})(function() {
	throw new Error('Some error.');
}, function(err) {
	throw new Error('Another error.');
})(function(err) {
	finalizers.b6 = true;
	check(err && err.message === 'Another error.');
})();

setTimeout(function() {
	check(finalizers.a1);
	check(finalizers.a2);
	check(finalizers.a3);
	check(finalizers.a35);
	check(finalizers.a4);
	check(finalizers.a5);
	check(finalizers.a6);

	check(finalizers.b1);
	check(finalizers.b2);
	check(finalizers.b3);
	check(finalizers.b4);
	check(finalizers.b5);
	check(finalizers.b6);

	console.log('\nTesting completed.');
}, 2000);
<|endoftext|>


<commit_before>// Send back all owned mangas
Meteor.publish('allOwnedMangas', function(userId) {
	return Mangas.find({
		"user": userId,
		"owned": true
	});
});

// Send back all missing mangas
Meteor.publish('allMissingMangas', function(userId) {
	return Mangas.find({
		"user": userId,
		"owned": false
	});
});

// Send back the data about a tome
Meteor.publish('tomeDetails', function(id) {
	return Mangas.find({
		"_id": id
	});
});

// Send back all tomes for a mangasName
Meteor.publish('allTomes', function(userId, name) {
	return Mangas.find({
		"user": userId,
		"name": name
	});
});

// Send back all tomes for a userId
Meteor.publish('allTomesForUser', function(userId) {
	return Mangas.find({
		"user": userId
	});
});
<commit_msg>Update publication<commit_after>// Send back all owned mangas
Meteor.publish('allOwnedMangas', (userId) => {
	return Mangas.find({
		user: userId,
		owned: true
	}, {
		fields: {
			title: 1,
			cover: 1,
			name: 1,
			number: 1,
			owned: 1,
			user: 1
		}
	});
});

// Send back all missing mangas
Meteor.publish('allMissingMangas', (userId) => {
	return Mangas.find({
		user: userId,
		owned: false
	}, {
		fields: {
			title: 1,
			cover: 1,
			name: 1,
			number: 1,
			user: 1,
			owned: 1
		}
	});
});

// Send back the data about a tome
Meteor.publish('tomeDetails', (id) => {
	return Mangas.find({ _id: id });
});

// Send back all tomes for a mangasName
Meteor.publish('allTomes', (userId, name) => {
	return Mangas.find({
		user: userId,
		name
	});
});

// Send back all tomes for a userId
Meteor.publish('allTomesForUser', (userId) => {
	return Mangas.find({ user: userId }, {
		fields: {
			owned: 1,
			number: 1,
			user: 1
		}
	});
});
<|endoftext|>


<commit_before>'use strict';

const fs = require('fs-extra');
const path = require('path');
const tmp = require('tmp');
const winston = require('winston');

const EPUB = require('@daisy/epub-utils').EPUB;
const Report = require('@daisy/ace-report').Report;
const checker = require('../checker/checker.js');

tmp.setGracefulCleanup();

module.exports = function ace(epubPath, options) {
  return new Promise((resolve, reject) => {
    // the jobid option just gets returned in the resolve/reject
    // so the calling function can track which job finished
    var jobId = 'jobid' in options ? options.jobid : '';
    winston.verbose("ACE", options);

    // Check that the EPUB exists
    const epubPathResolved = path.resolve(options.cwd, epubPath);
    if (!fs.existsSync(epubPathResolved)) {
      winston.error(`Couldn’t find EPUB file '${epubPath}'`);
      return reject(jobId);
    }

    // Process options
    /* eslint-disable no-param-reassign */
    if (typeof options.tmpdir === 'string') {
      options.tmpdir = path.resolve(options.cwd, options.tmpdir);
      if (!fs.existsSync(options.tmpdir)) {
        fs.ensureDirSync(options.tmpdir);
      }
    } else if (options.tmpdir === undefined) {
      options.tmpdir = tmp.dirSync({ unsafeCleanup: true }).name;
    }
    if (typeof options.outdir === 'string') {
      options.outdir = path.resolve(options.cwd, options.outdir);
      if (!fs.existsSync(options.outdir)) {
        fs.ensureDirSync(options.outdir);
      }
    } else {
      delete options.outdir;
    }

    winston.info("Processing " + epubPath);

    /* eslint-enable no-param-reassign */

    // Unzip the EPUB
    const epub = new EPUB(epubPathResolved);
    epub.extract()
    .then(() => epub.parse())
    // initialize the report
    .then(() => new Report(epub, options.outdir))
    // Check each Content Doc
    .then(report => checker.check(epub, report))
    // Process the Results
    .then((report) => {
      if (options.outdir === undefined) {
        report.cleanData();
        process.stdout.write(`${JSON.stringify(report.json, null, '  ')}\n`);
        return report;
      }
      return report.copyData(options.outdir)
      .then(() => report.cleanData())
      .then(() => Promise.all([
          report.saveJson(options.outdir),
          report.saveHtml(options.outdir)
      ]))
      .then(() => report);
    })
    .then((report) => {
      winston.info('Done.');
      resolve([jobId, report.json]);
    })
    .catch((err) => {
      winston.error(`Unexpected error: ${(err.message !== undefined) ? err.message : err}`);
      if (err.stack !== undefined) winston.debug(err.stack);
      reject(jobId);
    });
  });
};
<commit_msg>feat(logging): verbose output includes node and os versions<commit_after>'use strict';

const fs = require('fs-extra');
const path = require('path');
const tmp = require('tmp');
const winston = require('winston');
const os = require('os');

const EPUB = require('@daisy/epub-utils').EPUB;
const Report = require('@daisy/ace-report').Report;
const checker = require('../checker/checker.js');

tmp.setGracefulCleanup();

module.exports = function ace(epubPath, options) {
  return new Promise((resolve, reject) => {
    // the jobid option just gets returned in the resolve/reject
    // so the calling function can track which job finished
    var jobId = 'jobid' in options ? options.jobid : '';
    winston.verbose("ACE", options);
    winston.verbose(`Node ${process.version}, ${os.type()} v${os.release()}`);

    // Check that the EPUB exists
    const epubPathResolved = path.resolve(options.cwd, epubPath);
    if (!fs.existsSync(epubPathResolved)) {
      winston.error(`Couldn’t find EPUB file '${epubPath}'`);
      return reject(jobId);
    }

    // Process options
    /* eslint-disable no-param-reassign */
    if (typeof options.tmpdir === 'string') {
      options.tmpdir = path.resolve(options.cwd, options.tmpdir);
      if (!fs.existsSync(options.tmpdir)) {
        fs.ensureDirSync(options.tmpdir);
      }
    } else if (options.tmpdir === undefined) {
      options.tmpdir = tmp.dirSync({ unsafeCleanup: true }).name;
    }
    if (typeof options.outdir === 'string') {
      options.outdir = path.resolve(options.cwd, options.outdir);
      if (!fs.existsSync(options.outdir)) {
        fs.ensureDirSync(options.outdir);
      }
    } else {
      delete options.outdir;
    }

    winston.info("Processing " + epubPath);

    /* eslint-enable no-param-reassign */

    // Unzip the EPUB
    const epub = new EPUB(epubPathResolved);
    epub.extract()
    .then(() => epub.parse())
    // initialize the report
    .then(() => new Report(epub, options.outdir))
    // Check each Content Doc
    .then(report => checker.check(epub, report))
    // Process the Results
    .then((report) => {
      if (options.outdir === undefined) {
        report.cleanData();
        process.stdout.write(`${JSON.stringify(report.json, null, '  ')}\n`);
        return report;
      }
      return report.copyData(options.outdir)
      .then(() => report.cleanData())
      .then(() => Promise.all([
          report.saveJson(options.outdir),
          report.saveHtml(options.outdir)
      ]))
      .then(() => report);
    })
    .then((report) => {
      winston.info('Done.');
      resolve([jobId, report.json]);
    })
    .catch((err) => {
      winston.error(`Unexpected error: ${(err.message !== undefined) ? err.message : err}`);
      if (err.stack !== undefined) winston.debug(err.stack);
      reject(jobId);
    });
  });
};
<|endoftext|>


<commit_before>/*
 * Copyright 1999-2011 Luca Garulli (l.garulli--at--orientechnologies.com)
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

/**
 * Client-side controller to develop rich-client web applications.
 *
 * @author Luca Garulli (l.garulli--at--orientechnologies.com)
 */

function OController(options) {
	this.parameters = {};
	this.cachedPages = {};
	this.options = {
		debug : false,
		cachePages : false
	}

	if (options) {
		for (o in options)
			this.options[o] = options[o];
	}

	OController.prototype.loadPage = function(component, file, callback, cache) {
		if (cache == null)
			cache = this.cachePages;

		var content = this.cachedPages[file];

		if (content == null) {
			var me = this;
			$('#' + component).load(file, function(content) {
				if (cache)
					me.cachedPages[file] = content;

				try {
					onPageLoad();
				} catch (e) {
				}

				if (callback != null)
					callback();
			});
		} else {
			$('#' + component).html(content);
			$('#' + component).ready(function() {
				if (callback != null)
					callback();
			});
		}

		parent.location.hash = file;
	}

	OController.prototype.parameter = function(name, value) {
		if (value == undefined)
			// GET
			return this.parameters[name];
		else if (value == null)
			// REMOVE
			return this.parameters.slice(name);
		else
			// SET
			return this.parameters[name] = value;
	}
}<commit_msg>Optional rewriteUrl parameter in orientdb-controller.js.<commit_after>/*
 * Copyright 1999-2011 Luca Garulli (l.garulli--at--orientechnologies.com)
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

/**
 * Client-side controller to develop rich-client web applications.
 *
 * @author Luca Garulli (l.garulli--at--orientechnologies.com)
 */

function OController(options) {
	this.parameters = {};
	this.cachedPages = {};
	this.options = {
		rewriteUrl : false,
		debug : false,
		cachePages : false
	}

	if (options) {
		for (o in options)
			this.options[o] = options[o];
	}

	OController.prototype.loadPage = function(component, file, callback, cache) {
		if (cache == null)
			cache = this.cachePages;

		var content = this.cachedPages[file];

		if (content == null) {
			var me = this;
			$('#' + component).load(file, function(content) {
				if (cache)
					me.cachedPages[file] = content;

				try {
					onPageLoad();
				} catch (e) {
				}

				if (callback != null)
					callback();
			});
		} else {
			$('#' + component).html(content);
			$('#' + component).ready(function() {
				if (callback != null)
					callback();
			});
		}

		if (this.rewriteUrl)
			parent.location.hash = file;
	}

	OController.prototype.parameter = function(name, value) {
		if (value == undefined)
			// GET
			return this.parameters[name];
		else if (value == null)
			// REMOVE
			return this.parameters.slice(name);
		else
			// SET
			return this.parameters[name] = value;
	}
}<|endoftext|>


<commit_before>var should = require('should')
  , mongoose = require('mongoose');
  , mongooseCacher = require('../index.js');

describe('mongoose Query object', function() {
  mongooseCacher(mongoose);
});
<commit_msg>Fixing typo in test<commit_after>var should = require('should')
  , mongoose = require('mongoose')
  , mongooseCacher = require('../index.js');

describe('mongoose Query object', function() {
  mongooseCacher(mongoose);
});
<|endoftext|>


<commit_before>import fs from 'fs'
import ModularScale from '../dist/ModularScale'
import plugin from '../'
import postcss from 'postcss'
import test from 'ava'

function run (t, input, output, opts = {}, strict = true) {
  return postcss([plugin(opts)])
    .process(input)
    .then(result => {
      t.same(result.css, output)
      if (strict) t.same(result.warnings().length, 0)
    })
}

function readFile (path) {
  return fs.readFileSync(path, 'utf8')
}

test('ModularScale default options', t => {
  var ms = new ModularScale()
  t.plan(3)
  t.same(ms(-1), 0.618)
  t.same(ms(0), 1)
  t.same(ms(1), 1.618)
})

test('ModularScale supplied ratio', t => {
  var ms = new ModularScale({ ratio: 1.5 })
  t.plan(3)
  t.same(ms(-1), 0.667)
  t.same(ms(0), 1)
  t.same(ms(1), 1.5)
})

test('ModularScale supplied ratio and multiple bases', t => {
  var ms = new ModularScale({ ratio: 1.5, bases: [1, 1.25] })
  t.plan(5)
  t.same(ms(-6), 0.296)
  t.same(ms(-1), 0.833)
  t.same(ms(0), 1)
  t.same(ms(1), 1.25)
  t.same(ms(6), 3.375)
})

test('ModularScale with extreme values', t => {
  var ms = new ModularScale({ ratio: 1.5 })
  t.plan(2)
  t.same(ms(-6), 0.088)
  t.same(ms(16), 656.841)
})

test('ModularScale supplied precision', t => {
  var ms = new ModularScale({ ratio: 1.5, precision: 4 })
  t.plan(1)
  t.same(ms(5), 7.5938)
})

test('ModularScale errors with bad ratio', t => {
  t.plan(2)
  t.throws(
    () => new ModularScale({ ratio: 'foo' }),
    TypeError,
    'Throws TypeError when ratio is not a number'
  )
  t.throws(
    () => new ModularScale({ ratio: 1 }),
    TypeError,
    'Throws TypeError when ratio is not greater than 1'
  )
})

test('ModularScale errors with bad bases', t => {
  t.plan(3)
  t.throws(
    () => new ModularScale({ bases: 'foo' }),
    TypeError,
    'Throws TypeError when bases is not an array'
  )
  t.throws(
    () => new ModularScale({ bases: ['a', 1] }),
    TypeError,
    'Throws TypeError when bases contains a non-number'
  )
  t.throws(
    () => new ModularScale({ bases: [0, 1] }),
    TypeError,
    'Throws TypeError when bases contains a number not greater than 0'
  )
})

test('ModularScale with ratio smaller than base (issue #15)', t => {
  var ms = new ModularScale({ ratio: 1.125, bases: [1, 1.225] })
  t.plan(2)
  t.same(ms(-1), 0.968)
  t.same(ms(1), 1.089)
})

test('ModularScale with bases out of order', t => {
  var ms = new ModularScale({ ratio: 1.125, bases: [1.225, 1] })
  t.plan(2)
  t.same(ms(-1), 0.968)
  t.same(ms(1), 1.089)
})

test('Works with a default ratio', t => {
  var input = readFile('./default-in.css')
  var expected = readFile('./default-out.css')
  return run(t, input, expected)
})

test('Works with a supplied ratio', t => {
  var input = readFile('./supplied-in.css')
  var expected = readFile('./supplied-out.css')
  return run(t, input, expected)
})

test('Works with named ratios', t => {
  var input = readFile('./namedRatio-in.css')
  var expected = readFile('./namedRatio-out.css')
  return run(t, input, expected)
})

test('Works with multiple bases and values', t => {
  var input = readFile('./multiple-in.css')
  var expected = readFile('./multiple-out.css')
  return run(t, input, expected)
})

test('Works with bases larger than ratios (issue #15)', t => {
  var input = readFile('./basesLarger-in.css')
  var expected = readFile('./basesLarger-out.css')
  return run(t, input, expected)
})

test('Works with calc()', t => {
  var input = readFile('./calc-in.css')
  var expected = readFile('./calc-out.css')
  return run(t, input, expected)
})

test('Ignores invalid unit name', t => {
  var input = readFile('./invalid-in.css')
  var expected = readFile('./invalid-out.css')
  return run(t, input, expected)
})

test('Works with a custom unit name', t => {
  var input = readFile('./customName-in.css')
  var expected = readFile('./customName-out.css')
  return run(t, input, expected, { name: 'mods' })
})

test('Works with precision override', t => {
  var input = readFile('./customPrec-in.css')
  var expected = readFile('./customPrec-out.css')
  return run(t, input, expected, { precision: 4 })
})

test('Does what the docs show for example', t => {
  var input = readFile('./docsExample-in.css')
  var expected = readFile('./docsExample-out.css')
  return run(t, input, expected)
})
<commit_msg>Update AVA assertions<commit_after>import fs from 'fs'
import path from 'path'
import ModularScale from '../dist/ModularScale'
import plugin from '../'
import postcss from 'postcss'
import test from 'ava'

function run (t, input, output, opts = {}, strict = true) {
  return postcss([plugin(opts)])
    .process(input)
    .then(result => {
      t.deepEqual(result.css, output)
      if (strict) t.deepEqual(result.warnings().length, 0)
    })
}

function readFile (file) {
  return fs.readFileSync(path.resolve(__dirname, file), 'utf8')
}

test('ModularScale default options', t => {
  var ms = new ModularScale()
  t.plan(3)
  t.deepEqual(ms(-1), 0.618)
  t.deepEqual(ms(0), 1)
  t.deepEqual(ms(1), 1.618)
})

test('ModularScale supplied ratio', t => {
  var ms = new ModularScale({ ratio: 1.5 })
  t.plan(3)
  t.deepEqual(ms(-1), 0.667)
  t.deepEqual(ms(0), 1)
  t.deepEqual(ms(1), 1.5)
})

test('ModularScale supplied ratio and multiple bases', t => {
  var ms = new ModularScale({ ratio: 1.5, bases: [1, 1.25] })
  t.plan(5)
  t.deepEqual(ms(-6), 0.296)
  t.deepEqual(ms(-1), 0.833)
  t.deepEqual(ms(0), 1)
  t.deepEqual(ms(1), 1.25)
  t.deepEqual(ms(6), 3.375)
})

test('ModularScale with extreme values', t => {
  var ms = new ModularScale({ ratio: 1.5 })
  t.plan(2)
  t.deepEqual(ms(-6), 0.088)
  t.deepEqual(ms(16), 656.841)
})

test('ModularScale supplied precision', t => {
  var ms = new ModularScale({ ratio: 1.5, precision: 4 })
  t.plan(1)
  t.deepEqual(ms(5), 7.5938)
})

test('ModularScale errors with bad ratio', t => {
  t.plan(2)
  t.throws(
    () => new ModularScale({ ratio: 'foo' }),
    TypeError,
    'Throws TypeError when ratio is not a number'
  )
  t.throws(
    () => new ModularScale({ ratio: 1 }),
    TypeError,
    'Throws TypeError when ratio is not greater than 1'
  )
})

test('ModularScale errors with bad bases', t => {
  t.plan(3)
  t.throws(
    () => new ModularScale({ bases: 'foo' }),
    TypeError,
    'Throws TypeError when bases is not an array'
  )
  t.throws(
    () => new ModularScale({ bases: ['a', 1] }),
    TypeError,
    'Throws TypeError when bases contains a non-number'
  )
  t.throws(
    () => new ModularScale({ bases: [0, 1] }),
    TypeError,
    'Throws TypeError when bases contains a number not greater than 0'
  )
})

test('ModularScale with ratio smaller than base (issue #15)', t => {
  var ms = new ModularScale({ ratio: 1.125, bases: [1, 1.225] })
  t.plan(2)
  t.deepEqual(ms(-1), 0.968)
  t.deepEqual(ms(1), 1.089)
})

test('ModularScale with bases out of order', t => {
  var ms = new ModularScale({ ratio: 1.125, bases: [1.225, 1] })
  t.plan(2)
  t.deepEqual(ms(-1), 0.968)
  t.deepEqual(ms(1), 1.089)
})

test('Works with a default ratio', t => {
  var input = readFile('./default-in.css')
  var expected = readFile('./default-out.css')
  return run(t, input, expected)
})

test('Works with a supplied ratio', t => {
  var input = readFile('./supplied-in.css')
  var expected = readFile('./supplied-out.css')
  return run(t, input, expected)
})

test('Works with named ratios', t => {
  var input = readFile('./namedRatio-in.css')
  var expected = readFile('./namedRatio-out.css')
  return run(t, input, expected)
})

test('Works with multiple bases and values', t => {
  var input = readFile('./multiple-in.css')
  var expected = readFile('./multiple-out.css')
  return run(t, input, expected)
})

test('Works with bases larger than ratios (issue #15)', t => {
  var input = readFile('./basesLarger-in.css')
  var expected = readFile('./basesLarger-out.css')
  return run(t, input, expected)
})

test('Works with calc()', t => {
  var input = readFile('./calc-in.css')
  var expected = readFile('./calc-out.css')
  return run(t, input, expected)
})

test('Ignores invalid unit name', t => {
  var input = readFile('./invalid-in.css')
  var expected = readFile('./invalid-out.css')
  return run(t, input, expected)
})

test('Works with a custom unit name', t => {
  var input = readFile('./customName-in.css')
  var expected = readFile('./customName-out.css')
  return run(t, input, expected, { name: 'mods' })
})

test('Works with precision override', t => {
  var input = readFile('./customPrec-in.css')
  var expected = readFile('./customPrec-out.css')
  return run(t, input, expected, { precision: 4 })
})

test('Does what the docs show for example', t => {
  var input = readFile('./docsExample-in.css')
  var expected = readFile('./docsExample-out.css')
  return run(t, input, expected)
})
<|endoftext|>


<commit_before>var test = require('tape'),
    fs = require('fs'),
    path = require('path'),
    Templator = require('../');

function process (filename, options, st) {
  var templator = new Templator(options),
      input = 'test/fixtures/' + filename,
      output = 'test/expected/' + filename;

  st.equal(templator.processFile(input), fs.readFileSync(output).toString(),
           'processed content should match expected');
  st.end();
}

test('Templator options', function (t) {

  t.test('templator.cwd is set to default', function (st) {
    var templator = new Templator();
    st.equal(templator.cwd, path.resolve('./'), 'should have correct path property');
    st.end();
  });

  t.test('templator.cwd is set as string', function (st) {
    var templator = new Templator('somedir');
    st.equal(templator.cwd, path.resolve('somedir'), 'should have correct path property');
    st.end();
  });

  t.test('templator.cwd is set in options object', function (st) {
    var templator = new Templator({path: 'somedir'});
    st.equal(templator.cwd, path.resolve('somedir'), 'should have correct path property');
    st.end();
  });

});

test('Templator processFile', function (t) {

  t.test('process file with no includes', function (st) {
    process('no-includes.html', {}, st);
  });

  t.test('process file with no path resolutions', function (st) {
    process('no-resolve.html', {}, st);
  });

  t.test('process file with includes', function (st) {
    process('includes.html', 'test/fixtures/includes', st);
  });

  t.test('process file with includes without .md', function (st) {
    process('no-md.html', 'test/fixtures/includes', st);
  });

  t.test('process file with relative includes', function (st) {
    process('relative.html', {}, st);
  });

});
<commit_msg>Improve process function<commit_after>var test = require('tape'),
    fs = require('fs'),
    path = require('path'),
    Templator = require('../');

function process (filename, options, st) {
  var templator = new Templator(options),
      input = 'test/fixtures/' + filename,
      output = 'test/expected/' + filename;

  var actual = templator.processFile(input);

  fs.readFile(output, function (err, data) {
    st.equal(actual, data.toString(), 'processed content should match expected');
    st.end();
  });
}

test('Templator options', function (t) {

  t.test('templator.cwd is set to default', function (st) {
    var templator = new Templator();
    st.equal(templator.cwd, path.resolve('./'), 'should have correct path property');
    st.end();
  });

  t.test('templator.cwd is set as string', function (st) {
    var templator = new Templator('somedir');
    st.equal(templator.cwd, path.resolve('somedir'), 'should have correct path property');
    st.end();
  });

  t.test('templator.cwd is set in options object', function (st) {
    var templator = new Templator({path: 'somedir'});
    st.equal(templator.cwd, path.resolve('somedir'), 'should have correct path property');
    st.end();
  });

});

test('Templator processFile', function (t) {

  t.test('process file with no includes', function (st) {
    process('no-includes.html', {}, st);
  });

  t.test('process file with no path resolutions', function (st) {
    process('no-resolve.html', {}, st);
  });

  t.test('process file with includes', function (st) {
    process('includes.html', 'test/fixtures/includes', st);
  });

  t.test('process file with includes without .md', function (st) {
    process('no-md.html', 'test/fixtures/includes', st);
  });

  t.test('process file with relative includes', function (st) {
    process('relative.html', {}, st);
  });

});
<|endoftext|>


<commit_before>var assert = require('chai').assert,
    expect = require('chai').expect,
    Typeson = require('typeson'),
    arrayFrom = require('../utils/array-from-iterator');

describe('Built-in', function() {
  describe('Date', function () {
    it('should get back a real Date instance with the original time milliseconds', function () {
        var typeson = new Typeson().register(require('../types/date'));
        var json = typeson.stringify(new Date(1234567));
        var obj = typeson.parse(json);
        expect(obj).to.be.an.instanceOf(Date);
        expect(obj.getTime()).to.equal(1234567);
    });
  });

  describe('Error', function () {
    it('should get back real Error instances corresponding to their types and with the original name and message', function () {
        var typeson = new Typeson().register([require('../types/error'), require('../types/errors.js')]);
        var json = typeson.stringify({
            e1: new Error("Error1"),
            e2: new TypeError("Error2"),
            e3: new RangeError("Error3"),
            e4: new SyntaxError("Error4"),
            e5: new ReferenceError("Error5")
        });
        var obj = typeson.parse(json);
        expect(obj.e1).to.be.an.instanceOf(Error);
        expect(obj.e1.name).to.equal("Error");
        expect(obj.e2).to.be.an.instanceOf(TypeError);
        expect(obj.e2.name).to.equal("TypeError");
        expect(obj.e3).to.be.an.instanceOf(RangeError);
        expect(obj.e3.name).to.equal("RangeError");
        expect(obj.e4).to.be.an.instanceOf(SyntaxError);
        expect(obj.e4.name).to.equal("SyntaxError");
        expect(obj.e5).to.be.an.instanceOf(ReferenceError);
        expect(obj.e5.name).to.equal("ReferenceError");
    });
  });

  describe('Map', function () {
    it('should get back a real Map instance with the original data and use complex types also in contained items', function () {
        var typeson = new Typeson().register(require('../presets/builtin'));
        var map = new Map();
        var error = new Error("Error here"),
            date = new Date(10000);

        map.set(error, date);
        var json = typeson.stringify({m: map});
        var obj = typeson.parse(json);
        expect(obj.m).to.be.an.instanceOf(Map);
        expect(arrayFrom(obj.m.keys())[0]).to.be.an.instanceOf(Error);
        expect(arrayFrom(obj.m.values())[0]).to.be.an.instanceOf(Date);
    });
  });

  describe('Set', function () {
    it('should get back a real Set instance with the original data and use complex types also in contained items', function () {
        var typeson = new Typeson().register(require('../presets/builtin'));
        var set = new Set();
        var error = new Error("Error here"),
            date = new Date(10000),
            str = "",
            o = {
                a: error
            };

        set.add(o);
        set.add(date);
        set.add(str);

        var json = typeson.stringify({s: set});
        var obj = typeson.parse(json);

        expect(obj.s).to.be.an.instanceOf(Set);

        var a = arrayFrom(obj.s.values());
        expect(a[0].a).to.be.an.instanceOf(Error);
        expect(a[1]).to.be.an.instanceOf(Date);
        expect(a[2]).to.be.a('string');
    });
  });

  describe('TypedArrays', function(){
    describe('Float64Array', function() {
        it('should get back real Float64Array instance with original array content', function () {
            var typeson = new Typeson().register([
                require('../types/arraybuffer'),
                require('../types/typed-arrays')
            ]);
            var a = new Float64Array(3);
            a[0] = 23.8;
            a[1] = -15;
            a[2] = 99;
            var json = typeson.stringify({a: a});
            var obj = typeson.parse(json);
            expect(obj.a).to.be.an.instanceOf(Float64Array);
            expect(obj.a.length).to.equal(3);
            expect(obj.a[0]).to.equal(23.8);
            expect(obj.a[1]).to.equal(-15);
            expect(obj.a[2]).to.equal(99);
        });
    });

    describe('Uint16 arrays over invalid unicode range', function() {
       it('should work to use any 16-bit number no matter whether it is invalid unicode or not', function(){
            var typeson = new Typeson().register([
                require('../types/arraybuffer'),
                require('../types/typed-arrays')
            ]);
            var a = new Uint16Array(0x0900),
                i = a.length;
            while (i--) a[i] = i + 0xd780;
            var json = typeson.stringify({a: a});
            //console.log(json);

            // Emulate a textencoder that eliminates invalid UTF chars
            i = json.length;
            var copy = new Uint16Array(i);
            while (i--) {
                var ch = json.charCodeAt(i);
                copy[i] = ch >= 0xd800 && ch < 0xe000 ? 0xfffd : ch;
            }
            json = String.fromCharCode.apply(null, copy);

            var obj = typeson.parse(json);
            expect(obj.a).to.be.an.instanceOf(Uint16Array);
            expect(obj.a.length).to.equal(a.length);
            obj.a.forEach(function (x, i) {
                expect(x).to.equal(i + 0xd780);
            });
       });
    });

    describe("Int8 arrays with odd length", function () {
        it('should be possible to use an odd length of an Int8Array', function() {
            var typeson = new Typeson().register([
                require('../types/arraybuffer'),
                require('../types/typed-arrays')
            ]);
            var a = new Int8Array(3);
            a[0] = 0;
            a[1] = 1;
            a[2] = 2;
            var json = typeson.stringify(a);
            console.log(json);
            var a2 = typeson.parse(json);
            expect(a2.length).to.equal(3);
            expect(a2[0]).to.equal(0);
            expect(a2[1]).to.equal(1);
            expect(a2[2]).to.equal(2);
        });
    });
  });
});
<commit_msg>- Testing: Add undefined and sparseUndefined test (will require new    publishing of typeson)<commit_after>var assert = require('chai').assert,
    expect = require('chai').expect,
    Typeson = require('typeson'),
    arrayFrom = require('../utils/array-from-iterator');

describe('Built-in', function() {
  describe('Date', function () {
    it('should get back a real Date instance with the original time milliseconds', function () {
        var typeson = new Typeson().register(require('../types/date'));
        var json = typeson.stringify(new Date(1234567));
        var obj = typeson.parse(json);
        expect(obj).to.be.an.instanceOf(Date);
        expect(obj.getTime()).to.equal(1234567);
    });
  });

  describe('Error', function () {
    it('should get back real Error instances corresponding to their types and with the original name and message', function () {
        var typeson = new Typeson().register([require('../types/error'), require('../types/errors.js')]);
        var json = typeson.stringify({
            e1: new Error("Error1"),
            e2: new TypeError("Error2"),
            e3: new RangeError("Error3"),
            e4: new SyntaxError("Error4"),
            e5: new ReferenceError("Error5")
        });
        var obj = typeson.parse(json);
        expect(obj.e1).to.be.an.instanceOf(Error);
        expect(obj.e1.name).to.equal("Error");
        expect(obj.e2).to.be.an.instanceOf(TypeError);
        expect(obj.e2.name).to.equal("TypeError");
        expect(obj.e3).to.be.an.instanceOf(RangeError);
        expect(obj.e3.name).to.equal("RangeError");
        expect(obj.e4).to.be.an.instanceOf(SyntaxError);
        expect(obj.e4.name).to.equal("SyntaxError");
        expect(obj.e5).to.be.an.instanceOf(ReferenceError);
        expect(obj.e5.name).to.equal("ReferenceError");
    });
  });

  describe('Map', function () {
    it('should get back a real Map instance with the original data and use complex types also in contained items', function () {
        var typeson = new Typeson().register(require('../presets/builtin'));
        var map = new Map();
        var error = new Error("Error here"),
            date = new Date(10000);

        map.set(error, date);
        var json = typeson.stringify({m: map});
        var obj = typeson.parse(json);
        expect(obj.m).to.be.an.instanceOf(Map);
        expect(arrayFrom(obj.m.keys())[0]).to.be.an.instanceOf(Error);
        expect(arrayFrom(obj.m.values())[0]).to.be.an.instanceOf(Date);
    });
  });

  describe('Set', function () {
    it('should get back a real Set instance with the original data and use complex types also in contained items', function () {
        var typeson = new Typeson().register(require('../presets/builtin'));
        var set = new Set();
        var error = new Error("Error here"),
            date = new Date(10000),
            str = "",
            o = {
                a: error
            };

        set.add(o);
        set.add(date);
        set.add(str);

        var json = typeson.stringify({s: set});
        var obj = typeson.parse(json);

        expect(obj.s).to.be.an.instanceOf(Set);

        var a = arrayFrom(obj.s.values());
        expect(a[0].a).to.be.an.instanceOf(Error);
        expect(a[1]).to.be.an.instanceOf(Date);
        expect(a[2]).to.be.a('string');
    });
  });

  describe('TypedArrays', function(){
    describe('Float64Array', function() {
        it('should get back real Float64Array instance with original array content', function () {
            var typeson = new Typeson().register([
                require('../types/arraybuffer'),
                require('../types/typed-arrays')
            ]);
            var a = new Float64Array(3);
            a[0] = 23.8;
            a[1] = -15;
            a[2] = 99;
            var json = typeson.stringify({a: a});
            var obj = typeson.parse(json);
            expect(obj.a).to.be.an.instanceOf(Float64Array);
            expect(obj.a.length).to.equal(3);
            expect(obj.a[0]).to.equal(23.8);
            expect(obj.a[1]).to.equal(-15);
            expect(obj.a[2]).to.equal(99);
        });
    });

    describe('Uint16 arrays over invalid unicode range', function() {
       it('should work to use any 16-bit number no matter whether it is invalid unicode or not', function(){
            var typeson = new Typeson().register([
                require('../types/arraybuffer'),
                require('../types/typed-arrays')
            ]);
            var a = new Uint16Array(0x0900),
                i = a.length;
            while (i--) a[i] = i + 0xd780;
            var json = typeson.stringify({a: a});
            //console.log(json);

            // Emulate a textencoder that eliminates invalid UTF chars
            i = json.length;
            var copy = new Uint16Array(i);
            while (i--) {
                var ch = json.charCodeAt(i);
                copy[i] = ch >= 0xd800 && ch < 0xe000 ? 0xfffd : ch;
            }
            json = String.fromCharCode.apply(null, copy);

            var obj = typeson.parse(json);
            expect(obj.a).to.be.an.instanceOf(Uint16Array);
            expect(obj.a.length).to.equal(a.length);
            obj.a.forEach(function (x, i) {
                expect(x).to.equal(i + 0xd780);
            });
       });
    });

    describe("Int8 arrays with odd length", function () {
        it('should be possible to use an odd length of an Int8Array', function() {
            var typeson = new Typeson().register([
                require('../types/arraybuffer'),
                require('../types/typed-arrays')
            ]);
            var a = new Int8Array(3);
            a[0] = 0;
            a[1] = 1;
            a[2] = 2;
            var json = typeson.stringify(a);
            console.log(json);
            var a2 = typeson.parse(json);
            expect(a2.length).to.equal(3);
            expect(a2[0]).to.equal(0);
            expect(a2[1]).to.equal(1);
            expect(a2[2]).to.equal(2);
        });
    });
  });
  describe("undefined type", function () {
      it('should be possible to restore `undefined` values', function() {
          var typeson = new Typeson().register([
              require('../types/undefined')
          ]);
          var a = [undefined, {b: undefined, c: [3, null, , undefined]}];
          var json = typeson.stringify(a);
          var a2 = typeson.parse(json);
          expect(a2.length).to.equal(2);
          expect(a2[0]).to.equal(undefined);
          expect(a2[1].b).to.equal(undefined);
          expect(a2[1].c[1]).to.not.equal(undefined);
          expect(a2[1].c[2]).to.equal(undefined);
          expect(a2[1].c[3]).to.equal(undefined);

          expect('0' in a2).to.be.true;
          expect('b' in a2[1]).to.be.true;
          expect('1' in a2[1].c).to.be.true;
          expect('2' in a2[1].c).to.be.false;
          expect('3' in a2[1].c).to.be.true;
      });
  });
});
<|endoftext|>


<commit_before>/*!
 * stream-loader <https://github.com/jonschlinkert/stream-loader>
 *
 * Copyright (c) 2015, Jon Schlinkert.
 * Licensed under the MIT license.
 */

'use strict';

/* deps: mocha */
var path = require('path');
var assert = require('assert');
var through = require('through2');
var gulp = require('gulp');
var File = require('vinyl');
var vfs = require('vinyl-fs');
var dest = require('dest');
var del = require('del');

// var contents = require('file-contents');
var utils = require('../lib/utils');
var loader = require('../');

describe('loader', function () {
  it('should return a function:', function () {
    assert.equal(typeof loader(), 'function');
  });

  it('should read a glob of files:', function (done) {
    var src = loader(function (options) {
      return through.obj(function (file, enc, cb) {
        return cb();
      })
    });

    src('fixtures/*.txt')
      .pipe(through.obj(function (file, enc, cb) {
        assert.equal(typeof file.path, 'string');
        assert.equal(Buffer.isBuffer(file.contents), false);
        this.push(file);
        cb();
      }))
      .pipe(utils.drain(done));
  });

  it('should pass options to `glob`:', function (done) {
    var src = loader(function (options) {
      return through.obj(function (file, enc, cb) {
        return cb();
      });
    });

    src('*.txt', {cwd: 'fixtures'})
      .pipe(through.obj(function (file, enc, cb) {
        assert.equal(typeof file.path, 'string');
        assert.equal(Buffer.isBuffer(file.contents), false);
        this.push(file);
        cb();
      }))
      .pipe(utils.drain(done));
  });

  it('should take a callback on the loader:', function (done) {
    var src = loader(function (options) {
      return through.obj(function (file, enc, cb) {
        file.foo = 'bar';
        this.push(utils.toVinyl(file));
        return cb();
      })
    });

    src('fixtures/*.txt')
      .pipe(through.obj(function (file, enc, cb) {
        assert.equal(file.foo, 'bar');
        this.push(file);
        cb();
      }))
      .pipe(utils.drain(done));
  });

  it('should convert the file to a vinyl File object:', function (done) {
    var src = loader(function (options) {
      return through.obj(function (file, enc, cb) {
        this.push(utils.toVinyl(file));
        return cb();
      })
    });

    src('fixtures/*.txt')
      .pipe(through.obj(function (file, enc, cb) {
        assert.equal(file instanceof File, true);
        this.push(file);
        cb();
      }))
      .pipe(utils.drain(done));
  });

  it('should add the contents property to a file object:', function (done) {
    this.timeout(5000);

    var src = loader({read: true}, function (opts) {
      return utils.base(opts, function (file, options) {
        return utils.toVinyl(file, options);
      });
    });

    var i = 0;

    src('node_modules/**/*')
      .pipe(src('lib/**/*.js'))
      .pipe(src('fixtures/*.txt'))
      .pipe(src('fixtures/**/*.txt'))
      .pipe(src('fixtures/**/*.md'))
      .pipe(src('fixtures/**/*.js'))
      // .pipe(contents({read: false}))
      .pipe(through.obj(function (file, enc, cb) {
        i++;
        this.push(file);
        return cb();
      }))
      .on('end', function () {
        console.log('read', i, 'files');
      })
      .pipe(utils.drain(done));
  });

  it('should push files into a vinyl src stream:', function (done) {
    var src = loader(function (options) {
      return through.obj(function (file, enc, cb) {
        this.push(utils.toVinyl(file));
        return cb();
      })
    });

    var files = {};
    gulp.src('*.js')
      .pipe(src('fixtures/*.txt'))
      .pipe(src('fixtures/*.md'))
      .pipe(through.obj(function (file, enc, cb) {
        files[file.path] = file;
        this.push(file);
        cb();
      }))
      .pipe(dest('actual'))
      .on('end', function() {
        assert.equal(Object.keys(files).length > 1, true);
        del('actual', done);
      });
  });

  it('should passthrough files when no pattern is given', function (done) {
    var src = loader(function (options) {
      return through.obj(function (file, enc, cb) {
        return cb();
      })
    });

    var files1 = [], files2 = [];
    src('fixtures/*.txt')
      .pipe(through.obj(function (file, enc, cb) {
        files1.push(file);
        cb(null, file);
      }))
      .pipe(src([]))
      .pipe(through.obj(function (file, enc, cb) {
        files2.push(file);
        cb(null, file);
      }))
      .on('end', function () {
        assert.deepEqual(files1, files2);
      })
      .pipe(utils.drain(done));
  });
});
<commit_msg>ensure that files are pushed through<commit_after>/*!
 * stream-loader <https://github.com/jonschlinkert/stream-loader>
 *
 * Copyright (c) 2015, Jon Schlinkert.
 * Licensed under the MIT license.
 */

'use strict';

/* deps: mocha */
var path = require('path');
var assert = require('assert');
var through = require('through2');
var gulp = require('gulp');
var File = require('vinyl');
var vfs = require('vinyl-fs');
var dest = require('dest');
var del = require('del');

// var contents = require('file-contents');
var utils = require('../lib/utils');
var loader = require('../');

describe('loader', function () {
  it('should return a function:', function () {
    assert.equal(typeof loader(), 'function');
  });

  it('should read a glob of files:', function (done) {
    var src = loader(function (options) {
      return through.obj(function (file, enc, cb) {
        this.push(file);
        return cb();
      })
    });

    src('fixtures/*.txt')
      .pipe(through.obj(function (file, enc, cb) {
        assert.equal(typeof file.path, 'string');
        assert.equal(Buffer.isBuffer(file.contents), false);
        this.push(file);
        cb();
      }))
      .pipe(utils.drain(done));
  });

  it('should pass options to `glob`:', function (done) {
    var src = loader(function (options) {
      return through.obj(function (file, enc, cb) {
        this.push(file);
        return cb();
      });
    });

    src('*.txt', {cwd: 'fixtures'})
      .pipe(through.obj(function (file, enc, cb) {
        assert.equal(typeof file.path, 'string');
        assert.equal(Buffer.isBuffer(file.contents), false);
        this.push(file);
        cb();
      }))
      .pipe(utils.drain(done));
  });

  it('should take a callback on the loader:', function (done) {
    var src = loader(function (options) {
      return through.obj(function (file, enc, cb) {
        file.foo = 'bar';
        this.push(utils.toVinyl(file));
        return cb();
      })
    });

    src('fixtures/*.txt')
      .pipe(through.obj(function (file, enc, cb) {
        assert.equal(file.foo, 'bar');
        this.push(file);
        cb();
      }))
      .pipe(utils.drain(done));
  });

  it('should convert the file to a vinyl File object:', function (done) {
    var src = loader(function (options) {
      return through.obj(function (file, enc, cb) {
        this.push(utils.toVinyl(file));
        return cb();
      })
    });

    src('fixtures/*.txt')
      .pipe(through.obj(function (file, enc, cb) {
        assert.equal(file instanceof File, true);
        this.push(file);
        cb();
      }))
      .pipe(utils.drain(done));
  });

  it('should add the contents property to a file object:', function (done) {
    this.timeout(5000);

    var src = loader({read: true}, function (opts) {
      return utils.base(opts, function (file, options) {
        return utils.toVinyl(file, options);
      });
    });

    var i = 0;

    src('node_modules/**/*')
      .pipe(src('lib/**/*.js'))
      .pipe(src('fixtures/*.txt'))
      .pipe(src('fixtures/**/*.txt'))
      .pipe(src('fixtures/**/*.md'))
      .pipe(src('fixtures/**/*.js'))
      // .pipe(contents({read: false}))
      .pipe(through.obj(function (file, enc, cb) {
        i++;
        this.push(file);
        return cb();
      }))
      .on('end', function () {
        console.log('read', i, 'files');
      })
      .pipe(utils.drain(done));
  });

  it('should push files into a vinyl src stream:', function (done) {
    var src = loader(function (options) {
      return through.obj(function (file, enc, cb) {
        this.push(utils.toVinyl(file));
        return cb();
      })
    });

    var files = {};
    gulp.src('*.js')
      .pipe(src('fixtures/*.txt'))
      .pipe(src('fixtures/*.md'))
      .pipe(through.obj(function (file, enc, cb) {
        files[file.path] = file;
        this.push(file);
        cb();
      }))
      .pipe(dest('actual'))
      .on('end', function() {
        assert.equal(Object.keys(files).length > 1, true);
        del('actual', done);
      });
  });

  it('should passthrough files when no pattern is given', function (done) {
    var src = loader(function (options) {
      return through.obj(function (file, enc, cb) {
        this.push(file);
        return cb();
      })
    });

    var files1 = [], files2 = [];
    src('fixtures/*.txt')
      .pipe(through.obj(function (file, enc, cb) {
        files1.push(file);
        cb(null, file);
      }))
      .pipe(src([]))
      .pipe(through.obj(function (file, enc, cb) {
        files2.push(file);
        cb(null, file);
      }))
      .on('end', function () {
        assert.deepEqual(files1, files2);
      })
      .pipe(utils.drain(done));
  });
});
<|endoftext|>


<commit_before>chrome.tabs.onUpdated.addListener(
    function(tabId, changeInfo, tab) {
        var url = tab.url;
        if (url.indexOf('://www.bing.com/maps/default.aspx') > 0 && changeInfo.status == 'loading') {
            var rtpIndex = url.indexOf("rtp=");
            if (rtpIndex >= 0) {
                var rtp = url.substr(rtpIndex + 4);
                rtp = rtp.substr(0, rtp.indexOf('&'));
                var address = rtp.substr(rtp.lastIndexOf('_') + 1);
                chrome.tabs.update(tabId, {url: 'https://www.google.com/maps/preview/place/' + address});
            }
        }
    }
)
<commit_msg>Fixing bug where links with coords only didn't work<commit_after>chrome.tabs.onUpdated.addListener(
    function(tabId, changeInfo, tab) {
        var url = tab.url;
        if (url.indexOf('://www.bing.com/maps/default.aspx') > 0 && changeInfo.status == 'loading') {
            var rtpIndex = url.indexOf("rtp=");
            if (rtpIndex >= 0) {
                var rtp = url.substr(rtpIndex + 4);
                rtp = rtp.substr(0, rtp.indexOf('&'));
                var data = rtp.substr(rtp.indexOf('pos.') + 4).split('_');
                var googleParam;
                if (data.length >= 4) {
                    googleParam = data.slice(3).join(', ');
                } else {
                    googleParam = data.slice(0,2).join(',');
                }
                chrome.tabs.update(tabId, {url: 'https://www.google.com/maps/preview/place/' + googleParam});
            }
        }
    }
)
<|endoftext|>


<commit_before>var chai = require('chai');
var should = chai.should();

describe('TribuneData', function() {
  var tribune = require('../lib/tribuneData');

  describe('Crime', function() {
    it()
  });
});
<commit_msg>Working on tests still<commit_after>var chai = require('chai');
var should = chai.should();

describe('TribuneData', function() {
  var tribune = require('../lib/tribuneData');

  describe('getYearCrimeCount', function() {
    it('should return a number', function(done) {
      tribune.getYearCrimeCount(1, 2016, function(err, num) {
        if(err) {
          done(err);
        } else {
          num.should.be.a('number');
          done();
        }
      });
    });

  });
});
<|endoftext|>


<commit_before>/**
 * Copyright (C) 2016 panto.xyz
 * test.js
 *
 * changelog
 * 2016-06-21[19:03:41]:revised
 *
 * @author yanni4night@gmail.com
 * @version 0.0.16
 * @since 0.0.1
 */
'use strict';

const Panto = require('../src/panto');
const panto = require('../');
const assert = require('assert');
const Transformer = require('panto-transformer');
const Stream = require('panto-stream');
const {
    isFunction
} = require('lodash');

/*global describe,it*/
/*eslint no-console: ["error", { allow: ["error"] }] */
describe('panto', () => {
    describe('#constructor', () => {
        it('should define frozen "options"', () => {
            assert.ok('options' in panto, '"options" in panto');
            assert.ok(!!panto.options.get('output'), '"output" in panto.options');
            assert.deepEqual(panto.options.get('cwd'), process.cwd(), '"cwd" in panto.options');
            assert.ok('' === panto.options.get('binary_resource'),
                '"binary_resource" in panto.options');
            assert.throws(() => {
                panto.options = 1;
            }, 'set "panto.options"');
            assert.throws(() => {
                delete panto.options;
            }, 'delete "panto.options"');
        });
        it('should define frozen "file"', () => {
            assert.ok('file' in panto);
            assert.throws(() => {
                delete panto.file;
            }, '"panto.file" is frozen');
        });
        it('should define frozen "util"', () => {
            assert.ok('util' in panto, '"util" in panto');
            assert.ok('_' in panto, '"_" in panto');
            assert.throws(() => {
                delete panto._;
            }, '"panto._" is frozen');
        });
    });
    describe('#setOptions#getOption', () => {
        it('should set to the options', () => {
            const panto = new Panto();
            panto.setOptions({
                cwd: 'xyz'
            });
            assert.deepEqual(panto.getOption('cwd'), 'xyz', '"panto.options.cwd" equals "xyz"');
            assert.deepEqual(panto.getOption('noexist', 'default'), 'default', 'get default');
        });
    });
    describe('#getFiles', () => {
        it('should get the files', done => {
            const panto = new Panto();

            panto.setOptions({
                cwd: __dirname + '/fixtures/'
            });

            panto.getFiles().then(filenames => {
                assert.ok(filenames.indexOf('javascripts/a.js') > -1,
                    'found "javascripts/a.js"');
                assert.ok(filenames.indexOf('javascripts/b.js') > -1,
                    'found "javascripts/b.js"');
                done();
            });
        });
    });
    describe('#pick', () => {
        it('should pick the files', done => {
            const panto = new Panto();

            panto.setOptions({
                cwd: __dirname + '/fixtures/'
            });

            const s = panto.pick('**/*.js').end('js');

            s.push({
                filename: 'javascripts/a.js',
                cmd: 'add'
            });

            s.flow().then(files => {
                assert.ok(files.some(file => file.filename === 'javascripts/a.js'),
                    'match "javascripts/a.js"');
            }).then(() => done());
        });
    });

    describe('#build', function () {
        this.timeout(2e3);
        it('should get all the files', done => {
            const panto = new Panto();

            panto.setOptions({
                cwd: __dirname + '/fixtures/'
            });

            panto.pick('**/*.js').end('js');
            panto.pick('**/*.css').end('css');

            panto.build().then(files => {
                assert.ok(files.some(file => file.filename === 'javascripts/a.js'),
                    'match "javascripts/a.js"');
                assert.ok(files.some(file => file.filename === 'javascripts/b.js'),
                    'match "javascripts/a.js"');
                assert.ok(files.some(file => file.filename === 'stylesheets/a.css'),
                    'match "stylesheets/a.css"');
                assert.ok(files.some(file => file.filename === 'stylesheets/b.css'),
                    'match "stylesheets/b.css"');
            }).then(() => done());
        });
    });

    describe('#clear', function () {
        this.timeout(2e3);
        it('should clear streams', done => {
            const panto = new Panto();

            panto.setOptions({
                cwd: __dirname + '/fixtures/'
            });

            panto.pick('**/*.js').end('js');

            panto.build().then(files => {
                assert.ok(files.some(file => file.filename === 'javascripts/a.js'),
                    'match "javascripts/a.js"');
                assert.ok(files.some(file => file.filename === 'javascripts/b.js'),
                    'match "javascripts/a.js"');
            }).then(() => {
                assert.deepEqual(panto.clear(), panto, 'clear() return self');
                return panto.build();
            }).then(files => {
                assert.deepEqual(files, [], 'no files due to no streams');
            }).then(() => done());
        });
    });

    describe('#rest', function () {
        this.timeout(3e3);
        it('should pick the rest', done => {
            const restFiles = [];

            class FinalTransformer extends Transformer {
                _transform(file) {
                    this.options.collection.push(file);
                    return super._transform(file);
                }
            }

            const panto = new Panto();

            panto.setOptions({
                cwd: __dirname + '/fixtures/'
            });

            panto.rest().pipe(new FinalTransformer({
                collection: restFiles
            })).end('rest');

            panto.pick('**/*.js').end('*.js');
            panto.pick('**/*.css').end('*.css');

            panto.build().then(() => {
                assert.ok(restFiles.some(file => file.filename === 'README.md'),
                    '"README.md" rested');
            }).then(() => done()).catch(e => console.error(e));
        });
    });
    describe('#loadTransformer', () => {
        it('should load the Transformer', () => {
            class Foo {}
            panto.loadTransformer('foo', Foo);
            assert.ok(isFunction(new Stream().foo), '"new Stream().foo" is function');
            assert.ok(new Stream().foo() instanceof Stream,
                '"new Stream().foo()" is an instance of "Foo"');
        });
    });
});<commit_msg>add watch test<commit_after>/**
 * Copyright (C) 2016 panto.xyz
 * test.js
 *
 * changelog
 * 2016-06-21[19:03:41]:revised
 *
 * @author yanni4night@gmail.com
 * @version 0.0.16
 * @since 0.0.1
 */
'use strict';

const Panto = require('../src/panto');
const panto = require('../');
const assert = require('assert');
const Transformer = require('panto-transformer');
const Stream = require('panto-stream');
const {
    isFunction
} = require('lodash');

/*global describe,it*/
/*eslint no-console: ["error", { allow: ["error"] }] */
describe('panto', () => {
    describe('#constructor', () => {
        it('should define frozen "options"', () => {
            assert.ok('options' in panto, '"options" in panto');
            assert.ok(!!panto.options.get('output'), '"output" in panto.options');
            assert.deepEqual(panto.options.get('cwd'), process.cwd(), '"cwd" in panto.options');
            assert.ok('' === panto.options.get('binary_resource'),
                '"binary_resource" in panto.options');
            assert.throws(() => {
                panto.options = 1;
            }, 'set "panto.options"');
            assert.throws(() => {
                delete panto.options;
            }, 'delete "panto.options"');
        });
        it('should define frozen "file"', () => {
            assert.ok('file' in panto);
            assert.throws(() => {
                delete panto.file;
            }, '"panto.file" is frozen');
        });
        it('should define frozen "util"', () => {
            assert.ok('util' in panto, '"util" in panto');
            assert.ok('_' in panto, '"_" in panto');
            assert.throws(() => {
                delete panto._;
            }, '"panto._" is frozen');
        });
    });
    describe('#setOptions#getOption', () => {
        it('should set to the options', () => {
            const panto = new Panto();
            panto.setOptions({
                cwd: 'xyz'
            });
            assert.deepEqual(panto.getOption('cwd'), 'xyz', '"panto.options.cwd" equals "xyz"');
            assert.deepEqual(panto.getOption('noexist', 'default'), 'default', 'get default');
        });
    });
    describe('#getFiles', () => {
        it('should get the files', done => {
            const panto = new Panto();

            panto.setOptions({
                cwd: __dirname + '/fixtures/'
            });

            panto.getFiles().then(filenames => {
                assert.ok(filenames.indexOf('javascripts/a.js') > -1,
                    'found "javascripts/a.js"');
                assert.ok(filenames.indexOf('javascripts/b.js') > -1,
                    'found "javascripts/b.js"');
                done();
            });
        });
    });
    describe('#pick', () => {
        it('should pick the files', done => {
            const panto = new Panto();

            panto.setOptions({
                cwd: __dirname + '/fixtures/'
            });

            const s = panto.pick('**/*.js').end('js');

            s.push({
                filename: 'javascripts/a.js',
                cmd: 'add'
            });

            s.flow().then(files => {
                assert.ok(files.some(file => file.filename === 'javascripts/a.js'),
                    'match "javascripts/a.js"');
            }).then(() => done());
        });
    });

    describe('#build', function () {
        this.timeout(2e3);
        it('should get all the files', done => {
            const panto = new Panto();

            panto.setOptions({
                cwd: __dirname + '/fixtures/'
            });

            panto.pick('**/*.js').end('js');
            panto.pick('**/*.css').end('css');

            panto.build().then(files => {
                assert.ok(files.some(file => file.filename === 'javascripts/a.js'),
                    'match "javascripts/a.js"');
                assert.ok(files.some(file => file.filename === 'javascripts/b.js'),
                    'match "javascripts/a.js"');
                assert.ok(files.some(file => file.filename === 'stylesheets/a.css'),
                    'match "stylesheets/a.css"');
                assert.ok(files.some(file => file.filename === 'stylesheets/b.css'),
                    'match "stylesheets/b.css"');
            }).then(() => done());
        });
    });

    describe('#clear', function () {
        this.timeout(2e3);
        it('should clear streams', done => {
            const panto = new Panto();

            panto.setOptions({
                cwd: __dirname + '/fixtures/'
            });

            panto.pick('**/*.js').end('js');

            panto.build().then(files => {
                assert.ok(files.some(file => file.filename === 'javascripts/a.js'),
                    'match "javascripts/a.js"');
                assert.ok(files.some(file => file.filename === 'javascripts/b.js'),
                    'match "javascripts/a.js"');
            }).then(() => {
                assert.deepEqual(panto.clear(), panto, 'clear() return self');
                return panto.build();
            }).then(files => {
                assert.deepEqual(files, [], 'no files due to no streams');
            }).then(() => done());
        });
    });

    describe('#rest', function () {
        this.timeout(3e3);
        it('should pick the rest', done => {
            const restFiles = [];

            class FinalTransformer extends Transformer {
                _transform(file) {
                    this.options.collection.push(file);
                    return super._transform(file);
                }
            }

            const panto = new Panto();

            panto.setOptions({
                cwd: __dirname + '/fixtures/'
            });

            panto.rest().pipe(new FinalTransformer({
                collection: restFiles
            })).end('rest');

            panto.pick('**/*.js').end('*.js');
            panto.pick('**/*.css').end('*.css');

            panto.build().then(() => {
                assert.ok(restFiles.some(file => file.filename === 'README.md'),
                    '"README.md" rested');
            }).then(() => done()).catch(e => console.error(e));
        });
    });
    describe('#watch', function () {
        this.timeout(5e3);
        it('', done => {
            const panto = new Panto();

            panto.setOptions({
                cwd: __dirname + '/fixtures/'
            });
            const watcher = panto.watch();
            watcher.close();
            done();
        });
    });
    describe('#loadTransformer', () => {
        it('should load the Transformer', () => {
            class Foo {}
            panto.loadTransformer('foo', Foo);
            assert.ok(isFunction(new Stream().foo), '"new Stream().foo" is function');
            assert.ok(new Stream().foo() instanceof Stream,
                '"new Stream().foo()" is an instance of "Foo"');
        });
    });
});<|endoftext|>


<commit_before>/**
 * User: azu
 * Date: 2013/05/18
 * License: MIT License
 */
var assert = require("assert")
describe('Function', function (){
    describe('When function contain /* comment */', function (){
        it('should contain /* comment */', function (){
            var result = (function(){/*comment*/}).toString();
            var isContain = result.indexOf("/*comment*/") !== -1;
            assert.ok(isContain, "result contain /*comment*/");
        });
    });
    describe('When function contain multiline /*comment*/', function (){
        it('should contain /* comment */', function (){
            var result = (function (){/*
            comment
            */}).toString();
            var isContain = result.indexOf("comment") !== -1;
            assert.ok(isContain, "result contain comment");
        });
    });
    describe('When function contain //comment ', function (){
        it('should contain /* comment */', function (){
            var result = (function (){
                // comment
            }).toString();
            var isContain = result.indexOf("// comment") !== -1;
            assert.ok(isContain, "result contain comment");
        });
    });
});<commit_msg>more simple<commit_after>/**
 * User: azu
 * Date: 2013/05/18
 * License: MIT License
 */
var assert = require("assert")
describe('Function', function (){
    describe('When function contain /* comment */', function (){
        it('should contain comment', function (){
            var result = (function(){/*comment*/}).toString();
            var isContain = result.indexOf("comment") !== -1;
            assert.ok(isContain, "result contain comment");
        });
    });
    describe('When function contain multiline /*comment*/', function (){
        it('should contain comment', function (){
            var result = (function (){/*
            comment
            */}).toString();
            var isContain = result.indexOf("comment") !== -1;
            assert.ok(isContain, "result contain comment");
        });
    });
    describe('When function contain //comment ', function (){
        it('should contain comment', function (){
            var result = (function (){
                // comment
            }).toString();
            var isContain = result.indexOf("// comment") !== -1;
            assert.ok(isContain, "result contain comment");
        });
    });
});<|endoftext|>


<commit_before>var assert = require('chai').assert;
var Q = require('q');
var collection = require('../index.js');

describe('plugin', function(){

    var plugin = collection('test', function(pages, next){

        pages.push('a');

        next(pages);
    });

    it('should act on all desired properties as if they are pages', function(done){

        plugin([{}, {}, {}], function(pages){

            assert.deepEqual(pages, [ { test: ['a'] }, { test: ['a'] }, { test: ['a'] } ]);

            done();
        });
    });

    describe('when the property already exists and is an array', function(){

        it('should work with it', function(done){

            plugin([{}, {test: ['b']}, {}], function(pages){

                assert.deepEqual(pages, [ { test: ['a'] }, { test: ['b', 'a'] }, { test: ['a'] } ]);

                done();
            });
        });
    });

    describe('when the property already exists but is not an array', function(){

        it('should replace it', function(done){

            plugin([{}, {test: 'a'}, {}], function(pages){

                assert.deepEqual(pages, [ { test: ['a'] }, { test: ['a'] }, { test: ['a'] } ]);

                done();
            });
        });
    });
});
<commit_msg>Improve test output<commit_after>var assert = require('chai').assert;
var Q = require('q');
var collection = require('../index.js');

describe('plugin', function(){

    var plugin = collection('test', function(pages, next){

        pages.push('a');

        next(pages);
    });

    it('should act on all desired properties as if they are pages', function(done){

        plugin([{}, {}, {}], function(pages){

            assert.deepEqual(pages, [ { test: ['a'] }, { test: ['a'] }, { test: ['a'] } ]);

            done();
        });
    });

    it('should append to existing property that is an array', function(done){

        plugin([{test: ['b']}], function(pages){

            assert.deepEqual(pages, [ { test: ['b', 'a'] } ]);

            done();
        });
    });

    it('should replace existing property that is not an array', function(done){

        plugin([{test: 'a'}], function(pages){

            assert.deepEqual(pages, [ { test: ['a'] } ]);

            done();
        });
    });
});
<|endoftext|>