<commit_before>var assert = require('assert');
var whosit = require('../lib');

describe('Western Order', function() {
    it('Shawn', function() {
        var name = whosit.parse('Shawn');
        assert.equal(name.first, 'Shawn');
    });

    it('Shawn Miller', function() {
        var name = whosit.parse('Shawn Miller');
        assert.equal(name.first, 'Shawn');
        assert.equal(name.last, 'Miller');
    });

    it('Shawn Michael Miller', function() {
        var name = whosit.parse('Shawn Michael Miller');
        assert.equal(name.first, 'Shawn');
        assert.equal(name.middle, 'Michael');
        assert.equal(name.last, 'Miller');
    });

    it('Mr. Shawn Michael Miller', function() {
        var name = whosit.parse('Mr. Shawn Michael Miller');
        assert.equal(name.salutation, 'Mr.');
        assert.equal(name.first, 'Shawn');
        assert.equal(name.middle, 'Michael');
        assert.equal(name.last, 'Miller');
    });

    it('Shawn Michael Miller Sr', function() {
        var name = whosit.parse('Shawn Michael Miller Sr');
        assert.equal(name.first, 'Shawn');
        assert.equal(name.middle, 'Michael');
        assert.equal(name.last, 'Miller');
        assert.equal(name.suffix, 'Sr');
    });

    it('Mr. Shawn Michael Miller Sr.', function() {
        var name = whosit.parse('Mr. Shawn Michael Miller Sr.');
        assert.equal(name.salutation, 'Mr.');
        assert.equal(name.first, 'Shawn');
        assert.equal(name.middle, 'Michael');
        assert.equal(name.last, 'Miller');
        assert.equal(name.suffix, 'Sr.');
    });

    it('Mister Rogers', function() {
        var name = whosit.parse('Mister Rogers');
        assert.equal(name.salutation, 'Mister');
        assert.equal(name.last, 'Rogers');
    });

    it('Doctor Who', function() {
        var name = whosit.parse('Doctor Who');
        assert.equal(name.salutation, 'Doctor');
        assert.equal(name.last, 'Who');
    });

    it('Dr. Dre', function() {
        var name = whosit.parse('Dr. Dre');
        assert.equal(name.salutation, 'Dr.');
        assert.equal(name.last, 'Dre');
    });

    it('Prof. Dre', function() {
        var name = whosit.parse('Prof. Plum');
        assert.equal(name.salutation, 'Prof.');
        assert.equal(name.last, 'Plum');
    });

    it('Professor Plum', function() {
        var name = whosit.parse('Professor Plum');
        assert.equal(name.salutation, 'Professor');
        assert.equal(name.last, 'Plum');
    });
});

// http://en.wikipedia.org/wiki/Personal_name#Lexical_order
// http://en.wikipedia.org/wiki/Surname#Order_of_names
// https://github.com/freshlogic/whosit/pull/1
describe('Lexical Order', function() {
    it('Miller,Shawn', function() {
        var name = whosit.parse('Miller,Shawn');
        assert.equal(name.first, 'Shawn');
        assert.equal(name.last, 'Miller');
    });

    it('Miller, Shawn', function() {
        var name = whosit.parse('Miller, Shawn');
        assert.equal(name.first, 'Shawn');
        assert.equal(name.last, 'Miller');
    });

    it('Miller, Shawn, Prof.', function() {
        var name = whosit.parse('Miller, Shawn, Prof.');
        assert.equal(name.salutation, 'Prof.');
        assert.equal(name.first, 'Shawn');
        assert.equal(name.last, 'Miller');
    });

    it('Miller,Shawn Michael', function() {
        var name = whosit.parse('Miller,Shawn Michael');
        assert.equal(name.first, 'Shawn');
        assert.equal(name.middle, 'Michael');
        assert.equal(name.last, 'Miller');
    });

    it('Miller, Shawn Michael', function() {
        var name = whosit.parse('Miller, Shawn Michael');
        assert.equal(name.first, 'Shawn');
        assert.equal(name.middle, 'Michael');
        assert.equal(name.last, 'Miller');
    });

    it('Miller, Shawn Michael, Prof.', function() {
        var name = whosit.parse('Miller, Shawn Michael, Prof.');
        assert.equal(name.salutation, 'Prof.');
        assert.equal(name.first, 'Shawn');
        assert.equal(name.middle, 'Michael');
        assert.equal(name.last, 'Miller');
    });
});
<commit_msg>Added test case for better whitespace handling<commit_after>var assert = require('assert');
var whosit = require('../lib');

describe('Western Order', function() {
    it('Shawn', function() {
        var name = whosit.parse('Shawn');
        assert.equal(name.first, 'Shawn');
    });

    it('Shawn Miller', function() {
        var name = whosit.parse('Shawn Miller');
        assert.equal(name.first, 'Shawn');
        assert.equal(name.last, 'Miller');
    });

    it(' Shawn  Miller ', function() {
        var name = whosit.parse(' Shawn  Miller ');
        assert.equal(name.first, 'Shawn');
        assert.equal(name.last, 'Miller');
    });

    it('Shawn Michael Miller', function() {
        var name = whosit.parse('Shawn Michael Miller');
        assert.equal(name.first, 'Shawn');
        assert.equal(name.middle, 'Michael');
        assert.equal(name.last, 'Miller');
    });

    it('Mr. Shawn Michael Miller', function() {
        var name = whosit.parse('Mr. Shawn Michael Miller');
        assert.equal(name.salutation, 'Mr.');
        assert.equal(name.first, 'Shawn');
        assert.equal(name.middle, 'Michael');
        assert.equal(name.last, 'Miller');
    });

    it('Shawn Michael Miller Sr', function() {
        var name = whosit.parse('Shawn Michael Miller Sr');
        assert.equal(name.first, 'Shawn');
        assert.equal(name.middle, 'Michael');
        assert.equal(name.last, 'Miller');
        assert.equal(name.suffix, 'Sr');
    });

    it('Mr. Shawn Michael Miller Sr.', function() {
        var name = whosit.parse('Mr. Shawn Michael Miller Sr.');
        assert.equal(name.salutation, 'Mr.');
        assert.equal(name.first, 'Shawn');
        assert.equal(name.middle, 'Michael');
        assert.equal(name.last, 'Miller');
        assert.equal(name.suffix, 'Sr.');
    });

    it('Mister Rogers', function() {
        var name = whosit.parse('Mister Rogers');
        assert.equal(name.salutation, 'Mister');
        assert.equal(name.last, 'Rogers');
    });

    it('Doctor Who', function() {
        var name = whosit.parse('Doctor Who');
        assert.equal(name.salutation, 'Doctor');
        assert.equal(name.last, 'Who');
    });

    it('Dr. Dre', function() {
        var name = whosit.parse('Dr. Dre');
        assert.equal(name.salutation, 'Dr.');
        assert.equal(name.last, 'Dre');
    });

    it('Prof. Dre', function() {
        var name = whosit.parse('Prof. Plum');
        assert.equal(name.salutation, 'Prof.');
        assert.equal(name.last, 'Plum');
    });

    it('Professor Plum', function() {
        var name = whosit.parse('Professor Plum');
        assert.equal(name.salutation, 'Professor');
        assert.equal(name.last, 'Plum');
    });
});

// http://en.wikipedia.org/wiki/Personal_name#Lexical_order
// http://en.wikipedia.org/wiki/Surname#Order_of_names
// https://github.com/freshlogic/whosit/pull/1
describe('Lexical Order', function() {
    it('Miller,Shawn', function() {
        var name = whosit.parse('Miller,Shawn');
        assert.equal(name.first, 'Shawn');
        assert.equal(name.last, 'Miller');
    });

    it('Miller, Shawn', function() {
        var name = whosit.parse('Miller, Shawn');
        assert.equal(name.first, 'Shawn');
        assert.equal(name.last, 'Miller');
    });

    it('Miller, Shawn, Prof.', function() {
        var name = whosit.parse('Miller, Shawn, Prof.');
        assert.equal(name.salutation, 'Prof.');
        assert.equal(name.first, 'Shawn');
        assert.equal(name.last, 'Miller');
    });

    it('Miller,Shawn Michael', function() {
        var name = whosit.parse('Miller,Shawn Michael');
        assert.equal(name.first, 'Shawn');
        assert.equal(name.middle, 'Michael');
        assert.equal(name.last, 'Miller');
    });

    it('Miller, Shawn Michael', function() {
        var name = whosit.parse('Miller, Shawn Michael');
        assert.equal(name.first, 'Shawn');
        assert.equal(name.middle, 'Michael');
        assert.equal(name.last, 'Miller');
    });

    it('Miller, Shawn Michael, Prof.', function() {
        var name = whosit.parse('Miller, Shawn Michael, Prof.');
        assert.equal(name.salutation, 'Prof.');
        assert.equal(name.first, 'Shawn');
        assert.equal(name.middle, 'Michael');
        assert.equal(name.last, 'Miller');
    });
});
<|endoftext|>


<commit_before>/* =========================================================================
 *
 * Tests
 *      Runs a variety of tests for the logging system
 *
 * ========================================================================= */
var mocha = require('mocha');
var should = require('chai').should();
var _ = require('lodash');
var request = require('request');
var chai = require('chai');
var assert = chai.assert;

// Our library
var logger = require('../lib/bragi');

// we need to capture log output
var logs = [];
var origLog = console.log;

