<commit_before>'use strict';

require('mocha');

var rimraf = require('rimraf');
var assert = require('assert');
var utils = require('../lib/utils');
var macros = require('../');
var parser;
var store;

describe('macro-store', function() {
  beforeEach(function(cb) {
    store = new utils.Store('macros', {cwd: 'actual'});
    parser = macros({store: store});
    rimraf('actual', cb);
  });
  afterEach(rimraf.bind(rimraf, 'actual'));

  it('should export a function', function() {
    assert.equal(typeof macros, 'function');
  });

  it('should return a parser function when called', function() {
    assert.equal(typeof macros('custom-macros-store'), 'function');
  });

  it('should set a macro using `--macro`', function() {
    var res = parser(['--macro', 'foo', 'foo', 'bar', 'baz']);
    assert.deepEqual(res, { _: ['foo', 'bar', 'baz'], macro: 'foo' });
    assert.deepEqual(store.get(['macro', 'foo']), ['foo', 'bar', 'baz']);
  });

  it('should set a macro using `--macro set`', function() {
    var res = parser(['--macro', 'set', 'foo', 'foo', 'bar', 'baz']);
    assert.deepEqual(res, { _: ['foo', 'foo', 'bar', 'baz'], macro: 'set' });
    assert.deepEqual(store.get(['macro', 'foo']), ['foo', 'bar', 'baz']);
  });

  it('should set a macro using `--macro=set`', function() {
    var res = parser(['--macro=set', 'foo', 'foo', 'bar', 'baz']);
    assert.deepEqual(res, { _: ['foo', 'foo', 'bar', 'baz'], macro: 'set' });
    assert.deepEqual(store.get(['macro', 'foo']), ['foo', 'bar', 'baz']);
  });

  it('should get macros from the store', function() {
    parser(['--macro', 'foo', 'foo', 'bar', 'baz']);
    assert.deepEqual(parser('foo'), { _: ['foo', 'bar', 'baz'] });
  });

  it('should get a complex macro from the store', function() {
    parser(['--macro', 'foo', 'foo', 'bar', 'baz', '--verbose', '--cwd', 'docs']);
    assert.deepEqual(parser('foo'), { _: ['foo', 'bar', 'baz'], verbose: true, cwd: 'docs' });
  });

  it('should return original name when macro is not set in the store', function() {
    assert.deepEqual(parser('foo'), { _: ['foo'] });
  });

  it('should not process macros when `--no-macro` is set', function() {
    assert.deepEqual(parser(['foo', '--no-macro']), { _: ['foo'], macro: false });
  });

  it('should del macros from the store', function() {
    parser(['--macro', 'foo', 'foo', 'bar', 'baz']);
    assert.deepEqual(parser('foo'), { _: ['foo', 'bar', 'baz'] });

    parser(['--macro', 'del', 'foo']);
    assert.deepEqual(parser('foo'), { _: ['foo'] });
  });

  it('should delete all macros when no macro is specified for `--del`', function() {
    parser(['--macro', 'foo', 'foo', 'bar', 'baz']);
    parser(['--macro', 'qux', 'beep', 'boop', 'bop']);
    assert.deepEqual(parser('foo'), { _: ['foo', 'bar', 'baz'] });
    assert.deepEqual(parser('qux'), { _: ['beep', 'boop', 'bop'] });

    parser(['--macro', 'del']);
    assert.deepEqual(parser(['foo', 'qux']), { _: ['foo', 'qux'] });
  });
});
<commit_msg>update tests for isMacro changes<commit_after>'use strict';

require('mocha');

var rimraf = require('rimraf');
var assert = require('assert');
var utils = require('../lib/utils');
var macros = require('../');
var parser;
var store;

describe('macro-store', function() {
  beforeEach(function(cb) {
    store = new utils.Store('macros', {cwd: 'actual'});
    parser = macros({store: store});
    rimraf('actual', cb);
  });
  afterEach(rimraf.bind(rimraf, 'actual'));

  it('should export a function', function() {
    assert.equal(typeof macros, 'function');
  });

  it('should return a parser function when called', function() {
    assert.equal(typeof macros('custom-macros-store'), 'function');
  });

  it('should set a macro using `--macro`', function() {
    var res = parser(['--macro', 'foo', 'foo', 'bar', 'baz']);
    assert.deepEqual(res, { _: ['foo', 'bar', 'baz'], macro: 'foo' });
    assert.deepEqual(store.get(['macro', 'foo']), ['foo', 'bar', 'baz']);
  });

  it('should set a macro using `--macro set`', function() {
    var res = parser(['--macro', 'set', 'foo', 'foo', 'bar', 'baz']);
    assert.deepEqual(res, { _: ['foo', 'foo', 'bar', 'baz'], macro: 'set' });
    assert.deepEqual(store.get(['macro', 'foo']), ['foo', 'bar', 'baz']);
  });

  it('should set a macro using `--macro=set`', function() {
    var res = parser(['--macro=set', 'foo', 'foo', 'bar', 'baz']);
    assert.deepEqual(res, { _: ['foo', 'foo', 'bar', 'baz'], macro: 'set' });
    assert.deepEqual(store.get(['macro', 'foo']), ['foo', 'bar', 'baz']);
  });

  it('should get macros from the store', function() {
    parser(['--macro', 'foo', 'foo', 'bar', 'baz']);
    assert.deepEqual(parser('foo'), { _: ['foo', 'bar', 'baz'], isMacro: 'foo' });
  });

  it('should get a complex macro from the store', function() {
    parser(['--macro', 'foo', 'foo', 'bar', 'baz', '--verbose', '--cwd', 'docs']);
    assert.deepEqual(parser('foo'), { _: ['foo', 'bar', 'baz'], verbose: true, cwd: 'docs', isMacro: 'foo' });
  });

  it('should return original name when macro is not set in the store', function() {
    assert.deepEqual(parser('foo'), { _: ['foo'] });
  });

  it('should not process macros when `--no-macro` is set', function() {
    assert.deepEqual(parser(['foo', '--no-macro']), { _: ['foo'], macro: false });
  });

  it('should del macros from the store', function() {
    parser(['--macro', 'foo', 'foo', 'bar', 'baz']);
    assert.deepEqual(parser('foo'), { _: ['foo', 'bar', 'baz'], isMacro: 'foo' });

    parser(['--macro', 'del', 'foo']);
    assert.deepEqual(parser('foo'), { _: ['foo'] });
  });

  it('should delete all macros when no macro is specified for `--del`', function() {
    parser(['--macro', 'foo', 'foo', 'bar', 'baz']);
    parser(['--macro', 'qux', 'beep', 'boop', 'bop']);
    assert.deepEqual(parser('foo'), { _: ['foo', 'bar', 'baz'], isMacro: 'foo' });
    assert.deepEqual(parser('qux'), { _: ['beep', 'boop', 'bop'], isMacro: 'qux' });

    parser(['--macro', 'del']);
    assert.deepEqual(parser(['foo', 'qux']), { _: ['foo', 'qux'] });
  });
});
<|endoftext|>


<commit_before>'use strict';

const	freeport	= require('freeport'),
	Session	= require('../index.js'),
	request	= require('request').defaults({'jar': true}),
	assert	= require('assert'),
	Lutils	= require('larvitutils'),
	lutils	= new Lutils(),
	App	= require('larvitbase'),
	log	= new lutils.Log('warn'),
	fs	= require('fs'),
	db	= require('larvitdb'),
	session	= new Session({'db': db, 'log': log});

before(function (done) {
	function checkEmptyDb() {
		db.query('SHOW TABLES', function (err, rows) {
			if (err) throw err;

			if (rows.length) {
				log.error('Database is not empty. To make a test, you must supply an empty database!');
				assert.deepEqual(rows.length, 0);
				process.exit(1);
			}

			done();
		});
	}

	function runDbSetup(confFile) {
		log.verbose('larvitsession: DB config file: "' + confFile + '"');
		log.verbose('larvitsession: DB config: ' + JSON.stringify(require(confFile)));

		db.setup(require(confFile), function (err) {
			if (err) throw err;

			checkEmptyDb();
		});
	}

console.log('process.env.DB_CONF_FILE: ' + process.env.DB_CONF_FILE);
console.log(process.cwd());
console.log(fs.existsSync(process.cwd() + '/' + process.env.DB_CONF_FILE));

	if (fs.existsSync(__dirname + '/../config/db_test.json')) {
		runDbSetup('../config/db_test.json');
	} else if (process.env.DB_CONF_FILE && fs.existsSync(process.env.DB_CONF_FILE)) {
		runDbSetup(process.env.DB_CONF_FILE);
	} else {
		throw new Error('No database configuration found');
	}
});

after(function (done) {
	// We set a timeout here, since the server will fiddle with the database a bit after the response have been sent
	setTimeout(function () {
		db.removeAllTables(function (err) {
			if (err) throw err;
			done();
			process.exit();
		});
	}, 1000);
});

describe('Basics', function () {
	let	httpPort,
		app;

	it('Setup http server', function (done) {
		freeport(function (err, port) {
			let	found	= false;

			if (err) throw err;

			httpPort	= port;

			app = new App({
				'httpOptions': port,
				'middlewares': [function (req, res, cb) {
					if (JSON.stringify(req.session.data) === '{}') {
						req.session.data	= 'hej test test';
					} else {
						found	= true;
						assert.strictEqual(req.session.data, 'hej test test');
					}

					res.end('gordon');

					cb();
				}]
			});

			app.middlewares.unshift(function (req, res, cb) { session.start(req, res, cb); });
			app.middlewares.unshift(require('cookies').express());
			app.middlewares.push(function (req, res, cb) { session.writeToDb(req, res, cb); });

			app.start(function (err) {
				if (err) throw err;
				request('http://localhost:' + port, function (err) {
					if (err) throw err;
					request('http://localhost:' + port, function (err, response, body) {
						if (err) throw err;
						assert.strictEqual(body,	'gordon');
						assert.strictEqual(found,	true);
						done();
					});
				});
			});
		});
	});

	it('Testing if sessions table got created', function (done) {
		request('http://localhost:' + httpPort, function (err) {
			if (err) throw err;
			db.query('SELECT * FROM sessions', function (err, result) {
				if (err) throw err;

				assert.strictEqual(JSON.parse(result[0].json), 'hej test test');

				request('http://localhost:' + httpPort, function (err) {
					if (err) throw err;
					done(); // At least we know the sessions table have been created....
				});
			});
		});
	});
});
<commit_msg>Increased logging<commit_after>'use strict';

