<commit_before>'use strict';

var expect = require('chai').expect;
var Parser = require('../lib/parser');
var util   = require('../lib/util');

describe('AST',function () {
    var sql, parser = new Parser();

    function getParsedSql(sql) {
        var ast = parser.parse(sql);
        return util.astToSQL(ast);
    }

    describe('select statement', function () {
        it('should support MySQL query options', function () {
            sql = 'SELECT SQL_CALC_FOUND_ROWS SQL_BUFFER_RESULT col1 FROM t';
            expect(getParsedSql(sql)).to.equal(sql);
        });

        describe('expression', function () {
            it('should support asterisk', function () {
                sql = 'SELECT * FROM t';
                expect(getParsedSql(sql)).to.equal(sql);
            });

            it('should escape reserved keywords', function () {
                sql = 'SELECT col."select" FROM t';
                expect(getParsedSql(sql)).to.equal(sql);
            });

            it('should escape reserved keywords in aliases', function () {
                sql = 'SELECT col AS "index" FROM t';
                expect(getParsedSql(sql)).to.equal(sql);
            });

            it('should escape aliases with non-identifier chars (/a-z0-9_/i)', function () {
                sql = 'SELECT col AS \'foo bar\' FROM t';
                expect(getParsedSql(sql)).to.contain('col AS \'foo bar\'');
            });

            ["'", '"', 'n', 't', '\\'].forEach(function (char) {
                it('should escape char "' + char + '"', function () {
                    sql = "SELECT ' escape \\" + char + " '";
                    expect(getParsedSql(sql)).to.equal(sql);
                });
            });

            it('should support boolean values', function () {
                sql = 'SELECT false, true';
                expect(getParsedSql(sql)).to.equal('SELECT FALSE, TRUE');
            });

            it('should support string values', function () {
                sql = 'SELECT col1, \'foo\' AS bar';
                expect(getParsedSql(sql)).to.equal(sql);
            });

            it('should support null values', function () {
                sql = 'SELECT null';
                expect(getParsedSql(sql)).to.equal('SELECT NULL');
            });

            it('should support parentheses', function () {
                sql = 'SELECT (2 + 3) * 4';
                expect(getParsedSql(sql)).to.equal(sql);
            });

            it('should support functions', function () {
                sql = 'SELECT md5(\'foo\')';
                expect(getParsedSql(sql)).to.equal(sql);
            });

            it('should support aggregate functions', function () {
                sql = 'SELECT COUNT(distinct t.id) FROM t';
                expect(getParsedSql(sql)).to.equal('SELECT COUNT(DISTINCT t.id) FROM t');
            });

            it('should support unary operators', function () {
                sql = 'SELECT (not true), !t.foo as foo FROM t';
                expect(getParsedSql(sql)).to.equal('SELECT (NOT TRUE), NOT t.foo AS foo FROM t');
            });

            it('should support casts', function () {
                sql = 'SELECT CAST(col AS INTEGER) FROM t';
                expect(getParsedSql(sql)).to.equal(sql);
            });

            it('should support sub-selects', function () {
                sql = 'SELECT \'string\', (SELECT col FROM t2) subSelect FROM t1';
                expect(getParsedSql(sql)).to.equal('SELECT \'string\', (SELECT col FROM t2) AS subSelect FROM t1');
            });
        });

        describe('joins', function () {
            it('should support implicit joins', function () {
                sql = 'SELECT a , b.c FROM a ,b';
                expect(getParsedSql(sql)).to.equal('SELECT a, b.c FROM a, b');
            });

            it('should support (INNER) JOINs', function () {
                sql = 'SELECT a FROM t1 join t2 on t1.t2id = t2.t1id';
                expect(getParsedSql(sql)).to.equal('SELECT a FROM t1 INNER JOIN t2 ON t1.t2id = t2.t1id');
            });

            it('should support LEFT JOINs', function () {
                sql = 'SELECT a FROM t1 left join t2 on t1.t2id = t2.t1id';
                expect(getParsedSql(sql)).to.equal('SELECT a FROM t1 LEFT JOIN t2 ON t1.t2id = t2.t1id');
            });

            it('should support multiple joins', function () {
                sql = 'SELECT a FROM t1 LEFT JOIN t2 ON t1.t2id = t2.t1id INNER JOIN t3 ON t1.t3id = t3.t1id';
                expect(getParsedSql(sql)).to.equal(sql);
            });

            it('should support alias for base table', function () {
                sql = 'SELECT col1 FROM awesome_table t';
                expect(getParsedSql(sql)).to.equal('SELECT col1 FROM awesome_table AS t');
            });

            it('should support joins with tables from other databases', function () {
                sql = 'SELECT col1 FROM t JOIN otherdb.awesome_table at ON t.id = at.tid';
                expect(getParsedSql(sql)).to.equal('SELECT col1 FROM t INNER JOIN otherdb.awesome_table AS at ON t.id = at.tid');
            });

            it('should support aliases in joins', function () {
                sql = 'SELECT col1 FROM t1 LEFT JOIN awesome_table AS t2 ON t1.id = t2.t1id';
                expect(getParsedSql(sql)).to.equal(sql);
            });
        });

        describe('where clause', function () {
            ['<', '<=', '=', '!=', '>=', '>'].forEach(function (operator) {
                it('should support simple "' + operator + '" comparison', function () {
                    sql = 'SELECT a fRom db.t wHERE type ' + operator + ' 3';
                    expect(getParsedSql(sql)).to.equal('SELECT a FROM db.t WHERE type ' + operator + ' 3');
                });
            });

            var operatorMap = { '=': 'IN', '!=': 'NOT IN' };
            Object.keys(operatorMap).forEach(function (operator) {
                var astOperator = operatorMap[operator];

                it('should convert "' + operator + '" to ' + astOperator + ' operator for array values', function () {
                    var ast = {
                        type: 'select',
                        options: null,
                        distinct: null,
                        columns: [{ expr: { type: 'column_ref', table: null, column: 'a' }, as: null }],
                        from: [{ db: null, table: 't', as: null }],
                        where: {
                            type: 'binary_expr',
                            operator: operator,
                            left: { type: 'column_ref', table: null, column: 'id' },
                            right: {
                                type: 'expr_list',
                                value: [{ type: 'number', value: 1 }, { type: 'number', value: 2 }]
                            }
                        },
                        groupby: null,
                        limit: null
                    };

                    expect(util.astToSQL(ast)).to.equal('SELECT a FROM t WHERE id ' + astOperator + ' (1, 2)');
                });
            });

            ['IN', 'NOT IN'].forEach(function (operator) {
                it('should support ' + operator + ' operator', function () {
                    sql = 'SELECT a FROM t WHERE id ' + operator.toLowerCase() + ' (1, 2, 3)';
                    expect(getParsedSql(sql)).to.equal('SELECT a FROM t WHERE id ' + operator + ' (1, 2, 3)');
                });
            });

            it('should support BETWEEN operator', function () {
                sql = 'SELECT a FROM t WHERE id between \'1\' and 1337';
                expect(getParsedSql(sql)).to.equal('SELECT a FROM t WHERE id BETWEEN \'1\' AND 1337');
            });

            it('should support boolean values', function () {
                sql = 'SELECT col1 FROM t WHERE col2 = false';
                expect(getParsedSql(sql)).to.equal('SELECT col1 FROM t WHERE col2 = FALSE');
            });

            it('should support string values', function () {
                sql = 'SELECT col1 FROM t WHERE col2 = \'foobar\'';
                expect(getParsedSql(sql)).to.equal(sql);
            });

            it('should support null values', function () {
                sql = 'SELECT col1 FROM t WHERE col2 IS NULL';
                expect(getParsedSql(sql)).to.equal(sql);
            });

            it('should support array values', function () {
                sql = 'SELECT col1 FROM t WHERE col2 IN (1, 3, 5, 7)';
                expect(getParsedSql(sql)).to.equal(sql);
            });
        });

        describe('group clause', function () {
            it('should support single expressions', function () {
                sql = 'SELECT a FROM t group by t.b';
                expect(getParsedSql(sql)).to.equal('SELECT a FROM t GROUP BY t.b');
            });

            it('should support multiple expressions', function () {
                sql = 'SELECT a FROM t GROUP BY t.b, tc';
                expect(getParsedSql(sql)).to.equal(sql);
            });
        });

        describe('order clause', function () {
            it('should support implicit sort order', function () {
                sql = 'SELECT a FROM t order by id';
                expect(getParsedSql(sql)).to.equal('SELECT a FROM t ORDER BY id ASC');
            });

            it('should support explicit sort order', function () {
                sql = 'SELECT a FROM t order by id desc';
                expect(getParsedSql(sql)).to.equal('SELECT a FROM t ORDER BY id DESC');
            });

            it('should support multiple expressions', function () {
                sql = 'SELECT a FROM t order by id desc, name asc';
                expect(getParsedSql(sql)).to.equal('SELECT a FROM t ORDER BY id DESC, name ASC');
            });

            it('should support complex expressions', function () {
                sql = 'SELECT a FROM t ORDER BY rand() ASC';
                expect(getParsedSql(sql)).to.equal(sql);
            });
        });

        describe('limit clause', function () {
            it('should work w/o offset', function () {
                sql = 'SELECT a FROM t limit 10';
                expect(getParsedSql(sql)).to.equal('SELECT a FROM t LIMIT 0,10');
            });

            it('should work w/ offset', function () {
                sql = 'SELECT a FROM t limit 10, 10';
                expect(getParsedSql(sql)).to.equal('SELECT a FROM t LIMIT 10,10');
            });
        });

        describe('union operator', function () {
            it('should combine multiple statements', function () {
                sql = 'select 1 union select \'1\' union select a from t union (select true)';
                expect(getParsedSql(sql)).to.equal('SELECT 1 UNION SELECT \'1\' UNION SELECT a FROM t UNION SELECT TRUE');
            });
        });
    });

    describe('control flow', function () {
        describe('case operator', function () {
            it('should support case-when', function () {
                sql = 'select case when 1 then "one" when 2 then "two" END';
                expect(getParsedSql(sql)).to.equal('SELECT CASE WHEN 1 THEN \'one\' WHEN 2 THEN \'two\' END');
            });

            it('should support case-when-else', function () {
                sql = 'select case FUNC(a) when 1 then "one" when 2 then "two" else "more" END FROM t';
                expect(getParsedSql(sql)).to.equal('SELECT CASE FUNC(a) WHEN 1 THEN \'one\' WHEN 2 THEN \'two\' ELSE \'more\' END FROM t');
            });
        });

        describe('if function', function() {
            it('should support simple calls', function () {
                sql = 'SELECT IF(col1 = \'xyz\', \'foo\', \'bar\') FROM t';
                expect(getParsedSql(sql)).to.equal(sql);
            });
        });
    });

    describe('placeholder', function () {
        var ast;

        it('should replace single parameter', function () {
            ast = parser.parse('SELECT col FROM t WHERE id = :id');
            ast = util.replaceParams(ast, { id: 1 });

            expect(ast.where).to.eql({
                type: 'binary_expr',
                operator: '=',
                left: { type: 'column_ref', table: null, column: 'id' },
                right: { type: 'number', value: 1 }
            });
        });

        it('should replace multiple parameters', function () {
            ast = parser.parse('SELECT col FROM t WHERE id = :id AND type = :type');
            ast = util.replaceParams(ast, { id: 1, type: 'foobar' });

            expect(ast.where).to.eql({
                type: 'binary_expr',
                operator: 'AND',
                left: {
                    type: 'binary_expr',
                    operator: '=',
                    left: { type: 'column_ref', table: null, column: 'id' },
                    right: { type: 'number', value: 1 }
                },
                right: {
                    type: 'binary_expr',
                    operator: '=',
                    left: { type: 'column_ref', table: null, column: 'type' },
                    right: { type: 'string', value: 'foobar' }
                }
            });
        });

        it('should set parameter with string', function () {
            ast = parser.parse('SELECT col1 FROM t WHERE col2 = :name');
            ast = util.replaceParams(ast, { name: 'John Doe' });

            expect(ast.where).to.eql({
                type: 'binary_expr',
                operator: '=',
                left: { type: 'column_ref', table: null, column: 'col2' },
                right: { type: 'string', value: 'John Doe' }
            });
        });

        it('should set parameter with boolean value', function () {
            ast = parser.parse('SELECT col1 FROM t WHERE isMain = :main');
            ast = util.replaceParams(ast, { main: true });

            expect(ast.where).to.eql({
                type: 'binary_expr',
                operator: '=',
                left: { type: 'column_ref', table: null, column: 'isMain' },
                right: { type: 'bool', value: true }
            });
        });

        it('should set parameter with null value', function () {
            ast = parser.parse('SELECT col1 FROM t WHERE col2 = :param');
            ast = util.replaceParams(ast, { param: null });

            expect(ast.where).to.eql({
                type: 'binary_expr',
                operator: '=',
                left: { type: 'column_ref', table: null, column: 'col2' },
                right: { type: 'null', value: null }
            });
        });

        it('should set parameter with array as value', function () {
            ast = parser.parse('SELECT col1 FROM t WHERE id = :ids');
            ast = util.replaceParams(ast, { ids: [1, 3, 5, 7] });

            expect(ast.where).to.eql({
                type: 'binary_expr',
                operator: '=',
                left: { type: 'column_ref', table: null, column: 'id' },
                right: {
                    type: 'expr_list',
                    value: [
                        { type: 'number', value: 1 },
                        { type: 'number', value: 3 },
                        { type: 'number', value: 5 },
                        { type: 'number', value: 7 }
                    ]
                }
            });
        });

        it('should throw an exception if no value for parameter is available', function () {
            ast = parser.parse('SELECT col FROM t WHERE id = :id');

            expect(function () {
                util.replaceParams(ast, { foo: 'bar' });
            }).to.throw('no value for parameter :id found');
        });

        it('should return new AST object', function () {
            var resolvedParamAST;

            ast = parser.parse('SELECT col FROM t WHERE id = :id');
            resolvedParamAST = util.replaceParams(ast, { id: 1 });

            expect(ast).to.not.eql(resolvedParamAST);
        });
    });

    describe('unsupported statements', function () {
        var unsupportedStatements = {
            insert: 'INSERT INTO t (col1, col2) VALUES (1, 2)',
            update: 'UPDATE t SET col1 = 5 WHERE id = 1337'
        };

        Object.keys(unsupportedStatements).forEach(function (stmtType) {
            it('should throw exception for ' + stmtType + ' statements', function () {
                expect(function () {
                    getParsedSql(unsupportedStatements[stmtType]);
                }).to.throw(Error, 'Only SELECT statements supported at the moment');
            });
        });
    });
});
<commit_msg>Renamed variable<commit_after>'use strict';