console.log = function logOverride(msg) {
    logs.push([].slice.call(arguments));
    //// to hide all logs:
    //origLog.apply(console.log, arguments);
};
// --------------------------------------
//
// Logging Tests
//
// --------------------------------------
describe('Bragi: Javascript Logger', function(){

    // ----------------------------------
    //
    // Reset logs, logLevel, and history before *each* test
    //
    // ----------------------------------
    beforeEach(function(){
        logs = [];
        logger.options.logLevel = true;
        logger.history = {};
    });

    // ----------------------------------
    // Basic logging tests
    // ----------------------------------
    describe('log() by group', function(){

        describe('log everything', function(){
            it('should log everything', function(){
                logger.options.logLevel = true;
                logger.log('group1', 'hello');
                logs.length.should.equal(1);
            });

            it('should log everything', function(){
                logger.options.logLevel = true;
                logger.log('group1', 'hello');
                logger.log('group2', 'hello');
                logger.log('group3', 'hello');
                logs.length.should.equal(3);
            });
        });

        describe('log by groups', function(){
            it('should only log one group', function(){
                logger.options.logLevel = ['group1'];
                logger.log('group1', 'logged');

                logger.log('some-group-group1', 'not logged');
                logger.log('group2', 'not logged');
                logs.length.should.equal(1);
            });

            it('should log multiple groups', function(){
                logger.options.logLevel = ['group1', 'group2'];
                logger.log('group1', 'logged');
                logger.log('group2', 'logged');

                logger.log('group3', 'not logged');
                logs.length.should.equal(2);
            });

            it('should log subgroups', function(){
                logger.options.logLevel = ['group1:subgroup1'];
                logger.log('group1:subgroup1', 'logged');

                logger.log('group1:subgroup2', 'not logged');
                logs.length.should.equal(1);
            });

            it('should log subgroups and their subgroups', function(){
                logger.options.logLevel = ['group1:subgroup1'];
                logger.log('group1:subgroup1', 'logged');
                logger.log('group1:subgroup1:subgroup2', 'logged');

                logger.log('group1:subgroup2', 'not logged');
                logger.log('blabla:group1:subgroup1', 'not logged');
                logs.length.should.equal(2);
            });

            it('should log deep subgroups', function(){
                logger.options.logLevel = ['group1:subgroup1:subgroup2:subgroup3'];
                logger.log('group1:subgroup1:subgroup2:subgroup3', 'logged');
                logger.log('group1:subgroup1:subgroup2:subgroup3:subgroup4', 'logged');

                logger.log('group1', 'NOT logged');
                logger.log('group1:subgroup1', 'NOT logged');
                logger.log('group1:subgroup1:subgroup3:subgroup3:subgroup4', 'NOT logged');
                logger.log('group1:subgroup2', 'not logged');
                logger.log('blabla:group1:subgroup1', 'not logged');
                logs.length.should.equal(2);
            });

            describe('regular expressions', function(){
                it('should test for /group1/', function(){
                    logger.options.logLevel = [/group1/];
                    logger.log('group1:subgroup1:subgroup2:subgroup3', 'logged');
                    logger.log('group1:subgroup1:subgroup2:subgroup3:subgroup4', 'logged');
                    logger.log('group1', 'logged');
                    logger.log('group1:subgroup1', 'logged');
                    logger.log('group1:subgroup1:subgroup3:subgroup3:subgroup4', 'logged');
                    logger.log('group1:subgroup2', 'logged');
                    // NOTE: This is a regex, so "subgroup1" WILL match (because
                    // group1 is found in the string)
                    logger.log('blabla:group2:subgroup1', 'logged');

                    logger.log('bbla:nomatch', 'not logged');
                    logger.log('group2', 'not logged');

                    logs.length.should.equal(7);
                });

                it('should test for /^group1/ (match at start of string)', function(){
                    logger.options.logLevel = [/^group1/];
                    logger.log('group1:subgroup1:subgroup2:subgroup3', 'logged');
                    logger.log('group1:subgroup1:subgroup2:subgroup3:subgroup4', 'logged');
                    logger.log('group1', 'logged');

                    logger.log('group2:group1', 'not logged');
                    logger.log('blabla:group2:subgroup1', 'not logged');
                    logger.log('bbla:nomatch', 'not logged');

                    logs.length.should.equal(3);
                });

                it('should test for /.*subgroup1/ (match anything that contains subgroup1)', function(){
                    logger.options.logLevel = [/.*subgroup1/];
                    logger.log('group1:subgroup1:subgroup2:subgroup3', 'logged');
                    logger.log('group1:subgroup1:subgroup2:subgroup3:subgroup4', 'logged');
                    logger.log('blabla:innerbla:subgroup1', 'logged');
                    logger.log('blabla:group2:subgroup1', 'logged');

                    logger.log('group1', 'not logged');
                    logger.log('group2:group1', 'not logged');
                    logger.log('bbla:nomatch', 'not logged');

                    logs.length.should.equal(4);
                });
            });
        });
    });

    // ----------------------------------
    // Util
    // ----------------------------------
    describe('Util tests', function(){

        describe('print() function', function(){
            it('should return string with right colors', function(){
                var string = logger.util.print('Test', 'red');
                assert(string.indexOf(logger.util.colors.red) === 0);
                assert(string.indexOf(logger.util.colors.reset) !== -1);
            });
        });

        describe('Symbols', function(){
            it('should return some symbols', function(){
                assert(logger.util.symbols.success.indexOf('✔') !== -1);
            });
        });
    });

    // ----------------------------------
    // History Tests
    // ----------------------------------
    describe('History tests', function(){
        it('should log some group and story history', function(){
            logger.options.logLevel = true;

            logger.log('h1', 'hello');
            assert(logger.history.h1.length === 1);
        });

        it('should log some group and story history for multiple groups', function(){
            logger.options.logLevel = true;

            logger.log('h2', 'hello');
            assert(logger.history.h2.length === 1);

            logger.log('h2', 'hello again');
            assert(logger.history.h2.length === 2);

            logger.log('h3', 'hello again');
            assert(logger.history.h3.length === 1);
            assert(logger.history.h2.length === 2);

            logger.log('h4', 'hello there');
            logger.log('h4', 'oh hi');
            assert(logger.history.h2.length === 2);
            assert(logger.history.h3.length === 1);
            assert(logger.history.h4.length === 2);
        });

        it('should not add logs to history if log level is not in logLevel array', function(){
            logger.options.logLevel = ['h1only'];

            logger.log('h1only', 'this is logged in history');
            // won't get added to history since it's not logged
            logger.log('h2only', 'this is not logged');

            assert(logger.history.h1only.length === 1);
            assert(logger.history.h2only === undefined);
        });

        it('should add everything to history if storeAllHistory is true', function(){
            logger.options.storeAllHistory = true;
            logger.options.logLevel = ['h1only'];

            logger.log('h1only', 'this is logged in history');
            logger.log('h2only', 'this is also logged in history, but NOT logged to console');
            logger.log('h3only', 'this is also logged in history, but NOT logged to console');

            assert(logs.length === 1);
            assert(logger.history.h1only.length === 1);
            assert(logger.history.h2only.length === 1);
            assert(logger.history.h3only.length === 1);
            assert(logger.history.blabla === undefined);
        });

    });

    // ----------------------------------
    //
    // Reset the console log functionality when done
    //
    // ----------------------------------
    after(function(){
        console.log = origLog;
    });
});
<commit_msg>removes unnecessary dependencies<commit_after>/* =========================================================================
 *
 * Tests
 *      Runs a variety of tests for the logging system
 *
 * ========================================================================= */
var mocha = require('mocha');
var should = require('chai').should();
var chai = require('chai');
var assert = chai.assert;

// Our library
var logger = require('../lib/bragi');

// we need to capture log output
var logs = [];
var origLog = console.log;

