<commit_before>/*global describe, it, beforeEach, afterEach*/
/*jshint expr: true*/
'use strict';

var chai = require('chai');
var sinon = require('sinon');
var sinonChai = require('sinon-chai');
var util = require('util');

var healthcheck = require('..');
var constants = require('../constants.js');
var errorMessages = constants.ErrorMessages;

chai.use(sinonChai);
chai.should();

describe('healthcheck-middleware', function() {

	describe('options', function() {
		var req, res, next;
		var uptime;
		var memory;

		beforeEach(function() {
			res = {
				status: sinon.stub(),
				json: sinon.stub()
			};
			res.status.returns(res);

			uptime = 999;
			memory = {
				rss: 50,
				heapTotal: 51,
				heapUsed: 52,
			};

			sinon.stub(process, 'uptime').returns(uptime);
			sinon.stub(process, 'memoryUsage').returns(memory);
		});

		afterEach(function() {
			res = undefined;
			uptime = undefined;
			memory = undefined;

			process.uptime.restore();
			process.memoryUsage.restore();
		});

		describe('when not provided', function() {
			it('responds with 200 status', function() {
				healthcheck()(req, res, next);
				res.status.should.have.been.calledWith(200);
			});

			it('responds with json containing successful status, uptime and memoryUsage', function() {
				var expected = {
					status: constants.Status.Success,
					uptime: uptime,
					memoryUsage: memory
				};

				healthcheck()(req, res, next);
				res.json.should.have.been.calledWith(expected);
			});
		});

		describe('when non-object provided', function() {
			it('throws InvalidOptionsError', function() {
				var check = function() {
					healthcheck('woo');
				};

				check.should.Throw(errorMessages.InvalidOptionsError);
			});
		});

		describe('when empty object provided', function() {
			it('responds with 200 status', function() {
				healthcheck({})(req, res, next);
				res.status.should.have.been.calledWith(200);
			});

			it('responds with json containing successful status, uptime and memoryUsage', function() {
				var expected = {
					status: constants.Status.Success,
					uptime: uptime,
					memoryUsage: memory
				};

				healthcheck({})(req, res, next);
				res.json.should.have.been.calledWith(expected);
			});

		});

	});

	describe('options.addChecks', function() {
		var req, res, next;

		beforeEach(function() {
			res = {
				status: sinon.stub(),
				json: sinon.stub()
			};
			res.status.returns(res);
		});

		afterEach(function() {
			res = undefined;
		});

		describe('when non-function provided', function() {
			it('throws FunctionError', function() {
				var check = function() {
					healthcheck({addChecks: 'blah'});
				};

				check.should.Throw(errorMessages.FunctionError);
			});
		});

		describe('when function provided', function() {
			it('executes provided function', function() {
				var customChecks = sinon.spy();
				healthcheck({addChecks: customChecks})(req, res, next);

				customChecks.should.have.been.calledOnce;
			});
		});

		describe('when error thrown', function() {
			it('responds with status 500', function() {
				var customChecks = function() {
					throw new Error('BOOM');
				};

				healthcheck({addChecks: customChecks})(req, res, next);
				res.status.should.have.been.calledWith(500);
			});

			it('responds with json containing failure status and error message', function() {
				var errorMessage = 'BOOM';
				var expected = {
					status: constants.Status.Failure,
					message: errorMessage
				};

				var customChecks = function() {
					throw new Error(errorMessage);
				};

				healthcheck({addChecks: customChecks})(req, res, next);
				res.json.should.have.been.calledWith(expected);
			});
		});

		describe('when fail called', function() {
			it('responds with status 500', function() {
				var customChecks = function(fail) {
					fail();
				};

				healthcheck({addChecks: customChecks})(req, res, next);
				res.status.should.have.been.calledWith(500);
			});

			it('responds with json containing failure status and error message from parameter', function() {
				var errorMessage = 'BOOM';
				var expected = {
					status: constants.Status.Failure,
					message: errorMessage
				};

				var customChecks = function(fail) {
					fail(new Error(errorMessage));
				};

				healthcheck({addChecks: customChecks})(req, res, next);
				res.json.should.have.been.calledWith(expected);
			});

		});

		describe('when pass called', function() {
			var uptime;
			var memory;

			beforeEach(function() {
				uptime = 999;
				memory = {
					rss: 50,
					heapTotal: 51,
					heapUsed: 52,
				};

				sinon.stub(process, 'uptime').returns(uptime);
				sinon.stub(process, 'memoryUsage').returns(memory);
			});

			afterEach(function() {
				uptime = undefined;
				memory = undefined;

				process.uptime.restore();
				process.memoryUsage.restore();
			});

			it('responds with status 200', function() {
				var customChecks = function(fail, pass) {
					pass();
				};

				healthcheck({addChecks: customChecks})(req, res, next);
				res.status.should.have.been.calledWith(200);
			});

			describe('without custom pass info', function() {
				it('responds with json containing successful status, uptime and memoryUsage', function() {
					var expected = {
						status: constants.Status.Success,
						uptime: uptime,
						memoryUsage: memory
					};

					var customChecks = function(fail, pass) {
						pass();
					};

					healthcheck({addChecks: customChecks})(req, res, next);

					res.json.should.have.been.calledWith(expected);
				});
			});

			describe('with custom pass info', function() {
				it('responds with json containing custom pass info + successful status, uptime and memoryUsage', function() {
					var customPassInfo = {
						custom: 'yes'
					};

					var expected = {
						custom: 'yes',
						status: constants.Status.Success,
						uptime: uptime,
						memoryUsage: memory
					};

					var customChecks = function(fail, pass) {
						pass(customPassInfo);
					};

					healthcheck({addChecks: customChecks})(req, res, next);

					res.json.should.have.been.calledWith(expected);
				});

				it('responds with json containing custom pass info overrides for status, uptime and memoryUsage', function() {
					var customPassInfo = {
						custom: 'yes',
						status: 'YES',
						uptime: 1000,
						memoryUsage: 1001
					};

					var expected = {
						custom: customPassInfo.custom,
						status: customPassInfo.status,
						uptime: customPassInfo.uptime,
						memoryUsage: customPassInfo.memoryUsage
					};

					var customChecks = function(fail, pass) {
						pass(customPassInfo);
					};

					healthcheck({addChecks: customChecks})(req, res, next);

					res.json.should.have.been.calledWith(expected);
				});
			});
		});
	});

	describe('options.healthInfo', function() {
		var req, res, next;

		beforeEach(function() {
			res = {
				status: sinon.stub(),
				json: sinon.stub()
			};
			res.status.returns(res);
		});

		afterEach(function() {
			res = undefined;
		});

		describe('when non-function provided', function() {
			it('throws FunctionError', function() {
				var check = function() {
					healthcheck({healthInfo: 'blah'});
				};

				check.should.Throw(errorMessages.FunctionError);
			});
		});

		describe('when function provided', function() {
			it('executes provided healthInfo', function() {
				var customHealthInfo = sinon.spy();
				healthcheck({healthInfo: customHealthInfo})(req, res, next);

				customHealthInfo.should.have.been.calledOnce;
			});
		});

		describe('when nothing returned', function() {
			it('renders empty json', function() {
				var customHealthInfo = function() {
					return;
				};

				healthcheck({healthInfo: customHealthInfo})(req, res, next);

				res.json.should.have.been.calledWith({});
			});
		});

		describe('when json returned', function() {
			it('renders returned json', function() {
				var returnData = {
					whereAmI: 'no here',
					status: 'YES',
					uptime: 1000,
					memoryUsage: 1001
				};

				var customHealthInfo = function() {
					return returnData;
				};

				healthcheck({healthInfo: customHealthInfo})(req, res, next);

				res.json.should.have.been.calledWith(returnData);
			});
		});

		describe('when string returned', function() {
			it('renders json with { message: string }', function() {
				var stringValue = 'my string value';
				var customHealthInfo = function() {
					return stringValue;
				};

				healthcheck({healthInfo: customHealthInfo})(req, res, next);

				res.json.should.have.been.calledWith({message: stringValue});
			});
		});

		describe('when non-json/string returned', function() {
			it('renders json with { message: returnedValue.toString() }', function() {
				var returnValue = function() { return 'whaty?'; };
				var customHealthInfo = function() {
					return returnValue;
				};

				healthcheck({healthInfo: customHealthInfo})(req, res, next);

				res.json.should.have.been.calledWith({message: returnValue.toString()});
			});
		});

		describe('when error thrown', function() {
			var uptime;
			var memory;

			beforeEach(function() {
				uptime = 999;
				memory = {
					rss: 50,
					heapTotal: 51,
					heapUsed: 52,
				};

				sinon.stub(process, 'uptime').returns(uptime);
				sinon.stub(process, 'memoryUsage').returns(memory);
			});

			afterEach(function() {
				uptime = undefined;
				memory = undefined;

				process.uptime.restore();
				process.memoryUsage.restore();
			});

			it('responds with status 200', function() {
				var customHealthInfo = function() {
					throw new Error('BOOM');
				};

				healthcheck({healthInfo: customHealthInfo})(req, res, next);
				res.status.should.have.been.calledWith(200);
			});

			it('responds with json containing successful status and warning message', function() {
				var errorMessage = 'BOOM';
				var expected = {
					status: constants.Status.Success,
					warning: util.format('%s: %s', errorMessages.HealthInfoError, errorMessage)
				};

				var customHealthInfo = function() {
					throw new Error(errorMessage);
				};

				healthcheck({healthInfo: customHealthInfo})(req, res, next);
				res.json.should.have.been.calledWith(expected);
			});

		});

	});
});<commit_msg>moved before/after test methods to be same set for all tests<commit_after>/*global describe, it, beforeEach, afterEach*/
/*jshint expr: true*/
'use strict';