const	freeport	= require('freeport'),
	Session	= require('../index.js'),
	request	= require('request').defaults({'jar': true}),
	assert	= require('assert'),
	Lutils	= require('larvitutils'),
	lutils	= new Lutils(),
	App	= require('larvitbase'),
	log	= new lutils.Log('verbose'),
	fs	= require('fs'),
	db	= require('larvitdb'),
	session	= new Session({'db': db, 'log': log});

before(function (done) {
	function checkEmptyDb() {
		db.query('SHOW TABLES', function (err, rows) {
			if (err) throw err;

			if (rows.length) {
				log.error('Database is not empty. To make a test, you must supply an empty database!');
				assert.deepEqual(rows.length, 0);
				process.exit(1);
			}

			done();
		});
	}

	function runDbSetup(confFile) {
		log.verbose('larvitsession: DB config file: "' + confFile + '"');
		log.verbose('larvitsession: DB config: ' + JSON.stringify(require(confFile)));

		db.setup(require(confFile), function (err) {
			if (err) throw err;

			checkEmptyDb();
		});
	}

	if (fs.existsSync(__dirname + '/../config/db_test.json')) {
		runDbSetup('../config/db_test.json');
	} else if (process.env.DB_CONF_FILE && fs.existsSync(process.env.DB_CONF_FILE)) {
		runDbSetup(process.env.DB_CONF_FILE);
	} else {
		throw new Error('No database configuration found');
	}
});

after(function (done) {
	// We set a timeout here, since the server will fiddle with the database a bit after the response have been sent
	setTimeout(function () {
		db.removeAllTables(function (err) {
			if (err) throw err;
			done();
			process.exit();
		});
	}, 1000);
});

describe('Basics', function () {
	let	httpPort,
		app;

	it('Setup http server', function (done) {
		freeport(function (err, port) {
			let	found	= false;

			if (err) throw err;

			httpPort	= port;

			app = new App({
				'httpOptions': port,
				'middlewares': [function (req, res, cb) {
					if (JSON.stringify(req.session.data) === '{}') {
						req.session.data	= 'hej test test';
					} else {
						found	= true;
						assert.strictEqual(req.session.data, 'hej test test');
					}

					res.end('gordon');

					cb();
				}]
			});

			app.middlewares.unshift(function (req, res, cb) { session.start(req, res, cb); });
			app.middlewares.unshift(require('cookies').express());
			app.middlewares.push(function (req, res, cb) { session.writeToDb(req, res, cb); });

			app.start(function (err) {
				if (err) throw err;
				request('http://localhost:' + port, function (err) {
					if (err) throw err;
					request('http://localhost:' + port, function (err, response, body) {
						if (err) throw err;
						assert.strictEqual(body,	'gordon');
						assert.strictEqual(found,	true);
						done();
					});
				});
			});
		});
	});

	it('Testing if sessions table got created', function (done) {
		request('http://localhost:' + httpPort, function (err) {
			if (err) throw err;
			db.query('SELECT * FROM sessions', function (err, result) {
				if (err) throw err;

				assert.strictEqual(JSON.parse(result[0].json), 'hej test test');

				request('http://localhost:' + httpPort, function (err) {
					if (err) throw err;
					done(); // At least we know the sessions table have been created....
				});
			});
		});
	});
});
<|endoftext|>


<commit_before>var assert = require('assert');
var fs = require('fs');

var networking = require('../modules/networking');
var helpers = require('../modules/helpers');
var config = require('../modules/config');
var skins = require('../modules/skins');
var cache = require("../modules/cache");

// we don't want tests to fail because of slow internet
config.http_timeout = 3000;

var uuids = fs.readFileSync('test/uuids.txt').toString().split("\n");
var usernames = fs.readFileSync('test/usernames.txt').toString().split("\n");
// Get a random UUID + username in order to prevent rate limiting
var uuid = uuids[Math.round(Math.random() * (uuids.length - 1))];
var username = usernames[Math.round(Math.random() * (usernames.length - 1))];