console.log = function logOverride(msg) {
    logs.push([].slice.call(arguments));
    //// to hide all logs:
    //origLog.apply(console.log, arguments);
};
// --------------------------------------
//
// Logging Tests
//
// --------------------------------------
describe('Bragi: Javascript Logger', function(){

    // ----------------------------------
    //
    // Reset logs, logLevel, and history before *each* test
    //
    // ----------------------------------
    beforeEach(function(){
        logs = [];
        logger.options.logLevel = true;
        logger.history = {};
    });

    // ----------------------------------
    // Basic logging tests
    // ----------------------------------
    describe('log() by group', function(){

        describe('log everything', function(){
            it('should log everything', function(){
                logger.options.logLevel = true;
                logger.log('group1', 'hello');
                logs.length.should.equal(1);
            });

            it('should log everything', function(){
                logger.options.logLevel = true;
                logger.log('group1', 'hello');
                logger.log('group2', 'hello');
                logger.log('group3', 'hello');
                logs.length.should.equal(3);
            });
        });

        describe('log by groups', function(){
            it('should only log one group', function(){
                logger.options.logLevel = ['group1'];
                logger.log('group1', 'logged');

                logger.log('some-group-group1', 'not logged');
                logger.log('group2', 'not logged');
                logs.length.should.equal(1);
            });

            it('should log multiple groups', function(){
                logger.options.logLevel = ['group1', 'group2'];
                logger.log('group1', 'logged');
                logger.log('group2', 'logged');

                logger.log('group3', 'not logged');
                logs.length.should.equal(2);
            });

            it('should log subgroups', function(){
                logger.options.logLevel = ['group1:subgroup1'];
                logger.log('group1:subgroup1', 'logged');

                logger.log('group1:subgroup2', 'not logged');
                logs.length.should.equal(1);
            });

            it('should log subgroups and their subgroups', function(){
                logger.options.logLevel = ['group1:subgroup1'];
                logger.log('group1:subgroup1', 'logged');
                logger.log('group1:subgroup1:subgroup2', 'logged');

                logger.log('group1:subgroup2', 'not logged');
                logger.log('blabla:group1:subgroup1', 'not logged');
                logs.length.should.equal(2);
            });

            it('should log deep subgroups', function(){
                logger.options.logLevel = ['group1:subgroup1:subgroup2:subgroup3'];
                logger.log('group1:subgroup1:subgroup2:subgroup3', 'logged');
                logger.log('group1:subgroup1:subgroup2:subgroup3:subgroup4', 'logged');

                logger.log('group1', 'NOT logged');
                logger.log('group1:subgroup1', 'NOT logged');
                logger.log('group1:subgroup1:subgroup3:subgroup3:subgroup4', 'NOT logged');
                logger.log('group1:subgroup2', 'not logged');
                logger.log('blabla:group1:subgroup1', 'not logged');
                logs.length.should.equal(2);
            });

            describe('regular expressions', function(){
                it('should test for /group1/', function(){
                    logger.options.logLevel = [/group1/];
                    logger.log('group1:subgroup1:subgroup2:subgroup3', 'logged');
                    logger.log('group1:subgroup1:subgroup2:subgroup3:subgroup4', 'logged');
                    logger.log('group1', 'logged');
                    logger.log('group1:subgroup1', 'logged');
                    logger.log('group1:subgroup1:subgroup3:subgroup3:subgroup4', 'logged');
                    logger.log('group1:subgroup2', 'logged');
                    // NOTE: This is a regex, so "subgroup1" WILL match (because
                    // group1 is found in the string)
                    logger.log('blabla:group2:subgroup1', 'logged');

                    logger.log('bbla:nomatch', 'not logged');
                    logger.log('group2', 'not logged');

                    logs.length.should.equal(7);
                });

                it('should test for /^group1/ (match at start of string)', function(){
                    logger.options.logLevel = [/^group1/];
                    logger.log('group1:subgroup1:subgroup2:subgroup3', 'logged');
                    logger.log('group1:subgroup1:subgroup2:subgroup3:subgroup4', 'logged');
                    logger.log('group1', 'logged');

                    logger.log('group2:group1', 'not logged');
                    logger.log('blabla:group2:subgroup1', 'not logged');
                    logger.log('bbla:nomatch', 'not logged');

                    logs.length.should.equal(3);
                });

                it('should test for /.*subgroup1/ (match anything that contains subgroup1)', function(){
                    logger.options.logLevel = [/.*subgroup1/];
                    logger.log('group1:subgroup1:subgroup2:subgroup3', 'logged');
                    logger.log('group1:subgroup1:subgroup2:subgroup3:subgroup4', 'logged');
                    logger.log('blabla:innerbla:subgroup1', 'logged');
                    logger.log('blabla:group2:subgroup1', 'logged');

                    logger.log('group1', 'not logged');
                    logger.log('group2:group1', 'not logged');
                    logger.log('bbla:nomatch', 'not logged');

                    logs.length.should.equal(4);
                });
            });
        });
    });

    // ----------------------------------
    // Util
    // ----------------------------------
    describe('Util tests', function(){

        describe('print() function', function(){
            it('should return string with right colors', function(){
                var string = logger.util.print('Test', 'red');
                assert(string.indexOf(logger.util.colors.red) === 0);
                assert(string.indexOf(logger.util.colors.reset) !== -1);
            });
        });

        describe('Symbols', function(){
            it('should return some symbols', function(){
                assert(logger.util.symbols.success.indexOf('✔') !== -1);
            });
        });
    });

    // ----------------------------------
    // History Tests
    // ----------------------------------
    describe('History tests', function(){
        it('should log some group and story history', function(){
            logger.options.logLevel = true;

            logger.log('h1', 'hello');
            assert(logger.history.h1.length === 1);
        });

        it('should log some group and story history for multiple groups', function(){
            logger.options.logLevel = true;

            logger.log('h2', 'hello');
            assert(logger.history.h2.length === 1);

            logger.log('h2', 'hello again');
            assert(logger.history.h2.length === 2);

            logger.log('h3', 'hello again');
            assert(logger.history.h3.length === 1);
            assert(logger.history.h2.length === 2);

            logger.log('h4', 'hello there');
            logger.log('h4', 'oh hi');
            assert(logger.history.h2.length === 2);
            assert(logger.history.h3.length === 1);
            assert(logger.history.h4.length === 2);
        });

        it('should not add logs to history if log level is not in logLevel array', function(){
            logger.options.logLevel = ['h1only'];

            logger.log('h1only', 'this is logged in history');
            // won't get added to history since it's not logged
            logger.log('h2only', 'this is not logged');

            assert(logger.history.h1only.length === 1);
            assert(logger.history.h2only === undefined);
        });

        it('should add everything to history if storeAllHistory is true', function(){
            logger.options.storeAllHistory = true;
            logger.options.logLevel = ['h1only'];

            logger.log('h1only', 'this is logged in history');
            logger.log('h2only', 'this is also logged in history, but NOT logged to console');
            logger.log('h3only', 'this is also logged in history, but NOT logged to console');

            assert(logs.length === 1);
            assert(logger.history.h1only.length === 1);
            assert(logger.history.h2only.length === 1);
            assert(logger.history.h3only.length === 1);
            assert(logger.history.blabla === undefined);
        });

    });

    // ----------------------------------
    //
    // Reset the console log functionality when done
    //
    // ----------------------------------
    after(function(){
        console.log = origLog;
    });
});
<|endoftext|>


<commit_before>'use strict';

let glider = require('..'),
	should = require('should');

const PORT = process.env.TRAVIS ? '5432' : '55432',
	CONSTRING = `postgresql://postgres@localhost:${PORT}/postgres`,
	DB = glider(CONSTRING);

it('creates a Database', function() {
	should.exist(DB);
	DB.should.be.an.instanceOf(glider.Database);
	DB.conString.should.equal(CONSTRING);
});

it('connects to a database', function() {
	return DB.connect().then(client => client.done());
});

it('errors on connect error', function() {
	let db = glider('postgres://baduser@localhost:55432/postgres');
	return db.connect().then(
		() => should.not.exist(1),
		err => err.code.should.equal('28000')
	);
});

it('executes basic select query', function() {
	return DB.query('select 1::int as number;')
		.then(result => result.rows[0].number.should.equal(1));
});

it('errors on bad query', function() {
	return DB.query('wtf;').then(
		() => should.not.exist(1),
		err => err.message.should.containEql('syntax error')
	);
});
<commit_msg>fix code tests for multiple envs<commit_after>'use strict';

let glider = require('..'),
	should = require('should');

const PORT = process.env.TRAVIS ? '5432' : '55432',
	CONSTRING = `postgresql://postgres@localhost:${PORT}/postgres`,
	DB = glider(CONSTRING);

it('creates a Database', function() {
	should.exist(DB);
	DB.should.be.an.instanceOf(glider.Database);
	DB.conString.should.equal(CONSTRING);
});

it('connects to a database', function() {
	return DB.connect().then(client => client.done());
});

it('errors on connect error', function() {
	let db = glider('postgres://baduser@localhost:55432/postgres');
	return db.connect().then(
		() => should.not.exist(1),
		err => ['28000', 'ECONNREFUSED'].should.containEql(err.code)
	);
});

it('executes basic select query', function() {
	return DB.query('select 1::int as number;')
		.then(result => result.rows[0].number.should.equal(1));
});

it('errors on bad query', function() {
	return DB.query('wtf;').then(
		() => should.not.exist(1),
		err => err.message.should.containEql('syntax error')
	);
});
<|endoftext|>


<commit_before>/* eslint global-require:0, no-undef: 0 */
'use strict';

process.env.NODE_ENV = 'test';

const app = require('../lib/app')();
const request = require('supertest-as-promised').agent(app.listen());
const expect = require('chai').expect;
const searchError = require('./util/searchError');

describe('search', () => {
    it('should answer to requests with "total" and "results"', () => {
        return request
            .get('/search')
            .query({ term: 'express' })
            .expect(200)
            .then((res) => {
                expect(res.body.total).to.be.a('number');
                expect(res.body.results).to.be.instanceof(Array).with.length.above(0);
            });
    });

    it('"test" should show "mocha", "chai" & "jasmine-core" first', () => {
        const wantedResults = {
            mocha: 0,
            'jasmine-core': 0,
            chai: 0,
        };

        return request
            .get('/search')
            .query({ term: 'test', size: 10 })
            .expect(200)
            .then((res) => {
                const results = res.body.results.map((result) => result.name);

                expect(searchError(wantedResults, results)).to.be.below(4);
            });
    });
});
<commit_msg>Temporarily disable test, since they require connection to elasticsearch<commit_after>/* eslint global-require:0, no-undef: 0 */
'use strict';

process.env.NODE_ENV = 'test';

// const app = require('../lib/app')();
// const request = require('supertest-as-promised').agent(app.listen());
// const expect = require('chai').expect;
// const searchError = require('./util/searchError');

describe('search', () => {
    // it('should answer to requests with "total" and "results"', () => {
    //     return request
    //         .get('/search')
    //         .query({ term: 'express' })
    //         .expect(200)
    //         .then((res) => {
    //             expect(res.body.total).to.be.a('number');
    //             expect(res.body.results).to.be.instanceof(Array).with.length.above(0);
    //         });
    // });
    //
    // it('"test" should show "mocha", "chai" & "jasmine-core" first', () => {
    //     const wantedResults = {
    //         mocha: 0,
    //         'jasmine-core': 0,
    //         chai: 0,
    //     };
    //
    //     return request
    //         .get('/search')
    //         .query({ term: 'test', size: 10 })
    //         .expect(200)
    //         .then((res) => {
    //             const results = res.body.results.map((result) => result.name);
    //
    //             expect(searchError(wantedResults, results)).to.be.below(4);
    //         });
    // });
});
<|endoftext|>


<commit_before>var request = require('supertest')
  , assert = require('assert')
  , request = request('http://localhost:1235/api/v1')
  , API_key = 'xxx'

describe('Users API', function() {
  var userId

  it('should create a new user', function(done) {
    request
    .post('/users')
    .set('X-API-Key', API_key)
    .send({name: 'Foo Bar'/*, type: '', foreignId: 1234*/})
    .expect(200)
    .expect('Content-Type', /json/)
    .end(function(err, res) {
      if(err) return done(err)
      userId = res.body.id
      done()
    })
  })

  it('should retrieve a user', function(done) {
    request
    .get('/users/'+userId)
    .set('X-API-Key', API_key)
    .expect(200)
    .expect('Content-Type', /json/)
    .expect(function(res) {
      assert(res.body.id == userId)
    })
    .end(done)
  })

  it('should delete a user', function(done) {
    request
    .delete('/users/'+userId)
    .set('X-API-Key', API_key)
    .expect(200)
    .expect('Content-Type', /json/)

    .end(function(err) {
      if(err) return done(err)

      request
      .get('/users/'+userId)
      .set('X-API-Key', API_key)
      .expect(404)
      .expect('Content-Type', /json/)
      .end(done)
    })
  })

})

describe('Documents API', function() {

  var userId
  before(function(done) {
    // create a new user
    request
      .post('/users')
      .set('X-API-Key', API_key)
      .send({name: 'Foo Bar'/*, type: '', foreignId: 1234*/})
      .end(function(err, res) {
        if(err) return done(err)
        userId = res.body.id
        done()
      })
  })

  var documentId

  it('should create a new document', function(done) {
    request
    .post('/documents')
    .set('X-API-Key', API_key)
    .send({type: 'text'})
    .expect(200)
    .expect('Content-Type', /json/)
    .end(function(err, res) {
      if(err) return done(err)
      documentId = res.body.id
      done()
    })
  })

  it('should retrieve a document', function(done) {
    request
    .get('/documents/'+documentId)
    .set('X-API-Key', API_key)
    .expect(200)
    .expect('Content-Type', /json/)
    .expect(function(res) {
      assert(res.body.id == documentId)
    })
    .end(done)
  })

  it('should change a document', function(done) {
    request
    .post('/documents/'+documentId+'/pendingChanges')
    .set('X-API-Key', API_key)
    .send({changes: '+foo', parent: 0, user: userId})
    .expect(200)
    .expect('Content-Type', /json/)
    .expect(function(res) {
      assert(res.body.id == documentId)
    })
    .end(done)
  })

  it('should delete a document', function(done) {
    request
    .delete('/documents/'+documentId)
    .set('X-API-Key', API_key)
    .expect(200)
    .expect('Content-Type', /json/)

    .end(function(err) {
      if(err) return done(err)

      request
      .get('/documents/'+userId)
      .set('X-API-Key', API_key)
      .expect(404)
      .expect('Content-Type', /json/)
      .end(done)
    })
  })
})
<commit_msg>Fix document:destroy test<commit_after>var request = require('supertest')
  , assert = require('assert')
  , request = request('http://localhost:1235/api/v1')
  , API_key = 'xxx'