var chai = require('chai');
var sinon = require('sinon');
var sinonChai = require('sinon-chai');
var util = require('util');

var healthcheck = require('..');
var constants = require('../constants.js');
var errorMessages = constants.ErrorMessages;

chai.use(sinonChai);
chai.should();

describe('healthcheck-middleware', function() {
	var req, res, next;
	var uptime;
	var memory;

	beforeEach(function() {
		res = {
			status: sinon.stub(),
			json: sinon.stub()
		};
		res.status.returns(res);

		uptime = 999;
		memory = {
			rss: 50,
			heapTotal: 51,
			heapUsed: 52,
		};

		sinon.stub(process, 'uptime').returns(uptime);
		sinon.stub(process, 'memoryUsage').returns(memory);
	});

	afterEach(function() {
		res = undefined;
		uptime = undefined;
		memory = undefined;

		process.uptime.restore();
		process.memoryUsage.restore();
	});

	describe('options', function() {
		describe('when not provided', function() {
			it('responds with 200 status', function() {
				healthcheck()(req, res, next);
				res.status.should.have.been.calledWith(200);
			});

			it('responds with json containing successful status, uptime and memoryUsage', function() {
				var expected = {
					status: constants.Status.Success,
					uptime: uptime,
					memoryUsage: memory
				};

				healthcheck()(req, res, next);
				res.json.should.have.been.calledWith(expected);
			});
		});

		describe('when non-object provided', function() {
			it('throws InvalidOptionsError', function() {
				var check = function() {
					healthcheck('woo');
				};

				check.should.Throw(errorMessages.InvalidOptionsError);
			});
		});

		describe('when empty object provided', function() {
			it('responds with 200 status', function() {
				healthcheck({})(req, res, next);
				res.status.should.have.been.calledWith(200);
			});

			it('responds with json containing successful status, uptime and memoryUsage', function() {
				var expected = {
					status: constants.Status.Success,
					uptime: uptime,
					memoryUsage: memory
				};

				healthcheck({})(req, res, next);
				res.json.should.have.been.calledWith(expected);
			});
		});
	});

	describe('options.addChecks', function() {
		describe('when non-function provided', function() {
			it('throws FunctionError', function() {
				var check = function() {
					healthcheck({addChecks: 'blah'});
				};

				check.should.Throw(errorMessages.FunctionError);
			});
		});

		describe('when function provided', function() {
			it('executes provided function', function() {
				var customChecks = sinon.spy();
				healthcheck({addChecks: customChecks})(req, res, next);

				customChecks.should.have.been.calledOnce;
			});
		});

		describe('when error thrown', function() {
			it('responds with status 500', function() {
				var customChecks = function() {
					throw new Error('BOOM');
				};

				healthcheck({addChecks: customChecks})(req, res, next);
				res.status.should.have.been.calledWith(500);
			});

			it('responds with json containing failure status and error message', function() {
				var errorMessage = 'BOOM';
				var expected = {
					status: constants.Status.Failure,
					message: errorMessage
				};

				var customChecks = function() {
					throw new Error(errorMessage);
				};

				healthcheck({addChecks: customChecks})(req, res, next);
				res.json.should.have.been.calledWith(expected);
			});
		});

		describe('when fail called', function() {
			it('responds with status 500', function() {
				var customChecks = function(fail) {
					fail();
				};

				healthcheck({addChecks: customChecks})(req, res, next);
				res.status.should.have.been.calledWith(500);
			});

			it('responds with json containing failure status and error message from parameter', function() {
				var errorMessage = 'BOOM';
				var expected = {
					status: constants.Status.Failure,
					message: errorMessage
				};

				var customChecks = function(fail) {
					fail(new Error(errorMessage));
				};

				healthcheck({addChecks: customChecks})(req, res, next);
				res.json.should.have.been.calledWith(expected);
			});

		});

		describe('when pass called', function() {
			it('responds with status 200', function() {
				var customChecks = function(fail, pass) {
					pass();
				};

				healthcheck({addChecks: customChecks})(req, res, next);
				res.status.should.have.been.calledWith(200);
			});

			describe('without custom pass info', function() {
				it('responds with json containing successful status, uptime and memoryUsage', function() {
					var expected = {
						status: constants.Status.Success,
						uptime: uptime,
						memoryUsage: memory
					};

					var customChecks = function(fail, pass) {
						pass();
					};

					healthcheck({addChecks: customChecks})(req, res, next);

					res.json.should.have.been.calledWith(expected);
				});
			});

			describe('with custom pass info', function() {
				it('responds with json containing custom pass info + successful status, uptime and memoryUsage', function() {
					var customPassInfo = {
						custom: 'yes'
					};

					var expected = {
						custom: 'yes',
						status: constants.Status.Success,
						uptime: uptime,
						memoryUsage: memory
					};

					var customChecks = function(fail, pass) {
						pass(customPassInfo);
					};

					healthcheck({addChecks: customChecks})(req, res, next);

					res.json.should.have.been.calledWith(expected);
				});

				it('responds with json containing custom pass info overrides for status, uptime and memoryUsage', function() {
					var customPassInfo = {
						custom: 'yes',
						status: 'YES',
						uptime: 1000,
						memoryUsage: 1001
					};

					var expected = {
						custom: customPassInfo.custom,
						status: customPassInfo.status,
						uptime: customPassInfo.uptime,
						memoryUsage: customPassInfo.memoryUsage
					};

					var customChecks = function(fail, pass) {
						pass(customPassInfo);
					};

					healthcheck({addChecks: customChecks})(req, res, next);

					res.json.should.have.been.calledWith(expected);
				});
			});
		});
	});

	describe('options.healthInfo', function() {
		describe('when non-function provided', function() {
			it('throws FunctionError', function() {
				var check = function() {
					healthcheck({healthInfo: 'blah'});
				};

				check.should.Throw(errorMessages.FunctionError);
			});
		});

		describe('when function provided', function() {
			it('executes provided healthInfo', function() {
				var customHealthInfo = sinon.spy();
				healthcheck({healthInfo: customHealthInfo})(req, res, next);

				customHealthInfo.should.have.been.calledOnce;
			});
		});

		describe('when nothing returned', function() {
			it('renders empty json', function() {
				var customHealthInfo = function() {
					return;
				};

				healthcheck({healthInfo: customHealthInfo})(req, res, next);

				res.json.should.have.been.calledWith({});
			});
		});

		describe('when json returned', function() {
			it('renders returned json', function() {
				var returnData = {
					whereAmI: 'no here',
					status: 'YES',
					uptime: 1000,
					memoryUsage: 1001
				};

				var customHealthInfo = function() {
					return returnData;
				};

				healthcheck({healthInfo: customHealthInfo})(req, res, next);

				res.json.should.have.been.calledWith(returnData);
			});
		});

		describe('when string returned', function() {
			it('renders json with { message: string }', function() {
				var stringValue = 'my string value';
				var customHealthInfo = function() {
					return stringValue;
				};

				healthcheck({healthInfo: customHealthInfo})(req, res, next);

				res.json.should.have.been.calledWith({message: stringValue});
			});
		});

		describe('when non-json/string returned', function() {
			it('renders json with { message: returnedValue.toString() }', function() {
				var returnValue = function() { return 'whaty?'; };
				var customHealthInfo = function() {
					return returnValue;
				};

				healthcheck({healthInfo: customHealthInfo})(req, res, next);

				res.json.should.have.been.calledWith({message: returnValue.toString()});
			});
		});

		describe('when error thrown', function() {
			it('responds with status 200', function() {
				var customHealthInfo = function() {
					throw new Error('BOOM');
				};

				healthcheck({healthInfo: customHealthInfo})(req, res, next);
				res.status.should.have.been.calledWith(200);
			});

			it('responds with json containing successful status and warning message', function() {
				var errorMessage = 'BOOM';
				var expected = {
					status: constants.Status.Success,
					warning: util.format('%s: %s', errorMessages.HealthInfoError, errorMessage)
				};

				var customHealthInfo = function() {
					throw new Error(errorMessage);
				};

				healthcheck({healthInfo: customHealthInfo})(req, res, next);
				res.json.should.have.been.calledWith(expected);
			});
		});
	});
});<|endoftext|>


<commit_before>var stream = require('../lib/twitter-stream.js');
var testUserConfig = require('../user-config.json');
var fs = require('fs');

exports['fileSize'] = function(test) {

  fs.writeFile('./testfile.json', "");
  stream.getCompareFileSize('./testfile.json', "2 MB",function(ret){
    test.equal(ret,0);
  });

  stream.getCompareFileSize('./testfile.json', "10 B",function(ret){
    test.equal(ret,0);
  });

  stream.getCompareFileSize('./user-config.json', "300 B",function(ret){
    test.equal(ret,1);
  });

  test.done();
};

exports['testStreams'] = function(test) {

  stream.initConfig();
  var client = stream.createClient();
  var writeStream = fs.createWriteStream("./testfile.json", {'flags': 'a'});

  stream.saveStream(client,writeStream,1);
  setTimeout(function(){writeStream.end();},2500);

  test.notEqual(typeof client, new Object());
  test.done();
};

exports['unwatch'] = function(test) {

  test.expect(1);
    fs.unwatchFile("./testfile.json");

    test.ok(true);
    test.done();
};
<commit_msg>more tests<commit_after>var stream = require('../lib/twitter-stream.js');
var testUserConfig = require('../user-config.json');
var fs = require('fs');

exports['checkValues'] = function (test) {
    stream.initConfig();
    test.notEqual(stream.getStorage().length,0);
    test.notEqual(stream.getConnection().size,0);
    test.done();
};