describe('Crafatar', function() {
  before(function() {
    cache.get_redis().flushall();
  });

  describe('UUID/username', function() {
    it("should be an invalid uuid", function(done) {
      assert.strictEqual(helpers.uuid_valid("g098cb60fa8e427cb299793cbd302c9a"), false);
      done();
    });
    it("should be an invalid uuid", function(done) {
      assert.strictEqual(helpers.uuid_valid(""), false);
      done();
    });
    it("should be an invalid username", function(done) {
      assert.strictEqual(helpers.uuid_valid("usernäme"), false);
      done();
    });
    it("should be an invalid username", function(done) {
      assert.strictEqual(helpers.uuid_valid("user-name"), false);
      done();
    });
    it("should be an invalid username", function(done) {
      assert.strictEqual(helpers.uuid_valid("ThisNameIsTooLong"), false);
      done();
    });
    it("should be a valid uuid", function(done) {
      assert.strictEqual(helpers.uuid_valid("0098cb60fa8e427cb299793cbd302c9a"), true);
      done();
    });
    it("should be a valid uuid", function(done) {
      assert.strictEqual(helpers.uuid_valid("0098cb60-fa8e-427c-b299-793cbd302c9a"), true);
      done();
    });
    it("should be a valid username", function(done) {
      assert.strictEqual(helpers.uuid_valid("__niceUs3rname__"), true);
      done();
    });
    it("should be a valid username", function(done) {
      assert.strictEqual(helpers.uuid_valid("a"), true);
      done();
    });
    it("should not exist (uuid)", function(done) {
      networking.get_skin_url("00000000000000000000000000000000", function(err, profile) {
        assert.strictEqual(err, 0);
        done();
      });
    });
    it("should not exist (username)", function(done) {
      networking.get_skin_url("Steve", function(err, profile) {
        assert.strictEqual(err, 0);
        done();
      });
    });
  });

  describe('Networking: Avatar', function() {
    it("should be downloaded (uuid)", function(done) {
      helpers.get_avatar(uuid, false, 160, function(err, status, image) {
        assert.strictEqual(status, 2);
        done();
      });
    });
    it("should be cached (uuid)", function(done) {
      helpers.get_avatar(uuid, false, 160, function(err, status, image) {
        assert.strictEqual(status, 1);
        done();
      });
    });
    /* We can't test this because of mojang's rate limits :(
    it("should be checked (uuid)", function(done) {
      var original_cache_time = config.local_cache_time;
      config.local_cache_time = 0;
      helpers.get_avatar(uuid, false, 160, function(err, status, image) {
        assert.strictEqual(status, 3);
        config.local_cache_time = original_cache_time;
        done();
      });
    });
    */
    it("should be downloaded (username)", function(done) {
      helpers.get_avatar(username, false, 160, function(err, status, image) {
        assert.strictEqual(status, 2);
        done();
      });
    });
    it("should be cached (username)", function(done) {
      helpers.get_avatar(username, false, 160, function(err, status, image) {
        assert.strictEqual(status, 1);
        done();
      });
    });
    it("should be checked (username)", function(done) {
      var original_cache_time = config.local_cache_time;
      config.local_cache_time = 0;
      helpers.get_avatar(username, false, 160, function(err, status, image) {
        assert.strictEqual(status, 3);
        config.local_cache_time = original_cache_time;
        done();
      });
    });
    it("should not exist (but account does)", function(done) {
      // profile 'Alex'
      helpers.get_avatar("ec561538f3fd461daff5086b22154bce", false, 160, function(err, status, image) {
        assert.strictEqual(status, 3);
        done();
      });
    });
    it("should default to Alex", function(done) {
      assert.strictEqual(skins.default_skin("ec561538f3fd461daff5086b22154bce"), "alex");
      done();
    });
    it("should default to Steve", function(done) {
      assert.strictEqual(skins.default_skin("b8ffc3d37dbf48278f69475f6690aabd"), "steve");
      done();
    });
  });

  describe('Mojang Errors', function() {
    before(function() {
      cache.get_redis().flushall();
    });
    it("should be rate limited", function(done) {
      helpers.get_avatar(uuid, false, 160, function(err, status, image) {
        assert.strictEqual(err, null);
        done();
      });
    });
    it("should time out on profile download", function(done) {
      var original_timeout = config.http_timeout;
      config.http_timeout = 1;
      networking.get_skin_url("069a79f444e94726a5befca90e38aaf5", function(err, profile) {
        assert.strictEqual(err.code, "ETIMEDOUT");
        config.http_timeout = original_timeout;
        done();
      });
    });
    it("should time out on skin download", function(done) {
      var original_timeout = config.http_timeout;
      config.http_timeout = 1;
      networking.skin_file("http://textures.minecraft.net/texture/477be35554684c28bdeee4cf11c591d3c88afb77e0b98da893fd7bc318c65184", "face.png", "helm.png", function(err) {
        assert.strictEqual(err.code, "ETIMEDOUT");
        config.http_timeout = original_timeout;
        done();
      });
    });
  });
});
<commit_msg>add test for timing out on username info (#14)<commit_after>var assert = require('assert');
var fs = require('fs');

var networking = require('../modules/networking');
var helpers = require('../modules/helpers');
var config = require('../modules/config');
var skins = require('../modules/skins');
var cache = require("../modules/cache");

// we don't want tests to fail because of slow internet
config.http_timeout = 3000;

var uuids = fs.readFileSync('test/uuids.txt').toString().split("\n");
var usernames = fs.readFileSync('test/usernames.txt').toString().split("\n");
// Get a random UUID + username in order to prevent rate limiting
var uuid = uuids[Math.round(Math.random() * (uuids.length - 1))];
var username = usernames[Math.round(Math.random() * (usernames.length - 1))];

describe('Crafatar', function() {
  before(function() {
    cache.get_redis().flushall();
  });

  describe('UUID/username', function() {
    it("should be an invalid uuid", function(done) {
      assert.strictEqual(helpers.uuid_valid("g098cb60fa8e427cb299793cbd302c9a"), false);
      done();
    });
    it("should be an invalid uuid", function(done) {
      assert.strictEqual(helpers.uuid_valid(""), false);
      done();
    });
    it("should be an invalid username", function(done) {
      assert.strictEqual(helpers.uuid_valid("usernäme"), false);
      done();
    });
    it("should be an invalid username", function(done) {
      assert.strictEqual(helpers.uuid_valid("user-name"), false);
      done();
    });
    it("should be an invalid username", function(done) {
      assert.strictEqual(helpers.uuid_valid("ThisNameIsTooLong"), false);
      done();
    });
    it("should be a valid uuid", function(done) {
      assert.strictEqual(helpers.uuid_valid("0098cb60fa8e427cb299793cbd302c9a"), true);
      done();
    });
    it("should be a valid uuid", function(done) {
      assert.strictEqual(helpers.uuid_valid("0098cb60-fa8e-427c-b299-793cbd302c9a"), true);
      done();
    });
    it("should be a valid username", function(done) {
      assert.strictEqual(helpers.uuid_valid("__niceUs3rname__"), true);
      done();
    });
    it("should be a valid username", function(done) {
      assert.strictEqual(helpers.uuid_valid("a"), true);
      done();
    });
    it("should not exist (uuid)", function(done) {
      networking.get_skin_url("00000000000000000000000000000000", function(err, profile) {
        assert.strictEqual(err, 0);
        done();
      });
    });
    it("should not exist (username)", function(done) {
      networking.get_skin_url("Steve", function(err, profile) {
        assert.strictEqual(err, 0);
        done();
      });
    });
  });

  describe('Networking: Avatar', function() {
    it("should be downloaded (uuid)", function(done) {
      helpers.get_avatar(uuid, false, 160, function(err, status, image) {
        assert.strictEqual(status, 2);
        done();
      });
    });
    it("should be cached (uuid)", function(done) {
      helpers.get_avatar(uuid, false, 160, function(err, status, image) {
        assert.strictEqual(status, 1);
        done();
      });
    });
    /* We can't test this because of mojang's rate limits :(
    it("should be checked (uuid)", function(done) {
      var original_cache_time = config.local_cache_time;
      config.local_cache_time = 0;
      helpers.get_avatar(uuid, false, 160, function(err, status, image) {
        assert.strictEqual(status, 3);
        config.local_cache_time = original_cache_time;
        done();
      });
    });
    */
    it("should be downloaded (username)", function(done) {
      helpers.get_avatar(username, false, 160, function(err, status, image) {
        assert.strictEqual(status, 2);
        done();
      });
    });
    it("should be cached (username)", function(done) {
      helpers.get_avatar(username, false, 160, function(err, status, image) {
        assert.strictEqual(status, 1);
        done();
      });
    });
    it("should be checked (username)", function(done) {
      var original_cache_time = config.local_cache_time;
      config.local_cache_time = 0;
      helpers.get_avatar(username, false, 160, function(err, status, image) {
        assert.strictEqual(status, 3);
        config.local_cache_time = original_cache_time;
        done();
      });
    });
    it("should not exist (but account does)", function(done) {
      // profile 'Alex'
      helpers.get_avatar("ec561538f3fd461daff5086b22154bce", false, 160, function(err, status, image) {
        assert.strictEqual(status, 3);
        done();
      });
    });
    it("should default to Alex", function(done) {
      assert.strictEqual(skins.default_skin("ec561538f3fd461daff5086b22154bce"), "alex");
      done();
    });
    it("should default to Steve", function(done) {
      assert.strictEqual(skins.default_skin("b8ffc3d37dbf48278f69475f6690aabd"), "steve");
      done();
    });
  });

  describe('Mojang Errors', function() {
    before(function() {
      cache.get_redis().flushall();
    });
    it("should be rate limited", function(done) {
      helpers.get_avatar(uuid, false, 160, function(err, status, image) {
        assert.strictEqual(err, null);
        done();
      });
    });
    it("should time out on uuid info download", function(done) {
      var original_timeout = config.http_timeout;
      config.http_timeout = 1;
      networking.get_skin_url("069a79f444e94726a5befca90e38aaf5", function(err, skin_url) {
        assert.strictEqual(err.code, "ETIMEDOUT");
        config.http_timeout = original_timeout;
        done();
      });
    });
    it("should time out on username info download", function(done) {
      var original_timeout = config.http_timeout;
      config.http_timeout = 1;
      networking.get_skin_url("redstone_sheep", function(err, skin_url) {
        assert.strictEqual(err.code, "ETIMEDOUT");
        config.http_timeout = original_timeout;
        done();
      });
    });
    it("should time out on skin download", function(done) {
      var original_timeout = config.http_timeout;
      config.http_timeout = 1;
      networking.skin_file("http://textures.minecraft.net/texture/477be35554684c28bdeee4cf11c591d3c88afb77e0b98da893fd7bc318c65184", "face.png", "helm.png", function(err) {
        assert.strictEqual(err.code, "ETIMEDOUT");
        config.http_timeout = original_timeout;
        done();
      });
    });
  });
});
<|endoftext|>


<commit_before>'use strict';

var assert = require('assert'),
    Ausweisnummer = require('../'),
    AssertionError = assert.AssertionError;

var old_valid = '1220001297D640812517103198';

describe('old-format ausweisnummer', function () {

    describe('valid', function () {

        it('should pass constructor', function () {
            assert.doesNotThrow(function () {
                new Ausweisnummer(old_valid);
            });
        });

        it('should split the ID into parts', function () {
            var an = new Ausweisnummer(old_valid);

            assert.equal(122000129, an.number);
            assert.equal(7, an.number_cd);

            assert.equal(640812, an.birthdate);
            assert.equal(5, an.birthdate_cd);

            assert.equal(171031, an.expiry);
            assert.equal(9, an.expiry_cd);

            assert.equal(8, an.full_cd);
        });
    });

    describe('invalid', function () {

        it('should detect wrong number check digit', function () {
            assert.throws(function () {
                // 7 -> 9
                new Ausweisnummer('1220001299D640812517103198');
            }, /invalid number_cd/);
        });

        it('should detect invalid birthdate part format', function () {
            assert.throws(function () {
                // 13th month
                new Ausweisnummer('1220001297D641312517103198');
            }, /birthdate is invalid/);
        });

        it('should detect wrong birthdate check digit', function () {
            assert.throws(function () {
                // 5 -> 4
                new Ausweisnummer('1220001297D640812417103198');
            }, /invalid birthdate_cd/);
        });

        it('should detect invalid expiry date part format', function () {
            assert.throws(function () {
                // 32 days in a month
                new Ausweisnummer('1220001297D640812517103298');
            }, /expiry is invalid/);
        });

        it('should detect wrong expiry date check digit', function () {
            assert.throws(function () {
                new Ausweisnummer('1220001297D640812517103188');
            }, /invalid expiry_cd/);
        });

        it('should detect wrong full check digit', function () {
            assert.throws(function () {
                new Ausweisnummer('1220001297D640812517103199');
            }, /invalid full_cd/);
        });
    });
});

var new_valid = 'T22000129364081252010315D4';

describe('new-format ausweisnummer', function () {

    describe('valid', function () {

        it('should pass constructor', function () {
            assert.doesNotThrow(function () {
                new Ausweisnummer(new_valid);
            });
        });

        it('should split the ID into parts', function () {
            var an = new Ausweisnummer(new_valid);

            assert.equal('T22000129', an.number);
            assert.equal(3, an.number_cd);

            assert.equal(640812, an.birthdate);
            assert.equal(5, an.birthdate_cd);

            assert.equal(201031, an.expiry);
            assert.equal(5, an.expiry_cd);

            assert.equal(4, an.full_cd);
        });
    });

    describe('invalid', function () {
        it('should detect invalid number part format', function () {
            assert.throws(function () {
                // A not allowed in number part
                new Ausweisnummer('A22000129364081252010315D4');
            }, /number is invalid/);
        });

        it('should detect wrong number check digit', function () {
            assert.throws(function () {
                new Ausweisnummer('T22000129264081252010315D4');
            }, /invalid number_cd/);
        });

        // 13 months
        it('should detect invalid birthdate part format', function () {
            assert.throws(function () {
                new Ausweisnummer('T22000129364131252010315D4');
            }, /birthdate is invalid/);
        });

        it('should detect wrong birthdate check digit', function () {
            assert.throws(function () {
                new Ausweisnummer('T22000129364081242010315D4');
            }, /invalid birthdate_cd/);
        });

        // 32 days
        it('should detect invalid expiry date part format', function () {
            assert.throws(function () {
                new Ausweisnummer('T22000129364081252010325D4');
            }, /expiry is invalid/);
        });

        it('should detect wrong expiry date check digit', function () {
            assert.throws(function () {
                new Ausweisnummer('T22000129364081252010316D4');
            }, /invalid expiry_cd/);
        });

        it('should detect wrong full check digit', function () {
            assert.throws(function () {
                new Ausweisnummer('T22000129364081252010315D0');
            }, /invalid full_cd/);
        });
    });
});

describe('wrong format', function () {
    it('should validate 26 chars are passed in', function () {
        assert.throws(function () {
            new Ausweisnummer('12345678');
        }, /id must be 26 characters long/);
    });

    it('should validate from the nationality position that format is wrong', function () {
        assert.throws(function () {
            new Ausweisnummer('T22000D1293640812520103150');
        }, /unrecognized id format/);
    });
});
<commit_msg>Match the correct message<commit_after>'use strict';

var assert = require('assert'),
    Ausweisnummer = require('../'),
    AssertionError = assert.AssertionError;

var old_valid = '1220001297D640812517103198';

describe('old-format ausweisnummer', function () {

    describe('valid', function () {

        it('should pass constructor', function () {
            assert.doesNotThrow(function () {
                new Ausweisnummer(old_valid);
            });
        });

        it('should split the ID into parts', function () {
            var an = new Ausweisnummer(old_valid);

            assert.equal(122000129, an.number);
            assert.equal(7, an.number_cd);

            assert.equal(640812, an.birthdate);
            assert.equal(5, an.birthdate_cd);

            assert.equal(171031, an.expiry);
            assert.equal(9, an.expiry_cd);

            assert.equal(8, an.full_cd);
        });
    });

    describe('invalid', function () {

        it('should detect wrong number check digit', function () {
            assert.throws(function () {
                // 7 -> 9
                new Ausweisnummer('1220001299D640812517103198');
            }, /invalid number_cd/);
        });

        it('should detect invalid birthdate part format', function () {
            assert.throws(function () {
                // 13th month
                new Ausweisnummer('1220001297D641312517103198');
            }, /birthdate has invalid format/);
        });

        it('should detect wrong birthdate check digit', function () {
            assert.throws(function () {
                // 5 -> 4
                new Ausweisnummer('1220001297D640812417103198');
            }, /invalid birthdate_cd/);
        });

        it('should detect invalid expiry date part format', function () {
            assert.throws(function () {
                // 32 days in a month
                new Ausweisnummer('1220001297D640812517103298');
            }, /expiry has invalid format/);
        });

        it('should detect wrong expiry date check digit', function () {
            assert.throws(function () {
                new Ausweisnummer('1220001297D640812517103188');
            }, /invalid expiry_cd/);
        });

        it('should detect wrong full check digit', function () {
            assert.throws(function () {
                new Ausweisnummer('1220001297D640812517103199');
            }, /invalid full_cd/);
        });
    });
});

var new_valid = 'T22000129364081252010315D4';

describe('new-format ausweisnummer', function () {

    describe('valid', function () {

        it('should pass constructor', function () {
            assert.doesNotThrow(function () {
                new Ausweisnummer(new_valid);
            });
        });

        it('should split the ID into parts', function () {
            var an = new Ausweisnummer(new_valid);

            assert.equal('T22000129', an.number);
            assert.equal(3, an.number_cd);

            assert.equal(640812, an.birthdate);
            assert.equal(5, an.birthdate_cd);

            assert.equal(201031, an.expiry);
            assert.equal(5, an.expiry_cd);

            assert.equal(4, an.full_cd);
        });
    });

    describe('invalid', function () {
        it('should detect invalid number part format', function () {
            assert.throws(function () {
                // A not allowed in number part
                new Ausweisnummer('A22000129364081252010315D4');
            }, /number has invalid format/);
        });

        it('should detect wrong number check digit', function () {
            assert.throws(function () {
                new Ausweisnummer('T22000129264081252010315D4');
            }, /invalid number_cd/);
        });

        // 13 months
        it('should detect invalid birthdate part format', function () {
            assert.throws(function () {
                new Ausweisnummer('T22000129364131252010315D4');
            }, /birthdate has invalid format/);
        });

        it('should detect wrong birthdate check digit', function () {
            assert.throws(function () {
                new Ausweisnummer('T22000129364081242010315D4');
            }, /invalid birthdate_cd/);
        });

        // 32 days
        it('should detect invalid expiry date part format', function () {
            assert.throws(function () {
                new Ausweisnummer('T22000129364081252010325D4');
            }, /expiry has invalid format/);
        });

        it('should detect wrong expiry date check digit', function () {
            assert.throws(function () {
                new Ausweisnummer('T22000129364081252010316D4');
            }, /invalid expiry_cd/);
        });

        it('should detect wrong full check digit', function () {
            assert.throws(function () {
                new Ausweisnummer('T22000129364081252010315D0');
            }, /invalid full_cd/);
        });
    });
});

describe('wrong format', function () {
    it('should validate 26 chars are passed in', function () {
        assert.throws(function () {
            new Ausweisnummer('12345678');
        }, /id must be 26 characters long/);
    });

    it('should validate from the nationality position that format is wrong', function () {
        assert.throws(function () {
            new Ausweisnummer('T22000D1293640812520103150');
        }, /unrecognized id format/);
    });
});
<|endoftext|>


<commit_before>// @flow

import * as React from 'react'
import {View, Text, StyleSheet, Platform} from 'react-native'
import Icon from 'react-native-vector-icons/Entypo'
import type {ViewType} from '../views'
import LinearGradient from 'react-native-linear-gradient'
import {Touchable} from '@frogpond/touchable'
import {transparent} from '@frogpond/colors'
import {homescreenForegroundDark, homescreenForegroundLight} from './colors'
import {iPhoneX} from '@frogpond/device'

type Props = {
	view: ViewType,
	onPress: () => any,
}

export function HomeScreenButton({view, onPress}: Props) {
	const foreground =
		view.foreground === 'light' ? styles.lightForeground : styles.darkForeground

	return (
		<TouchableButton
			gradient={view.gradient}
			label={view.title}
			onPress={onPress}
			tint={view.tint}
		>
			<View style={styles.contents}>
				<Icon name={view.icon} size={32} style={[foreground, styles.icon]} />
				<Text style={[foreground, styles.text]}>{view.title}</Text>
			</View>
		</TouchableButton>
	)
}

function TouchableButton({onPress, label, children, tint, gradient}) {
	if (Platform.OS === 'android') {
		return (
			<Tint gradient={gradient} tint={tint}>
				<TouchableWrapper label={label} onPress={onPress}>
					{children}
				</TouchableWrapper>
			</Tint>
		)
	} else {
		return (
			<TouchableWrapper label={label} onPress={onPress}>
				<Tint gradient={gradient} tint={tint}>
					{children}
				</Tint>
			</TouchableWrapper>
		)
	}
}

function TouchableWrapper({onPress, children, label}) {
	return (
		<Touchable
			accessibilityLabel={label}
			accessibilityRole="button"
			accessible={true}
			highlight={false}
			onPress={onPress}
		>
			{children}
		</Touchable>
	)
}

function Tint({tint = 'black', gradient, children}) {
	if (!gradient) {
		const bg = {backgroundColor: tint}
		return <View style={[styles.button, bg]}>{children}</View>
	}

	return (
		<LinearGradient
			colors={gradient}
			end={{x: 0, y: 0.85}}
			start={{x: 0, y: 0.05}}
			style={styles.button}
		>
			{children}
		</LinearGradient>
	)
}

export const CELL_MARGIN = 10
const cellVerticalPadding = 8
const cellHorizontalPadding = 4

const styles = StyleSheet.create({
	button: {
		elevation: 2,
		borderRadius: Platform.OS === 'ios' ? (iPhoneX ? 17 : 6) : 3,

		marginBottom: CELL_MARGIN,
		marginLeft: CELL_MARGIN / 2,
		marginRight: CELL_MARGIN / 2,
	},
	contents: {
		alignItems: 'center',
		justifyContent: 'center',

		paddingTop: cellVerticalPadding,
		paddingBottom: cellVerticalPadding / 2,
		paddingHorizontal: cellHorizontalPadding,
	},
	icon: {
		backgroundColor: transparent,
	},
	text: {
		backgroundColor: transparent,
		fontFamily: Platform.OS === 'ios' ? 'System' : 'sans-serif-condensed',
		fontSize: 14,
	},
	lightForeground: {
		color: homescreenForegroundLight,
	},
	darkForeground: {
		color: homescreenForegroundDark,
	},
})
<commit_msg>add more typedefs to Home/Button<commit_after>// @flow

import * as React from 'react'
import {View, Text, StyleSheet, Platform} from 'react-native'
import Icon from 'react-native-vector-icons/Entypo'
import type {ViewType} from '../views'
import LinearGradient from 'react-native-linear-gradient'
import {Touchable} from '@frogpond/touchable'
import {transparent} from '@frogpond/colors'
import {homescreenForegroundDark, homescreenForegroundLight} from './colors'
import {iPhoneX} from '@frogpond/device'

type Props = {
	view: ViewType,
	onPress: () => any,
}

export function HomeScreenButton({view, onPress}: Props) {
	const foreground =
		view.foreground === 'light' ? styles.lightForeground : styles.darkForeground

	return (
		<TouchableButton
			gradient={view.gradient}
			label={view.title}
			onPress={onPress}
			tint={view.tint}
		>
			<View style={styles.contents}>
				<Icon name={view.icon} size={32} style={[foreground, styles.icon]} />
				<Text style={[foreground, styles.text]}>{view.title}</Text>
			</View>
		</TouchableButton>
	)
}

type TouchableButtonProps = {
	onPress: () => void,
	label: string,
	children: React.Node,
	tint: string,
	gradient: ?[string, string],
}

function TouchableButton(props: TouchableButtonProps) {
	let {onPress, label, children, tint, gradient} = props

	if (Platform.OS === 'android') {
		return (
			<Tint gradient={gradient} tint={tint}>
				<TouchableWrapper label={label} onPress={onPress}>
					{children}
				</TouchableWrapper>
			</Tint>
		)
	} else {
		return (
			<TouchableWrapper label={label} onPress={onPress}>
				<Tint gradient={gradient} tint={tint}>
					{children}
				</Tint>
			</TouchableWrapper>
		)
	}
}

type TouchableWrapperProps = {
	onPress: () => void,
	label: string,
	children: React.Node,
}

function TouchableWrapper({onPress, children, label}: TouchableWrapperProps) {
	return (
		<Touchable
			accessibilityLabel={label}
			accessibilityRole="button"
			accessible={true}
			highlight={false}
			onPress={onPress}
		>
			{children}
		</Touchable>
	)
}

type TintProps = {
	children: React.Node,
	tint: string,
	gradient: ?[string, string],
}

function Tint({tint = 'black', gradient, children}: TintProps) {
	if (!gradient) {
		const bg = {backgroundColor: tint}
		return <View style={[styles.button, bg]}>{children}</View>
	}

	return (
		<LinearGradient
			colors={gradient}
			end={{x: 0, y: 0.85}}
			start={{x: 0, y: 0.05}}
			style={styles.button}
		>
			{children}
		</LinearGradient>
	)
}

export const CELL_MARGIN = 10
const cellVerticalPadding = 8
const cellHorizontalPadding = 4

const styles = StyleSheet.create({
	button: {
		elevation: 2,
		borderRadius: Platform.OS === 'ios' ? (iPhoneX ? 17 : 6) : 3,

		marginBottom: CELL_MARGIN,
		marginLeft: CELL_MARGIN / 2,
		marginRight: CELL_MARGIN / 2,
	},
	contents: {
		alignItems: 'center',
		justifyContent: 'center',

		paddingTop: cellVerticalPadding,
		paddingBottom: cellVerticalPadding / 2,
		paddingHorizontal: cellHorizontalPadding,
	},
	icon: {
		backgroundColor: transparent,
	},
	text: {
		backgroundColor: transparent,
		fontFamily: Platform.OS === 'ios' ? 'System' : 'sans-serif-condensed',
		fontSize: 14,
	},
	lightForeground: {
		color: homescreenForegroundLight,
	},
	darkForeground: {
		color: homescreenForegroundDark,
	},
})
<|endoftext|>


<commit_before>
/*!
 * Express - Server
 * Copyright(c) 2010 TJ Holowaychuk <tj@vision-media.ca>
 * MIT Licensed
 */

/**
 * Module dependencies.
 */

var url = require('url')
  , view = require('./view')
  , connect = require('connect')
  , utils = connect.utils
  , queryString = require('querystring')
  , router = require('connect/middleware/router');

/**
 * Initialize a new `Server` with optional `middleware`.
 *
 * @param {Array} middleware
 * @api public
 */

var Server = exports = module.exports = function Server(middleware){
  var self = this;
  this.config = {};
  this.settings = {};
  this.redirects = {};
  this.isCallbacks = {};
  this.viewHelpers = {};
  this.dynamicViewHelpers = {};
  this.errorHandlers = [];
  connect.Server.call(this, middleware || []);

  // Default "home" to /
  this.set('home', '/');

  // TODO: remove when Connect removes "Server" ...
  this.showVersion = false;

  // Set "env" to NODE_ENV, defaulting to "development"
  this.set('env', process.env.NODE_ENV || 'development');

  // Expose objects to each other
  this.use(function(req, res, next){
    req.query = {};
    res.headers = { 'X-Powered-By': 'Express' };
    req.app = res.app = self;
    req.res = res;
    res.req = req;
    req.next = next;
    // Assign req.params.get
    if (req.url.indexOf('?') > 0) {
      var query = url.parse(req.url).query;
      req.query = exports.parseQueryString(query);
    }
    next();
  });

  // Use router, expose as app.get(), etc
  var fn = router(function(app){ self.routes = app; });
  this.__defineGetter__('router', function(){
    this.__usedRouter = true;
    return fn;
  });

  // Default production configuration
  this.configure('production', function(){
    this.enable('cache views');
  });
};

/**
 * Inherit from `connect.Server`.
 */

Server.prototype.__proto__ = connect.Server.prototype;

/**
 * Support swappable querystring parsers.
 */

exports.parseQueryString = queryString.parse;

/**
 * Proxy in order to register error handlers.
 */

Server.prototype.listen = function(){
  this.registerErrorHandlers();
  connect.Server.prototype.listen.apply(this, arguments);
};

/**
 * Proxy in order to register error handlers.
 */

Server.prototype.listenFD = function(){
  this.registerErrorHandlers();
  connect.Server.prototype.listenFD.apply(this, arguments);
};

/**
 * Register error handlers. This is automatically
 * called from within `Server#listen()` and `Server#listenFD()`.
 *
 * @return {Server} for chaining
 * @api public
 */

Server.prototype.registerErrorHandlers = function(){
  this.errorHandlers.forEach(function(fn){
    this.use(function(err, req, res, next){
      fn.apply(this, arguments);
    });
  }, this);
  return this;
};

/**
 * Proxy `connect.Server#use()` to apply settings to
 * mounted applications.
 *
 * @param {String|Function|Server} route
 * @param {Function|Server} middleware
 * @return {Server} for chaining
 * @api public
 */

Server.prototype.use = function(route, middleware){
  if (typeof route !== 'string') {
    middleware = route, route = '/';
  }

  connect.Server.prototype.use.call(this, route, middleware);

  // Mounted an app
  if (middleware instanceof Server) {
    // Home is /:route/:home
    var app = middleware
      , home = app.set('home');
    if (home === '/') home = '';
    app.set('home', (app.route || '') + home);
    app.parent = this;
    // Mounted hook
    if (app.__mounted) app.__mounted.call(app, this);
  }

  return this;
};

/**
 * Assign a callback `fn` which is called
 * when this `Server` is passed to `Server#use()`.
 *
 * Examples:
 *
 *    var app = express.createServer(),
 *        blog = express.createServer();
 *
 *    blog.mounted(function(parent){
 *        // parent is app
 *        // "this" is blog
 *    });
 *
 *    app.use(blog);
 *
 * @param {Function} fn
 * @return {Server} for chaining
 * @api public
 */

Server.prototype.mounted = function(fn){
  this.__mounted = fn;
  return this;
};

/**
 * See: view.register.
 *
 * @return {Server} for chaining
 * @api public
 */

Server.prototype.register = function(){
  view.register.apply(this, arguments);
  return this;
};

/**
 * Register the given view helpers `obj`. This method
 * can be called several times to apply additional helpers.
 *
 * @param {Object} obj
 * @return {Server} for chaining
 * @api public
 */

Server.prototype.helpers = function(obj){
  utils.merge(this.viewHelpers, obj);
  return this;
};

/**
 * Register the given dynamic view helpers `obj`. This method
 * can be called several times to apply additional helpers.
 *
 * @param {Object} obj
 * @return {Server} for chaining
 * @api public
 */

Server.prototype.dynamicHelpers = function(obj){
  utils.merge(this.dynamicViewHelpers, obj);
  return this;
};

/**
 * Assign a custom exception handler callback `fn`.
 * These handlers are always _last_ in the middleware stack.
 *
 * @param {Function} fn
 * @return {Server} for chaining
 * @api public
 */

Server.prototype.error = function(fn){
  this.errorHandlers.push(fn);
  return this;
};

/**
 * Register the given callback `fn` for the given `type`.
 *
 * @param {String} type
 * @param {Function} fn
 * @return {Server} for chaining
 * @api public
 */

Server.prototype.is = function(type, fn){
  if (!fn) return this.isCallbacks[type];
  this.isCallbacks[type] = fn;
  return this;
};

/**
 * Assign `setting` to `val`, or return `setting`'s value.
 * Mounted servers inherit their parent server's settings.
 *
 * @param {String} setting
 * @param {String} val
 * @return {Server|Mixed} for chaining, or the setting value
 * @api public
 */

Server.prototype.set = function(setting, val){
  if (val === undefined) {
    if (this.settings.hasOwnProperty(setting)) {
      return this.settings[setting];
    } else if (this.parent) {
      return this.parent.set(setting);
    }
  } else {
    this.settings[setting] = val;
    return this;
  }
};

/**
 * Enable `setting`.
 *
 * @param {String} setting
 * @return {Server} for chaining
 * @api public
 */

Server.prototype.enable = function(setting){
  return this.set(setting, true);
};

/**
 * Disable `setting`.
 *
 * @param {String} setting
 * @return {Server} for chaining
 * @api public
 */

Server.prototype.disable = function(setting){
  return this.set(setting, false);
};

/**
 * Redirect `key` to `url`.
 *
 * @param {String} key
 * @param {String} url
 * @return {Server} for chaining
 * @api public
 */

Server.prototype.redirect = function(key, url){
  this.redirects[key] = url;
  return this;
};

/**
 * Configure callback for the given `env`.
 *
 * @param {String} env
 * @param {Function} fn
 * @return {Server} for chaining
 * @api public
 */

Server.prototype.configure = function(env, fn){
  if (typeof env === 'function') {
    fn = env, env = 'all';
  }
  if (env === 'all' || this.set('env') === env) {
    fn.call(this);
  }
  return this;
};

// Generate routing methods

(function(method){
  Server.prototype[method] = function(path, fn){
    var self = this;

    // Ensure router is mounted
    if (!this.__usedRouter) {
      this.use(this.router);
    }

    // Route specific middleware support
    if (arguments.length > 2) {
      var args = Array.prototype.slice.call(arguments, 1);
      fn = args.pop();
      (function stack(middleware){
        middleware.forEach(function(fn){
          if (Array.isArray(fn)) {
            stack(fn);
          } else {
            self[method](path, fn);
          }
        });
      })(args);
    }

    // Generate the route
    this.routes[method](path, fn);
    return this;
  };
  return arguments.callee;
})('get')('post')('put')('delete')('all');

// Alias delete as "del"

Server.prototype.del = Server.prototype.delete;
<commit_msg>misc refactoring<commit_after>
/*!
 * Express - Server
 * Copyright(c) 2010 TJ Holowaychuk <tj@vision-media.ca>
 * MIT Licensed
 */

/**
 * Module dependencies.
 */

var url = require('url')
  , view = require('./view')
  , connect = require('connect')
  , utils = connect.utils
  , queryString = require('querystring')
  , router = require('connect/middleware/router');

/**
 * Initialize a new `Server` with optional `middleware`.
 *
 * @param {Array} middleware
 * @api public
 */

var Server = exports = module.exports = function Server(middleware){
  var self = this;
  this.config = {};
  this.settings = {};
  this.redirects = {};
  this.isCallbacks = {};
  this.viewHelpers = {};
  this.dynamicViewHelpers = {};
  this.errorHandlers = [];
  connect.Server.call(this, middleware || []);

  // Default "home" to /
  this.set('home', '/');

  // TODO: remove when Connect removes "Server" ...
  this.showVersion = false;

  // Set "env" to NODE_ENV, defaulting to "development"
  this.set('env', process.env.NODE_ENV || 'development');

  // Expose objects to each other
  this.use(function(req, res, next){
    req.query = {};
    res.headers = { 'X-Powered-By': 'Express' };
    req.app = res.app = self;
    req.res = res;
    res.req = req;
    req.next = next;
    // Assign req.params.get
    if (req.url.indexOf('?') > 0) {
      var query = url.parse(req.url).query;
      req.query = exports.parseQueryString(query);
    }
    next();
  });

  // Use router, expose as app.get(), etc
  var fn = router(function(app){ self.routes = app; });
  this.__defineGetter__('router', function(){
    this.__usedRouter = true;
    return fn;
  });

  // Default production configuration
  this.configure('production', function(){
    this.enable('cache views');
  });
};

/**
 * Inherit from `connect.Server`.
 */

Server.prototype.__proto__ = connect.Server.prototype;

/**
 * Support swappable querystring parsers.
 */

exports.parseQueryString = queryString.parse;

/**
 * Proxy in order to register error handlers.
 */

Server.prototype.listen = function(){
  this.registerErrorHandlers();
  connect.Server.prototype.listen.apply(this, arguments);
};

/**
 * Proxy in order to register error handlers.
 */

Server.prototype.listenFD = function(){
  this.registerErrorHandlers();
  connect.Server.prototype.listenFD.apply(this, arguments);
};

/**
 * Register error handlers. This is automatically
 * called from within `Server#listen()` and `Server#listenFD()`.
 *
 * @return {Server} for chaining
 * @api public
 */

Server.prototype.registerErrorHandlers = function(){
  this.errorHandlers.forEach(function(fn){
    this.use(function(err, req, res, next){
      fn.apply(this, arguments);
    });
  }, this);
  return this;
};

/**
 * Proxy `connect.Server#use()` to apply settings to
 * mounted applications.
 *
 * @param {String|Function|Server} route
 * @param {Function|Server} middleware
 * @return {Server} for chaining
 * @api public
 */

Server.prototype.use = function(route, middleware){
  if (typeof route !== 'string') {
    middleware = route, route = '/';
  }

  connect.Server.prototype.use.call(this, route, middleware);

  // Mounted an app
  if (middleware instanceof Server) {
    // Home is /:route/:home
    var app = middleware
      , home = app.set('home');
    if (home === '/') home = '';
    app.set('home', (app.route || '') + home);
    app.parent = this;
    // Mounted hook
    if (app.__mounted) app.__mounted.call(app, this);
  }

  return this;
};

/**
 * Assign a callback `fn` which is called
 * when this `Server` is passed to `Server#use()`.
 *
 * Examples:
 *
 *    var app = express.createServer(),
 *        blog = express.createServer();
 *
 *    blog.mounted(function(parent){
 *        // parent is app
 *        // "this" is blog
 *    });
 *
 *    app.use(blog);
 *
 * @param {Function} fn
 * @return {Server} for chaining
 * @api public
 */

Server.prototype.mounted = function(fn){
  this.__mounted = fn;
  return this;
};

/**
 * See: view.register.
 *
 * @return {Server} for chaining
 * @api public
 */

Server.prototype.register = function(){
  view.register.apply(this, arguments);
  return this;
};

/**
 * Register the given view helpers `obj`. This method
 * can be called several times to apply additional helpers.
 *
 * @param {Object} obj
 * @return {Server} for chaining
 * @api public
 */

Server.prototype.helpers = function(obj){
  utils.merge(this.viewHelpers, obj);
  return this;
};

/**
 * Register the given dynamic view helpers `obj`. This method
 * can be called several times to apply additional helpers.
 *
 * @param {Object} obj
 * @return {Server} for chaining
 * @api public
 */

Server.prototype.dynamicHelpers = function(obj){
  utils.merge(this.dynamicViewHelpers, obj);
  return this;
};

/**
 * Assign a custom exception handler callback `fn`.
 * These handlers are always _last_ in the middleware stack.
 *
 * @param {Function} fn
 * @return {Server} for chaining
 * @api public
 */

Server.prototype.error = function(fn){
  this.errorHandlers.push(fn);
  return this;
};

/**
 * Register the given callback `fn` for the given `type`.
 *
 * @param {String} type
 * @param {Function} fn
 * @return {Server} for chaining
 * @api public
 */

Server.prototype.is = function(type, fn){
  if (!fn) return this.isCallbacks[type];
  this.isCallbacks[type] = fn;
  return this;
};

/**
 * Assign `setting` to `val`, or return `setting`'s value.
 * Mounted servers inherit their parent server's settings.
 *
 * @param {String} setting
 * @param {String} val
 * @return {Server|Mixed} for chaining, or the setting value
 * @api public
 */

Server.prototype.set = function(setting, val){
  if (val === undefined) {
    if (this.settings.hasOwnProperty(setting)) {
      return this.settings[setting];
    } else if (this.parent) {
      return this.parent.set(setting);
    }
  } else {
    this.settings[setting] = val;
    return this;
  }
};

/**
 * Enable `setting`.
 *
 * @param {String} setting
 * @return {Server} for chaining
 * @api public
 */

Server.prototype.enable = function(setting){
  return this.set(setting, true);
};

/**
 * Disable `setting`.
 *
 * @param {String} setting
 * @return {Server} for chaining
 * @api public
 */

Server.prototype.disable = function(setting){
  return this.set(setting, false);
};

/**
 * Redirect `key` to `url`.
 *
 * @param {String} key
 * @param {String} url
 * @return {Server} for chaining
 * @api public
 */

Server.prototype.redirect = function(key, url){
  this.redirects[key] = url;
  return this;
};

/**
 * Configure callback for the given `env`.
 *
 * @param {String} env
 * @param {Function} fn
 * @return {Server} for chaining
 * @api public
 */

Server.prototype.configure = function(env, fn){
  if (typeof env === 'function') {
    fn = env, env = 'all';
  }
  if ('all' == env || env == this.settings.env) {
    fn.call(this);
  }
  return this;
};

// Generate routing methods

(function(method){
  Server.prototype[method] = function(path, fn){
    var self = this;

    // Ensure router is mounted
    if (!this.__usedRouter) {
      this.use(this.router);
    }

    // Route specific middleware support
    if (arguments.length > 2) {
      var args = Array.prototype.slice.call(arguments, 1);
      fn = args.pop();
      (function stack(middleware){
        middleware.forEach(function(fn){
          if (Array.isArray(fn)) {
            stack(fn);
          } else {
            self[method](path, fn);
          }
        });
      })(args);
    }

    // Generate the route
    this.routes[method](path, fn);
    return this;
  };
  return arguments.callee;
})('get')('post')('put')('delete')('all');

// Alias delete as "del"

Server.prototype.del = Server.prototype.delete;
<|endoftext|>


<commit_before>define(function(require) {
    'use strict';

    var SecurityAccessLevelsComponent;
    var BaseComponent = require('oroui/js/app/components/base/component');
    var routing = require('routing');
    var _ = require('underscore');
    var $ = require('jquery');
    var mediator = require('oroui/js/mediator');
    require('jquery.select2');

    SecurityAccessLevelsComponent = BaseComponent.extend({
        element: null,

        defaultOptions: {
            accessLevelFieldSelector: '.access_level_value',
            accessLevelLinkSelector: '.access_level_value a',
            selectDivSelector: '.access_level_value_choice',
            linkDivSelector: 'access_level_value_link',
            accessLevelRoute: 'oro_security_access_levels',
            objectIdentityAttribute: 'data-identity',
            selectorNameAttribute: 'data-selector-name',
            selectorIdAttribute: 'data-selector-id',
            valueAttribute: 'data-value'
        },

        dataCache: {},

        options: {},

        initialize: function(options) {
            var self = this;
            this.options = _.extend({}, this.defaultOptions, options);
            this.element = options._sourceElement;
            this.element.find(this.options.accessLevelFieldSelector).each(function() {
                var $field = $(this);
                var $input = $field.find('input');
                var permissionName = $field.siblings('input').val();
                var oid = $field.attr(self.options.objectIdentityAttribute);
                var url = routing.generate(self.options.accessLevelRoute, {oid: oid.replace(/\\/g, '_')});
                $input.select2({
                    initSelection: function(element, callback) {
                        callback({id: $input.val(), text: $input.data('valueText')});
                    },
                    query: _.bind(self._select2Query, self, url),
                    minimumResultsForSearch: -1
                }).on('change.' + self.cid, function(e) {
                    mediator.trigger('securityAccessLevelsComponent:link:click', {
                        accessLevel: e.val,
                        identityId: oid,
                        permissionName: permissionName
                    });
                });
            });
        },

        _select2Query: function(url, query) {
            var self = this;
            if (url in this.dataCache) {
                query.callback({results: this.dataCache[url]});
            } else {
                $.ajax({
                    url: url,
                    success: function(data) {
                        var options = [];
                        _.each(_.omit(data, 'template_name'), function(val, key) {
                            options.push({id: key, text: val});
                        });
                        self.dataCache[url] = options;
                        query.callback({results: options});
                    }
                });
            }
        },

        /**
         * @inheritDoc
         */
        dispose: function() {
            if (this.disposed) {
                return;
            }

            if (this.element) {
                this.element.find(this.options.accessLevelFieldSelector).each(function() {
                    $(this).find('input').off('chenge.' + this.cid).select2('destroy');
                });
            }

            SecurityAccessLevelsComponent.__super__.dispose.call(this);
        }
    });

    return SecurityAccessLevelsComponent;
});
<commit_msg>BAP-9874: small fixes<commit_after>define(function(require) {
    'use strict';

    var SecurityAccessLevelsComponent;
    var BaseComponent = require('oroui/js/app/components/base/component');
    var routing = require('routing');
    var _ = require('underscore');
    var $ = require('jquery');
    var mediator = require('oroui/js/mediator');
    require('jquery.select2');

    SecurityAccessLevelsComponent = BaseComponent.extend({
        element: null,

        defaultOptions: {
            accessLevelFieldSelector: '.access_level_value',
            accessLevelLinkSelector: '.access_level_value a',
            selectDivSelector: '.access_level_value_choice',
            linkDivSelector: 'access_level_value_link',
            accessLevelRoute: 'oro_security_access_levels',
            objectIdentityAttribute: 'data-identity',
            selectorNameAttribute: 'data-selector-name',
            selectorIdAttribute: 'data-selector-id',
            valueAttribute: 'data-value'
        },

        dataCache: null,

        options: {},

        initialize: function(options) {
            var self = this;
            this.dataCache = {};
            this.options = _.extend({}, this.defaultOptions, options);
            this.element = options._sourceElement;
            this.element.find(this.options.accessLevelFieldSelector).each(function() {
                var $field = $(this);
                var $input = $field.find('input');
                var permissionName = $field.siblings('input').val();
                var oid = $field.attr(self.options.objectIdentityAttribute);
                var url = routing.generate(self.options.accessLevelRoute, {oid: oid.replace(/\\/g, '_')});
                $input.select2({
                    initSelection: function(element, callback) {
                        callback({id: $input.val(), text: $input.data('valueText')});
                    },
                    query: _.bind(self._select2Query, self, url),
                    minimumResultsForSearch: -1
                }).on('change.' + self.cid, function(e) {
                    mediator.trigger('securityAccessLevelsComponent:link:click', {
                        accessLevel: e.val,
                        identityId: oid,
                        permissionName: permissionName
                    });
                });
            });
        },

        _select2Query: function(url, query) {
            var self = this;
            if (url in this.dataCache) {
                query.callback({results: this.dataCache[url]});
            } else {
                $.ajax({
                    url: url,
                    success: function(data) {
                        var options = [];
                        _.each(_.omit(data, 'template_name'), function(val, key) {
                            options.push({id: key, text: val});
                        });
                        self.dataCache[url] = options;
                        query.callback({results: options});
                    }
                });
            }
        },

        /**
         * @inheritDoc
         */
        dispose: function() {
            if (this.disposed) {
                return;
            }

            if (this.element) {
                this.element.find(this.options.accessLevelFieldSelector).each(function() {
                    $(this).find('input').off('change.' + this.cid).select2('destroy');
                });
            }

            SecurityAccessLevelsComponent.__super__.dispose.call(this);
        }
    });

    return SecurityAccessLevelsComponent;
});
<|endoftext|>


<commit_before>var rbush = require('../rbush.js'),
    assert = require('assert');

describe('rbush', function () {
    var tree = new rbush();

    tree.load([[0, 0, 0, 0], [10, 10, 10, 10], [20, 20, 20, 20], [25, 0, 25, 0], [35, 10, 35, 10], [45, 20, 45, 20],
        [0, 25, 0, 25], [10, 35, 10, 35], [20, 45, 20, 45], [25, 25, 25, 25], [35, 35, 35, 35], [45, 45, 45, 45],
        [50, 0, 50, 0], [60, 10, 60, 10], [70, 20, 70, 20], [75, 0, 75, 0], [85, 10, 85, 10], [95, 20, 95, 20],
        [50, 25, 50, 25], [60, 35, 60, 35], [70, 45, 70, 45], [75, 25, 75, 25], [85, 35, 85, 35], [95, 45, 95, 45],
        [0, 50, 0, 50], [10, 60, 10, 60], [20, 70, 20, 70], [25, 50, 25, 50], [35, 60, 35, 60], [45, 70, 45, 70],
        [0, 75, 0, 75], [10, 85, 10, 85],  [20, 95, 20, 95], [25, 75, 25, 75], [35, 85, 35, 85], [45, 95, 45, 95],
        [50, 50, 50, 50], [60, 60, 60, 60], [70, 70, 70, 70], [75, 50, 75, 50], [85, 60, 85, 60], [95, 70, 95, 70],
        [50, 75, 50, 75], [60, 85, 60, 85], [70, 95, 70, 95], [75, 75, 75, 75], [85, 85, 85, 85], [95, 95, 95, 95]]);

    describe('search', function () {
        it('finds points given a bbox', function () {
            var result = tree.search([40, 20, 80, 70]);

            var sorted = [];
            for (var i = 0; i < result.length; i++) {
                sorted[i] = result[i][0] + ',' + result[i][1];
            }
            sorted.sort();

            assert.deepEqual(sorted,
                ['70,20', '75,25', '45,45', '50,50', '60,60', '70,70',
                 '45,20', '45,70', '75,50', '50,25', '60,35', '70,45'].sort());
        });
    });
});
<commit_msg>improve test<commit_after>var rbush = require('../rbush.js'),
    assert = require('assert');

describe('rbush', function () {

    var data = [[0, 0, 0, 0], [10, 10, 10, 10], [20, 20, 20, 20], [25, 0, 25, 0], [35, 10, 35, 10], [45, 20, 45, 20],
        [0, 25, 0, 25], [10, 35, 10, 35], [20, 45, 20, 45], [25, 25, 25, 25], [35, 35, 35, 35], [45, 45, 45, 45],
        [50, 0, 50, 0], [60, 10, 60, 10], [70, 20, 70, 20], [75, 0, 75, 0], [85, 10, 85, 10], [95, 20, 95, 20],
        [50, 25, 50, 25], [60, 35, 60, 35], [70, 45, 70, 45], [75, 25, 75, 25], [85, 35, 85, 35], [95, 45, 95, 45],
        [0, 50, 0, 50], [10, 60, 10, 60], [20, 70, 20, 70], [25, 50, 25, 50], [35, 60, 35, 60], [45, 70, 45, 70],
        [0, 75, 0, 75], [10, 85, 10, 85],  [20, 95, 20, 95], [25, 75, 25, 75], [35, 85, 35, 85], [45, 95, 45, 95],
        [50, 50, 50, 50], [60, 60, 60, 60], [70, 70, 70, 70], [75, 50, 75, 50], [85, 60, 85, 60], [95, 70, 95, 70],
        [50, 75, 50, 75], [60, 85, 60, 85], [70, 95, 70, 95], [75, 75, 75, 75], [85, 85, 85, 85], [95, 95, 95, 95]];

    var testTree = {
        "children": [{
            "children": [
                {"children": [[0, 0, 0, 0], [0, 25, 0, 25]], "leaf": true, "bbox": [0, 0, 0, 25]},
                {"children": [[10, 10, 10, 10], [10, 35, 10, 35]], "leaf": true, "bbox": [10, 10, 10, 35]},
                {"children": [[20, 20, 20, 20], [20, 45, 20, 45]], "leaf": true, "bbox": [20, 20, 20, 45]},
                {"children": [[25, 0, 25, 0], [25, 25, 25, 25]], "leaf": true, "bbox": [25, 0, 25, 25]},
                {"children": [[35, 10, 35, 10], [35, 35, 35, 35]], "leaf": true, "bbox": [35, 10, 35, 35]},
                {"children": [[45, 20, 45, 20], [45, 45, 45, 45]], "leaf": true, "bbox": [45, 20, 45, 45]}
            ],
            "bbox": [0, 0, 45, 45]
        }, {
            "children": [
                {"children": [[0, 50, 0, 50], [0, 75, 0, 75]], "leaf": true, "bbox": [0, 50, 0, 75]},
                {"children": [[10, 60, 10, 60], [10, 85, 10, 85]], "leaf": true, "bbox": [10, 60, 10, 85]},
                {"children": [[20, 70, 20, 70], [20, 95, 20, 95]], "leaf": true, "bbox": [20, 70, 20, 95]},
                {"children": [[25, 50, 25, 50], [25, 75, 25, 75]], "leaf": true, "bbox": [25, 50, 25, 75]},
                {"children": [[35, 60, 35, 60], [35, 85, 35, 85]], "leaf": true, "bbox": [35, 60, 35, 85]},
                {"children": [[45, 70, 45, 70], [45, 95, 45, 95]], "leaf": true, "bbox": [45, 70, 45, 95]}
            ],
            "bbox": [0, 50, 45, 95]
        }, {
            "children": [
                {"children": [[50, 0, 50, 0], [50, 25, 50, 25]], "leaf": true, "bbox": [50, 0, 50, 25]},
                {"children": [[60, 10, 60, 10], [60, 35, 60, 35]], "leaf": true, "bbox": [60, 10, 60, 35]},
                {"children": [[70, 20, 70, 20], [70, 45, 70, 45]], "leaf": true, "bbox": [70, 20, 70, 45]},
                {"children": [[75, 0, 75, 0], [75, 25, 75, 25]], "leaf": true, "bbox": [75, 0, 75, 25]},
                {"children": [[85, 10, 85, 10], [85, 35, 85, 35]], "leaf": true, "bbox": [85, 10, 85, 35]},
                {"children": [[95, 20, 95, 20], [95, 45, 95, 45]], "leaf": true, "bbox": [95, 20, 95, 45]}
            ],
            "bbox": [50, 0, 95, 45]
        }, {
            "children": [
                {"children": [[50, 75, 50, 75], [50, 50, 50, 50]], "leaf": true, "bbox": [50, 50, 50, 75]},
                {"children": [[60, 60, 60, 60], [60, 85, 60, 85]], "leaf": true, "bbox": [60, 60, 60, 85]},
                {"children": [[70, 95, 70, 95], [70, 70, 70, 70]], "leaf": true, "bbox": [70, 70, 70, 95]},
                {"children": [[75, 75, 75, 75], [75, 50, 75, 50]], "leaf": true, "bbox": [75, 50, 75, 75]},
                {"children": [[85, 85, 85, 85], [85, 60, 85, 60]], "leaf": true, "bbox": [85, 60, 85, 85]},
                {"children": [[95, 70, 95, 70], [95, 95, 95, 95]], "leaf": true, "bbox": [95, 70, 95, 95]}
            ],
            "bbox": [50, 50, 95, 95]
        }],
        "bbox": [0, 0, 95, 95]
    };

    describe('load', function () {
        it('bulk-loads the given data and forms a balanced search tree', function () {
            var tree = rbush().load(data);

            assert.deepEqual(tree.data, testTree);
        });
    });

    describe('search', function () {
        it('finds points given a bbox', function () {
            var tree = rbush().load(data);

            var result = tree.search([40, 20, 80, 70]);

            var sorted = [];
            for (var i = 0; i < result.length; i++) {
                sorted[i] = result[i][0] + ',' + result[i][1];
            }
            sorted.sort();

            assert.deepEqual(sorted,
                ['70,20', '75,25', '45,45', '50,50', '60,60', '70,70',
                 '45,20', '45,70', '75,50', '50,25', '60,35', '70,45'].sort());
        });
    });
});
<|endoftext|>


<commit_before>'use strict';

var TypeIndex = require('./type-index');

var walkers = exports;

walkers.topScan = function (node, nodeIndex, parent, opts) {
  if (parent) {
    // We would like to avoid spinning an extra loop through the starting
    // node's siblings just to count its typeIndex.
    throw Error('topScan is supposed to be called from the root node');
  }

  if (!opts.typeIndex) {
    opts.iterator(node, nodeIndex, parent);
  }
  walkers.descendant.apply(this, arguments);
};

walkers.descendant = function (node, nodeIndex, parent, opts) {
  if (!node.children || !node.children.length) {
    return;
  }

  if (opts.typeIndex) {
    var typeIndex = TypeIndex();
  }

  node.children.forEach(function (child, childIndex) {
    opts.iterator(child, childIndex, node,
                  opts.typeIndex ? { typeIndex: typeIndex(child) } : undefined);
    walkers.descendant(child, childIndex, node, opts);
  });
};

walkers.child = function (node, nodeIndex, parent, opts) {
  if (!node.children || !node.children.length) {
    return;
  }

  if (opts.typeIndex) {
    var typeIndex = TypeIndex();
  }

  node.children.forEach(function (child, childIndex) {
    opts.iterator(child, childIndex, node,
                  opts.typeIndex ? { typeIndex: typeIndex(child) } : undefined);
  });
};

walkers.adjacentSibling = function (node, nodeIndex, parent, opts) {
  if (!parent) {
    return;
  }

  if (opts.typeIndex) {
    var typeIndex = TypeIndex();

    // Prefill type indexes with preceding nodes.
    for (var prevIndex = 0; prevIndex <= nodeIndex; ++prevIndex) {
      typeIndex(parent.children[prevIndex]);
    }
  }

  if (++nodeIndex < parent.children.length) {
    node = parent.children[nodeIndex];
    opts.iterator(node, nodeIndex, parent,
                  opts.typeIndex ? { typeIndex: typeIndex(node) } : undefined);
  }
};

walkers.generalSibling = function (node, nodeIndex, parent, opts) {
  if (!parent) {
    return;
  }

  if (opts.typeIndex) {
    var typeIndex = TypeIndex();

    // Prefill type indexes with preceding nodes.
    for (var prevIndex = 0; prevIndex <= nodeIndex; ++prevIndex) {
      typeIndex(parent.children[prevIndex]);
    }
  }

  while (++nodeIndex < parent.children.length) {
    node = parent.children[nodeIndex];
    opts.iterator(node, nodeIndex, parent,
                  opts.typeIndex ? { typeIndex: typeIndex(node) } : undefined);
  }
};
<commit_msg>ast-walkers: add comment explaining searchOpts<commit_after>'use strict';

var TypeIndex = require('./type-index');

var walkers = exports;

// All walkers accept `opts` arguments (occasionally referred to as
// `searchOpts`) which is an object with the following fields:
//
//   - iterator: function(node, nodeIndex, parent, [props]))
//         function running once for each node being walked over, in order
//
//   - [typeIndex]: boolean=false
//         if true, `props` will have an integer `typeIndex` field which
//         represents a node index among all its sibling of the same type
//

walkers.topScan = function (node, nodeIndex, parent, opts) {
  if (parent) {
    // We would like to avoid spinning an extra loop through the starting
    // node's siblings just to count its typeIndex.
    throw Error('topScan is supposed to be called from the root node');
  }

  if (!opts.typeIndex) {
    opts.iterator(node, nodeIndex, parent);
  }
  walkers.descendant.apply(this, arguments);
};

walkers.descendant = function (node, nodeIndex, parent, opts) {
  if (!node.children || !node.children.length) {
    return;
  }

  if (opts.typeIndex) {
    var typeIndex = TypeIndex();
  }

  node.children.forEach(function (child, childIndex) {
    opts.iterator(child, childIndex, node,
                  opts.typeIndex ? { typeIndex: typeIndex(child) } : undefined);
    walkers.descendant(child, childIndex, node, opts);
  });
};

walkers.child = function (node, nodeIndex, parent, opts) {
  if (!node.children || !node.children.length) {
    return;
  }

  if (opts.typeIndex) {
    var typeIndex = TypeIndex();
  }

  node.children.forEach(function (child, childIndex) {
    opts.iterator(child, childIndex, node,
                  opts.typeIndex ? { typeIndex: typeIndex(child) } : undefined);
  });
};

walkers.adjacentSibling = function (node, nodeIndex, parent, opts) {
  if (!parent) {
    return;
  }

  if (opts.typeIndex) {
    var typeIndex = TypeIndex();

    // Prefill type indexes with preceding nodes.
    for (var prevIndex = 0; prevIndex <= nodeIndex; ++prevIndex) {
      typeIndex(parent.children[prevIndex]);
    }
  }

  if (++nodeIndex < parent.children.length) {
    node = parent.children[nodeIndex];
    opts.iterator(node, nodeIndex, parent,
                  opts.typeIndex ? { typeIndex: typeIndex(node) } : undefined);
  }
};

walkers.generalSibling = function (node, nodeIndex, parent, opts) {
  if (!parent) {
    return;
  }

  if (opts.typeIndex) {
    var typeIndex = TypeIndex();

    // Prefill type indexes with preceding nodes.
    for (var prevIndex = 0; prevIndex <= nodeIndex; ++prevIndex) {
      typeIndex(parent.children[prevIndex]);
    }
  }

  while (++nodeIndex < parent.children.length) {
    node = parent.children[nodeIndex];
    opts.iterator(node, nodeIndex, parent,
                  opts.typeIndex ? { typeIndex: typeIndex(node) } : undefined);
  }
};
<|endoftext|>


<commit_before>var should = require('should');
var sinon = require('sinon');
var Influx = require('../');

describe('Influx', function() {
  var store;
  afterEach(function() {
    store.destroy();
  });
  it('has no default state', function() {
    store = Influx.Store();
    should(store).have.property('state');
    should(store.state).not.be.ok;
  });
  it('has no default handlers', function() {
    store = Influx.Store();
    should(store).have.property('handlers');
    should(store.handlers).eql({});
  });
  it('has no default callbacks', function() {
    store = Influx.Store();
    should(store).have.property('callbacks');
    should(store.callbacks.length).equal(0);
  });
  it('accepts and returns state', function() {
    store = Influx.Store({foo: 'bar'});
    should(store.state).be.ok;
    should(store.state.foo).equal('bar');
    should(store.currentState()).eql({foo: 'bar'});
  });
  it('stores handle actions and callbacks', function() {
    store = Influx.Store({foo: 'bar'});
    var fooHandler = sinon.spy();
    var callback = sinon.spy();
    store.registerHandler('fooAction', fooHandler);
    store.registerCallback(callback);
    Influx.Action('fooAction');
    should(fooHandler.called).be.true;
    should(callback.called).be.true;
  });
  it('callbacks and handlers are bound to the store context', function() {
    store = Influx.Store({foo: 'bar'});
    var fooHandler = function() {
      should(this).eql(store);
    };
    var callback = function() {
      should(this).eql(store);
    };
    store.registerHandler('fooAction', fooHandler);
    store.registerCallback(callback);
    Influx.Action('fooAction');
  });
  it('registerCallback is chainable', function() {
    store = Influx.Store({foo: 'bar'});
    var fooHandler1 = sinon.spy();
    var fooHandler2 = sinon.spy();
    store.registerHandler('fooAction1', fooHandler1)
      .registerHandler('fooAction2', fooHandler2);
    Influx.Action('fooAction1');
    Influx.Action('fooAction2');
    should(fooHandler1.called).be.true;
    should(fooHandler2.called).be.true;
  });
  it('emits a change event', function() {
    store = Influx.Store({foo: 'bar'});
    var eventListener = sinon.spy();
    store.on(Influx.change, eventListener)
    var fooHandler = sinon.spy();
    store.registerHandler('fooAction', fooHandler);
    Influx.Action('fooAction');
    should(eventListener.called).be.true;
  });
  it('change events emitted only once', function() {
    store = Influx.Store({foo: 'bar'});
    var eventListener = sinon.spy();
    store.on(Influx.change, eventListener)
    var handler1 = sinon.spy();
    var handler2 = sinon.spy();
    var handler3 = sinon.spy();
    store.registerHandler('handled', [handler1, handler2, handler3])
    Influx.Action('handled');
    should(eventListener.called).be.true;
    should(eventListener.calledOnce).be.true;
  });
});
<commit_msg>remove old name from tests<commit_after>var should = require('should');
var sinon = require('sinon');
var Miniflux = require('../');

describe('Miniflux', function() {
  var store;
  afterEach(function() {
    store.destroy();
  });
  it('has no default state', function() {
    store = Miniflux.Store();
    should(store).have.property('state');
    should(store.state).not.be.ok;
  });
  it('has no default handlers', function() {
    store = Miniflux.Store();
    should(store).have.property('handlers');
    should(store.handlers).eql({});
  });
  it('has no default callbacks', function() {
    store = Miniflux.Store();
    should(store).have.property('callbacks');
    should(store.callbacks.length).equal(0);
  });
  it('accepts and returns state', function() {
    store = Miniflux.Store({foo: 'bar'});
    should(store.state).be.ok;
    should(store.state.foo).equal('bar');
    should(store.currentState()).eql({foo: 'bar'});
  });
  it('stores handle actions and callbacks', function() {
    store = Miniflux.Store({foo: 'bar'});
    var fooHandler = sinon.spy();
    var callback = sinon.spy();
    store.registerHandler('fooAction', fooHandler);
    store.registerCallback(callback);
    Miniflux.Action('fooAction');
    should(fooHandler.called).be.true;
    should(callback.called).be.true;
  });
  it('callbacks and handlers are bound to the store context', function() {
    store = Miniflux.Store({foo: 'bar'});
    var fooHandler = function() {
      should(this).eql(store);
    };
    var callback = function() {
      should(this).eql(store);
    };
    store.registerHandler('fooAction', fooHandler);
    store.registerCallback(callback);
    Miniflux.Action('fooAction');
  });
  it('registerCallback is chainable', function() {
    store = Miniflux.Store({foo: 'bar'});
    var fooHandler1 = sinon.spy();
    var fooHandler2 = sinon.spy();
    store.registerHandler('fooAction1', fooHandler1)
      .registerHandler('fooAction2', fooHandler2);
    Miniflux.Action('fooAction1');
    Miniflux.Action('fooAction2');
    should(fooHandler1.called).be.true;
    should(fooHandler2.called).be.true;
  });
  it('emits a change event', function() {
    store = Miniflux.Store({foo: 'bar'});
    var eventListener = sinon.spy();
    store.on(Miniflux.change, eventListener)
    var fooHandler = sinon.spy();
    store.registerHandler('fooAction', fooHandler);
    Miniflux.Action('fooAction');
    should(eventListener.called).be.true;
  });
  it('change events emitted only once', function() {
    store = Miniflux.Store({foo: 'bar'});
    var eventListener = sinon.spy();
    store.on(Miniflux.change, eventListener)
    var handler1 = sinon.spy();
    var handler2 = sinon.spy();
    var handler3 = sinon.spy();
    store.registerHandler('handled', [handler1, handler2, handler3])
    Miniflux.Action('handled');
    should(eventListener.called).be.true;
    should(eventListener.calledOnce).be.true;
  });
});
<|endoftext|>