describe('Users API', function() {
  var userId

  it('should create a new user', function(done) {
    request
    .post('/users')
    .set('X-API-Key', API_key)
    .send({name: 'Foo Bar'/*, type: '', foreignId: 1234*/})
    .expect(200)
    .expect('Content-Type', /json/)
    .end(function(err, res) {
      if(err) return done(err)
      userId = res.body.id
      done()
    })
  })

  it('should retrieve a user', function(done) {
    request
    .get('/users/'+userId)
    .set('X-API-Key', API_key)
    .expect(200)
    .expect('Content-Type', /json/)
    .expect(function(res) {
      assert(res.body.id == userId)
    })
    .end(done)
  })

  it('should delete a user', function(done) {
    request
    .delete('/users/'+userId)
    .set('X-API-Key', API_key)
    .expect(200)
    .expect('Content-Type', /json/)

    .end(function(err) {
      if(err) return done(err)

      request
      .get('/users/'+userId)
      .set('X-API-Key', API_key)
      .expect(404)
      .expect('Content-Type', /json/)
      .end(done)
    })
  })

})

describe('Documents API', function() {

  var userId
  before(function(done) {
    // create a new user
    request
      .post('/users')
      .set('X-API-Key', API_key)
      .send({name: 'Foo Bar'/*, type: '', foreignId: 1234*/})
      .end(function(err, res) {
        if(err) return done(err)
        userId = res.body.id
        done()
      })
  })

  var documentId

  it('should create a new document', function(done) {
    request
    .post('/documents')
    .set('X-API-Key', API_key)
    .send({type: 'text'})
    .expect(200)
    .expect('Content-Type', /json/)
    .end(function(err, res) {
      if(err) return done(err)
      documentId = res.body.id
      done()
    })
  })

  it('should retrieve a document', function(done) {
    request
    .get('/documents/'+documentId)
    .set('X-API-Key', API_key)
    .expect(200)
    .expect('Content-Type', /json/)
    .expect(function(res) {
      assert(res.body.id == documentId)
    })
    .end(done)
  })

  it('should change a document', function(done) {
    request
    .post('/documents/'+documentId+'/pendingChanges')
    .set('X-API-Key', API_key)
    .send({changes: '+foo', parent: 0, user: userId})
    .expect(200)
    .expect('Content-Type', /json/)
    .expect(function(res) {
      assert(res.body.id == documentId)
    })
    .end(done)
  })

  it('should delete a document', function(done) {
    request
    .delete('/documents/'+documentId)
    .set('X-API-Key', API_key)
    .expect(200)
    .expect('Content-Type', /json/)

    .end(function(err) {
      if(err) return done(err)

      request
      .get('/documents/'+documentId)
      .set('X-API-Key', API_key)
      .expect(404)
      .expect('Content-Type', /json/)
      .end(done)
    })
  })
})
<|endoftext|>


<commit_before>const path = require('path');
const EventEmitter = require('events');
const rread = require('readdir-recursive');
const Command = require('./Command');
const Inhibitor = require('./Inhibitor');

class CommandHandler extends EventEmitter {
    /**
     * Creates a new CommandHandler.
     * @param {Framework} framework The Akairo framework.
     */
    constructor(framework){
        super();

        /**
         * The Akairo framework.
         * @type {Framework}
         */
        this.framework = framework;

        /**
         * Directory to commands.
         * @type {string}
         */
        this.commandDirectory = path.resolve(this.framework.options.commandDirectory);

        /**
         * Directory to inhibitors.
         * @type {string}
         */
        this.inhibitorDirectory = path.resolve(this.framework.options.inhibitorDirectory);

        /**
         * Commands loaded, mapped by ID to Command.
         * @type {Map.<string, Command>}
         */
        this.commands = new Map();

        /**
         * Commands categories mapped by name to Array of Commands.
         * @type {Map.<string, Array.<Command>>}
         */
        this.categories = new Map();

        /**
         * Inhibitors loaded, mapped by ID to Inhibitor.
         * @type {Map.<string, Inhibitor>}
         */
        this.inhibitors = new Map();

        let cmdPaths = rread.fileSync(this.commandDirectory);
        cmdPaths.forEach(filepath => {
            this.loadCommand(filepath);
        });

        let inhibPaths = rread.fileSync(this.inhibitorDirectory);
        inhibPaths.forEach(filepath => {
            this.loadInhibitor(filepath);
        });
    }

    /**
     * Loads a Command.
     * @param {string} filepath Path to file.
     */
    loadCommand(filepath){
        let command = require(filepath);

        if (!(command instanceof Command)) return;
        if (this.commands.has(command.id)) throw new Error(`Command ${command.id} already loaded.`);

        command.filepath = filepath;
        command.framework = this.framework;
        command.commandHandler = this;

        this.commands.set(command.id, command);
        this.categories.get(command.options.category).push(command);
    }

    /**
     * Adds a Command.
     * @param {string} filename Filename to lookup in the directory.
     */
    addCommand(filename){
        let files = rread.fileSync(this.commandDirectory);
        let filepath = files.find(file => file.endsWith(`${filename}.js`));

        if (!filepath){
            throw new Error(`File ${filename} not found.`);
        }

        this.loadCommand(filepath);
    }

    /**
     * Removes a Command.
     * @param {string} id ID of the Command.
     */
    removeCommand(id){
        let command = this.commands.get(id);
        if (!command) throw new Error(`Command ${id} does not exist.`);

        delete require.cache[require.resolve(command.filepath)];
        this.commands.delete(command.id);

        let category = this.categories.get(command.options.category);
        category.splice(category.indexOf(command), 1);
    }

    /**
     * Reloads a Command.
     * @param {string} id ID of the Command.
     */
    reloadCommand(id){
        let command = this.commands.get(id);
        if (!command) throw new Error(`Command ${id} does not exist.`);

        let filepath = command.filepath;

        delete require.cache[require.resolve(command.filepath)];
        this.commands.delete(command.id);

        let category = this.categories.get(command.options.category);
        category.splice(category.indexOf(command), 1);

        this.loadCommand(filepath);
    }

    /**
     * Finds a command by alias.
     * @param {string} name Alias to find with.
     */
    findCommand(name){
        return Array.from(this.commands.values()).find(command => {
            return command.aliases.some(a => a.toLowerCase() === name.toLowerCase());
        });
    }

    /**
     * Finds a category by name.
     * @param {string} name Name to find with.
     */
    findCategory(name){
        let cat = Array.from(this.categories).find(cat => cat[0].toLowerCase() === name.toLowerCase());
        return cat ? cat[1] : null;
    }

    /**
     * Loads an Inhibitor.
     * @param {string} filepath Path to file.
     */
    loadInhibitor(filepath){
        let inhibitor = require(filepath);

        if (!(inhibitor instanceof Inhibitor)) return;
        if (this.inhibitors.has(inhibitor.id)) throw new Error(`Inhibitor ${inhibitor.id} already loaded.`);

        inhibitor.filepath = filepath;
        inhibitor.framework = this.framework;
        inhibitor.commandHandler = this;

        this.inhibitors.set(inhibitor.id, inhibitor);
    }

    /**
     * Adds an Inhibitor.
     * @param {string} filename Filename to lookup in the directory.
     */
    addInhibitor(filename){
        let files = rread.fileSync(this.inhibitorDirectory);
        let filepath = files.find(file => file.endsWith(`${filename}.js`));

        if (!filepath){
            throw new Error(`File ${filename} not found.`);
        }

        this.loadInhibitor(filepath);
    }

    /**
     * Removes an Inhibitor.
     * @param {string} id ID of the Inhibitor.
     */
    removeInhibitor(id){
        let inhibitor = this.inhibitors.get(id);
        if (!inhibitor) throw new Error(`Inhibitor ${id} does not exist.`);

        delete require.cache[require.resolve(inhibitor.filepath)];
        this.inhibitors.delete(inhibitor.id);
    }

    /**
     * Reloads an Inhibitor.
     * @param {string} id ID of the Inhibitor.
     */
    reloadInhibitor(id){
        let inhibitor = this.inhibitors.get(id);
        if (!inhibitor) throw new Error(`Inhibitor ${id} does not exist.`);

        let filepath = inhibitor.filepath;

        delete require.cache[require.resolve(inhibitor.filepath)];
        this.inhibitors.delete(inhibitor.id);

        this.loadInhibitor(filepath);
    }