exports['fileSize'] = function(test) {

  fs.writeFile('./testfile.json', "");
  stream.getCompareFileSize('./testfile.json', "2 MB",function(ret){
    test.equal(ret,0);
  });

  stream.getCompareFileSize('./testfile.json', "10 B",function(ret){
    test.equal(ret,0);
  });

  stream.getCompareFileSize('./user-config.json', "300 B",function(ret){
    test.equal(ret,1);
  });

  test.done();
};

exports['testStreams'] = function(test) {

  stream.initConfig();
  var client = stream.createClient();
  var writeStream = fs.createWriteStream("./testfile.json", {'flags': 'a'});

  stream.saveStream(client,writeStream,1);
  setTimeout(function(){writeStream.end();},2500);

  test.notEqual(typeof client, new Object());
  test.done();
};

exports['unwatch'] = function(test) {

  test.expect(1);
    fs.unwatchFile("./testfile.json");

    test.ok(true);
    test.done();
};
<|endoftext|>


<commit_before>// Karma configuration

var fs = require("fs");
module.exports = function(config) {
  var customLaunchers = {
    'SL_Chrome_Latest': {
      base: 'SauceLabs',
      browserName: 'chrome',
      platform: 'linux'
    },
    'SL_Chrome_48': {
      base: 'SauceLabs',
      browserName: 'chrome',
      platform: 'OS X 10.10',
      version: '48',
    },
    'SL_Firefox_Latest': {
      base: 'SauceLabs',
      browserName: 'firefox',
      platform: 'linux'
    },
    'SL_Safari_Latest': {
      base: 'SauceLabs',
      browserName: 'safari',
      platform: 'OS X 10.11'
    },
    'SL_Safari_8': {
      base: 'SauceLabs',
      browserName: 'safari',
      platform: 'OS X 10.10',
      version: '8',
    },
    'SL_Opera_12': {
      base: 'SauceLabs',
      browserName: 'opera',
      platform: 'Windows 7',
      version: '12'
    },
    'SL_Edge': {
      base: 'SauceLabs',
      browserName: 'microsoftedge',
      platform: 'Windows 10'
    },
    'SL_IE_10': {
      base: 'SauceLabs',
      browserName: 'internet explorer',
      platform: 'Windows 7',
      version: '10'
    },
    'SL_IE_9': {
      base: 'SauceLabs',
      browserName: 'internet explorer',
      platform: 'Windows 7',
      version: '9'
    }
  };

  var reporters = ['dots'];
  var browsers = [];
  var singlerun = false;
  var concurrency = Infinity;

  if (process.env.SAUCE_USERNAME) {
    reporters.push('saucelabs');
    Array.prototype.push.apply(browsers, Object.keys(customLaunchers));
    singlerun = true;
    concurrency = 2;
  }

  config.set({
    basePath: '',
    frameworks: ['jasmine'],
    sauceLabs: {
      recordScreenshots: false,
      avoidProxy: true,
      connectOptions: {
        port: 5757,
        logfile: 'sauce_connect.log'
      },
      public: 'public'
    },
    files: [
      'ts/build/integration-tests.js'
    ],
    preprocessors: {
      '**/*.js': ['sourcemap']
    },
    reporters: reporters,
    port: 9876,
    protocol: "https",
    httpsServerOptions: {
      key: fs.readFileSync('../misc/localhost.key', 'utf8'),
      cert: fs.readFileSync('../misc/localhost.crt', 'utf8')
    },
    colors: true,
    client: {
      captureConsole: true,
      runInParent: true,
      useIframe: false,
    },
    autoWatch: true,
    browsers: browsers,
    captureTimeout: 120000,
    customLaunchers: customLaunchers,
    singleRun: singlerun,
    concurrency: concurrency
  })
};
<commit_msg>Removed browsers that do not support tests over https<commit_after>// Karma configuration

var fs = require("fs");
module.exports = function(config) {
  var customLaunchers = {
    'SL_Chrome_Latest': {
      base: 'SauceLabs',
      browserName: 'chrome',
      platform: 'OS X 10.10'
    },
    'SL_Chrome_48': {
      base: 'SauceLabs',
      browserName: 'chrome',
      platform: 'OS X 10.10',
      version: '48'
    },
    'SL_Chrome_41': { // Fetch support added in Chrome 42
      base: 'SauceLabs',
      browserName: 'chrome',
      platform: 'OS X 10.10',
      version: '41'
    },
    'SL_Firefox_Latest': {
      base: 'SauceLabs',
      browserName: 'firefox',
      platform: 'OS X 10.10'
    },
    'SL_Firefox_52': {
      base: 'SauceLabs',
      browserName: 'firefox',
      platform: 'OS X 10.10',
      version: '52'
    },
    'SL_Firefox_38': { // Fetch support added in Firefox 39
      base: 'SauceLabs',
      browserName: 'firefox',
      platform: 'OS X 10.10',
      version: '38'
    }
  };

  var reporters = ['dots'];
  var browsers = [];
  var singlerun = false;
  var concurrency = Infinity;

  if (process.env.SAUCE_USERNAME) {
    reporters.push('saucelabs');
    Array.prototype.push.apply(browsers, Object.keys(customLaunchers));
    singlerun = true;
    concurrency = 2;
  }

  config.set({
    basePath: '',
    frameworks: ['jasmine'],
    sauceLabs: {
      recordScreenshots: false,
      avoidProxy: true,
      connectOptions: {
        port: 5757,
        logfile: 'sauce_connect.log'
      },
      public: 'public'
    },
    files: [
      'ts/build/integration-tests.js'
    ],
    preprocessors: {
      '**/*.js': ['sourcemap']
    },
    reporters: reporters,
    port: 9876,
    protocol: "https",
    httpsServerOptions: {
      key: fs.readFileSync('../misc/localhost.key', 'utf8'),
      cert: fs.readFileSync('../misc/localhost.crt', 'utf8')
    },
    colors: true,
    client: {
      captureConsole: true,
      runInParent: true,
      useIframe: false,
    },
    autoWatch: true,
    browsers: browsers,
    captureTimeout: 120000,
    customLaunchers: customLaunchers,
    singleRun: singlerun,
    concurrency: concurrency
  })
};
<|endoftext|>


<commit_before>// Karma configuration
// Generated on 2017-01-30

module.exports = function(config) {
  'use strict';

  config.set({
    // enable / disable watching file and executing tests whenever any file changes
    autoWatch: true,

    // base path, that will be used to resolve files and exclude
    basePath: '',

    // testing framework to use (jasmine/mocha/qunit/...)
    // as well as any additional frameworks (requirejs/chai/sinon/...)
    frameworks: [
      'jasmine'
    ],

    // list of files / patterns to load in the browser
    files: [
    ],

    // list of files / patterns to exclude
    exclude: [
    ],

    // web server port
    port: 8080,

    // Start these browsers, currently available:
    // - Chrome
    // - ChromeCanary
    // - Firefox
    // - Opera
    // - Safari (only Mac)
    // - PhantomJS
    // - IE (only Windows)
    browsers: [
      'PhantomJS'
    ],

    // Which plugins to enable
    plugins: [
      'karma-phantomjs-launcher',
      'karma-jasmine'
    ],

    // Continuous Integration mode
    // if true, it capture browsers, run tests and exit
    singleRun: false,

    colors: true,

    // level of logging
    // possible values: LOG_DISABLE || LOG_ERROR || LOG_WARN || LOG_INFO || LOG_DEBUG
    logLevel: config.LOG_INFO,

    // Uncomment the following lines if you are using grunt's server to run the tests
    // proxies: {
    //   '/': 'http://localhost:9000/'
    // },
    // URL root prevent conflicts with the site root
    // urlRoot: '_karma_'
  });
};
<commit_msg>Remove random file<commit_after><|endoftext|>


<commit_before>// Karma configuration
// Generated on Thu Mar 12 2015 18:13:33 GMT-0300 (ART)

module.exports = function(config) {
  config.set({

    // base path that will be used to resolve all patterns (eg. files, exclude)
    basePath: '..',

    // frameworks to use
    // available frameworks: https://npmjs.org/browse/keyword/karma-adapter
    frameworks: ['jasmine'],

    // list of files / patterns to load in the browser
    files: [
      'bower_components/fastclick/lib/fastclick.js',
      'bower_components/qrcode-generator/js/qrcode.js',
      'bower_components/qrcode-decoder-js/lib/qrcode-decoder.js',
      'bower_components/moment/min/moment-with-locales.js',
      'bower_components/angular/angular.js',
      'bower_components/angular-ui-router/release/angular-ui-router.js',
      'bower_components/angular-local-storage/dist/angular-local-storage.js',
      'bower_components/angular-foundation/mm-foundation.js',
      'bower_components/angular-foundation/mm-foundation-tpls.js',
      'bower_components/angular-animate/angular-animate.js',
      'bower_components/angular-moment/angular-moment.js',
      'bower_components/ng-lodash/build/ng-lodash.js',
      'bower_components/angular-qrcode/qrcode.js',
      'bower_components/angular-gettext/dist/angular-gettext.js',
      'bower_components/angular-touch/angular-touch.js',
      'bower_components/angular-ui-switch/angular-ui-switch.js',
      'node_modules/angular-mocks/angular-mocks.js',
      'src/js/**/*.js',
      'test/**/*.js'
    ],

    // list of files to exclude
    exclude: [
      'src/js/translations.js',
      'src/js/version.js',
      'test/karma.conf.js',
      'test/old/*'
    ],

    // preprocess matching files before serving them to the browser
    // available preprocessors: https://npmjs.org/browse/keyword/karma-preprocessor
    preprocessors: {
      'src/js/**/*.js': ['coverage']
    },

    // test results reporter to use
    // possible values: 'dots', 'progress'
    // available reporters: https://npmjs.org/browse/keyword/karma-reporter
    reporters: ['progress', , 'coverage'],

    // optionally, configure the reporter
    coverageReporter: {
      dir: 'coverage/',
      reporters: [{
        type: 'html',
        subdir: 'report-html'
      }, {
        type: 'lcov',
        subdir: 'report-lcov'
      }, {
        type: 'text-summary'
      }]
    },

    // web server port
    port: 9876,

    // enable / disable colors in the output (reporters and logs)
    colors: true,

    // level of logging
    // possible values: config.LOG_DISABLE || config.LOG_ERROR || config.LOG_WARN || config.LOG_INFO || config.LOG_DEBUG
    logLevel: config.LOG_INFO,

    // enable / disable watching file and executing tests whenever any file changes
    autoWatch: true,

    // start these browsers
    // available browser launchers: https://npmjs.org/browse/keyword/karma-launcher
    browsers: ['PhantomJS'],

    // Continuous Integration mode
    // if true, Karma captures browsers, runs the tests and exits
    singleRun: false
  });
};
<commit_msg>Fix karma test<commit_after>// Karma configuration
// Generated on Thu Mar 12 2015 18:13:33 GMT-0300 (ART)