var expect = require('chai').expect;
var Parser = require('../lib/parser');
var util   = require('../lib/util');

describe('AST',function () {
    var sql, parser = new Parser();

    function getParsedSql(sql) {
        var ast = parser.parse(sql);
        return util.astToSQL(ast);
    }

    describe('select statement', function () {
        it('should support MySQL query options', function () {
            sql = 'SELECT SQL_CALC_FOUND_ROWS SQL_BUFFER_RESULT col1 FROM t';
            expect(getParsedSql(sql)).to.equal(sql);
        });

        describe('expression', function () {
            it('should support asterisk', function () {
                sql = 'SELECT * FROM t';
                expect(getParsedSql(sql)).to.equal(sql);
            });

            it('should escape reserved keywords', function () {
                sql = 'SELECT col."select" FROM t';
                expect(getParsedSql(sql)).to.equal(sql);
            });

            it('should escape reserved keywords in aliases', function () {
                sql = 'SELECT col AS "index" FROM t';
                expect(getParsedSql(sql)).to.equal(sql);
            });

            it('should escape aliases with non-identifier chars (/a-z0-9_/i)', function () {
                sql = 'SELECT col AS \'foo bar\' FROM t';
                expect(getParsedSql(sql)).to.contain('col AS \'foo bar\'');
            });

            ["'", '"', 'n', 't', '\\'].forEach(function (char) {
                it('should escape char "' + char + '"', function () {
                    sql = "SELECT ' escape \\" + char + " '";
                    expect(getParsedSql(sql)).to.equal(sql);
                });
            });

            it('should support boolean values', function () {
                sql = 'SELECT false, true';
                expect(getParsedSql(sql)).to.equal('SELECT FALSE, TRUE');
            });

            it('should support string values', function () {
                sql = 'SELECT col1, \'foo\' AS bar';
                expect(getParsedSql(sql)).to.equal(sql);
            });

            it('should support null values', function () {
                sql = 'SELECT null';
                expect(getParsedSql(sql)).to.equal('SELECT NULL');
            });

            it('should support parentheses', function () {
                sql = 'SELECT (2 + 3) * 4';
                expect(getParsedSql(sql)).to.equal(sql);
            });

            it('should support functions', function () {
                sql = 'SELECT md5(\'foo\')';
                expect(getParsedSql(sql)).to.equal(sql);
            });

            it('should support aggregate functions', function () {
                sql = 'SELECT COUNT(distinct t.id) FROM t';
                expect(getParsedSql(sql)).to.equal('SELECT COUNT(DISTINCT t.id) FROM t');
            });

            it('should support unary operators', function () {
                sql = 'SELECT (not true), !t.foo as foo FROM t';
                expect(getParsedSql(sql)).to.equal('SELECT (NOT TRUE), NOT t.foo AS foo FROM t');
            });

            it('should support casts', function () {
                sql = 'SELECT CAST(col AS INTEGER) FROM t';
                expect(getParsedSql(sql)).to.equal(sql);
            });

            it('should support sub-selects', function () {
                sql = 'SELECT \'string\', (SELECT col FROM t2) subSelect FROM t1';
                expect(getParsedSql(sql)).to.equal('SELECT \'string\', (SELECT col FROM t2) AS subSelect FROM t1');
            });
        });

        describe('joins', function () {
            it('should support implicit joins', function () {
                sql = 'SELECT a , b.c FROM a ,b';
                expect(getParsedSql(sql)).to.equal('SELECT a, b.c FROM a, b');
            });

            it('should support (INNER) JOINs', function () {
                sql = 'SELECT a FROM t1 join t2 on t1.t2id = t2.t1id';
                expect(getParsedSql(sql)).to.equal('SELECT a FROM t1 INNER JOIN t2 ON t1.t2id = t2.t1id');
            });

            it('should support LEFT JOINs', function () {
                sql = 'SELECT a FROM t1 left join t2 on t1.t2id = t2.t1id';
                expect(getParsedSql(sql)).to.equal('SELECT a FROM t1 LEFT JOIN t2 ON t1.t2id = t2.t1id');
            });

            it('should support multiple joins', function () {
                sql = 'SELECT a FROM t1 LEFT JOIN t2 ON t1.t2id = t2.t1id INNER JOIN t3 ON t1.t3id = t3.t1id';
                expect(getParsedSql(sql)).to.equal(sql);
            });

            it('should support alias for base table', function () {
                sql = 'SELECT col1 FROM awesome_table t';
                expect(getParsedSql(sql)).to.equal('SELECT col1 FROM awesome_table AS t');
            });

            it('should support joins with tables from other databases', function () {
                sql = 'SELECT col1 FROM t JOIN otherdb.awesome_table at ON t.id = at.tid';
                expect(getParsedSql(sql)).to.equal('SELECT col1 FROM t INNER JOIN otherdb.awesome_table AS at ON t.id = at.tid');
            });

            it('should support aliases in joins', function () {
                sql = 'SELECT col1 FROM t1 LEFT JOIN awesome_table AS t2 ON t1.id = t2.t1id';
                expect(getParsedSql(sql)).to.equal(sql);
            });
        });

        describe('where clause', function () {
            ['<', '<=', '=', '!=', '>=', '>'].forEach(function (operator) {
                it('should support simple "' + operator + '" comparison', function () {
                    sql = 'SELECT a fRom db.t wHERE type ' + operator + ' 3';
                    expect(getParsedSql(sql)).to.equal('SELECT a FROM db.t WHERE type ' + operator + ' 3');
                });
            });

            var operatorMap = { '=': 'IN', '!=': 'NOT IN' };
            Object.keys(operatorMap).forEach(function (operator) {
                var sqlOperator = operatorMap[operator];

                it('should convert "' + operator + '" to ' + sqlOperator + ' operator for array values', function () {
                    var ast = {
                        type: 'select',
                        options: null,
                        distinct: null,
                        columns: [{ expr: { type: 'column_ref', table: null, column: 'a' }, as: null }],
                        from: [{ db: null, table: 't', as: null }],
                        where: {
                            type: 'binary_expr',
                            operator: operator,
                            left: { type: 'column_ref', table: null, column: 'id' },
                            right: {
                                type: 'expr_list',
                                value: [{ type: 'number', value: 1 }, { type: 'number', value: 2 }]
                            }
                        },
                        groupby: null,
                        limit: null
                    };

                    expect(util.astToSQL(ast)).to.equal('SELECT a FROM t WHERE id ' + sqlOperator + ' (1, 2)');
                });
            });

            ['IN', 'NOT IN'].forEach(function (operator) {
                it('should support ' + operator + ' operator', function () {
                    sql = 'SELECT a FROM t WHERE id ' + operator.toLowerCase() + ' (1, 2, 3)';
                    expect(getParsedSql(sql)).to.equal('SELECT a FROM t WHERE id ' + operator + ' (1, 2, 3)');
                });
            });

            it('should support BETWEEN operator', function () {
                sql = 'SELECT a FROM t WHERE id between \'1\' and 1337';
                expect(getParsedSql(sql)).to.equal('SELECT a FROM t WHERE id BETWEEN \'1\' AND 1337');
            });

            it('should support boolean values', function () {
                sql = 'SELECT col1 FROM t WHERE col2 = false';
                expect(getParsedSql(sql)).to.equal('SELECT col1 FROM t WHERE col2 = FALSE');
            });

            it('should support string values', function () {
                sql = 'SELECT col1 FROM t WHERE col2 = \'foobar\'';
                expect(getParsedSql(sql)).to.equal(sql);
            });

            it('should support null values', function () {
                sql = 'SELECT col1 FROM t WHERE col2 IS NULL';
                expect(getParsedSql(sql)).to.equal(sql);
            });

            it('should support array values', function () {
                sql = 'SELECT col1 FROM t WHERE col2 IN (1, 3, 5, 7)';
                expect(getParsedSql(sql)).to.equal(sql);
            });
        });

        describe('group clause', function () {
            it('should support single expressions', function () {
                sql = 'SELECT a FROM t group by t.b';
                expect(getParsedSql(sql)).to.equal('SELECT a FROM t GROUP BY t.b');
            });

            it('should support multiple expressions', function () {
                sql = 'SELECT a FROM t GROUP BY t.b, tc';
                expect(getParsedSql(sql)).to.equal(sql);
            });
        });

        describe('order clause', function () {
            it('should support implicit sort order', function () {
                sql = 'SELECT a FROM t order by id';
                expect(getParsedSql(sql)).to.equal('SELECT a FROM t ORDER BY id ASC');
            });

            it('should support explicit sort order', function () {
                sql = 'SELECT a FROM t order by id desc';
                expect(getParsedSql(sql)).to.equal('SELECT a FROM t ORDER BY id DESC');
            });

            it('should support multiple expressions', function () {
                sql = 'SELECT a FROM t order by id desc, name asc';
                expect(getParsedSql(sql)).to.equal('SELECT a FROM t ORDER BY id DESC, name ASC');
            });

            it('should support complex expressions', function () {
                sql = 'SELECT a FROM t ORDER BY rand() ASC';
                expect(getParsedSql(sql)).to.equal(sql);
            });
        });

        describe('limit clause', function () {
            it('should work w/o offset', function () {
                sql = 'SELECT a FROM t limit 10';
                expect(getParsedSql(sql)).to.equal('SELECT a FROM t LIMIT 0,10');
            });

            it('should work w/ offset', function () {
                sql = 'SELECT a FROM t limit 10, 10';
                expect(getParsedSql(sql)).to.equal('SELECT a FROM t LIMIT 10,10');
            });
        });

        describe('union operator', function () {
            it('should combine multiple statements', function () {
                sql = 'select 1 union select \'1\' union select a from t union (select true)';
                expect(getParsedSql(sql)).to.equal('SELECT 1 UNION SELECT \'1\' UNION SELECT a FROM t UNION SELECT TRUE');
            });
        });
    });

    describe('control flow', function () {
        describe('case operator', function () {
            it('should support case-when', function () {
                sql = 'select case when 1 then "one" when 2 then "two" END';
                expect(getParsedSql(sql)).to.equal('SELECT CASE WHEN 1 THEN \'one\' WHEN 2 THEN \'two\' END');
            });

            it('should support case-when-else', function () {
                sql = 'select case FUNC(a) when 1 then "one" when 2 then "two" else "more" END FROM t';
                expect(getParsedSql(sql)).to.equal('SELECT CASE FUNC(a) WHEN 1 THEN \'one\' WHEN 2 THEN \'two\' ELSE \'more\' END FROM t');
            });
        });

        describe('if function', function() {
            it('should support simple calls', function () {
                sql = 'SELECT IF(col1 = \'xyz\', \'foo\', \'bar\') FROM t';
                expect(getParsedSql(sql)).to.equal(sql);
            });
        });
    });

    describe('placeholder', function () {
        var ast;

        it('should replace single parameter', function () {
            ast = parser.parse('SELECT col FROM t WHERE id = :id');
            ast = util.replaceParams(ast, { id: 1 });

            expect(ast.where).to.eql({
                type: 'binary_expr',
                operator: '=',
                left: { type: 'column_ref', table: null, column: 'id' },
                right: { type: 'number', value: 1 }
            });
        });

        it('should replace multiple parameters', function () {
            ast = parser.parse('SELECT col FROM t WHERE id = :id AND type = :type');
            ast = util.replaceParams(ast, { id: 1, type: 'foobar' });

            expect(ast.where).to.eql({
                type: 'binary_expr',
                operator: 'AND',
                left: {
                    type: 'binary_expr',
                    operator: '=',
                    left: { type: 'column_ref', table: null, column: 'id' },
                    right: { type: 'number', value: 1 }
                },
                right: {
                    type: 'binary_expr',
                    operator: '=',
                    left: { type: 'column_ref', table: null, column: 'type' },
                    right: { type: 'string', value: 'foobar' }
                }
            });
        });

        it('should set parameter with string', function () {
            ast = parser.parse('SELECT col1 FROM t WHERE col2 = :name');
            ast = util.replaceParams(ast, { name: 'John Doe' });

            expect(ast.where).to.eql({
                type: 'binary_expr',
                operator: '=',
                left: { type: 'column_ref', table: null, column: 'col2' },
                right: { type: 'string', value: 'John Doe' }
            });
        });

        it('should set parameter with boolean value', function () {
            ast = parser.parse('SELECT col1 FROM t WHERE isMain = :main');
            ast = util.replaceParams(ast, { main: true });

            expect(ast.where).to.eql({
                type: 'binary_expr',
                operator: '=',
                left: { type: 'column_ref', table: null, column: 'isMain' },
                right: { type: 'bool', value: true }
            });
        });

        it('should set parameter with null value', function () {
            ast = parser.parse('SELECT col1 FROM t WHERE col2 = :param');
            ast = util.replaceParams(ast, { param: null });

            expect(ast.where).to.eql({
                type: 'binary_expr',
                operator: '=',
                left: { type: 'column_ref', table: null, column: 'col2' },
                right: { type: 'null', value: null }
            });
        });

        it('should set parameter with array as value', function () {
            ast = parser.parse('SELECT col1 FROM t WHERE id = :ids');
            ast = util.replaceParams(ast, { ids: [1, 3, 5, 7] });

            expect(ast.where).to.eql({
                type: 'binary_expr',
                operator: '=',
                left: { type: 'column_ref', table: null, column: 'id' },
                right: {
                    type: 'expr_list',
                    value: [
                        { type: 'number', value: 1 },
                        { type: 'number', value: 3 },
                        { type: 'number', value: 5 },
                        { type: 'number', value: 7 }
                    ]
                }
            });
        });

        it('should throw an exception if no value for parameter is available', function () {
            ast = parser.parse('SELECT col FROM t WHERE id = :id');

            expect(function () {
                util.replaceParams(ast, { foo: 'bar' });
            }).to.throw('no value for parameter :id found');
        });

        it('should return new AST object', function () {
            var resolvedParamAST;

            ast = parser.parse('SELECT col FROM t WHERE id = :id');
            resolvedParamAST = util.replaceParams(ast, { id: 1 });

            expect(ast).to.not.eql(resolvedParamAST);
        });
    });

    describe('unsupported statements', function () {
        var unsupportedStatements = {
            insert: 'INSERT INTO t (col1, col2) VALUES (1, 2)',
            update: 'UPDATE t SET col1 = 5 WHERE id = 1337'
        };

        Object.keys(unsupportedStatements).forEach(function (stmtType) {
            it('should throw exception for ' + stmtType + ' statements', function () {
                expect(function () {
                    getParsedSql(unsupportedStatements[stmtType]);
                }).to.throw(Error, 'Only SELECT statements supported at the moment');
            });
        });
    });
});
<|endoftext|>