    /**
     * Handles a Message.
     * @param {Discord.Message} message Message to handle.
     * @param {string} prefix Prefix for command.
     * @param {boolean} allowMention Allow mentions to the client user as a prefix.
     */
    handle(message, prefix, allowMention){
        let start;
        let mentionRegex = new RegExp(`^<@!?${this.framework.client.user.id}>`);
        let mentioned = message.content.match(mentionRegex);

        if (message.content.startsWith(prefix)){
            start = prefix;
        } else
        if (allowMention && mentioned){
            start = mentioned[0];
        } else {
            return this.emit('commandPrefixInvalid', message);
        }

        let firstWord = message.content.replace(start, '').search(/\S/) + start.length;
        let name = message.content.slice(firstWord).split(' ')[0];
        let command = this.findCommand(name);

        if (!command) return this.emit('commandInvalid', message);

        let block = reason => {
            this.emit('commandBlocked', message, command, reason);
        };

        if (message.author.id !== this.framework.client.user.id && this.framework.options.selfbot) return block('notSelf');
        if (message.author.id === this.framework.client.user.id && !this.framework.options.selfbot) return block('client');
        if (message.author.bot) return block('bot');
        if (command.options.ownerOnly && message.author.id !== this.framework.options.ownerID) return block('owner');
        if (command.options.channelRestriction === 'guild' && !message.guild) return block('guild');
        if (command.options.channelRestriction === 'dm' && message.guild) return block('dm');

        let results = [];

        this.inhibitors.forEach(inhibitor => {
            let inhibited = inhibitor.exec(message, command);

            if (inhibited instanceof Promise){
                return results.push(inhibited.catch(() => { throw inhibitor.reason; }));
            }

            if (!inhibited){
                return results.push(Promise.resolve());
            }

            results.push(Promise.reject(inhibitor.reason));
        });

        Promise.all(results).then(() => {
            let content = message.content.slice(message.content.indexOf(name) + name.length + 1);
            let args = command.parse(content);

            this.emit('commandStarted', message, command);
            let end = Promise.resolve(command.exec(message, args));

            end.then(() => {
                this.emit('commandFinished', message, command);
            }).catch(err => {
                this.emit('commandFinished', message, command);
                throw err;
            });
        }).catch(reason => {
            if (reason instanceof Error) throw reason;
            block(reason);
        });
    }
}

module.exports = CommandHandler;

/**
 * Emitted when a message does not start with the prefix.
 * @event CommandHandler#commandPrefixInvalid
 * @param {Discord.Message} message Message sent.
 */

/**
 * Emitted when a message does not match a command.
 * @event CommandHandler#commandInvalid
 * @param {Discord.Message} message Message sent.
 */

/**
 * Emitted when a command is blocked by an inhibitor.
 * @event CommandHandler#commandBlocked
 * @param {Discord.Message} message Message sent.
 * @param {Command} command Command blocked.
 * @param {string} reason Reason for the block.
 */

/**
 * Emitted when a command starts execution.
 * @event CommandHandler#commandStarted
 * @param {Discord.Message} message Message sent.
 * @param {Command} command Command executed.
 */

/**
 * Emitted when a command finishes execution.
 * @event CommandHandler#commandFinished
 * @param {Discord.Message} message Message sent.
 * @param {Command} command Command executed.
 */<commit_msg>fix category<commit_after>const path = require('path');
const EventEmitter = require('events');
const rread = require('readdir-recursive');
const Command = require('./Command');
const Inhibitor = require('./Inhibitor');

class CommandHandler extends EventEmitter {
    /**
     * Creates a new CommandHandler.
     * @param {Framework} framework The Akairo framework.
     */
    constructor(framework){
        super();

        /**
         * The Akairo framework.
         * @type {Framework}
         */
        this.framework = framework;

        /**
         * Directory to commands.
         * @type {string}
         */
        this.commandDirectory = path.resolve(this.framework.options.commandDirectory);

        /**
         * Directory to inhibitors.
         * @type {string}
         */
        this.inhibitorDirectory = path.resolve(this.framework.options.inhibitorDirectory);

        /**
         * Commands loaded, mapped by ID to Command.
         * @type {Map.<string, Command>}
         */
        this.commands = new Map();

        /**
         * Commands categories mapped by name to Array of Commands.
         * @type {Map.<string, Array.<Command>>}
         */
        this.categories = new Map();

        /**
         * Inhibitors loaded, mapped by ID to Inhibitor.
         * @type {Map.<string, Inhibitor>}
         */
        this.inhibitors = new Map();

        let cmdPaths = rread.fileSync(this.commandDirectory);
        cmdPaths.forEach(filepath => {
            this.loadCommand(filepath);
        });

        let inhibPaths = rread.fileSync(this.inhibitorDirectory);
        inhibPaths.forEach(filepath => {
            this.loadInhibitor(filepath);
        });
    }

    /**
     * Loads a Command.
     * @param {string} filepath Path to file.
     */
    loadCommand(filepath){
        let command = require(filepath);

        if (!(command instanceof Command)) return;
        if (this.commands.has(command.id)) throw new Error(`Command ${command.id} already loaded.`);

        command.filepath = filepath;
        command.framework = this.framework;
        command.commandHandler = this;

        this.commands.set(command.id, command);

        if (!this.categories.has(command.options.category)) this.categories.set(command.options.category, []);
        this.categories.get(command.options.category).push(command);
    }

    /**
     * Adds a Command.
     * @param {string} filename Filename to lookup in the directory.
     */
    addCommand(filename){
        let files = rread.fileSync(this.commandDirectory);
        let filepath = files.find(file => file.endsWith(`${filename}.js`));

        if (!filepath){
            throw new Error(`File ${filename} not found.`);
        }

        this.loadCommand(filepath);
    }

    /**
     * Removes a Command.
     * @param {string} id ID of the Command.
     */
    removeCommand(id){
        let command = this.commands.get(id);
        if (!command) throw new Error(`Command ${id} does not exist.`);

        delete require.cache[require.resolve(command.filepath)];
        this.commands.delete(command.id);

        let category = this.categories.get(command.options.category);
        category.splice(category.indexOf(command), 1);
    }

    /**
     * Reloads a Command.
     * @param {string} id ID of the Command.
     */
    reloadCommand(id){
        let command = this.commands.get(id);
        if (!command) throw new Error(`Command ${id} does not exist.`);

        let filepath = command.filepath;

        delete require.cache[require.resolve(command.filepath)];
        this.commands.delete(command.id);

        let category = this.categories.get(command.options.category);
        category.splice(category.indexOf(command), 1);

        this.loadCommand(filepath);
    }

    /**
     * Finds a command by alias.
     * @param {string} name Alias to find with.
     */
    findCommand(name){
        return Array.from(this.commands.values()).find(command => {
            return command.aliases.some(a => a.toLowerCase() === name.toLowerCase());
        });
    }

    /**
     * Finds a category by name.
     * @param {string} name Name to find with.
     */
    findCategory(name){
        let cat = Array.from(this.categories).find(cat => cat[0].toLowerCase() === name.toLowerCase());
        return cat ? cat[1] : null;
    }

    /**
     * Loads an Inhibitor.
     * @param {string} filepath Path to file.
     */
    loadInhibitor(filepath){
        let inhibitor = require(filepath);

        if (!(inhibitor instanceof Inhibitor)) return;
        if (this.inhibitors.has(inhibitor.id)) throw new Error(`Inhibitor ${inhibitor.id} already loaded.`);

        inhibitor.filepath = filepath;
        inhibitor.framework = this.framework;
        inhibitor.commandHandler = this;

        this.inhibitors.set(inhibitor.id, inhibitor);
    }

    /**
     * Adds an Inhibitor.
     * @param {string} filename Filename to lookup in the directory.
     */
    addInhibitor(filename){
        let files = rread.fileSync(this.inhibitorDirectory);
        let filepath = files.find(file => file.endsWith(`${filename}.js`));

        if (!filepath){
            throw new Error(`File ${filename} not found.`);
        }

        this.loadInhibitor(filepath);
    }

    /**
     * Removes an Inhibitor.
     * @param {string} id ID of the Inhibitor.
     */
    removeInhibitor(id){
        let inhibitor = this.inhibitors.get(id);
        if (!inhibitor) throw new Error(`Inhibitor ${id} does not exist.`);

        delete require.cache[require.resolve(inhibitor.filepath)];
        this.inhibitors.delete(inhibitor.id);
    }

    /**
     * Reloads an Inhibitor.
     * @param {string} id ID of the Inhibitor.
     */
    reloadInhibitor(id){
        let inhibitor = this.inhibitors.get(id);
        if (!inhibitor) throw new Error(`Inhibitor ${id} does not exist.`);

        let filepath = inhibitor.filepath;

        delete require.cache[require.resolve(inhibitor.filepath)];
        this.inhibitors.delete(inhibitor.id);

        this.loadInhibitor(filepath);
    }

    /**
     * Handles a Message.
     * @param {Discord.Message} message Message to handle.
     * @param {string} prefix Prefix for command.
     * @param {boolean} allowMention Allow mentions to the client user as a prefix.
     */
    handle(message, prefix, allowMention){
        let start;
        let mentionRegex = new RegExp(`^<@!?${this.framework.client.user.id}>`);
        let mentioned = message.content.match(mentionRegex);

        if (message.content.startsWith(prefix)){
            start = prefix;
        } else
        if (allowMention && mentioned){
            start = mentioned[0];
        } else {
            return this.emit('commandPrefixInvalid', message);
        }

        let firstWord = message.content.replace(start, '').search(/\S/) + start.length;
        let name = message.content.slice(firstWord).split(' ')[0];
        let command = this.findCommand(name);

        if (!command) return this.emit('commandInvalid', message);

        let block = reason => {
            this.emit('commandBlocked', message, command, reason);
        };

        if (message.author.id !== this.framework.client.user.id && this.framework.options.selfbot) return block('notSelf');
        if (message.author.id === this.framework.client.user.id && !this.framework.options.selfbot) return block('client');
        if (message.author.bot) return block('bot');
        if (command.options.ownerOnly && message.author.id !== this.framework.options.ownerID) return block('owner');
        if (command.options.channelRestriction === 'guild' && !message.guild) return block('guild');
        if (command.options.channelRestriction === 'dm' && message.guild) return block('dm');

        let results = [];

        this.inhibitors.forEach(inhibitor => {
            let inhibited = inhibitor.exec(message, command);

            if (inhibited instanceof Promise){
                return results.push(inhibited.catch(() => { throw inhibitor.reason; }));
            }

            if (!inhibited){
                return results.push(Promise.resolve());
            }

            results.push(Promise.reject(inhibitor.reason));
        });

        Promise.all(results).then(() => {
            let content = message.content.slice(message.content.indexOf(name) + name.length + 1);
            let args = command.parse(content);

            this.emit('commandStarted', message, command);
            let end = Promise.resolve(command.exec(message, args));

            end.then(() => {
                this.emit('commandFinished', message, command);
            }).catch(err => {
                this.emit('commandFinished', message, command);
                throw err;
            });
        }).catch(reason => {
            if (reason instanceof Error) throw reason;
            block(reason);
        });
    }
}

module.exports = CommandHandler;

/**
 * Emitted when a message does not start with the prefix.
 * @event CommandHandler#commandPrefixInvalid
 * @param {Discord.Message} message Message sent.
 */

/**
 * Emitted when a message does not match a command.
 * @event CommandHandler#commandInvalid
 * @param {Discord.Message} message Message sent.
 */