module.exports = function(config) {
  config.set({

    // base path that will be used to resolve all patterns (eg. files, exclude)
    basePath: '..',

    // frameworks to use
    // available frameworks: https://npmjs.org/browse/keyword/karma-adapter
    frameworks: ['jasmine'],

    // list of files / patterns to load in the browser
    files: [
      'bower_components/fastclick/lib/fastclick.js',
      'bower_components/modernizr/modernizr.js',
      'bower_components/qrcode-generator/js/qrcode.js',
      'bower_components/qrcode-decoder-js/lib/qrcode-decoder.js',
      'bower_components/moment/min/moment-with-locales.js',
      'bower_components/angular/angular.js',
      'bower_components/angular-ui-router/release/angular-ui-router.js',
      'bower_components/angular-foundation/mm-foundation.js',
      'bower_components/angular-foundation/mm-foundation-tpls.js',
      'bower_components/angular-animate/angular-animate.js',
      'bower_components/angular-moment/angular-moment.js',
      'bower_components/ng-lodash/build/ng-lodash.js',
      'bower_components/angular-qrcode/qrcode.js',
      'bower_components/angular-gettext/dist/angular-gettext.js',
      'bower_components/angular-touch/angular-touch.js',
      'bower_components/angular-ui-switch/angular-ui-switch.js',
      'node_modules/angular-mocks/angular-mocks.js',
      'src/js/**/*.js',
      'test/**/*.js'
    ],

    // list of files to exclude
    exclude: [
      'src/js/translations.js',
      'src/js/version.js',
      'test/karma.conf.js',
      'test/old/*'
    ],

    // preprocess matching files before serving them to the browser
    // available preprocessors: https://npmjs.org/browse/keyword/karma-preprocessor
    preprocessors: {
      'src/js/**/*.js': ['coverage']
    },

    // test results reporter to use
    // possible values: 'dots', 'progress'
    // available reporters: https://npmjs.org/browse/keyword/karma-reporter
    reporters: ['progress', , 'coverage'],

    // optionally, configure the reporter
    coverageReporter: {
      dir: 'coverage/',
      reporters: [{
        type: 'html',
        subdir: 'report-html'
      }, {
        type: 'lcov',
        subdir: 'report-lcov'
      }, {
        type: 'text-summary'
      }]
    },

    // web server port
    port: 9876,

    // enable / disable colors in the output (reporters and logs)
    colors: true,

    // level of logging
    // possible values: config.LOG_DISABLE || config.LOG_ERROR || config.LOG_WARN || config.LOG_INFO || config.LOG_DEBUG
    logLevel: config.LOG_INFO,

    // enable / disable watching file and executing tests whenever any file changes
    autoWatch: true,

    // start these browsers
    // available browser launchers: https://npmjs.org/browse/keyword/karma-launcher
    browsers: ['PhantomJS'],

    // Continuous Integration mode
    // if true, Karma captures browsers, runs the tests and exits
    singleRun: false
  });
};
<|endoftext|>


<commit_before>const saucelabsBrowsers = require('./saucelabs-browsers').browsers,
  RIOT_WITH_COMPILER_PATH = '../dist/riot/riot+compiler.js',
  RIOT_PATH = '../dist/riot/riot.js',
  isDebug = process.env.DEBUG,
  isSaucelabs = process.env.SAUCELABS,
  // split the riot+compiler tests from the normal riot core tests
  testsSetup = './specs/browser/index.js',
  testFiles = `./specs/${process.env.TEST_FOLDER}/**/*.spec.js`,
  needsCompiler = /compiler/.test(process.env.TEST_FOLDER),
  preprocessors = {},
  browsers = isSaucelabs ? Object.keys(saucelabsBrowsers) : ['ChromeHeadless']

module.exports = function(conf) {
  preprocessors[testFiles] = ['rollup']
  // enable the coverage for riot.js
  if (!needsCompiler && !isDebug) preprocessors[RIOT_PATH] = ['coverage']

  conf.set({
    basePath: '',
    autoWatch: true,
    frameworks: ['mocha'],
    proxies: {
      '/tag/': '/base/tag/'
    },
    files: [
      './helpers/polyfills.js',
      '../node_modules/chai/chai.js',
      '../node_modules/sinon/pkg/sinon.js',
      '../node_modules/sinon-chai/lib/sinon-chai.js',
      {
        pattern: 'tag/*.tag',
        served: true,
        included: false
      },
      needsCompiler ? RIOT_WITH_COMPILER_PATH : RIOT_PATH,
      testsSetup,
      testFiles
    ],
    sauceLabs: {
      build: 'TRAVIS #' + process.env.TRAVIS_BUILD_NUMBER + ' (' + process.env.TRAVIS_BUILD_ID + ')',
      tunnelIdentifier: process.env.TRAVIS_JOB_NUMBER,
      testName: `riotjs${ needsCompiler ? '+compiler' : ''}`,
    },
    captureTimeout: 300000,
    browserNoActivityTimeout: 300000,
    browserDisconnectTolerance: 2,
    customLaunchers: saucelabsBrowsers,
    browsers: browsers,

    reporters: ['progress', 'saucelabs'].concat(isSaucelabs ? [] : ['coverage']),
    preprocessors: preprocessors,

    rollupPreprocessor: {
      // use our default rollup plugins adding also the riot plugin
      // to import dinamically the tags
      external: ['riot', 'external-helpers'],
      plugins: [
        require('rollup-plugin-riot')()
      ].concat(require('../config/defaults').plugins),
      globals: {
        riot: 'riot'
      },
      format: 'iife'
      // sourceMap: 'inline' TODO: enable the sourcemaps in the compiler
    },

    client: {
      mocha: {
        timeout: isSaucelabs ? 30000 : 3000, // saucelab tests can be really really slow
        // change Karma's debug.html to the mocha web reporter
        reporter: 'html'
      }
    },

    coverageReporter: {
      dir: '../coverage',
      reporters: [{
        type: 'lcov',
        subdir: 'report-lcov'
      }]
    },

    singleRun: true
  })
}
<commit_msg>updated: fix travis unit test<commit_after>const saucelabsBrowsers = require('./saucelabs-browsers').browsers,
  RIOT_WITH_COMPILER_PATH = '../dist/riot/riot+compiler.js',
  RIOT_PATH = '../dist/riot/riot.js',
  isDebug = process.env.DEBUG,
  isSaucelabs = process.env.SAUCELABS,
  isTravis = !!process.env.TRAVIS_BUILD_NUMBER,
  // split the riot+compiler tests from the normal riot core tests
  testsSetup = './specs/browser/index.js',
  testFiles = `./specs/${process.env.TEST_FOLDER}/**/*.spec.js`,
  needsCompiler = /compiler/.test(process.env.TEST_FOLDER),
  preprocessors = {},
  browsers = isSaucelabs ? Object.keys(saucelabsBrowsers) : ['ChromeHeadlessNoSandbox']

module.exports = function(conf) {
  preprocessors[testFiles] = ['rollup']
  // enable the coverage for riot.js
  if (!needsCompiler && !isDebug) preprocessors[RIOT_PATH] = ['coverage']

  conf.set({
    basePath: '',
    autoWatch: true,
    frameworks: ['mocha'],
    proxies: {
      '/tag/': '/base/tag/'
    },
    files: [
      './helpers/polyfills.js',
      '../node_modules/chai/chai.js',
      '../node_modules/sinon/pkg/sinon.js',
      '../node_modules/sinon-chai/lib/sinon-chai.js',
      {
        pattern: 'tag/*.tag',
        served: true,
        included: false
      },
      needsCompiler ? RIOT_WITH_COMPILER_PATH : RIOT_PATH,
      testsSetup,
      testFiles
    ],
    sauceLabs: {
      build: 'TRAVIS #' + process.env.TRAVIS_BUILD_NUMBER + ' (' + process.env.TRAVIS_BUILD_ID + ')',
      tunnelIdentifier: process.env.TRAVIS_JOB_NUMBER,
      testName: `riotjs${ needsCompiler ? '+compiler' : ''}`,
    },
    captureTimeout: 300000,
    browserNoActivityTimeout: 300000,
    browserDisconnectTolerance: 2,
    customLaunchers: Object.assign(
      {
        ChromeHeadlessNoSandbox: {
          base: 'ChromeHeadless',
          flags: ['--no-sandbox'],
        }
      },
      saucelabsBrowsers
    ),
    browsers: browsers,

    reporters: ['saucelabs']
      .concat(isSaucelabs ? [] : ['coverage'])
      .concat(isTravis ? [] : 'progress'),

    preprocessors: preprocessors,

    rollupPreprocessor: {
      // use our default rollup plugins adding also the riot plugin
      // to import dinamically the tags
      external: ['riot', 'external-helpers'],
      plugins: [
        require('rollup-plugin-riot')()
      ].concat(require('../config/defaults').plugins),
      globals: {
        riot: 'riot'
      },
      format: 'iife'
      // sourceMap: 'inline' TODO: enable the sourcemaps in the compiler
    },

    client: {
      mocha: {
        timeout: isSaucelabs ? 30000 : 3000, // saucelab tests can be really really slow
        // change Karma's debug.html to the mocha web reporter
        reporter: 'html'
      }
    },

    coverageReporter: {
      dir: '../coverage',
      reporters: [{
        type: 'lcov',
        subdir: 'report-lcov'
      }]
    },

    singleRun: true
  })
}
<|endoftext|>