<commit_before>// GET /chat/{id}

TEST("The response has valid return code and content type.", function(Query) {

    var db = Query.mkdb();
    var auth = Query.auth(db);
    var id = Query.post(["db/",db,"/chat"],{},auth).id();
    return Query.get(["db/",db,"/chat/",id],auth)
	.assertStatus(200).assertIsJson();
});

TEST("Returns correct data as admin.", function(Query) {

    var created = {
	subject: "Hello, world!",
	custom: { a: true },
	audience: { admin: "anyone" }
    };

    var db = Query.mkdb();
    var auth = Query.auth(db);
    var id = Query.post(["db/",db,"/chat"],created,auth).id();
    return Query.get(["db/",db,"/chat/",id],auth).then(function(value) {

	var expected = $.extend({
	    id: id,
	    count: 0,
	    access: [ "admin", "view" ]
	}, created);

	delete value.last;

	return Assert.areEqual(expected, value);

    });

});

TODO("Returns correct subject.", function(next) {
    Assert.fail();
});

TODO("Returns 404 when database does not exist.", function(next) {
    Assert.fail();
});

TODO("Returns 404 when chatroom does not exist.", function(next) {
    Assert.fail();
});

TODO("Returns 401 when token is not valid.", function(next) {
    Assert.fail();
});

<commit_msg>Passing test on chatrooms<commit_after>// GET /chat/{id}

TEST("The response has valid return code and content type.", function(Query) {

    var db = Query.mkdb();
    var auth = Query.auth(db);
    var id = Query.post(["db/",db,"/chat"],{},auth).id();
    return Query.get(["db/",db,"/chat/",id],auth)
	.assertStatus(200).assertIsJson();
});

TEST("Returns correct data as admin.", function(Query) {

    var created = {
	subject: "Hello, world!",
	custom: { a: true },
	audience: { admin: "anyone" }
    };

    var db = Query.mkdb();
    var auth = Query.auth(db);
    var id = Query.post(["db/",db,"/chat"],created,auth).id();
    return Query.get(["db/",db,"/chat/",id],auth).then(function(value) {

	var expected = $.extend({
	    id: id,
	    count: 0,
	    access: [ "view","read","admin","moderate","write" ]
	}, created);

	delete value.info.last;

	return Assert.areEqual(expected, value.info);

    });

});

TODO("Returns correct subject.", function(next) {
    Assert.fail();
});

TODO("Returns 404 when database does not exist.", function(next) {
    Assert.fail();
});

TODO("Returns 404 when chatroom does not exist.", function(next) {
    Assert.fail();
});

TODO("Returns 401 when token is not valid.", function(next) {
    Assert.fail();
});

<|endoftext|>


<commit_before>/* jshint expr:true */
/* jshint loopfunc:true */
var chai = require('chai');
var rewire = require('rewire');

var cinnamon = rewire('../lib/cinnamon');

var expect = chai.expect;
var msg = {
    chat: {
        id: 1,
        username: 'cinnabot_is_cool',
        first_name: 'Mr',
        last_name: 'User'
    },
    from: {
        id: 1,
        username: 'cinnabot_is_cool',
        first_name: 'Mr',
        last_name: 'User'
    },
    text: '/cancel'
};

describe('cinnamon', function() {
    'use strict';
    this.slow(5000);

    var spaceIds = {1: 'Theme Room 1', 2: 'Theme Room 2', 3: 'CTPH', 4: 'Amphitheatre', 6: 'Chatterbox'};
    for (let spaceId in spaceIds) {
        let id = parseInt(spaceId);
        let name = spaceIds[spaceId];
        it('should return spaces information for ' + name, function(done) {
            cinnamon.getSpaces(id, function(msg) {
                expect(msg.startsWith(name)).to.be.true;
                done();
            });
        });
    }
});
<commit_msg>increase timeout value for cinnamon spaces tests<commit_after>/* jshint expr:true */
/* jshint loopfunc:true */
var chai = require('chai');
var rewire = require('rewire');

var cinnamon = rewire('../lib/cinnamon');

var expect = chai.expect;
var msg = {
    chat: {
        id: 1,
        username: 'cinnabot_is_cool',
        first_name: 'Mr',
        last_name: 'User'
    },
    from: {
        id: 1,
        username: 'cinnabot_is_cool',
        first_name: 'Mr',
        last_name: 'User'
    },
    text: '/cancel'
};

describe('cinnamon', function() {
    'use strict';
    this.slow(5000);
    this.timeout(10000);

    var spaceIds = {1: 'Theme Room 1', 2: 'Theme Room 2', 3: 'CTPH', 4: 'Amphitheatre', 6: 'Chatterbox'};
    for (let spaceId in spaceIds) {
        let id = parseInt(spaceId);
        let name = spaceIds[spaceId];
        it('should return spaces information for ' + name, function(done) {
            cinnamon.getSpaces(id, function(msg) {
                expect(msg.startsWith(name)).to.be.true;
                done();
            });
        });
    }
});
<|endoftext|>