/**
 * Emitted when a command is blocked by an inhibitor.
 * @event CommandHandler#commandBlocked
 * @param {Discord.Message} message Message sent.
 * @param {Command} command Command blocked.
 * @param {string} reason Reason for the block.
 */

/**
 * Emitted when a command starts execution.
 * @event CommandHandler#commandStarted
 * @param {Discord.Message} message Message sent.
 * @param {Command} command Command executed.
 */

/**
 * Emitted when a command finishes execution.
 * @event CommandHandler#commandFinished
 * @param {Discord.Message} message Message sent.
 * @param {Command} command Command executed.
 */<|endoftext|>


<commit_before>// Spec:
// 1. Url parsing
//    Find extraction patterns, return patterns and cleanUrl
// 2. Globbing
//    Check if the url pattern matches globbing and return content with imports
//    of found urls
// 3. Module importing
//    Find path to module file and return as url (findup / resolve / resolve-dir)
// 4. Once check - ignore if url imported
// 5. Selector filtering
//    Load CSS file, run css-selector-extract on it and return as content
// 6. Once
//    Track imported files and selectors

const chai = require('chai');
const chaiAsPromised = require('chai-as-promised');
const expect = require('chai').expect;
const fs = require('fs');
const sass = require('node-sass');
const NodeSassMagicImporter = require('../').NodeSassMagicImporter;
const path = require('path');

chai.use(chaiAsPromised);

describe('MagicImporter', () => {
  it('should be a function', () => {
    expect(NodeSassMagicImporter).to.be.a('function');
  });

  describe('#_parseUrl()', () => {
    let nodeSassMagicImporter = new NodeSassMagicImporter();

    it('should be a function', () => {
      expect(nodeSassMagicImporter._parseUrl).to.be.a('function');
    });

    it('should return an object with expected values', (done) => {
      let url = '{ .test1 as .test1-replaced, .test2 } from ~style.scss';
      let expectedResult = {
        url: 'style.scss',
        selectorFilters: ['.test1', '.test2'],
        selectorReplacements: { '.test1': '.test1-replaced' },
        prioritizeModuleResolve: true
      };

      return expect(nodeSassMagicImporter._parseUrl(url)).to.eventually.deep.equal(expectedResult).notify(done);
    });
  });

  describe('#_resolveGlob()', () => {
    let nodeSassMagicImporter = new NodeSassMagicImporter();

    it('should be a function', () => {
      expect(nodeSassMagicImporter._resolveGlob).to.be.a('function');
    });

    it('should return error message', (done) => {
      let url = 'style.scss';
      let expectedResult = 'No glob pattern found.';

      return expect(nodeSassMagicImporter._resolveGlob(url)).to.eventually.be.rejectedWith(expectedResult).notify(done);
    });

    it('should return content string with @import statements', (done) => {
      let url = 'files/resolve-glob/**/*.scss';
      let includePath = path.join(process.cwd(), 'test');
      let expectedResult = `@import '${path.join(includePath, 'files/resolve-glob/style1.scss')}';
@import '${path.join(includePath, 'files/resolve-glob/style2.scss')}';`;

      return expect(nodeSassMagicImporter._resolveGlob(url, [includePath])).to.eventually.equal(expectedResult).notify(done);
    });
  });

  describe('#_resolveModule()', () => {
    let nodeSassMagicImporter = new NodeSassMagicImporter();

    it('should be a function', () => {
      expect(nodeSassMagicImporter._resolveModule).to.be.a('function');
    });

    it('should return error message', (done) => {
      let url = 'non-existent-module';
      let cwd = path.join(process.cwd(), 'test/files/resolve-module');
      let expectedResult = `Module path "${url}" could not be resolved.`;

      return expect(nodeSassMagicImporter._resolveModule(url, cwd)).to.eventually.be.rejectedWith(expectedResult).notify(done);
    });

    it('should return absolute path to sass file defined in package.json', (done) => {
      let url = 'test-module';
      let cwd = path.join(process.cwd(), 'test/files/resolve-module');
      let expectedResult = path.join(cwd, 'node_modules/test-module/scss/style.scss');

      return expect(nodeSassMagicImporter._resolveModule(url, cwd)).to.eventually.equal(expectedResult).notify(done);
    });

    it('should return absolute path to sass file', (done) => {
      let url = 'test-module/scss/_partial.scss';
      let cwd = path.join(process.cwd(), 'test/files/resolve-module');
      let expectedResult = path.join(cwd, 'node_modules/test-module/scss/_partial.scss');

      return expect(nodeSassMagicImporter._resolveModule(url, cwd)).to.eventually.equal(expectedResult).notify(done);
    });

    it('should return absolute path to partial sass file', (done) => {
      let url = 'test-module/scss/partial';
      let cwd = path.join(process.cwd(), 'test/files/resolve-module');
      let expectedResult = path.join(cwd, 'node_modules/test-module/scss/_partial.scss');

      return expect(nodeSassMagicImporter._resolveModule(url, cwd)).to.eventually.equal(expectedResult).notify(done);
    });

    it('should return absolute path to sass file defined in package.json of nested module', (done) => {
      let url = 'nested-test-module';
      let cwd = path.join(process.cwd(), 'test/files/resolve-module');
      let expectedResult = path.join(cwd, 'node_modules/test-module/node_modules/nested-test-module/scss/style.scss');

      return expect(nodeSassMagicImporter._resolveModule(url, cwd)).to.eventually.equal(expectedResult).notify(done);
    });

    it('should return absolute path to sass file of nested module', (done) => {
      let url = 'nested-test-module/scss/_partial.scss';
      let cwd = path.join(process.cwd(), 'test/files/resolve-module');
      let expectedResult = path.join(cwd, 'node_modules/test-module/node_modules/nested-test-module/scss/_partial.scss');

      return expect(nodeSassMagicImporter._resolveModule(url, cwd)).to.eventually.equal(expectedResult).notify(done);
    });

    it('should return absolute path to partial sass file of nested module', (done) => {
      let url = 'nested-test-module/scss/partial';
      let cwd = path.join(process.cwd(), 'test/files/resolve-module');
      let expectedResult = path.join(cwd, 'node_modules/test-module/node_modules/nested-test-module/scss/_partial.scss');

      return expect(nodeSassMagicImporter._resolveModule(url, cwd)).to.eventually.equal(expectedResult).notify(done);
    });
  });

  describe('#_selectorFilter()', () => {
    let nodeSassMagicImporter = new NodeSassMagicImporter();

    it('should be a function', () => {
      expect(nodeSassMagicImporter._selectorFilter).to.be.a('function');
    });

    it('should return error message', (done) => {
      let filePath = '/file/does/not/exist.scss';
      let expectedResult = `File "${filePath}" not found.`;

      return expect(nodeSassMagicImporter._selectorFilter(filePath)).to.eventually.be.rejectedWith(expectedResult).notify(done);
    });

    it('should return filtered content string', (done) => {
      let filePath = path.join(process.cwd(), 'test/files/selector-filter/style.scss');
      let selectorFilters = ['.test-selector1'];
      let selectorReplacements = { '.test-selector1': '.test-selector-replaced1' };
      let expectedResult = fs.readFileSync(path.join(process.cwd(), 'test/files/selector-filter/expected-result.scss'), { encoding: 'utf8' });

      return expect(nodeSassMagicImporter._selectorFilter(filePath, selectorFilters, selectorReplacements)).to.eventually.equal(expectedResult).notify(done);
    });
  });

  describe('#_importOnceInit()', () => {
    let nodeSassMagicImporter = new NodeSassMagicImporter();

    it('should be a function', () => {
      expect(nodeSassMagicImporter._importOnceInit).to.be.a('function');
    });

    it('should set "this.importedStore" to empty object', () => {
      nodeSassMagicImporter._importOnceInit();
      expect(nodeSassMagicImporter.importedStore).to.be.an('object').and.to.be.empty;
    });
  });

  describe('#_importOnceTrack()', () => {
    let nodeSassMagicImporter = new NodeSassMagicImporter();

    it('should be a function', () => {
      expect(nodeSassMagicImporter._importOnceTrack).to.be.a('function');
    });

    it('should track the imported filePaths and selectorFilters', () => {
      let importerId = 'default';

      let filePath1 = '/test/file.scss';
      let selectorFilters1 = ['.test-selector-foo', '.test-selector-bar'];
      nodeSassMagicImporter._importOnceTrack(filePath1, selectorFilters1, importerId);

      let filePath2 = '/test/file.scss';
      let selectorFilters2 = ['.test-selector-foo', '.test-selector-baz'];
      nodeSassMagicImporter._importOnceTrack(filePath2, selectorFilters2, importerId);

      let filePath3 = '/another/test/file.scss';
      let selectorFilters3 = ['.test-selector-foo'];
      nodeSassMagicImporter._importOnceTrack(filePath3, selectorFilters3, importerId);

      let expectedResult = {
        'default': {
          '/test/file.scss': ['.test-selector-foo', '.test-selector-bar', '.test-selector-baz'],
          '/another/test/file.scss': ['.test-selector-foo']
        }
      };

      expect(nodeSassMagicImporter.importedStore).to.deep.equal(expectedResult);
    });
  });

  describe('#_importOnceCheck()', () => {
    let nodeSassMagicImporter = new NodeSassMagicImporter();
  });

  describe('#importer()', () => {
    let nodeSassMagicImporter = new NodeSassMagicImporter();
  });

  // describe('Test imports', () => {
  //   const defaultImportTest = function (testName, done) {
  //     const referenceCss = fs.readFileSync('test/css/' + testName + '-reference.css').toString();

  //     sass.render({
  //       file: 'test/css/' + testName + '.scss',
  //       importer: magicImporter,
  //       magicImporter: {
  //         importOnce: true,
  //         cssImport: true,
  //         extensions: ['.scss']
  //       }
  //     }, function (error, result) {
  //       if (!error) {
  //         expect(result.css.toString()).to.equal(referenceCss);
  //         done();
  //       }
  //     });
  //   }

  //   it('Combined', function (done) {
  //     const testName = 'combined';
  //     defaultImportTest(testName, done);
  //   });

  //   it('CSS', function (done) {
  //     const testName = 'css';
  //     defaultImportTest(testName, done);
  //   });

  //   it('Globbing', function (done) {
  //     const testName = 'globbing';
  //     defaultImportTest(testName, done);
  //   });

  //   it('Module', function (done) {
  //     const testName = 'module';
  //     defaultImportTest(testName, done);
  //   });

  //   it('Once', function (done) {
  //     const testName = 'once';
  //     defaultImportTest(testName, done);
  //   });

  //   it('Selectors', function (done) {
  //     const testName = 'selectors';
  //     defaultImportTest(testName, done);
  //   });
  // });
});
<commit_msg>add docbloc headlines to the test cases for better readability<commit_after>// Spec:
// 1. Url parsing
//    Find extraction patterns, return patterns and cleanUrl
// 2. Globbing
//    Check if the url pattern matches globbing and return content with imports
//    of found urls
// 3. Module importing
//    Find path to module file and return as url (findup / resolve / resolve-dir)
// 4. Once check - ignore if url imported
// 5. Selector filtering
//    Load CSS file, run css-selector-extract on it and return as content
// 6. Once
//    Track imported files and selectors