<commit_before>const assert = require('chai').assert;
const Level = require('../lib/level')

describe ("Level", function(){
  context('with default attributes', function(){
    var level = new Level(1, 1);
    var level6 = new Level(6, 60);

    it('should assign a number', function(){
      assert.equal(level.number, 1);
    })

    it('should assign a challenge', function(){
      assert.equal(level.challenge[0],  "abcdf");
    })

    it('should assign a score', function(){
      assert.equal(level.score, 1)
    })

    it('should assign start the index counter', function(){
      assert.equal(level.indexCounter, 0)
    })

    it('should assign a score', function(){
      assert.equal(level.score, 1)
    })

    it('should prepare a line', function(){
      var prepared = level.preparedLine(0)
      var expected = 'abcdf'
      assert.equal(prepared,expected)
    })

    it('finds the index of the next line', function(){
      assert.equal(level.indexOfNextLine("abcdf"), 1)
    })

    it('knows if there is another line', function(){
      assert.equal(level.thereIsAnotherLineInTheLevel(1), true)
      assert.equal(level.thereIsAnotherLineInTheLevel(100), undefined)
    })

    it("knows if there is another level", function(){
      assert.equal(level.thereIsAnotherLevel(), true)
      assert.equal(level6.thereIsAnotherLevel(), undefined)
    })

    it("adds bonus points at end of another level", function(){
      assert.equal(level.score, 1 )
      level.bonusPoints();
      assert.equal(level.score, 101 )
    })
  })
})
<commit_msg>Pending test<commit_after>const assert = require('chai').assert;
const Level = require('../lib/level')

describe ("Level", function(){
  context('with default attributes', function(){
    var level = new Level(1, 1);
    var level6 = new Level(6, 60);

    it('should assign a number', function(){
      assert.equal(level.number, 1);
    })

    it('should assign a challenge', function(){
      assert.equal(level.challenge[0],  "abcdf");
    })

    it('should assign a score', function(){
      assert.equal(level.score, 1)
    })

    it('should assign start the index counter', function(){
      assert.equal(level.indexCounter, 0)
    })

    it('should assign a score', function(){
      assert.equal(level.score, 1)
    })

    xit('should prepare a line', function(){
      var prepared = level.preparedLine(0)
     var expected = ''
      assert.equal(prepared,expected)
    })

    it('finds the index of the next line', function(){
      assert.equal(level.indexOfNextLine("abcdf"), 1)
    })

    it('knows if there is another line', function(){
      assert.equal(level.thereIsAnotherLineInTheLevel(1), true)
      assert.equal(level.thereIsAnotherLineInTheLevel(100), undefined)
    })

    it("knows if there is another level", function(){
      assert.equal(level.thereIsAnotherLevel(), true)
      assert.equal(level6.thereIsAnotherLevel(), undefined)
    })

    it("adds bonus points at end of another level", function(){
      assert.equal(level.score, 1 )
      level.bonusPoints();
      assert.equal(level.score, 101 )
    })
  })
})
<|endoftext|>


<commit_before>var rewire  = require('rewire'),
    sinon = require('sinon'),
    expect = require('chai').expect,
    Factory = require('../spec_helper').Factory,
    utils = require('../../lib/utils'),
    docker = require('../../lib/docker'),
    Runner = rewire('../../lib/runner');

var MAX_MEMORY         = Runner.__get__('MAX_MEMORY'),
    MAX_EXECUTION_TIME = Runner.__get__('MAX_EXECUTION_TIME');

describe('Runner', function() {
    var sleepCode   = Factory.create('sleepCode'),
        defaultCode = Factory.create('defaultCode');

    it('has a max execution time of 10 seconds', function() {
        expect(MAX_EXECUTION_TIME / 1000).to.equal(10);
    });

    beforeEach(function() {
        runner = new Runner();
    });

    describe('#run()', function() {
        context('when container creation succeed', function(done) {
            beforeEach(function(done) {
                // First we need to manually setup a container.
                return runner._createContainer(defaultCode)
                .then(function(container) {
                    // We stub our container attach to fail.
                    container.attach = sinon.stub().yields(new Error());

                    // We stub our runner client to yield this container.
                    setFakeContainerCreate(null, container);

                    return runner.run(defaultCode);
                })
                .then(function() {
                    done('Run should fail after container creation.');
                })
                .fail(function() {
                    done();
                });
            });

            afterEach(function() {
                revertContainerCreate();
            });

            it('has a container', function() {
                expect(runner.container).not.to.be.null;
            });

            it('creates a container with maxMemory set', function(done) {
                return runner._getContainer('Memory')
                .then(function(info) {
                    expect(info).to.equal(MAX_MEMORY);
                    done();
                });
            });

            it('creates a container with this language image', function(done) {
                var dockerClient = docker.getClient()

                var image = utils.formatImage(dockerClient.repository,
                    defaultCode.language,
                    dockerClient.tag
                );

                return runner._getContainer('Image')
                .then(function(info) {
                    expect(info).to.equal(image);
                    done();
                });
            });

            it('creates a container with this code command', function(done) {
                var cmd = utils.formatCmd(defaultCode.code);

                return runner._getContainer('Cmd')
                .then(function(info) {
                    expect(info).to.deep.equal([cmd]);
                    done();
                });
            });
        });

        context('when container creation failed', function(done) {
            beforeEach(function() {
                error = new Error();

                revert = runner.client.createContainer;

                setFakeContainerCreate(error);
            });

            afterEach(function() {
                revertContainerCreate();
            });

            expectError();
        });

        ['attach', 'start', 'wait', 'inspect', 'remove'].forEach(
            function (action) {
            context('when docker fail to '+action+' this container', function() {
                beforeEach(function(done) {
                    error = new Error();

                    // First we need to manually setup a container.
                    return runner._createContainer(defaultCode)
                    .then(function(container) {
                        // We stub our container action to fail.
                        container[action] = sinon.stub().yields(error);

                        setFakeContainerCreate(null, container);

                        done();
                    })
                    .fail(function(err) {
                        done(err);
                    });
                });

                afterEach(function() {
                    revertContainerCreate();
                });

                expectError();
            });
        });

        // For this context we are testing against a
        // code sample that writes both on stdout and
        // stderr, returns an exit code of 1, with a
        // really short execution time.
        context('when container exits', function() {
            beforeEach(function(done) {
                emited = attachRunnerEvents();

                run(defaultCode, done);
            });

            it('has emited container exit code', function() {
                expect(emited.exitCode).to.equal(defaultCode.exitCode);
            });

            it('has emited appropriate output on stdout', function() {
                expect(emited.output.stdout).to.equal(defaultCode.stdout);
            });

            it('has emited appropriate output on stderr', function() {
                expect(emited.output.stderr).to.equal(defaultCode.stderr);
            });

            it('has removed its container', function(done) {
                emited.container.inspect(function(err, data) {
                    expect(err).not.to.be.null;
                    done();
                });
            });

            it('has no container', function() {
                expect(runner.container).to.be.null;
            });
        });

        // For this context we are using a code sample
        // that should hang more than the test suite
        // default timeout, but runner should automatically
        // timeouts after maxExecutionTime and stop the
        // container, preventing these tests from timeouts.
        context('when execution is too long', function() {
            beforeEach(function() {
                fakeTimeout = 1;
                revert = Runner.__set__('MAX_EXECUTION_TIME', fakeTimeout);
            });

            afterEach(function() {
                revert();
            });

            it('emits a timeout and stops the container', function(done) {
                runner.on('timeout', function(executionTime) {
                    timeout = executionTime;
                });

                run(sleepCode, function(err) {
                    expect(timeout).to.equal(fakeTimeout);
                    done();
                });
            });
        });
    });

    describe('#stop()', function() {
        context('when idle', function() {
            it('does nothing', function() {
                expect(function() {
                    runner.stop();
                }).not.to.throw(Error);
            });
        });

        // For this context we are using a code example
        // that should hang more than the test suite
        // default timeout, if stop fails, these tests
        // should timeout.
        context('when running', function() {
            beforeEach(function(done) {
                runner.on('start', function() {
                    runner.stop();
                });

                emited = attachRunnerEvents();

                run(sleepCode, done);
            });

            // We must verify that the container doesn't
            // stop because of the code sent as parameter.
            it('stops the container execution', function() {
                expect(emited.output.stderr).to.equal('');
            });

            it("hasn't emited container exit code", function() {
                expect(emited.exitCode).to.be.null;
            });
        });
    });

    function attachRunnerEvents() {
        var emited = {
            output: { stdout: '', stderr: '' },
            exitCode: null,
            timeout: null,
            container: null,
        }

        runner.on('output', function(data) {
            emited.output[data.stream] += data.chunk;
        }).on('status', function(data) {
            emited.exitCode = data;
        }).on('timeout', function(data){
            emited.timeout = data;
        }).on('created', function(data){
            emited.container = data;
        });
        return emited;
    }

    function run(example, cb) {
        return runner.run(sleepCode)
        .then(function() {
            cb();
        })
        .fail(function(err) {
            cb(err);
        });
    }

    function expectError() {
        it('gets an error', function(done) {
            run(defaultCode, function(err) {
                expect(err).to.equal(error);
            });
        });
    }

    function setFakeContainerCreate(err, container) {
        containerCreate = runner.client.createContainer;

        // We stub our runner client to yield this container.
        runner.client.createContainer = sinon.stub().yields(err, container);
    }

    function revertContainerCreate() {
        if (typeof(containerCreate) == 'undefined') return;

        runner.client.createContainer = containerCreate;
    }
});
<commit_msg>add missing done in runner tests<commit_after>var rewire  = require('rewire'),
    sinon = require('sinon'),
    expect = require('chai').expect,
    Factory = require('../spec_helper').Factory,
    utils = require('../../lib/utils'),
    docker = require('../../lib/docker'),
    Runner = rewire('../../lib/runner');