<commit_before>var child_process = require('child_process'),
    path = require('path'),
    cli_path = path.resolve(path.join(__dirname, '../bin/cli.js'));

function attachConsole(child) {
    child.stdout.on('data', function(data) {
        console.log('stdout: ' + data);
    });

    child.stderr.on('data', function(data) {
        console.log('stderr: ' + data);
    });
}

module.exports = {
    'test skip' : function(beforeExit, assert) {
        var test_dir = path.resolve(path.join(__dirname, './fixtures/skip'));

        var ybuild = child_process.spawn('node', [cli_path, '.'], { cwd: test_dir, env: process.env });
        attachConsole(ybuild);

        ybuild.on('exit', function (code) {
            beforeExit(function() {
                assert.equal(1, code, 'exit status was ok (' + code + ')');
            })
        });
    }
}<commit_msg>Debugging cli unit tests.<commit_after>var child_process = require('child_process'),
    path = require('path'),
    fs = require('fs'),
    cli_path = path.resolve(path.join(__dirname, '../bin/cli.js'));

function attachConsole(child) {
    child.stdout.on('data', function(data) {
        console.log('stdout: ' + data);
    });

    child.stderr.on('data', function(data) {
        console.log('stderr: ' + data);
    });
}

module.exports = {
    'test write task is skipped by skip feature' : function(beforeExit, assert) {
        var test_dir = path.resolve(path.join(__dirname, './fixtures/test_skip')),
            build_dir = path.resolve(path.join(__dirname, './fixtures/build'));

        var ybuild = child_process.spawn('node', [cli_path, '.'], { cwd: test_dir, env: process.env });
        attachConsole(ybuild);

        ybuild.on('exit', function (code) {
            beforeExit(function() {
                assert.equal(0, code, 'exit status was ok (' + code + ')');
                assert.ok(!path.existsSync(path.join(build_dir, '/component.js')), build_dir + '/component.js should not exist');
                assert.ok(!path.existsSync(path.join(build_dir, '/component-min.js')), build_dir + '/component-min.js should not exist');
                assert.ok(!path.existsSync(path.join(build_dir, '/component-debug.js')), build_dir + '/component-debug.js should not exist');
            });
        });
    }
}<|endoftext|>


<commit_before>/**
 * Created by nuintun on 2015/4/29.
 */

'use strict';