const chai = require('chai');
const chaiAsPromised = require('chai-as-promised');
const expect = require('chai').expect;
const fs = require('fs');
const sass = require('node-sass');
const NodeSassMagicImporter = require('../').NodeSassMagicImporter;
const path = require('path');

chai.use(chaiAsPromised);

describe('MagicImporter', () => {
  it('should be a function', () => {
    expect(NodeSassMagicImporter).to.be.a('function');
  });

  /**
   * _parseUrl()
   */
  describe('#_parseUrl()', () => {
    let nodeSassMagicImporter = new NodeSassMagicImporter();

    it('should be a function', () => {
      expect(nodeSassMagicImporter._parseUrl).to.be.a('function');
    });

    it('should return an object with expected values', (done) => {
      let url = '{ .test1 as .test1-replaced, .test2 } from ~style.scss';
      let expectedResult = {
        url: 'style.scss',
        selectorFilters: ['.test1', '.test2'],
        selectorReplacements: { '.test1': '.test1-replaced' },
        prioritizeModuleResolve: true
      };

      return expect(nodeSassMagicImporter._parseUrl(url)).to.eventually.deep.equal(expectedResult).notify(done);
    });
  });

  /**
   * _resolveGlob()
   */
  describe('#_resolveGlob()', () => {
    let nodeSassMagicImporter = new NodeSassMagicImporter();

    it('should be a function', () => {
      expect(nodeSassMagicImporter._resolveGlob).to.be.a('function');
    });

    it('should return error message', (done) => {
      let url = 'style.scss';
      let expectedResult = 'No glob pattern found.';

      return expect(nodeSassMagicImporter._resolveGlob(url)).to.eventually.be.rejectedWith(expectedResult).notify(done);
    });

    it('should return content string with @import statements', (done) => {
      let url = 'files/resolve-glob/**/*.scss';
      let includePath = path.join(process.cwd(), 'test');
      let expectedResult = `@import '${path.join(includePath, 'files/resolve-glob/style1.scss')}';
@import '${path.join(includePath, 'files/resolve-glob/style2.scss')}';`;

      return expect(nodeSassMagicImporter._resolveGlob(url, [includePath])).to.eventually.equal(expectedResult).notify(done);
    });
  });

  /**
   * _resolveModule()
   */
  describe('#_resolveModule()', () => {
    let nodeSassMagicImporter = new NodeSassMagicImporter();

    it('should be a function', () => {
      expect(nodeSassMagicImporter._resolveModule).to.be.a('function');
    });

    it('should return error message', (done) => {
      let url = 'non-existent-module';
      let cwd = path.join(process.cwd(), 'test/files/resolve-module');
      let expectedResult = `Module path "${url}" could not be resolved.`;

      return expect(nodeSassMagicImporter._resolveModule(url, cwd)).to.eventually.be.rejectedWith(expectedResult).notify(done);
    });

    it('should return absolute path to sass file defined in package.json', (done) => {
      let url = 'test-module';
      let cwd = path.join(process.cwd(), 'test/files/resolve-module');
      let expectedResult = path.join(cwd, 'node_modules/test-module/scss/style.scss');

      return expect(nodeSassMagicImporter._resolveModule(url, cwd)).to.eventually.equal(expectedResult).notify(done);
    });

    it('should return absolute path to sass file', (done) => {
      let url = 'test-module/scss/_partial.scss';
      let cwd = path.join(process.cwd(), 'test/files/resolve-module');
      let expectedResult = path.join(cwd, 'node_modules/test-module/scss/_partial.scss');

      return expect(nodeSassMagicImporter._resolveModule(url, cwd)).to.eventually.equal(expectedResult).notify(done);
    });

    it('should return absolute path to partial sass file', (done) => {
      let url = 'test-module/scss/partial';
      let cwd = path.join(process.cwd(), 'test/files/resolve-module');
      let expectedResult = path.join(cwd, 'node_modules/test-module/scss/_partial.scss');

      return expect(nodeSassMagicImporter._resolveModule(url, cwd)).to.eventually.equal(expectedResult).notify(done);
    });

    it('should return absolute path to sass file defined in package.json of nested module', (done) => {
      let url = 'nested-test-module';
      let cwd = path.join(process.cwd(), 'test/files/resolve-module');
      let expectedResult = path.join(cwd, 'node_modules/test-module/node_modules/nested-test-module/scss/style.scss');

      return expect(nodeSassMagicImporter._resolveModule(url, cwd)).to.eventually.equal(expectedResult).notify(done);
    });

    it('should return absolute path to sass file of nested module', (done) => {
      let url = 'nested-test-module/scss/_partial.scss';
      let cwd = path.join(process.cwd(), 'test/files/resolve-module');
      let expectedResult = path.join(cwd, 'node_modules/test-module/node_modules/nested-test-module/scss/_partial.scss');

      return expect(nodeSassMagicImporter._resolveModule(url, cwd)).to.eventually.equal(expectedResult).notify(done);
    });

    it('should return absolute path to partial sass file of nested module', (done) => {
      let url = 'nested-test-module/scss/partial';
      let cwd = path.join(process.cwd(), 'test/files/resolve-module');
      let expectedResult = path.join(cwd, 'node_modules/test-module/node_modules/nested-test-module/scss/_partial.scss');

      return expect(nodeSassMagicImporter._resolveModule(url, cwd)).to.eventually.equal(expectedResult).notify(done);
    });
  });

  /**
   * _selectorFilter()
   */
  describe('#_selectorFilter()', () => {
    let nodeSassMagicImporter = new NodeSassMagicImporter();

    it('should be a function', () => {
      expect(nodeSassMagicImporter._selectorFilter).to.be.a('function');
    });

    it('should return error message', (done) => {
      let filePath = '/file/does/not/exist.scss';
      let expectedResult = `File "${filePath}" not found.`;

      return expect(nodeSassMagicImporter._selectorFilter(filePath)).to.eventually.be.rejectedWith(expectedResult).notify(done);
    });

    it('should return filtered content string', (done) => {
      let filePath = path.join(process.cwd(), 'test/files/selector-filter/style.scss');
      let selectorFilters = ['.test-selector1'];
      let selectorReplacements = { '.test-selector1': '.test-selector-replaced1' };
      let expectedResult = fs.readFileSync(path.join(process.cwd(), 'test/files/selector-filter/expected-result.scss'), { encoding: 'utf8' });

      return expect(nodeSassMagicImporter._selectorFilter(filePath, selectorFilters, selectorReplacements)).to.eventually.equal(expectedResult).notify(done);
    });
  });

  /**
   * _importOnceInit()
   */
  describe('#_importOnceInit()', () => {
    let nodeSassMagicImporter = new NodeSassMagicImporter();

    it('should be a function', () => {
      expect(nodeSassMagicImporter._importOnceInit).to.be.a('function');
    });

    it('should set "this.importedStore" to empty object', () => {
      nodeSassMagicImporter._importOnceInit();
      expect(nodeSassMagicImporter.importedStore).to.be.an('object').and.to.be.empty;
    });
  });

  /**
   * _importOnceTrack()
   */
  describe('#_importOnceTrack()', () => {
    let nodeSassMagicImporter = new NodeSassMagicImporter();

    it('should be a function', () => {
      expect(nodeSassMagicImporter._importOnceTrack).to.be.a('function');
    });

    it('should track the imported filePaths and selectorFilters', () => {
      let importerId = 'default';

      let filePath1 = '/test/file.scss';
      let selectorFilters1 = ['.test-selector-foo', '.test-selector-bar'];
      nodeSassMagicImporter._importOnceTrack(filePath1, selectorFilters1, importerId);

      let filePath2 = '/test/file.scss';
      let selectorFilters2 = ['.test-selector-foo', '.test-selector-baz'];
      nodeSassMagicImporter._importOnceTrack(filePath2, selectorFilters2, importerId);

      let filePath3 = '/another/test/file.scss';
      let selectorFilters3 = ['.test-selector-foo'];
      nodeSassMagicImporter._importOnceTrack(filePath3, selectorFilters3, importerId);

      let expectedResult = {
        'default': {
          '/test/file.scss': ['.test-selector-foo', '.test-selector-bar', '.test-selector-baz'],
          '/another/test/file.scss': ['.test-selector-foo']
        }
      };

      expect(nodeSassMagicImporter.importedStore).to.deep.equal(expectedResult);
    });
  });

  /**
   * _importOnceCheck()
   */
  describe('#_importOnceCheck()', () => {
    let nodeSassMagicImporter = new NodeSassMagicImporter();
  });

  /**
   * importer()
   */
  describe('#importer()', () => {
    let nodeSassMagicImporter = new NodeSassMagicImporter();
  });

  // describe('Test imports', () => {
  //   const defaultImportTest = function (testName, done) {
  //     const referenceCss = fs.readFileSync('test/css/' + testName + '-reference.css').toString();

  //     sass.render({
  //       file: 'test/css/' + testName + '.scss',
  //       importer: magicImporter,
  //       magicImporter: {
  //         importOnce: true,
  //         cssImport: true,
  //         extensions: ['.scss']
  //       }
  //     }, function (error, result) {
  //       if (!error) {
  //         expect(result.css.toString()).to.equal(referenceCss);
  //         done();
  //       }
  //     });
  //   }

  //   it('Combined', function (done) {
  //     const testName = 'combined';
  //     defaultImportTest(testName, done);
  //   });

  //   it('CSS', function (done) {
  //     const testName = 'css';
  //     defaultImportTest(testName, done);
  //   });

  //   it('Globbing', function (done) {
  //     const testName = 'globbing';
  //     defaultImportTest(testName, done);
  //   });

  //   it('Module', function (done) {
  //     const testName = 'module';
  //     defaultImportTest(testName, done);
  //   });

  //   it('Once', function (done) {
  //     const testName = 'once';
  //     defaultImportTest(testName, done);
  //   });

  //   it('Selectors', function (done) {
  //     const testName = 'selectors';
  //     defaultImportTest(testName, done);
  //   });
  // });
});
<|endoftext|>