var MAX_MEMORY         = Runner.__get__('MAX_MEMORY'),
    MAX_EXECUTION_TIME = Runner.__get__('MAX_EXECUTION_TIME');

describe('Runner', function() {
    var sleepCode   = Factory.create('sleepCode'),
        defaultCode = Factory.create('defaultCode');

    it('has a max execution time of 10 seconds', function() {
        expect(MAX_EXECUTION_TIME / 1000).to.equal(10);
    });

    beforeEach(function() {
        runner = new Runner();
    });

    describe('#run()', function() {
        context('when container creation succeed', function(done) {
            beforeEach(function(done) {
                // First we need to manually setup a container.
                return runner._createContainer(defaultCode)
                .then(function(container) {
                    // We stub our container attach to fail.
                    container.attach = sinon.stub().yields(new Error());

                    // We stub our runner client to yield this container.
                    setFakeContainerCreate(null, container);

                    return runner.run(defaultCode);
                })
                .then(function() {
                    done('Run should fail after container creation.');
                })
                .fail(function() {
                    done();
                });
            });

            afterEach(function() {
                revertContainerCreate();
            });

            it('has a container', function() {
                expect(runner.container).not.to.be.null;
            });

            it('creates a container with maxMemory set', function(done) {
                return runner._getContainer('Memory')
                .then(function(info) {
                    expect(info).to.equal(MAX_MEMORY);
                    done();
                });
            });

            it('creates a container with this language image', function(done) {
                var dockerClient = docker.getClient()

                var image = utils.formatImage(dockerClient.repository,
                    defaultCode.language,
                    dockerClient.tag
                );

                return runner._getContainer('Image')
                .then(function(info) {
                    expect(info).to.equal(image);
                    done();
                });
            });

            it('creates a container with this code command', function(done) {
                var cmd = utils.formatCmd(defaultCode.code);

                return runner._getContainer('Cmd')
                .then(function(info) {
                    expect(info).to.deep.equal([cmd]);
                    done();
                });
            });
        });

        context('when container creation failed', function(done) {
            beforeEach(function() {
                error = new Error();

                revert = runner.client.createContainer;

                setFakeContainerCreate(error);
            });

            afterEach(function() {
                revertContainerCreate();
            });

            expectError();
        });

        ['attach', 'start', 'wait', 'inspect', 'remove'].forEach(
            function (action) {
            context('when docker fail to '+action+' this container', function() {
                beforeEach(function(done) {
                    error = new Error();

                    // First we need to manually setup a container.
                    return runner._createContainer(defaultCode)
                    .then(function(container) {
                        // We stub our container action to fail.
                        container[action] = sinon.stub().yields(error);

                        setFakeContainerCreate(null, container);

                        done();
                    })
                    .fail(function(err) {
                        done(err);
                    });
                });

                afterEach(function() {
                    revertContainerCreate();
                });

                expectError();
            });
        });

        // For this context we are testing against a
        // code sample that writes both on stdout and
        // stderr, returns an exit code of 1, with a
        // really short execution time.
        context('when container exits', function() {
            beforeEach(function(done) {
                emited = attachRunnerEvents();

                run(defaultCode, done);
            });

            it('has emited container exit code', function() {
                expect(emited.exitCode).to.equal(defaultCode.exitCode);
            });

            it('has emited appropriate output on stdout', function() {
                expect(emited.output.stdout).to.equal(defaultCode.stdout);
            });

            it('has emited appropriate output on stderr', function() {
                expect(emited.output.stderr).to.equal(defaultCode.stderr);
            });

            it('has removed its container', function(done) {
                emited.container.inspect(function(err, data) {
                    expect(err).not.to.be.null;
                    done();
                });
            });

            it('has no container', function() {
                expect(runner.container).to.be.null;
            });
        });

        // For this context we are using a code sample
        // that should hang more than the test suite
        // default timeout, but runner should automatically
        // timeouts after maxExecutionTime and stop the
        // container, preventing these tests from timeouts.
        context('when execution is too long', function() {
            beforeEach(function() {
                fakeTimeout = 1;
                revert = Runner.__set__('MAX_EXECUTION_TIME', fakeTimeout);
            });

            afterEach(function() {
                revert();
            });

            it('emits a timeout and stops the container', function(done) {
                runner.on('timeout', function(executionTime) {
                    timeout = executionTime;
                });

                run(sleepCode, function(err) {
                    expect(timeout).to.equal(fakeTimeout);
                    done();
                });
            });
        });
    });

    describe('#stop()', function() {
        context('when idle', function() {
            it('does nothing', function() {
                expect(function() {
                    runner.stop();
                }).not.to.throw(Error);
            });
        });

        // For this context we are using a code example
        // that should hang more than the test suite
        // default timeout, if stop fails, these tests
        // should timeout.
        context('when running', function() {
            beforeEach(function(done) {
                runner.on('start', function() {
                    runner.stop();
                });

                emited = attachRunnerEvents();

                run(sleepCode, done);
            });

            // We must verify that the container doesn't
            // stop because of the code sent as parameter.
            it('stops the container execution', function() {
                expect(emited.output.stderr).to.equal('');
            });

            it("hasn't emited container exit code", function() {
                expect(emited.exitCode).to.be.null;
            });
        });
    });

    function attachRunnerEvents() {
        var emited = {
            output: { stdout: '', stderr: '' },
            exitCode: null,
            timeout: null,
            container: null,
        }

        runner.on('output', function(data) {
            emited.output[data.stream] += data.chunk;
        }).on('status', function(data) {
            emited.exitCode = data;
        }).on('timeout', function(data){
            emited.timeout = data;
        }).on('created', function(data){
            emited.container = data;
        });
        return emited;
    }

    function run(example, cb) {
        return runner.run(sleepCode)
        .then(function() {
            cb();
        })
        .fail(function(err) {
            cb(err);
        });
    }

    function expectError() {
        it('gets an error', function(done) {
            run(defaultCode, function(err) {
                expect(err).to.equal(error);
                done();
            });
        });
    }

    function setFakeContainerCreate(err, container) {
        containerCreate = runner.client.createContainer;

        // We stub our runner client to yield this container.
        runner.client.createContainer = sinon.stub().yields(err, container);
    }

    function revertContainerCreate() {
        if (typeof(containerCreate) == 'undefined') return;

        runner.client.createContainer = containerCreate;
    }
});
<|endoftext|>


<commit_before>var fs = require('fs');
var path = require('path');
var mkdirp = require('mkdirp');
var rimraf = require('rimraf');

// TODO: extract this to a separate module.
// TODO: pass errors to callback.

module.exports = function (paths, prefix, cb) {
  var dirs = [];
  var files = [];

  paths.forEach(function (p) {
    // TODO: symlink support (-> separator).
    if (p.substr(-1) === path.sep) {
      dirs.push(path.join(prefix, p));
    } else {
      dirs.push(path.join(prefix, path.dirname(path)));
      files.push(path.join(prefix, p));
    }
  });

  var pendingDirs = dirs.length;
  var pendingFiles = files.length;

  // TODO: normalize dirs before creating them to save syscalls.
  dirs.forEach(function (dir) {
    mkdirp(dir, function (err) {
      pendingDirs--;
      checkDirs();
    });
  });

  function mkfiles () {
    files.forEach(function (file) {
      fs.open(file, 'w', function (err, fd) {
        fs.close(fd, function (err) {
          pendingFiles--;
          checkFiles();
        });
      });
    });
  }

  function checkDirs () {
    if (!pendingDirs) mkfiles();
  }

  function checkFiles () {
    if (!pendingFiles) cb(null);
  }

  return { rm: function (cb) {
    rimraf(prefix, function (err) {
      if (cb) cb(err);
    });
  }};
}
<commit_msg>Fix bug in testfs dir extraction.<commit_after>var fs = require('fs');
var path = require('path');
var mkdirp = require('mkdirp');
var rimraf = require('rimraf');

// TODO: extract this to a separate module.
// TODO: pass errors to callback.

module.exports = function (paths, prefix, cb) {
  var dirs = [];
  var files = [];

  paths.forEach(function (p) {
    // TODO: symlink support (-> separator).
    if (p.substr(-1) === path.sep) {
      dirs.push(path.join(prefix, p));
    } else {
      dirs.push(path.join(prefix, path.dirname(p)));
      files.push(path.join(prefix, p));
    }
  });

  var pendingDirs = dirs.length;
  var pendingFiles = files.length;

  // TODO: normalize dirs before creating them to save syscalls.
  dirs.forEach(function (dir) {
    mkdirp(dir, function (err) {
      pendingDirs--;
      checkDirs();
    });
  });

  function mkfiles () {
    files.forEach(function (file) {
      fs.open(file, 'w', function (err, fd) {
        fs.close(fd, function (err) {
          pendingFiles--;
          checkFiles();
        });
      });
    });
  }

  function checkDirs () {
    if (!pendingDirs) mkfiles();
  }

  function checkFiles () {
    if (!pendingFiles) cb(null);
  }

  return { rm: function (cb) {
    rimraf(prefix, function (err) {
      if (cb) cb(err);
    });
  }};
}
<|endoftext|>