function parseDependencies(s, replace, includeAsync){
  if (replace === true) {
    includeAsync = true;
    replace = null;
  }

  if (s.indexOf('require') === -1) {
    return replace ? s : [];
  }

  var index = 0, peek = '', length = s.length, isReg = 1, modName = 0, res = [];
  var parentheseState = 0, parentheseStack = [];
  var braceState, braceStack = [], isReturn;
  var last;
  var flag;

  while (index < length) {
    readch();

    if (isBlank()) {
      if (isReturn && (peek === '\n' || peek === '\r')) {
        braceState = 0;
        isReturn = 0;
      }
    } else if (isQuote()) {
      dealQuote();

      isReg = 1;
      isReturn = 0;
      braceState = 0;
    } else if (peek === '/') {
      readch();

      if (peek === '/') {
        index = s.indexOf('\n', index);

        if (index === -1) {
          index = s.length;
        }
      } else if (peek === '*') {
        var i = s.indexOf('\n', index);
        index = s.indexOf('*/', index);

        if (index === -1) {
          index = length;
        } else {
          index += 2;
        }

        if (isReturn && i != -1 && i < index) {
          braceState = 0;
          isReturn = 0;
        }
      } else if (isReg) {
        dealReg();

        isReg = 0;
        isReturn = 0;
        braceState = 0;
      } else {
        index--;
        isReg = 1;
        isReturn = 0;
        braceState = 1;
      }
    } else if (isWord()) {
      dealWord();
    } else if (isNumber()) {
      dealNumber();

      isReturn = 0;
      braceState = 0;
    } else if (peek === '(') {
      parentheseStack.push(parentheseState);

      isReg = 1;
      isReturn = 0;
      braceState = 1;
    } else if (peek === ')') {
      isReg = parentheseStack.pop();
      isReturn = 0;
      braceState = 0;
    } else if (peek === '{') {
      if (isReturn) {
        braceState = 1;
      }

      braceStack.push(braceState);

      isReturn = 0;
      isReg = 1;
    } else if (peek === '}') {
      braceState = braceStack.pop();

      isReg = !braceState;
      isReturn = 0;
    } else {
      var next = s.charAt(index);

      if (peek === ';') {
        braceState = 0;
      } else if (peek === '-' && next === '-' || peek === '+' && next === '+' || peek === '=' && next === '>') {
        braceState = 0;
        index++;
      } else {
        braceState = 1;
      }

      isReg = peek != ']';
      isReturn = 0;
    }
  }

  return replace ? s : res;

  function readch(){
    peek = s.charAt(index++);
  }

  function isBlank(){
    return /\s/.test(peek);
  }

  function isQuote(){
    return peek === '"' || peek === "'";
  }

  function dealQuote(){
    var start = index;
    var c = peek;
    var end = s.indexOf(c, start);

    if (end === -1) {
      index = length;
    } else if (s.charAt(end - 1) != '\\') {
      index = end + 1;
    } else {
      while (index < length) {
        readch();

        if (peek === '\\') {
          index++;
        } else if (peek === c) {
          break;
        }
      }
    }

    if (modName) {
      var d = {
        'string': s.slice(last, s.indexOf(')', index) + 1),
        'path': s.slice(start, index - 1),
        'index': last,
        'flag': flag
      };

      res.push(d);

      if (replace) {
        var rep = replace(d);
        s = s.slice(0, last) + rep + s.slice(last + d.string.length);

        if (rep.length != d.string.length) {
          index = last + rep.length;
          length = s.length;
        }
      }

      modName = 0;
    }
  }

  function dealReg(){
    index--;

    while (index < length) {
      readch();

      if (peek === '\\') {
        index++;
      } else if (peek === '/') {
        break;
      } else if (peek === '[') {
        while (index < length) {
          readch();

          if (peek === '\\') {
            index++;
          } else if (peek === ']') {
            break;
          }
        }
      }
    }
  }

  function isWord(){
    return /[a-z_$]/i.test(peek);
  }

  function dealWord(){
    var s2 = s.slice(index - 1);
    var r = /^[\w$]+/.exec(s2)[0];

    parentheseState = {
      'if': 1,
      'for': 1,
      'while': 1,
      'with': 1
    }[r];
    isReg = {
      'break': 1,
      'case': 1,
      'continue': 1,
      'debugger': 1,
      'delete': 1,
      'do': 1,
      'else': 1,
      'false': 1,
      'if': 1,
      'in': 1,
      'instanceof': 1,
      'return': 1,
      'typeof': 1,
      'void': 1
    }[r];
    isReturn = r === 'return';
    braceState = {
      'instanceof': 1,
      'delete': 1,
      'void': 1,
      'typeof': 1,
      'return': 1
    }.hasOwnProperty(r);

    if (r === 'require') {
      modName = includeAsync
        ? /^require\s*(?:(?:\.[a-zA-Z_$][a-zA-Z0-9_$]*)|(?:\[\s*(['"]).*?\1\s*\]))?\s*\(\s*(?:(?:(['"]).+?\2)|\[.*?\])\s*[),]/.test(s2)
        : /^require\s*\(\s*(['"]).+?\1\s*[),]/.test(s2);
    } else {
      modName = false;
    }

    if (modName) {
      last = index - 1;
      r = includeAsync ?
        /^require\s*(?:(?:\.[a-zA-Z_$][a-zA-Z0-9_$]*)|(?:\[\s*(['"]).*?\1\s*\]))?\s*\(\s*(?:['"]|\[)/.exec(s2)[0]
        : /^require\s*\(\s*['"]/.exec(s2)[0];
      index += r.length - 2;
      flag = /^require\s*(?:(?:\.([a-zA-Z_$][a-zA-Z0-9_$]*))|(?:\[\s*(['"])(.*)?\2\s*\]))/.exec(s2);
      flag = flag ? flag[1] || flag[3] : null;
    } else {
      index += /^[\w$]+(?:\s*\.\s*[\w$]+)*/.exec(s2)[0].length - 1;
    }
  }

  function isNumber(){
    return /\d/.test(peek) || peek === '.' && /\d/.test(s.charAt(index));
  }

  function dealNumber(){
    var s2 = s.slice(index - 1);
    var r;

    if (peek === '.') {
      r = /^\.\d+(?:E[+-]?\d*)?\s*/i.exec(s2)[0];
    } else if (/^0x[\da-f]*/i.test(s2)) {
      r = /^0x[\da-f]*\s*/i.exec(s2)[0];
    } else {
      r = /^\d+\.?\d*(?:E[+-]?\d*)?\s*/i.exec(s2)[0];
    }

    index += r.length - 1;
    isReg = 0;
  }
}

module.exports = parseDependencies;<commit_msg>add source files<commit_after>/**
 * Created by nuintun on 2015/4/29.
 */

'use strict';

function parseDependencies(s, replace, includeAsync){
  if (replace === true) {
    includeAsync = true;
    replace = null;
  }

  if (s.indexOf('require') === -1) {
    return replace ? s : [];
  }

  var index = 0, peek = '', length = s.length, isReg = 1, modName = 0, res = [];
  var parentheseState = 0, parentheseStack = [];
  var braceState, braceStack = [], isReturn;
  var last;
  var flag;

  while (index < length) {
    readch();

    if (isBlank()) {
      if (isReturn && (peek === '\n' || peek === '\r')) {
        braceState = 0;
        isReturn = 0;
      }
    } else if (isQuote()) {
      dealQuote();

      isReg = 1;
      isReturn = 0;
      braceState = 0;
    } else if (peek === '/') {
      readch();

      if (peek === '/') {
        index = s.indexOf('\n', index);

        if (index === -1) {
          index = s.length;
        }
      } else if (peek === '*') {
        var i = s.indexOf('\n', index);
        index = s.indexOf('*/', index);

        if (index === -1) {
          index = length;
        } else {
          index += 2;
        }

        if (isReturn && i != -1 && i < index) {
          braceState = 0;
          isReturn = 0;
        }
      } else if (isReg) {
        dealReg();

        isReg = 0;
        isReturn = 0;
        braceState = 0;
      } else {
        index--;
        isReg = 1;
        isReturn = 0;
        braceState = 1;
      }
    } else if (isWord()) {
      dealWord();
    } else if (isNumber()) {
      dealNumber();

      isReturn = 0;
      braceState = 0;
    } else if (peek === '(') {
      parentheseStack.push(parentheseState);

      isReg = 1;
      isReturn = 0;
      braceState = 1;
    } else if (peek === ')') {
      isReg = parentheseStack.pop();
      isReturn = 0;
      braceState = 0;
    } else if (peek === '{') {
      if (isReturn) {
        braceState = 1;
      }

      braceStack.push(braceState);

      isReturn = 0;
      isReg = 1;
    } else if (peek === '}') {
      braceState = braceStack.pop();

      isReg = !braceState;
      isReturn = 0;
    } else {
      var next = s.charAt(index);

      if (peek === ';') {
        braceState = 0;
      } else if (peek === '-' && next === '-' || peek === '+' && next === '+' || peek === '=' && next === '>') {
        braceState = 0;
        index++;
      } else {
        braceState = 1;
      }

      isReg = peek != ']';
      isReturn = 0;
    }
  }

  return replace ? s : res;

  function readch(){
    peek = s.charAt(index++);
  }

  function isBlank(){
    return /\s/.test(peek);
  }

  function isQuote(){
    return peek === '"' || peek === "'";
  }

  function dealQuote(){
    var start = index;
    var c = peek;
    var end = s.indexOf(c, start);

    if (end === -1) {
      index = length;
    } else if (s.charAt(end - 1) != '\\') {
      index = end + 1;
    } else {
      while (index < length) {
        readch();

        if (peek === '\\') {
          index++;
        } else if (peek === c) {
          break;
        }
      }
    }

    if (modName) {
      var d = {
        'string': s.slice(last, s.indexOf(')', index) + 1),
        'path': s.slice(start, index - 1),
        'index': last,
        'flag': flag
      };

      res.push(d);

      if (replace) {
        var rep = replace(d);
        s = s.slice(0, last) + rep + s.slice(last + d.string.length);

        if (rep.length != d.string.length) {
          index = last + rep.length;
          length = s.length;
        }
      }

      modName = 0;
    }
  }

  function dealReg(){
    index--;

    while (index < length) {
      readch();

      if (peek === '\\') {
        index++;
      } else if (peek === '/') {
        break;
      } else if (peek === '[') {
        while (index < length) {
          readch();

          if (peek === '\\') {
            index++;
          } else if (peek === ']') {
            break;
          }
        }
      }
    }
  }

  function isWord(){
    return /[a-z_$]/i.test(peek);
  }

  function dealWord(){
    var s2 = s.slice(index - 1);
    var r = /^[\w$]+/.exec(s2)[0];

    parentheseState = {
      'if': 1,
      'for': 1,
      'while': 1,
      'with': 1
    }[r];
    isReg = {
      'break': 1,
      'case': 1,
      'continue': 1,
      'debugger': 1,
      'delete': 1,
      'do': 1,
      'else': 1,
      'false': 1,
      'if': 1,
      'in': 1,
      'instanceof': 1,
      'return': 1,
      'typeof': 1,
      'void': 1
    }[r];
    isReturn = r === 'return';
    braceState = {
      'instanceof': 1,
      'delete': 1,
      'void': 1,
      'typeof': 1,
      'return': 1
    }.hasOwnProperty(r);

    if (r === 'require') {
      modName = includeAsync
        ? /^require\s*(?:(?:\.[a-zA-Z_$][a-zA-Z0-9_$]*)|(?:\[\s*(['"]).*?\1\s*\]))?\s*\(\s*(?:(?:(['"]).+?\2)|\[.*?\])\s*[),]/.test(s2)
        : /^require\s*\(\s*(['"]).+?\1\s*[),]/.test(s2);
    } else {
      modName = 0;
    }

    if (modName) {
      last = index - 1;
      r = includeAsync ?
        /^require\s*(?:(?:\.[a-zA-Z_$][a-zA-Z0-9_$]*)|(?:\[\s*(['"]).*?\1\s*\]))?\s*\(\s*(?:['"]|\[)/.exec(s2)[0]
        : /^require\s*\(\s*['"]/.exec(s2)[0];
      index += r.length - 2;
      flag = /^require\s*(?:(?:\.([a-zA-Z_$][a-zA-Z0-9_$]*))|(?:\[\s*(['"])(.*)?\2\s*\]))/.exec(s2);
      flag = flag ? flag[1] || flag[3] : null;
    } else {
      index += /^[\w$]+(?:\s*\.\s*[\w$]+)*/.exec(s2)[0].length - 1;
    }
  }

  function isNumber(){
    return /\d/.test(peek) || peek === '.' && /\d/.test(s.charAt(index));
  }

  function dealNumber(){
    var s2 = s.slice(index - 1);
    var r;

    if (peek === '.') {
      r = /^\.\d+(?:E[+-]?\d*)?\s*/i.exec(s2)[0];
    } else if (/^0x[\da-f]*/i.test(s2)) {
      r = /^0x[\da-f]*\s*/i.exec(s2)[0];
    } else {
      r = /^\d+\.?\d*(?:E[+-]?\d*)?\s*/i.exec(s2)[0];
    }

    index += r.length - 1;
    isReg = 0;
  }
}

module.exports = parseDependencies;<|endoftext|>


<commit_before>var expect = expect || require('expect.js'),
    endianness = this.Enum ? 'LE' : require('os').endianness(),
    e = this.Enum || require('../index');

describe('Enum', function() {

  if (typeof(module) !== 'undefined' && module.exports) {
    describe('calling register', function() {

      it('it should register Enum on global namespace', function() {

        expect(global.Enum).not.to.be.ok();
        e.register();
        expect(Enum).to.be.ok();

      });

    });
  }

  describe('defining an enum', function() {

    var myEnum;

    describe('in a simple or complex way', function() {

      it('it should be tha same', function() {

        myEnum = new e(['A', 'B', 'C']);

        var myEnum2 = new e({'A': 1, 'B': 2, 'C': 4});

        expect(myEnum.A).to.eql(myEnum2.A);
        expect(myEnum.C).to.eql(myEnum2.C);

        expect(myEnum.A.value).to.eql(myEnum2.A.value);
        expect(myEnum.C.value).to.eql(myEnum2.C.value);

      });

      describe('it should be possible to', function() {

        it('get an enum item', function() {

          expect(myEnum.A).to.have.property('value', 1);
          expect(myEnum.A).to.have.property('key', 'A');

          expect(myEnum.C).to.have.property('value', 4);
          expect(myEnum.C).to.have.property('key', 'C');

        });

        it('get all enum values', function() {

          expect(myEnum.enums).to.be.an('array');
          expect(myEnum.enums).to.have.length(3);
          expect(myEnum.enums).to.contain(myEnum.A);
          expect(myEnum.enums).to.contain(myEnum.B);
          expect(myEnum.enums).to.contain(myEnum.C);

        });

        describe('call has', function() {

          describe('on a flagged enum item', function() {

            var myItem;

            before(function() {
              myItem = myEnum.get(3);
              expect(myEnum.get('A | B').value).to.eql(myItem.value);
            });

            it('with another item', function() {

              expect(myItem.has(myEnum.B)).to.be.ok();
              expect(myItem.has(myEnum.C)).not.to.be.ok();

            });

            it('with another key', function() {

              expect(myItem.has('B')).to.be.ok();
              expect(myItem.has('C')).not.to.be.ok();

            });

            it('with another value', function() {

              expect(myItem.has(2)).to.be.ok();
              expect(myItem.has(4)).not.to.be.ok();

            });

          });

        });

        describe('compare', function() {

          describe('an item and an item', function() {

            it('with is', function() {

              expect(myEnum.A.is(myEnum.A)).to.be.ok();
              expect(myEnum.C.is(myEnum.C)).to.be.ok();

            });

            it('with has', function() {

              expect(myEnum.A.has(myEnum.A)).to.be.ok();
              expect(myEnum.C.has(myEnum.C)).to.be.ok();

            });

            it('with ==', function() {

              expect(myEnum.A == myEnum.A).to.be.ok();
              expect(myEnum.C == myEnum.C).to.be.ok();

            });

            it('with ===', function() {

              expect(myEnum.A === myEnum.A).to.be.ok();
              expect(myEnum.C === myEnum.C).to.be.ok();

            });

          });

          describe('an item and a key', function() {

            it('with is', function() {

              expect(myEnum.A.is('A')).to.be.ok();
              expect(myEnum.C.is('C')).to.be.ok();

            });

            it('with has', function() {

              expect(myEnum.A.has('A')).to.be.ok();
              expect(myEnum.C.has('C')).to.be.ok();

            });

            it('with ==', function() {

              expect(myEnum.A == myEnum.A.value).to.be.ok();
              expect(myEnum.C == myEnum.C.value).to.be.ok();

            });

          });

          describe('an item and a value', function() {

            it('with is', function() {

              expect(myEnum.A.is(1)).to.be.ok();
              expect(myEnum.C.is(4)).to.be.ok();

            });

            it('with has', function() {

              expect(myEnum.A.has(1)).to.be.ok();
              expect(myEnum.C.has(4)).to.be.ok();

            });

          });

        });

        describe('call get and get', function() {

          it('an enum item by item', function() {

            expect(myEnum.get(myEnum.A)).to.have.property('value', 1);
            expect(myEnum.get(myEnum.A)).to.have.property('key', 'A');

            expect(myEnum.get(myEnum.C)).to.have.property('value', 4);
            expect(myEnum.get(myEnum.C)).to.have.property('key', 'C');

          });

          it('an enum item by flagged item', function() {

            var item = myEnum.get('A | B');

            expect(myEnum.get(item)).to.have.property('value', 3);
            expect(myEnum.get(item)).to.have.property('key', 'A | B');

          });

          it('an enum item by value', function() {

            expect(myEnum.get('A')).to.have.property('value', 1);
            expect(myEnum.get('A')).to.have.property('key', 'A');

            expect(myEnum.get('C')).to.have.property('value', 4);
            expect(myEnum.get('C')).to.have.property('key', 'C');

          });

          it('an enum item by key', function() {

            expect(myEnum.get(1)).to.have.property('value', 1);
            expect(myEnum.get(1)).to.have.property('key', 'A');

            expect(myEnum.get(4)).to.have.property('value', 4);
            expect(myEnum.get(4)).to.have.property('key', 'C');

          });

        });

        describe('call get with null and get', function() {

          it('null', function() {

            expect(myEnum.get(null)).to.eql(null);

          });

        });

        describe('call get with undefined and get', function() {

          it('null', function() {

            expect(myEnum.get(undefined)).to.eql(null);

          });

        });

        describe('call getValue and get', function() {

          it('an enum value by item', function() {

            expect(myEnum.getValue(myEnum.A)).to.eql(1);

            expect(myEnum.getValue(myEnum.C)).to.eql(4);

          });

          it('an enum value by key', function() {

            expect(myEnum.getValue('A')).to.eql(1);

            expect(myEnum.getValue('C')).to.eql(4);

          });

          it('an enum value by value', function() {

            expect(myEnum.getValue(1)).to.eql(1);

            expect(myEnum.getValue(4)).to.eql(4);

          });

        });

        describe('call getKey and get', function() {

          it('an enum key by item', function() {

            expect(myEnum.getKey(myEnum.A)).to.eql('A');

            expect(myEnum.getKey(myEnum.C)).to.eql('C');

          });

          it('an enum value by key', function() {

            expect(myEnum.getKey('A')).to.eql('A');

            expect(myEnum.getKey('C')).to.eql('C');

          });

          it('an enum value by value', function() {

            expect(myEnum.getKey(1)).to.eql('A');

            expect(myEnum.getKey(4)).to.eql('C');

          });

        });

      });

      describe('on an enum item it should be possible to', function() {

        it('call toString and get the key', function() {

          expect(myEnum.A.toString()).to.eql('A');

        });

        it('call toJSON and get the key', function() {

          expect(myEnum.A.toJSON()).to.eql('A');

        });

        it('call valueOf and get the value', function() {

          expect(myEnum.A.valueOf()).to.eql(myEnum.A.value);

        });

        it('use JavaScript | operator', function() {

          expect(myEnum.A | myEnum.B).to.eql(myEnum.getValue('A | B'));

          expect(myEnum.A | myEnum.C).to.eql(myEnum.getValue('A | C'));

          expect(myEnum.A | myEnum.B | myEnum.C).to.eql(myEnum.getValue('A | B | C'));

        });

        it('stringify JSON', function() {

          expect(JSON.stringify(myEnum.A)).to.eql('"A"');

        });

      });

    });

    describe('on an enum object', function(){

      var myEnum;

      before(function(){
        myEnum = new e({'A':1, 'B':2, 'C':4});
      });

      it('can not extend after creation', function() {

        var extendMyEnum = Object.isExtensible(myEnum);
        expect(extendMyEnum).to.be(false);

       });

      it('does not accept changes to existing property values, throws', function() {

        expect(myEnum).to.have.property('C');
        expect(function() {
          myEnum['C'] = 3;
        }).to.throwError("The value can not be set; Enum Type is not extensible.");
        expect(function() {
          Object.defineProperty(myEnum, 'C', {value: 3, writable:true, configurable: true});
        }).to.throwError();
        expect(myEnum.get('C')).to.have.property('value', 4);
        expect(myEnum).to.equal(myEnum);

      });

      it('can not define new properties, throws', function() {

        expect(function() {
          Object.defineProperty(myEnum, 'D', {writable: true, enumerable:true});
        }).to.throwError();
        expect(myEnum.D).to.be(undefined);
        expect(myEnum).not.to.have.property('D');
        expect(myEnum).to.equal(myEnum);

      });

      it('is persistent to deletes', function() {

        var deleteEnumItem = delete myEnum['A'];
        expect(deleteEnumItem).to.be(false);
        expect(myEnum).to.have.property('A');
        expect(myEnum.get('A')).to.have.property('value', 1);
        expect(myEnum).to.equal(myEnum);

      });

      it('creates unique identity for each property', function() {

        var myEnum1 = new e({'A':1, 'B':2, 'C':4});
        var myEnum2 = new e({'A':1, 'B':2, 'C':4});
        expect(myEnum1.A).not.to.equal(myEnum2.A);
        expect(myEnum1.B).not.to.equal(myEnum2.B);
        expect(myEnum1.C).not.to.equal(myEnum2.C);
        expect(myEnum1).not.to.equal(myEnum2);

      });

      it('respects the order of properties for equality', function() {

        var m1 = Object.keys(myEnum);
        var m2 = Object.keys(myEnum).reverse();
        expect(m1).not.to.equal(m2);

      });

    });

    describe('beeing flagged', function() {

      var myFlaggedEnum;

      before(function() {
        myFlaggedEnum = new e({'A': 1, 'B': 2, 'C': 4});
      });

      it('it should get the flagged value', function() {

        expect(myFlaggedEnum.get(1)).to.be(myFlaggedEnum.A);
        expect(myFlaggedEnum.get(2)).to.be(myFlaggedEnum.B);
        expect(myFlaggedEnum.get(3).is('A | B')).to.be(true);

      });

    });

    describe('not beeing flagged', function() {

      var myNonFlaggedEnum;

      before(function() {
        myNonFlaggedEnum = new e({'0': 0, 'A': 1, 'B': 2, 'B2': 3, 'C': 4});
      });

      it('it should not get the flagged value', function() {

        expect(myNonFlaggedEnum.get(1).is(myNonFlaggedEnum.A));
        expect(myNonFlaggedEnum.get(2).is(myNonFlaggedEnum.B));
        expect(myNonFlaggedEnum.get(3).is(myNonFlaggedEnum.B2));

      });

      describe('getting a non matching value', function() {

        it('it should return undefined', function() {

          expect(myNonFlaggedEnum.get(5)).to.not.be.ok();

        });

      });

      describe('call get with an non valid value and get', function() {

        it('null', function() {

          expect(myNonFlaggedEnum.get(12345)).to.eql(null);

        });

      });

      describe('call get with 0 and get', function() {

        it('null', function() {

          expect(myNonFlaggedEnum.get(0)).to.not.eql(null);

        });

      });

    });

    describe('and getting an item of it from an other enum', function () {

      it('it should return null', function() {

        var myEnum1 = new e(['A', 'B', 'C']);

        var myEnum2 = new e({'A': 1, 'B': 2, 'C': 4});

        expect(myEnum2.get(myEnum1.A)).to.eql(null);

      });

    });

    describe('ref Type interface', function () {

      it('should define a `size` Number', function () {

        var myEnum = new e(['A', 'B', 'C']);

        expect(myEnum.size).to.be.a('number');

      });

      it('should define an `indirection` Number', function () {

        var myEnum = new e(['A', 'B', 'C']);

        expect(myEnum.indirection).to.be.a('number');

      });

      it('should work with Buffer for `get()`', function () {

        var myEnum = new e(['A', 'B', 'C']);
        var buffer = new Buffer(myEnum.size);

        buffer['writeUInt32' + endianness](myEnum.B.value, 0);

        expect(myEnum.get(buffer)).to.eql(myEnum.B);

      });

      it('should work with Buffer for `set()`', function () {

        var myEnum = new e(['A', 'B', 'C']);
        var buffer = new Buffer(myEnum.size);

        myEnum.set(buffer, 0, myEnum.B);

        expect(buffer['readUInt32' + endianness](0)).to.eql(myEnum.B.value);

      });

    });

    describe('beeing not case sensitive', function() {

      var myEnum = new e(['One', 'tWo', 'ThrEE'], { ignoreCase: true });

      it('it should work correctly even if not requesting exactly the same key value', function() {

        expect(myEnum.get('one').value).to.eql(myEnum.One.value);
        expect(myEnum.get('two').value).to.eql(myEnum.tWo.value);
        expect(myEnum.get('THREE').value).to.eql(myEnum.ThrEE.value);

        expect(myEnum.One.is('onE')).to.eql(true);
        expect(myEnum.tWo.is('Two')).to.eql(true);
        expect(myEnum.ThrEE.is('three')).to.eql(true);

        expect(myEnum.One.has('onE')).to.eql(true);
        expect(myEnum.tWo.has('Two')).to.eql(true);
        expect(myEnum.ThrEE.has('three')).to.eql(true);

      });

    });

  });

});
<commit_msg>fix tests that weren't asserting anything<commit_after>var expect = expect || require('expect.js'),
    endianness = this.Enum ? 'LE' : require('os').endianness(),
    e = this.Enum || require('../index');

describe('Enum', function() {

  if (typeof(module) !== 'undefined' && module.exports) {
    describe('calling register', function() {

      it('it should register Enum on global namespace', function() {

        expect(global.Enum).not.to.be.ok();
        e.register();
        expect(Enum).to.be.ok();

      });

    });
  }

  describe('defining an enum', function() {

    var myEnum;

    describe('in a simple or complex way', function() {

      it('it should be tha same', function() {

        myEnum = new e(['A', 'B', 'C']);

        var myEnum2 = new e({'A': 1, 'B': 2, 'C': 4});

        expect(myEnum.A).to.eql(myEnum2.A);
        expect(myEnum.C).to.eql(myEnum2.C);

        expect(myEnum.A.value).to.eql(myEnum2.A.value);
        expect(myEnum.C.value).to.eql(myEnum2.C.value);

      });

      describe('it should be possible to', function() {

        it('get an enum item', function() {

          expect(myEnum.A).to.have.property('value', 1);
          expect(myEnum.A).to.have.property('key', 'A');

          expect(myEnum.C).to.have.property('value', 4);
          expect(myEnum.C).to.have.property('key', 'C');

        });

        it('get all enum values', function() {

          expect(myEnum.enums).to.be.an('array');
          expect(myEnum.enums).to.have.length(3);
          expect(myEnum.enums).to.contain(myEnum.A);
          expect(myEnum.enums).to.contain(myEnum.B);
          expect(myEnum.enums).to.contain(myEnum.C);

        });

        describe('call has', function() {

          describe('on a flagged enum item', function() {

            var myItem;

            before(function() {
              myItem = myEnum.get(3);
              expect(myEnum.get('A | B').value).to.eql(myItem.value);
            });

            it('with another item', function() {

              expect(myItem.has(myEnum.B)).to.be.ok();
              expect(myItem.has(myEnum.C)).not.to.be.ok();

            });

            it('with another key', function() {

              expect(myItem.has('B')).to.be.ok();
              expect(myItem.has('C')).not.to.be.ok();

            });

            it('with another value', function() {

              expect(myItem.has(2)).to.be.ok();
              expect(myItem.has(4)).not.to.be.ok();

            });

          });

        });

        describe('compare', function() {

          describe('an item and an item', function() {

            it('with is', function() {

              expect(myEnum.A.is(myEnum.A)).to.be.ok();
              expect(myEnum.C.is(myEnum.C)).to.be.ok();

            });

            it('with has', function() {

              expect(myEnum.A.has(myEnum.A)).to.be.ok();
              expect(myEnum.C.has(myEnum.C)).to.be.ok();

            });

            it('with ==', function() {

              expect(myEnum.A == myEnum.A).to.be.ok();
              expect(myEnum.C == myEnum.C).to.be.ok();

            });

            it('with ===', function() {

              expect(myEnum.A === myEnum.A).to.be.ok();
              expect(myEnum.C === myEnum.C).to.be.ok();

            });

          });

          describe('an item and a key', function() {

            it('with is', function() {

              expect(myEnum.A.is('A')).to.be.ok();
              expect(myEnum.C.is('C')).to.be.ok();

            });

            it('with has', function() {

              expect(myEnum.A.has('A')).to.be.ok();
              expect(myEnum.C.has('C')).to.be.ok();

            });

            it('with ==', function() {

              expect(myEnum.A == myEnum.A.value).to.be.ok();
              expect(myEnum.C == myEnum.C.value).to.be.ok();

            });

          });

          describe('an item and a value', function() {

            it('with is', function() {

              expect(myEnum.A.is(1)).to.be.ok();
              expect(myEnum.C.is(4)).to.be.ok();

            });

            it('with has', function() {

              expect(myEnum.A.has(1)).to.be.ok();
              expect(myEnum.C.has(4)).to.be.ok();

            });

          });

        });

        describe('call get and get', function() {

          it('an enum item by item', function() {

            expect(myEnum.get(myEnum.A)).to.have.property('value', 1);
            expect(myEnum.get(myEnum.A)).to.have.property('key', 'A');

            expect(myEnum.get(myEnum.C)).to.have.property('value', 4);
            expect(myEnum.get(myEnum.C)).to.have.property('key', 'C');

          });

          it('an enum item by flagged item', function() {

            var item = myEnum.get('A | B');

            expect(myEnum.get(item)).to.have.property('value', 3);
            expect(myEnum.get(item)).to.have.property('key', 'A | B');

          });

          it('an enum item by value', function() {

            expect(myEnum.get('A')).to.have.property('value', 1);
            expect(myEnum.get('A')).to.have.property('key', 'A');

            expect(myEnum.get('C')).to.have.property('value', 4);
            expect(myEnum.get('C')).to.have.property('key', 'C');

          });

          it('an enum item by key', function() {

            expect(myEnum.get(1)).to.have.property('value', 1);
            expect(myEnum.get(1)).to.have.property('key', 'A');

            expect(myEnum.get(4)).to.have.property('value', 4);
            expect(myEnum.get(4)).to.have.property('key', 'C');

          });

        });

        describe('call get with null and get', function() {

          it('null', function() {

            expect(myEnum.get(null)).to.eql(null);

          });

        });

        describe('call get with undefined and get', function() {

          it('null', function() {

            expect(myEnum.get(undefined)).to.eql(null);

          });

        });

        describe('call getValue and get', function() {

          it('an enum value by item', function() {

            expect(myEnum.getValue(myEnum.A)).to.eql(1);

            expect(myEnum.getValue(myEnum.C)).to.eql(4);

          });

          it('an enum value by key', function() {

            expect(myEnum.getValue('A')).to.eql(1);

            expect(myEnum.getValue('C')).to.eql(4);

          });

          it('an enum value by value', function() {

            expect(myEnum.getValue(1)).to.eql(1);

            expect(myEnum.getValue(4)).to.eql(4);

          });

        });

        describe('call getKey and get', function() {

          it('an enum key by item', function() {

            expect(myEnum.getKey(myEnum.A)).to.eql('A');

            expect(myEnum.getKey(myEnum.C)).to.eql('C');

          });

          it('an enum value by key', function() {

            expect(myEnum.getKey('A')).to.eql('A');

            expect(myEnum.getKey('C')).to.eql('C');

          });

          it('an enum value by value', function() {

            expect(myEnum.getKey(1)).to.eql('A');

            expect(myEnum.getKey(4)).to.eql('C');

          });

        });

      });

      describe('on an enum item it should be possible to', function() {

        it('call toString and get the key', function() {

          expect(myEnum.A.toString()).to.eql('A');

        });

        it('call toJSON and get the key', function() {

          expect(myEnum.A.toJSON()).to.eql('A');

        });

        it('call valueOf and get the value', function() {

          expect(myEnum.A.valueOf()).to.eql(myEnum.A.value);

        });

        it('use JavaScript | operator', function() {

          expect(myEnum.A | myEnum.B).to.eql(myEnum.getValue('A | B'));

          expect(myEnum.A | myEnum.C).to.eql(myEnum.getValue('A | C'));

          expect(myEnum.A | myEnum.B | myEnum.C).to.eql(myEnum.getValue('A | B | C'));

        });

        it('stringify JSON', function() {

          expect(JSON.stringify(myEnum.A)).to.eql('"A"');

        });

      });

    });

    describe('on an enum object', function(){

      var myEnum;

      before(function(){
        myEnum = new e({'A':1, 'B':2, 'C':4});
      });

      it('can not extend after creation', function() {

        var extendMyEnum = Object.isExtensible(myEnum);
        expect(extendMyEnum).to.be(false);

       });

      it('does not accept changes to existing property values, throws', function() {

        expect(myEnum).to.have.property('C');
        expect(function() {
          myEnum['C'] = 3;
        }).to.throwError("The value can not be set; Enum Type is not extensible.");
        expect(function() {
          Object.defineProperty(myEnum, 'C', {value: 3, writable:true, configurable: true});
        }).to.throwError();
        expect(myEnum.get('C')).to.have.property('value', 4);
        expect(myEnum).to.equal(myEnum);

      });

      it('can not define new properties, throws', function() {

        expect(function() {
          Object.defineProperty(myEnum, 'D', {writable: true, enumerable:true});
        }).to.throwError();
        expect(myEnum.D).to.be(undefined);
        expect(myEnum).not.to.have.property('D');
        expect(myEnum).to.equal(myEnum);

      });

      it('is persistent to deletes', function() {

        var deleteEnumItem = delete myEnum['A'];
        expect(deleteEnumItem).to.be(false);
        expect(myEnum).to.have.property('A');
        expect(myEnum.get('A')).to.have.property('value', 1);
        expect(myEnum).to.equal(myEnum);

      });

      it('creates unique identity for each property', function() {

        var myEnum1 = new e({'A':1, 'B':2, 'C':4});
        var myEnum2 = new e({'A':1, 'B':2, 'C':4});
        expect(myEnum1.A).not.to.equal(myEnum2.A);
        expect(myEnum1.B).not.to.equal(myEnum2.B);
        expect(myEnum1.C).not.to.equal(myEnum2.C);
        expect(myEnum1).not.to.equal(myEnum2);

      });

      it('respects the order of properties for equality', function() {

        var m1 = Object.keys(myEnum);
        var m2 = Object.keys(myEnum).reverse();
        expect(m1).not.to.equal(m2);

      });

    });

    describe('beeing flagged', function() {

      var myFlaggedEnum;

      before(function() {
        myFlaggedEnum = new e({'A': 1, 'B': 2, 'C': 4});
      });

      it('it should get the flagged value', function() {

        expect(myFlaggedEnum.get(1)).to.be(myFlaggedEnum.A);
        expect(myFlaggedEnum.get(2)).to.be(myFlaggedEnum.B);
        expect(myFlaggedEnum.get(3).is('A | B')).to.be(true);

      });

    });

    describe('not beeing flagged', function() {

      var myNonFlaggedEnum;

      before(function() {
        myNonFlaggedEnum = new e({'0': 0, 'A': 1, 'B': 2, 'B2': 3, 'C': 4});
      });

      it('it should not get the flagged value', function() {

        expect(myNonFlaggedEnum.get(1)).to.be(myNonFlaggedEnum.A);
        expect(myNonFlaggedEnum.get(2)).to.be(myNonFlaggedEnum.B);
        expect(myNonFlaggedEnum.get(3)).to.be(myNonFlaggedEnum.B2);

      });

      describe('getting a non matching value', function() {

        it('it should return undefined', function() {

          expect(myNonFlaggedEnum.get(5)).to.not.be.ok();

        });

      });

      describe('call get with an non valid value and get', function() {

        it('null', function() {

          expect(myNonFlaggedEnum.get(12345)).to.eql(null);

        });

      });

      describe('call get with 0 and get', function() {

        it('null', function() {

          expect(myNonFlaggedEnum.get(0)).to.not.eql(null);

        });

      });

    });

    describe('and getting an item of it from an other enum', function () {

      it('it should return null', function() {

        var myEnum1 = new e(['A', 'B', 'C']);

        var myEnum2 = new e({'A': 1, 'B': 2, 'C': 4});

        expect(myEnum2.get(myEnum1.A)).to.eql(null);

      });

    });

    describe('ref Type interface', function () {

      it('should define a `size` Number', function () {

        var myEnum = new e(['A', 'B', 'C']);

        expect(myEnum.size).to.be.a('number');

      });

      it('should define an `indirection` Number', function () {

        var myEnum = new e(['A', 'B', 'C']);

        expect(myEnum.indirection).to.be.a('number');

      });

      it('should work with Buffer for `get()`', function () {

        var myEnum = new e(['A', 'B', 'C']);
        var buffer = new Buffer(myEnum.size);

        buffer['writeUInt32' + endianness](myEnum.B.value, 0);

        expect(myEnum.get(buffer)).to.eql(myEnum.B);

      });

      it('should work with Buffer for `set()`', function () {

        var myEnum = new e(['A', 'B', 'C']);
        var buffer = new Buffer(myEnum.size);

        myEnum.set(buffer, 0, myEnum.B);

        expect(buffer['readUInt32' + endianness](0)).to.eql(myEnum.B.value);

      });

    });

    describe('beeing not case sensitive', function() {

      var myEnum = new e(['One', 'tWo', 'ThrEE'], { ignoreCase: true });

      it('it should work correctly even if not requesting exactly the same key value', function() {

        expect(myEnum.get('one').value).to.eql(myEnum.One.value);
        expect(myEnum.get('two').value).to.eql(myEnum.tWo.value);
        expect(myEnum.get('THREE').value).to.eql(myEnum.ThrEE.value);

        expect(myEnum.One.is('onE')).to.eql(true);
        expect(myEnum.tWo.is('Two')).to.eql(true);
        expect(myEnum.ThrEE.is('three')).to.eql(true);

        expect(myEnum.One.has('onE')).to.eql(true);
        expect(myEnum.tWo.has('Two')).to.eql(true);
        expect(myEnum.ThrEE.has('three')).to.eql(true);

      });

    });

  });

});
<|endoftext|>


<commit_before>var grunt = require('grunt'),
	sinon = require('sinon'),
	path = require('path'),
	ERB = require('../tasks/lib/erb'),
	exec = require('child_process').exec;

var read = function () {
	var filepath = path.join.apply(this, Array.prototype.slice.call(arguments));
	return grunt.util.normalizelf(grunt.file.read(filepath));
};

function executeGruntTestTask (task, cb) {
	exec('grunt --gruntfile gruntfile_test.js ' + task, cb);
}

exports.erb = {
	emptySrcFile: function (test) {
		executeGruntTestTask('erb:emptySrcFile', function (error, stdout, stdin) {
			test.ok(error !== null, 'should raise an error when no src files specified');
			test.done();
		});
	},
	emptyRubyFile: function (test) {
		executeGruntTestTask('erb:emptyRubyfile', function (error, stdout, stdin) {
			test.ok(error !== null, 'should raise an error when no ruby file specified');
			test.done();
		});
	},
	emptyDestPath: function (test) {
		executeGruntTestTask('erb:emptyDestPath', function (error, stdout, stdin) {
			test.ok(error !== null, 'should raise an error when no dest path is specified');
			test.done();
		});
	},
	nonExistingRubyFile: function (test) {
		executeGruntTestTask('erb:nonExistingRubyFile', function (error) {
			test.ok(error !== null, 'should raise an error when a non existing ruby file is specified');
			test.done();
		});
	},
	simpleConf: function (test) {
		executeGruntTestTask('erb:simpleConf', function (error) {
			test.equal(error, null, 'no error should be raised');

			var actual = read('test', 'fixtures', 'tmp', 'config-out.js'),
				expected = read('test', 'fixtures', 'expected', 'config-out.js');

			test.equal(actual, expected);

			test.done();
		});
	},
	nonExistingDestDir: function (test) {
		executeGruntTestTask('erb:nonExistingDestDir', function (error) {
			test.equal(error, null, 'no error should be raised');

			var actual = read('test', 'fixtures', 'tmp', 'new', 'other-conf.js'),
				expected = read('test', 'fixtures', 'expected', 'other-conf.js');

			test.equal(actual, expected);

			test.done();
		});
	}
};<commit_msg>Remove unused import in tests<commit_after>var grunt = require('grunt'),
	path = require('path'),
	exec = require('child_process').exec;

var read = function () {
	var filepath = path.join.apply(this, Array.prototype.slice.call(arguments));
	return grunt.util.normalizelf(grunt.file.read(filepath));
};

function executeGruntTestTask (task, cb) {
	exec('grunt --gruntfile gruntfile_test.js ' + task, cb);
}

exports.erb = {
	emptySrcFile: function (test) {
		executeGruntTestTask('erb:emptySrcFile', function (error, stdout, stdin) {
			test.ok(error !== null, 'should raise an error when no src files specified');
			test.done();
		});
	},
	emptyRubyFile: function (test) {
		executeGruntTestTask('erb:emptyRubyfile', function (error, stdout, stdin) {
			test.ok(error !== null, 'should raise an error when no ruby file specified');
			test.done();
		});
	},
	emptyDestPath: function (test) {
		executeGruntTestTask('erb:emptyDestPath', function (error, stdout, stdin) {
			test.ok(error !== null, 'should raise an error when no dest path is specified');
			test.done();
		});
	},
	nonExistingRubyFile: function (test) {
		executeGruntTestTask('erb:nonExistingRubyFile', function (error) {
			test.ok(error !== null, 'should raise an error when a non existing ruby file is specified');
			test.done();
		});
	},
	simpleConf: function (test) {
		executeGruntTestTask('erb:simpleConf', function (error) {
			test.equal(error, null, 'no error should be raised');

			var actual = read('test', 'fixtures', 'tmp', 'config-out.js'),
				expected = read('test', 'fixtures', 'expected', 'config-out.js');

			test.equal(actual, expected);

			test.done();
		});
	},
	nonExistingDestDir: function (test) {
		executeGruntTestTask('erb:nonExistingDestDir', function (error) {
			test.equal(error, null, 'no error should be raised');

			var actual = read('test', 'fixtures', 'tmp', 'new', 'other-conf.js'),
				expected = read('test', 'fixtures', 'expected', 'other-conf.js');

			test.equal(actual, expected);

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


<commit_before>'use strict';

var readFile = require('fs').readFile
  , ast      = require('./_ast-function')

  , pg = __dirname + '/__playground';

module.exports = function (t) {
	return {
		Normal: function (a, d) {
			readFile(pg + '/function.js', 'utf-8', function (err, str) {
				var plainR, astR;
				if (err) {
					d(err);
					return;
				}
				plainR = t('require')(str);
				astR = ast(str, 'require');
				a(plainR.length, astR.length, "Length");
				astR.forEach(function (val, i) { a.deep(plainR[i], val, i); });
				d();
			});
		},
		"One character name": function (a, d) {
			readFile(pg + '/function-one-char.js', 'utf-8', function (err, str) {
				var plainR, astR;
				if (err) {
					d(err);
					return;
				}
				plainR = t('_')(str);
				astR = ast(str, '_');
				a(plainR.length, astR.length, "Length");
				astR.forEach(function (val, i) { a.deep(plainR[i], val, i); });
				d();
			});
		},
		"Method": function (a, d) {
			readFile(pg + '/method.js', 'utf-8', function (err, str) {
				var plainR, astR;
				if (err) {
					d(err);
					return;
				}
				plainR = t('i18n.bind')(str);
				astR = ast(str, 'i18n', 'bind');
				a(plainR.length, astR.length, "Length");
				astR.forEach(function (val, i) { a.deep(plainR[i], val, i); });
				d();
			});
		}
	};
};
<commit_msg>-- lint<commit_after>'use strict';

var readFile = require('fs').readFile
  , ast      = require('./_ast-function')

  , pg = __dirname + '/__playground';

module.exports = function (t) {
	return {
		Normal: function (a, d) {
			readFile(pg + '/function.js', 'utf-8', function (err, str) {
				var plainR, astR;
				if (err) {
					d(err);
					return;
				}
				plainR = t('require')(str);
				astR = ast(str, 'require');
				a(plainR.length, astR.length, "Length");
				astR.forEach(function (val, i) { a.deep(plainR[i], val, i); });
				d();
			});
		},
		"One character name": function (a, d) {
			readFile(pg + '/function-one-char.js', 'utf-8', function (err, str) {
				var plainR, astR;
				if (err) {
					d(err);
					return;
				}
				plainR = t('_')(str);
				astR = ast(str, '_');
				a(plainR.length, astR.length, "Length");
				astR.forEach(function (val, i) { a.deep(plainR[i], val, i); });
				d();
			});
		},
		Method: function (a, d) {
			readFile(pg + '/method.js', 'utf-8', function (err, str) {
				var plainR, astR;
				if (err) {
					d(err);
					return;
				}
				plainR = t('i18n.bind')(str);
				astR = ast(str, 'i18n', 'bind');
				a(plainR.length, astR.length, "Length");
				astR.forEach(function (val, i) { a.deep(plainR[i], val, i); });
				d();
			});
		}
	};
};
<|endoftext|>


<commit_before>/**
 * Created by nuintun on 2015/5/5.
 */

'use strict';

var is = require('is');
var path = require('path');
var gulp = require('gulp');
var util = require('../lib/util');
var colors = util.colors;
var through = require('through2');
var transport = require('../lib/transport');

function listen(){
  return through.obj(function (file, encoding, done){
    console.log(colors.infoBold(file.path));
    console.log('\n');
    console.log(colors.verboseBold(JSON.stringify(file.package, null, 2)));
    console.log('\n');

    this.push(file);
    done();
  });
}

gulp.task('default', function (){
  gulp.src('assets/js/**/*.*', { base: 'assets/js' })
    .pipe(transport(util.extendOption({ wwwroot: './', css2js: true })));

  gulp.src('assets/css/**/*.*', { base: 'assets/css' })
    .pipe(transport(util.extendOption({ wwwroot: './' })));
});

gulp.task('watch', function (){
  gulp.watch('assets/js/**/*.*', function (e){
    if (e.type !== 'deleted') {
      return gulp.src(e.path, { base: 'assets/js' })
        .pipe(transport(util.extendOption({ wwwroot: './', css2js: true })));
    }
  });

  gulp.watch('assets/css/**/*.*', function (e){
    if (e.type !== 'deleted') {
      return gulp.src(e.path, { base: 'assets/css' })
        .pipe(transport(util.extendOption({ wwwroot: './' })));
    }
  });
});<commit_msg>add source files<commit_after>/**
 * Created by nuintun on 2015/5/5.
 */

'use strict';

var is = require('is');
var path = require('path');
var gulp = require('gulp');
var util = require('../lib/util');
var colors = util.colors;
var through = require('through2');
var transport = require('../lib/transport');

function listen(){
  return through.obj(function (file, encoding, done){
    console.log(colors.infoBold(file.path));
    console.log('\n');
    console.log(colors.verboseBold(JSON.stringify(file.package, null, 2)));
    console.log('\n');

    this.push(file);
    done();
  });
}

var alias = { 'class': 'base/class/1.2.0/class' };

gulp.task('default', function (){
  gulp.src('assets/js/**/*.*', { base: 'assets/js' })
    .pipe(transport(util.extendOption({ wwwroot: './', alias: alias, css2js: true })));

  gulp.src('assets/css/**/*.*', { base: 'assets/css' })
    .pipe(transport(util.extendOption({ wwwroot: './' })));
});

gulp.task('watch', function (){
  gulp.watch('assets/js/**/*.*', function (e){
    if (e.type !== 'deleted') {
      return gulp.src(e.path, { base: 'assets/js' })
        .pipe(transport(util.extendOption({ wwwroot: './', alias: alias, css2js: true })));
    }
  });

  gulp.watch('assets/css/**/*.*', function (e){
    if (e.type !== 'deleted') {
      return gulp.src(e.path, { base: 'assets/css' })
        .pipe(transport(util.extendOption({ wwwroot: './' })));
    }
  });
});<|endoftext|>


<commit_before>var should = require('should');
var hastings = require('./../lib/hastings');
var basepath = require('path').resolve('.');
var fs = require('fs');
var p = require('path');
var wrench = require('wrench');

describe('hastings', function() {
    it('should exist', function() {
        should.exist('hastings');
    });

    describe('path', function() {
        it('should be optional', function() {
            hastings.init(null, function(e, path) {
                path.should.equal(basepath + '/doc');
                fs.statSync(path).isDirectory().should.equal(true);
            });
        });

        it('should be used when provided', function() {
            hastings.init('custom/docs', function(e, path) {
                path.should.equal(basepath + '/custom/docs');
                fs.statSync(path).isDirectory().should.equal(true);
            });
        });

        it('should handle ./ as ./doc', function() {
            hastings.init('.', function(e, path) {
                path.should.equal(basepath + '/doc');
                fs.statSync(path).isDirectory().should.equal(true);
            });
        });

        it('should be absolute path', function() {
            hastings.init('.', function(e, path) {
                path.should.equal(basepath + '/doc');
            });
        });
    });

    describe('init', function() {
        var tmpPath = p.join(basepath, 'doc');
        var indexPath = p.join(tmpPath, 'index.md');
        beforeEach(function() {
            if (p.existsSync(tmpPath))
                wrench.rmdirSyncRecursive(tmpPath);
        });
        afterEach(function() {
            if (p.existsSync(tmpPath))
                wrench.rmdirSyncRecursive(tmpPath);
        });

        it('should exist', function() {
            hastings.should.have.property('init');
        });

        it('should use an existing directory', function() {
            // pre-create doc/ directory
            fs.mkdirSync(tmpPath);
            p.existsSync(tmpPath).should.equal(true);
            // now feed it to hastings
            hastings.init('doc', function(e, path) {
                fs.statSync(path).isDirectory().should.equal(true);
                fs.statSync(indexPath).isFile().should.equal(true);
            });
        });

        it('should create missing directories', function() {
            // no pre-created doc/ directory
            p.existsSync(tmpPath).should.equal(false);
            // now create it
            hastings.init('doc', function(e, path) {
                fs.statSync(path).isDirectory().should.equal(true);
                fs.statSync(indexPath).isFile().should.equal(true);
            });
        });

        it('should not replace an existing index.md', function() {
            wrench.copyDirSyncRecursive('test/res/doc', 'doc');
            hastings.init('doc', function(e, path) {
                fs.statSync(path).isDirectory().should.equal(true);
                fs.statSync(indexPath).isFile().should.equal(true);

                var expectedContent = fs.readFileSync('test/res/doc/index.md', 'utf-8');
                var actualContent = fs.readFileSync('doc/index.md', 'utf-8');
                actualContent.should.equal(expectedContent);
            });
        });
    });
});
<commit_msg>Refactor the path tests.<commit_after>var should = require('should');
var hastings = require('./../lib/hastings');
var basepath = require('path').resolve('.');
var fs = require('fs');
var p = require('path');
var wrench = require('wrench');

describe('hastings', function() {
    it('should exist', function() {
        should.exist('hastings');
    });

    describe('path', function() {
        it('should be optional', function() {
            hastings.path(null).should.equal(basepath + '/doc');
        });

        it('should be used when provided', function() {
            hastings.path('custom/docs').should.equal(basepath + '/custom/docs');
        });

        it('should handle ./ as ./doc', function() {
            hastings.path('.').should.equal(basepath + '/doc');
        });

        it('should be absolute path', function() {
            hastings.path('.').should.equal(basepath + '/doc');
        });
    });

    describe('init', function() {
        var tmpPath = p.join(basepath, 'doc');
        var indexPath = p.join(tmpPath, 'index.md');
        beforeEach(function() {
            if (p.existsSync(tmpPath))
                wrench.rmdirSyncRecursive(tmpPath);
        });
        afterEach(function() {
            if (p.existsSync(tmpPath))
                wrench.rmdirSyncRecursive(tmpPath);
        });

        it('should exist', function() {
            hastings.should.have.property('init');
        });

        it('should use an existing directory', function() {
            // pre-create doc/ directory
            fs.mkdirSync(tmpPath);
            p.existsSync(tmpPath).should.equal(true);
            // now feed it to hastings
            hastings.init('doc', function(e, path) {
                fs.statSync(path).isDirectory().should.equal(true);
                fs.statSync(indexPath).isFile().should.equal(true);
            });
        });

        it('should create missing directories', function() {
            // no pre-created doc/ directory
            p.existsSync(tmpPath).should.equal(false);
            // now create it
            hastings.init('doc', function(e, path) {
                fs.statSync(path).isDirectory().should.equal(true);
                fs.statSync(indexPath).isFile().should.equal(true);
            });
        });

        it('should not replace an existing index.md', function() {
            wrench.copyDirSyncRecursive('test/res/doc', 'doc');
            hastings.init('doc', function(e, path) {
                fs.statSync(path).isDirectory().should.equal(true);
                fs.statSync(indexPath).isFile().should.equal(true);

                var expectedContent = fs.readFileSync('test/res/doc/index.md', 'utf-8');
                var actualContent = fs.readFileSync('doc/index.md', 'utf-8');
                actualContent.should.equal(expectedContent);
            });
        });
    });
});
<|endoftext|>