<commit_before>var assert = require('assert');
var is = require('is2');
var makeObjConst = require('../lib/const-obj').makeObjConst;
var makePropConst = require('../lib/const-obj').makePropConst;

describe('makeObjConst()', function() {
    it('Should make an object\'s properties constant.', function() {
        var obj = {
            a: 111,
            b: '222',
            c: { d: 333 } };
        makeObjConst(obj);
        obj.a = 222;            // this is legal, but has no effect
        assert.ok(obj.a === 111);
        obj.b = 'Hmm';          // this is legal, but has no effect
        assert.ok(obj.b === '222');
        obj.c.d = true;
        assert.ok(obj.c.d === 333);
    });
});

describe('makePropConst()', function() {
    it('Should make a single property constant.', function() {
        var obj = { alpha: '0', beta: false };
        makePropConst(obj, 'alpha');
        obj.alpha = 678;
        assert.ok(obj.alpha === '0');
        obj.beta = true;
        assert.ok(obj.beta === true);
    });
});
<commit_msg>Changed location of file.<commit_after><|endoftext|>


<commit_before>'use strict';

var grunt = require('grunt');

var path = require('path');
var gruntfileFixture = path.join('test', 'fixtures', 'Gruntfile.js');

exports['grunt'] = {
  // Just testing that subprocessing grunt works
  'can spawn properly': function(test) {
    test.expect(1);
    grunt.util.spawn({
      grunt: true,
      args: ['--gruntfile', gruntfileFixture, 'okay'],
    }, function(err, result, code) {
      test.equal(code, 0, 'should have no error code');
      test.done();
    });
  },
  // Show that we get errors when we throw stuff
  'returns errors to calling process': function(test) {
    test.expect(2);
    grunt.util.spawn({
      grunt: true,
      args: ['--gruntfile', gruntfileFixture, 'fail'],
    }, function(err, result, code) {
      test.notEqual(code, 0, 'should return error code on assertion failure');
      var outHasFail = /Fatal error: broken/.test(result.stdout);
      test.ok(outHasFail, 'stdout should contain output indicating failure.');
      test.done();
    });
  }
};

exports['grunt-mocha-hack'] = {
  // Show that we can spawn the grunt-mocha-hack and get success
  'can spawn properly': function(test) {
    test.expect(3);
    grunt.util.spawn({
      grunt: true,
      args: ['--gruntfile', gruntfileFixture, 'mocha-hack:one'],
    }, function(err, result, code) {
      test.ok(/# tests 3/.test(result.stdout));
      test.ok(/# fail 0/.test(result.stdout));
      test.equal(code, 0, 'should have no error code');
      test.done();
    });
  },
  // Show that our errors do not cause mocha/grunt to quit abruptly.
  // Instead, we should get a complete and meaningful printout.
  'gets errors properly': function(test) {
    test.expect(3);
    grunt.util.spawn({
      grunt: true,
      args: ['--gruntfile', gruntfileFixture, 'mocha-hack:two'],
    }, function(err, result, code) {
      // console.log(result.stdout);
      test.ok(/# tests 3/.test(result.stdout));
      test.ok(/# fail 3/.test(result.stdout));
      test.equal(code, 3, 'should have error code - task failure');
      test.done();
    });
  }
  // TODO(gregp): test useColor flag?
};
<commit_msg>Add junky console.log's to debug travis<commit_after>'use strict';

var grunt = require('grunt');

var path = require('path');
var gruntfileFixture = path.join('test', 'fixtures', 'Gruntfile.js');

exports['grunt'] = {
  // Just testing that subprocessing grunt works
  'can spawn properly': function(test) {
    test.expect(1);
    grunt.util.spawn({
      grunt: true,
      args: ['--gruntfile', gruntfileFixture, 'okay'],
    }, function(err, result, code) {
      test.equal(code, 0, 'should have no error code');
      test.done();
    });
  },
  // Show that we get errors when we throw stuff
  'returns errors to calling process': function(test) {
    test.expect(2);
    grunt.util.spawn({
      grunt: true,
      args: ['--gruntfile', gruntfileFixture, 'fail'],
    }, function(err, result, code) {
      test.notEqual(code, 0, 'should return error code on assertion failure');
      var outHasFail = /Fatal error: broken/.test(result.stdout);
      test.ok(outHasFail, 'stdout should contain output indicating failure.');
      test.done();
    });
  }
};

exports['grunt-mocha-hack'] = {
  // Show that we can spawn the grunt-mocha-hack and get success
  'can spawn properly': function(test) {
    test.expect(3);
    grunt.util.spawn({
      grunt: true,
      args: ['--gruntfile', gruntfileFixture, 'mocha-hack:one'],
    }, function(err, result, code) {
      console.log(result.stdout);
      test.ok(/# tests 3/.test(result.stdout), 'should have run 3 tests');
      test.ok(/# fail 0/.test(result.stdout), 'should have failed 0 tests');
      test.equal(code, 0, 'should have no error code');
      test.done();
    });
  },
  // Show that our errors do not cause mocha/grunt to quit abruptly.
  // Instead, we should get a complete and meaningful printout.
  'gets errors properly': function(test) {
    test.expect(3);
    grunt.util.spawn({
      grunt: true,
      args: ['--gruntfile', gruntfileFixture, 'mocha-hack:two'],
    }, function(err, result, code) {
      console.log(result.stdout);
      test.ok(/# tests 3/.test(result.stdout), 'should have run 3 tests');
      test.ok(/# fail 3/.test(result.stdout), 'should have failed 3 tests');
      test.equal(code, 3, 'should have error code - task failure');
      test.done();
    });
  }
  // TODO(gregp): test useColor flag?
};
<|endoftext|>


<commit_before>var should = require("should"),
    PhantomManager = require("../lib/phantomManager.js"),
    path = require("path");

describe("phantom workers", function () {

    var phantomManager;

    it("should be able to communicate with phantom", function (done) {
        phantomManager = new PhantomManager({
            pathToPhantomScript: path.join(__dirname, "test-script", "script.js"),
            numberOfWorkers: 1
        });
        phantomManager.start(function(err) {
            if (err)
                return done(err);

            phantomManager.execute({foo: "test"}, function (err, res) {
                if (err)
                    return done(err);

                res.should.have.property("foo");
                res.foo.should.be.eql("test");
                done();
            });
        });
    });

    it("should spin up specified number of workers", function (done) {
        phantomManager = new PhantomManager({
            pathToPhantomScript: path.join(__dirname, "test-script", "script.js"),
            numberOfWorkers: 5
        });
        phantomManager.start(function (err) {
            if (err)
                return done(err);

            phantomManager._phantomInstances.should.have.length(5);
            done();
        });
    });

    it("timeout should emit event", function (done) {
        phantomManager = new PhantomManager({
            pathToPhantomScript: path.join(__dirname, "test-script", "timeout.js"),
            numberOfWorkers: 1,
            timeout: 10
        });
        phantomManager.on("timeout", function (workerInstance) {
            done();
        });
        phantomManager.start(function (err) {
            if (err)
                return done(err);

            phantomManager.execute({}, function(err) {
                if (!err)
                    return done(new Error("Should not execute successfully"));
            });
        });

        setTimeout(function () {
            done(new Error("worker was not recycled"));
        }, 1000);
    });

    it("timeout should cb error", function (done) {
        phantomManager = new PhantomManager({
            pathToPhantomScript: path.join(__dirname, "test-script", "timeout.js"),
            numberOfWorkers: 1,
            timeout: 10
        });

        phantomManager.start(function (err) {
            if (err)
                return done(err);

            return phantomManager.execute({}, function (err, res) {
                if (!err)
                    return done(new Error("timeout should fail promise"));
                done();
            });
        });
    });
});<commit_msg>fix test for travise<commit_after>var should = require("should"),
    PhantomManager = require("../lib/phantomManager.js"),
    path = require("path");

describe("phantom workers", function () {

    var phantomManager;

    it("should be able to communicate with phantom", function (done) {
        phantomManager = new PhantomManager({
            pathToPhantomScript: path.join(__dirname, "test-script", "script.js"),
            numberOfWorkers: 1
        });
        phantomManager.start(function(err) {
            if (err)
                return done(err);

            phantomManager.execute({foo: "test"}, function (err, res) {
                if (err)
                    return done(err);

                res.should.have.property("foo");
                res.foo.should.be.eql("test");
                done();
            });
        });
    });

    it("should spin up specified number of workers", function (done) {
        phantomManager = new PhantomManager({
            pathToPhantomScript: path.join(__dirname, "test-script", "script.js"),
            numberOfWorkers: 5
        });
        phantomManager.start(function (err) {
            if (err)
                return done(err);

            phantomManager._phantomInstances.should.have.length(5);
            done();
        });
    });

    it("timeout should emit event", function (done) {
        phantomManager = new PhantomManager({
            pathToPhantomScript: path.join(__dirname, "test-script", "timeout.js"),
            numberOfWorkers: 1,
            timeout: 10
        });
        var emited = false;
        phantomManager.on("timeout", function (workerInstance) {
            emited = true;
            done();
        });
        phantomManager.start(function (err) {
            if (err)
                return done(err);

            phantomManager.execute({}, function(err) {
                if (!err)
                    return done(new Error("Should not execute successfully"));
            });
        });

        setTimeout(function () {
            if (!emited)
                done(new Error("worker was not recycled"));
        }, 1500);
    });

    it("timeout should cb error", function (done) {
        phantomManager = new PhantomManager({
            pathToPhantomScript: path.join(__dirname, "test-script", "timeout.js"),
            numberOfWorkers: 1,
            timeout: 10
        });

        phantomManager.start(function (err) {
            if (err)
                return done(err);

            return phantomManager.execute({}, function (err, res) {
                if (!err)
                    return done(new Error("timeout should fail promise"));
                done();
            });
        });
    });
});<|endoftext|>