<commit_before>var sys = require('sys');
var fs = require('fs');
var net = require('net');
var events = require('events');
var path = require('path');
var pipe = require('pipe');

//-----------------------------Expose server API-----------------------------
exports.createServer = function(func ) {
    var server = new Server(func);
    return server;
};

function Server(func) {
     events.EventEmitter.call(this);

     this.sessions = {};

     var self = this;

     this.stream = net.createServer(function(stream) {

        var session = this;

        this.senderCompID = null;
        this.targetCompID = null;
        this.p = null;
        function SessionEmitterObj(){
            events.EventEmitter.call(this);
            this.write = function(data){session.p.pushOutgoing({data:data, type:'data'});};
        }
        sys.inherits(SessionEmitterObj,events.EventEmitter);

        this.sessionEmitter = new SessionEmitterObj();

        stream.on('connect', function() {
            session.sessionEmitter.emit('connect');

            session.p = pipe.makePipe(stream);
             //session.p.addHandler({incoming:function(ctx,event){ sys.log('indebug1:'+event); ctx.sendNext(event); }});
             //session.p.addHandler({outgoing:function(ctx,event){ sys.log('outdebug1:'+event); ctx.sendNext(event); }});
            session.p.addHandler(require('./handlers/fixFrameDecoder.js').newFixFrameDecoder());
             //session.p.addHandler({incoming:function(ctx,event){ sys.log('indebug2:'+event); ctx.sendNext(event); }});
             //session.p.addHandler({outgoing:function(ctx,event){ sys.log('outdebug2:'+event); ctx.sendNext(event); }});
            session.p.addHandler(require('./handlers/msgValidator.js').newMsgValidator());
             //session.p.addHandler({incoming:function(ctx,event){ sys.log('indebug3:'+event); ctx.sendNext(event); }});
             //session.p.addHandler({outgoing:function(ctx,event){ sys.log('outdebug3:'+event); ctx.sendNext(event); }});
            session.p.addHandler({outgoing:function(ctx,event){
                if(event.type==='data'){
                    session.sessionEmitter.emit('outgoingmsg',convertToMap(event.data));
                }
                ctx.sendNext(event);
            }});
            session.p.addHandler(require('./handlers/persister.js').newPersister(false));
             //session.p.addHandler({incoming:function(ctx,event){ sys.log('indebug4:'+event); ctx.sendNext(event); }});
             //session.p.addHandler({outgoing:function(ctx,event){ sys.log('outdebug4:'+event); ctx.sendNext(event); }});

            session.p.addHandler({incoming:function(ctx,event){
                if(event.type !== 'data'){
                    ctx.sendNext(event);
                    return;
                }
                session.sessionEmitter.emit('incomingmsg',event.data);

                /*if(event.data['35'] === '5'){
                    delete self.sessions[session.senderCompID + '-' + session.targetCompID];
                    session.sessionEmitter.emit('logoff', session.senderCompID, session.targetCompID);
                }*/

                ctx.sendNext(event);
            }});
            session.p.addHandler(require('./handlers/sessionProcessor.js').newSessionProcessor(false));
            session.p.addHandler({incoming:function(ctx,event){
                if(event.type === 'admin' && event.data === 'logon'){
                    session.sessionEmitter.emit('logon',ctx.state.session.senderCompID,ctx.state.session.targetCompID);
                    ctx.sendNext(event);
                    return;
                }
                else if(event.type === 'admin' && event.data === 'logoff'){
                    session.sessionEmitter.emit('logoff',ctx.state.session.senderCompID,ctx.state.session.targetCompID);
                    ctx.sendNext(event);
                    return;
                }

            }});

        });
        stream.on('data', function(data) { session.p.pushIncoming({data:data, type:'data'}); });

        func(session.sessionEmitter);

     });

     this.listen = function(port, host) { self.stream.listen(port, host); };
     this.write = function(targetCompID, data) { self.sessions[targetCompID].write(data); };
     this.logoff = function(targetCompID, logoffReason) { self.sessions[targetCompID].write({35:5, 58:logoffReason}); };
     this.kill = function(targetCompID, reason){ self.sessions[targetCompID].end(); };

}
sys.inherits(Server, events.EventEmitter);

//-----------------------------Expose client API-----------------------------
exports.createConnection = function(fixVersion, senderCompID, targetCompID, port, host) {
    return new Client({'8': fixVersion, '56': targetCompID, '49': senderCompID, '35': 'A', '90': '0', '108': '10'}, port, host);
};

exports.createConnectionWithLogonMsg = function(logonmsg, port, host) {
    return new Client(logonmsg, port, host);
};

function Client(logonmsg, port, host) {
    events.EventEmitter.call(this);

    this.session = null;
    var self = this;

    var stream = net.createConnection(port, host);

    this.p = pipe.makePipe(stream);
     //this.p.addHandler({incoming:function(ctx,event){ sys.log('indebug0:'+event); ctx.sendNext(event); }});
     //this.p.addHandler({outgoing:function(ctx,event){ sys.log('outdebug1:'+event); ctx.sendNext(event); }});
    this.p.addHandler(require('./handlers/fixFrameDecoder.js').newFixFrameDecoder());
     //this.p.addHandler({incoming:function(ctx,event){ sys.log('indebug1:'+event); ctx.sendNext(event); }});
     //this.p.addHandler({outgoing:function(ctx,event){ sys.log('outdebug1:'+event); ctx.sendNext(event); }});
    this.p.addHandler(require('./handlers/msgValidator.js').newMsgValidator());
    this.p.addHandler({outgoing:function(ctx,event){
        if(event.type==='data'){
            self.emit('outgoingmsg',convertToMap(event.data));
        }
        ctx.sendNext(event);
    }});
    this.p.addHandler(require('./handlers/persister.js').newPersister(true));
    this.p.addHandler({incoming:function(ctx,event){
        if(event.type==='data'){
            self.emit('incomingmsg',event.data);
        }
        ctx.sendNext(event);
    }});
    this.p.addHandler(require('./handlers/sessionProcessor.js').newSessionProcessor(true));
    this.p.addHandler({incoming:function(ctx,event){
        if(event.type==='admin' && event.data==='logon'){
            self.emit('logon', ctx.state.session.senderCompID, ctx.state.session.targetCompID);
        }
        ctx.sendNext(event);
    }});

    stream.on('connect', function() {
        self.emit('connect');
        self.p.pushOutgoing({data:logonmsg, type:'data'});
    });
    stream.on('data', function(data) { self.p.pushIncoming({data:data, type:'data'}); });

    this.write = function(data) { self.p.pushOutgoing(data); };
    this.logoff = function(logoffReason){ self.p.pushOutgoing({35:5, 58:logoffReason}) };
}
sys.inherits(Client, events.EventEmitter);

//TODO refactor, this is alraedy implemented in persister.js
//TODO refactor, this is already defined in persister.js
var SOHCHAR = String.fromCharCode(1);
function convertToMap(msg) {
    var fix = {};
    var keyvals = msg.split(SOHCHAR);
    for (var kv in Object.keys(keyvals)) {
        var kvpair = keyvals[kv].split('=');
        fix[kvpair[0]] = kvpair[1];
    }
    return fix;

}
<commit_msg>adds logon method to client, client no longer logs on automatically when connected<commit_after>var sys = require('sys');
var fs = require('fs');
var net = require('net');
var events = require('events');
var path = require('path');
var pipe = require('pipe');

//-----------------------------Expose server API-----------------------------
exports.createServer = function(func ) {
    var server = new Server(func);
    return server;
};

function Server(func) {
     events.EventEmitter.call(this);

     this.sessions = {};

     var self = this;

     this.stream = net.createServer(function(stream) {

        var session = this;

        this.senderCompID = null;
        this.targetCompID = null;
        this.p = null;
        function SessionEmitterObj(){
            events.EventEmitter.call(this);
            this.write = function(data){session.p.pushOutgoing({data:data, type:'data'});};
        }
        sys.inherits(SessionEmitterObj,events.EventEmitter);

        this.sessionEmitter = new SessionEmitterObj();

        stream.on('connect', function() {
            session.sessionEmitter.emit('connect');

            session.p = pipe.makePipe(stream);
             //session.p.addHandler({incoming:function(ctx,event){ sys.log('indebug1:'+event); ctx.sendNext(event); }});
             //session.p.addHandler({outgoing:function(ctx,event){ sys.log('outdebug1:'+event); ctx.sendNext(event); }});
            session.p.addHandler(require('./handlers/fixFrameDecoder.js').newFixFrameDecoder());
             //session.p.addHandler({incoming:function(ctx,event){ sys.log('indebug2:'+event); ctx.sendNext(event); }});
             //session.p.addHandler({outgoing:function(ctx,event){ sys.log('outdebug2:'+event); ctx.sendNext(event); }});
            session.p.addHandler(require('./handlers/msgValidator.js').newMsgValidator());
             //session.p.addHandler({incoming:function(ctx,event){ sys.log('indebug3:'+event); ctx.sendNext(event); }});
             //session.p.addHandler({outgoing:function(ctx,event){ sys.log('outdebug3:'+event); ctx.sendNext(event); }});
            session.p.addHandler({outgoing:function(ctx,event){
                if(event.type==='data'){
                    session.sessionEmitter.emit('outgoingmsg',convertToMap(event.data));
                }
                ctx.sendNext(event);
            }});
            session.p.addHandler(require('./handlers/persister.js').newPersister(false));
             //session.p.addHandler({incoming:function(ctx,event){ sys.log('indebug4:'+event); ctx.sendNext(event); }});
             //session.p.addHandler({outgoing:function(ctx,event){ sys.log('outdebug4:'+event); ctx.sendNext(event); }});

            session.p.addHandler({incoming:function(ctx,event){
                if(event.type !== 'data'){
                    ctx.sendNext(event);
                    return;
                }
                session.sessionEmitter.emit('incomingmsg',event.data);

                /*if(event.data['35'] === '5'){
                    delete self.sessions[session.senderCompID + '-' + session.targetCompID];
                    session.sessionEmitter.emit('logoff', session.senderCompID, session.targetCompID);
                }*/

                ctx.sendNext(event);
            }});
            session.p.addHandler(require('./handlers/sessionProcessor.js').newSessionProcessor(false));
            session.p.addHandler({incoming:function(ctx,event){
                if(event.type === 'admin' && event.data === 'logon'){
                    session.sessionEmitter.emit('logon',ctx.state.session.senderCompID,ctx.state.session.targetCompID);
                    ctx.sendNext(event);
                    return;
                }
                else if(event.type === 'admin' && event.data === 'logoff'){
                    session.sessionEmitter.emit('logoff',ctx.state.session.senderCompID,ctx.state.session.targetCompID);
                    ctx.sendNext(event);
                    return;
                }

            }});

        });
        stream.on('data', function(data) { session.p.pushIncoming({data:data, type:'data'}); });

        func(session.sessionEmitter);

     });

     this.listen = function(port, host) { self.stream.listen(port, host); };
     this.write = function(targetCompID, data) { self.sessions[targetCompID].write(data); };
     this.logoff = function(targetCompID, logoffReason) { self.sessions[targetCompID].write({35:5, 58:logoffReason}); };
     this.kill = function(targetCompID, reason){ self.sessions[targetCompID].end(); };

}
sys.inherits(Server, events.EventEmitter);

//-----------------------------Expose client API-----------------------------
exports.createConnection = function(fixVersion, senderCompID, targetCompID, port, host) {
    return new Client({'8': fixVersion, '56': targetCompID, '49': senderCompID, '35': 'A', '90': '0', '108': '10'}, port, host);
};

exports.createConnectionWithLogonMsg = function(logonmsg, port, host) {
    return new Client(logonmsg, port, host);
};

function Client(logonmsg, port, host) {
    events.EventEmitter.call(this);

    this.session = null;
    var self = this;

    var stream = net.createConnection(port, host);

    this.p = pipe.makePipe(stream);
     //this.p.addHandler({incoming:function(ctx,event){ sys.log('indebug0:'+event); ctx.sendNext(event); }});
     //this.p.addHandler({outgoing:function(ctx,event){ sys.log('outdebug1:'+event); ctx.sendNext(event); }});
    this.p.addHandler(require('./handlers/fixFrameDecoder.js').newFixFrameDecoder());
     //this.p.addHandler({incoming:function(ctx,event){ sys.log('indebug1:'+event); ctx.sendNext(event); }});
     //this.p.addHandler({outgoing:function(ctx,event){ sys.log('outdebug1:'+event); ctx.sendNext(event); }});
    this.p.addHandler(require('./handlers/msgValidator.js').newMsgValidator());
    this.p.addHandler({outgoing:function(ctx,event){
        if(event.type==='data'){
            self.emit('outgoingmsg',convertToMap(event.data));
        }
        ctx.sendNext(event);
    }});
    this.p.addHandler(require('./handlers/persister.js').newPersister(true));
    this.p.addHandler({incoming:function(ctx,event){
        if(event.type==='data'){
            self.emit('incomingmsg',event.data);
        }
        ctx.sendNext(event);
    }});
    this.p.addHandler(require('./handlers/sessionProcessor.js').newSessionProcessor(true));
    this.p.addHandler({incoming:function(ctx,event){
        if(event.type==='admin' && event.data==='logon'){
            self.emit('logon', ctx.state.session.senderCompID, ctx.state.session.targetCompID);
        }
        ctx.sendNext(event);
    }});

    stream.on('connect', function() {
        self.emit('connect');
    });
    stream.on('data', function(data) { self.p.pushIncoming({data:data, type:'data'}); });

    this.write = function(data) { self.p.pushOutgoing(data); };
    this.logoon = function(logoffReason){ self.p.pushOutgoing({data:logonmsg, type:'data'}); };
    this.logoff = function(logoffReason){ self.p.pushOutgoing({data:{35:5, 58:logoffReason}, type:'data'}) };
}
sys.inherits(Client, events.EventEmitter);

//TODO refactor, this is alraedy implemented in persister.js
//TODO refactor, this is already defined in persister.js
var SOHCHAR = String.fromCharCode(1);
function convertToMap(msg) {
    var fix = {};
    var keyvals = msg.split(SOHCHAR);
    for (var kv in Object.keys(keyvals)) {
        var kvpair = keyvals[kv].split('=');
        fix[kvpair[0]] = kvpair[1];
    }
    return fix;

}
<|endoftext|>


<commit_before><commit_msg>Possibly fixed lang detection script<commit_after><|endoftext|>


<commit_before>(function (root, factory) {
    if (typeof define === 'function' && define.amd) { // AMD
        define([], factory);
    } else if (typeof exports === 'object') { // Node, browserify and alike
        module.exports = factory();
    } else {
        // Browser globals (root is window)
        root.fnd = factory();
  }
}(this, function () {
    'use strict';

    var slice = Array.prototype.slice;
    function toArray (arrayLike) {
        return slice.call(arrayLike, 0);
    }

    function isQSASelector (selector) {
        return selector.indexOf(' ') > -1 && selector.indexOf(',') > -1 && selector.indexOf('>') > -1 && selector.indexOf('+') > -1 && selector.indexOf('~')&& selector.indexOf('[');
    }

    var strategies = {
        '#': function (selector, parent) {
            return document.getElementById(selector.substr(1));
        },
        '.': function (selector, parent) {
            return parent.getElementsByClassName(selector.substr(1))
        },
        'tagName': function (selector, parent) {
            return parent.getElementsByTagName(selector);
        },
        'qSA': function (selector, parent) {
            return parent.querySelectorAll(selector);
        }
    };

    function getStrategy (selector, parent) {
        var firstChar = selector.substr(0, 1);
        if (isQSASelector(selector) || (firstChar === '#' && parent !== document)) { // searching by id in some context falls back to qSA
            return strategies.qSA;
        } else {
            return strategies[firstChar] || strategies.tagName;
        }
    }

    function fnd (selector, parent) {
        parent = (parent || document);
        var searcher = getStrategy(selector, parent);
        var result = searcher(selector, parent);

        if (!result || !result.length) {
            return null;
        } else {
            if (result instanceof NodeList) {
                return toArray(result);
            } else {
                return [result];
            }
        }
    }

    var docEl = document.documentElement;
    var methodNames = ['matches', 'msMatchesSelector', 'mozMatchesSelector', 'webkitMatchesSelector', 'matchesSelector'];
    var matchesMethod = '';

    for (var i = 0, len = methodNames.length; i < len; i++) {
        if (docEl[methodNames[i]]) {
            matchesMethod = methodNames[i];
            break;
        }
    }

    fnd.is = function isFactory (selector) {
        return function (element) {
            return element[matchesMethod](selector)
        }
    };

    return fnd;
}));<commit_msg>event handling draft<commit_after>(function (root, factory) {
    if (typeof define === 'function' && define.amd) { // AMD
        define([], factory);
    } else if (typeof exports === 'object') { // Node, browserify and alike
        module.exports = factory();
    } else {
        // Browser globals (root is window)
        root.fnd = factory();
  }
}(this, function () {
    'use strict';

    var slice = Array.prototype.slice;
    function toArray (arrayLike) {
        return slice.call(arrayLike, 0);
    }

    function isQSASelector (selector) {
        return selector.indexOf(' ') > -1 && selector.indexOf(',') > -1 && selector.indexOf('>') > -1 && selector.indexOf('+') > -1 && selector.indexOf('~')&& selector.indexOf('[');
    }

    var strategies = {
        '#': function (selector, parent) {
            return document.getElementById(selector.substr(1));
        },
        '.': function (selector, parent) {
            return parent.getElementsByClassName(selector.substr(1))
        },
        'tagName': function (selector, parent) {
            return parent.getElementsByTagName(selector);
        },
        'qSA': function (selector, parent) {
            return parent.querySelectorAll(selector);
        }
    };

    function getStrategy (selector, parent) {
        var firstChar = selector.substr(0, 1);
        if (isQSASelector(selector) || (firstChar === '#' && parent !== document)) { // searching by id in some context falls back to qSA
            return strategies.qSA;
        } else {
            return strategies[firstChar] || strategies.tagName;
        }
    }

    function fnd (selector, parent) {
        parent = (parent || document);
        var searcher = getStrategy(selector, parent);
        var result = searcher(selector, parent);

        if (!result || !result.length) {
            return null;
        } else {
            if (result instanceof NodeList) {
                return toArray(result);
            } else {
                return [result];
            }
        }
    }

    var docEl = document.documentElement;
    var methodNames = ['matches', 'msMatchesSelector', 'mozMatchesSelector', 'webkitMatchesSelector', 'matchesSelector'];
    var matchesMethod = '';

    for (var i = 0, len = methodNames.length; i < len; i++) {
        if (docEl[methodNames[i]]) {
            matchesMethod = methodNames[i];
            break;
        }
    }

    fnd.is = function isFactory (selector) {
        return function (element) {
            return element[matchesMethod](selector)
        }
    };

    fnd.on = function (element) {
        var attach = element.addEventListener.bind(element);
        return function (eventName, handler, selector) {
            var bound;
            if (!selector) {
                bound = handler;
            } else {
                bound = function (event) {
                    if (fnd.is(selector)(event.target)) {
                        handler(event);
                    }
                }
            }

            element.addEventListener(eventName, bound, selector);
        }
    };

    return fnd;
}));<|endoftext|>


<commit_before><commit_msg>Update foo<commit_after>'use strict';
<|endoftext|>