<commit_before>var assert = require('assert'),
    path = require('path'),
    util = require('util'),
    checker = require('../lib/index'),
    args = require('../lib/args'),
    chalk = require('chalk'),
    fs = require('fs');

describe('main tests', function() {

    it('should load init', function() {
        assert.equal(typeof checker.init, 'function');
    });

    it('should load print', function() {
        assert.equal(typeof checker.print, 'function');
    });

    describe('should parse local with unknown', function(done) {
        var output;
        before(function(done) {
            checker.init({
                start: path.join(__dirname, '../')
            }, function (err, sorted) {
                output = sorted;
                done();
            });
        });

        it('and give us results', function () {
            assert.equal(Object.keys(output).length > 70, true);
            assert.equal(output['abbrev@1.0.7'].licenses, 'ISC');
        });

        it('and convert to CSV', function() {
            var str = checker.asCSV(output);
            assert.equal('"module name","license","repository"', str.split('\n')[0]);
            assert.equal('"abbrev@1.0.7","ISC","https://github.com/isaacs/abbrev-js"', str.split('\n')[1]);
        });
        it('and convert to MarkDown', function() {
            var str = checker.asMarkDown(output);
            assert.equal('[abbrev@1.0.7](https://github.com/isaacs/abbrev-js) - ISC', str.split('\n')[0]);
        });
    });

    describe('should parse local with unknown and custom format', function(done) {
        var output;
        before(function (done) {
            var format = {
                'name': '<<Default Name>>',
                'description': '<<Default Description>>',
                'pewpew': '<<Should Never be set>>'
            };

            checker.init({
                start: path.join(__dirname, '../'),
                customFormat: format
            }, function (err, sorted) {
                output = sorted;
                done();
            });
        });

        it('and give us results', function () {
            assert.ok(Object.keys(output).length > 70);
            assert.equal(output['abbrev@1.0.7'].description, 'Like ruby\'s abbrev module, but in js');
        });

        it('and convert to CSV', function() {
            var format = {
                'name': '<<Default Name>>',
                'description': '<<Default Description>>',
                'pewpew': '<<Should Never be set>>'
            };

            var str = checker.asCSV(output, format);
            assert.equal('"module name","name","description","pewpew"', str.split('\n')[0]);
            assert.equal('"abbrev@1.0.7","abbrev","Like ruby\'s abbrev module, but in js","<<Should Never be set>>"', str.split('\n')[1]);
        });

        it('and convert to MarkDown', function() {
            var format = {
                'name': '<<Default Name>>',
                'description': '<<Default Description>>',
                'pewpew': '<<Should Never be set>>'
            };

            var str = checker.asMarkDown(output, format);
            assert.equal(' - **[abbrev@1.0.7](https://github.com/isaacs/abbrev-js)**', str.split('\n')[0]);
        });
    });

    describe('should parse local without unknown', function() {
        var output;
        before(function(done) {
            checker.init({
                start: path.join(__dirname, '../'),
                unknown: true
            }, function (err, sorted) {
                output = sorted;
                done();
            });
        });

        it('should give us results', function () {
            assert.ok(output);
            assert.ok(Object.keys(output).length > 20);
        });
    });

    describe('should parse local with unknown and excludes', function() {
        var output;
        before(function (done) {
            checker.init({
                start: path.join(__dirname, '../'),
                exclude: "MIT, ISC"
            }, function (err, filtered) {
                output = filtered;
                done();
            });
        });

        it('should exclude MIT and ISC licensed modules from results', function () {
            var excluded = true;
            Object.keys(output).forEach(function(item) {
                if (output[item].licenses && (output[item].licenses == "MIT" || output[item].licenses == "ISC"))
                    excluded = false;
            });
            assert.ok(excluded);
        });
    });

    describe('error handler', function() {
        it('should init without errors', function(done) {
            checker.init({
                start: path.join(__dirname, '../'),
                development: true
            }, function (err) {
                assert.equal(err, null);
                done();
            });
        });

        it('should init with errors (npm packages not found)', function(done) {
            checker.init({
                start: 'C:\\'
            }, function (err) {
                assert.ok(util.isError(err));
                done();
            });
        });
    });

    describe('should parse with args', function() {
        var args = require('../lib/args.js');

        it('should handle undefined', function () {
            var result = args.defaults(undefined);
            assert.equal(result.color, chalk.supportsColor);
            assert.equal(result.start, path.resolve(path.join(__dirname, '../')));
        });

        it('should handle color undefined', function () {
            var result = args.defaults({color: undefined, start: path.resolve(path.join(__dirname, '../'))});
            assert.equal(result.color, chalk.supportsColor);
            assert.equal(result.start, path.resolve(path.join(__dirname, '../')));
        });

        ['json', 'markdown', 'csv'].forEach(function(type) {
            it('should disable color on ' + type, function () {
                var def = {
                    color: undefined,
                    start: path.resolve(path.join(__dirname, '../'))
                };
                def[type] = true;
                var result = args.defaults(def);
                assert.equal(result.color, false);
                assert.equal(result.start, path.resolve(path.join(__dirname, '../')));
            });
        });
    });

    describe('custom formats', function() {

        it('should create a custom format using customFormat successfully', function(done) {
            checker.init({
                start: path.join(__dirname, '../'),
                customFormat: {
                    'name': '<<Default Name>>',
                    'description': '<<Default Description>>',
                    'pewpew': '<<Should Never be set>>'
                }
            }, function (err, d) {
                Object.keys(d).forEach(function(item) {
                    assert.notEqual(d[item].name, undefined);
                    assert.notEqual(d[item].description, undefined);
                    assert.notEqual(d[item].pewpew, undefined);
                    assert.equal(d[item].pewpew, '<<Should Never be set>>');
                });
                done();
            });
        });

        it('should create a custom format using customPath', function(done) {
            process.argv.push('--customPath');
            process.argv.push('./customFormatExample.json');

            args = args.parse();
            args.start = path.join(__dirname, '../');

            process.argv.pop();
            process.argv.pop();

            checker.init(args, function (err, filtered) {
                var customFormatContent = fs.readFileSync(path.join(__dirname, './../customFormatExample.json'), 'utf8');

                assert.notEqual(customFormatContent, undefined);
                assert.notEqual(customFormatContent, null);

                var customJson = JSON.parse(customFormatContent);

                //Test dynamically with the file directly
                Object.keys(filtered).forEach(function(licenseItem) {
                    Object.keys(customJson).forEach(function(definedItem) {
                        assert.notEqual(filtered[licenseItem][definedItem], 'undefined');
                    });
                });
                done();
            });
        });

    });

    describe('should output the location of the license files', function() {

        it('as absolute paths', function (done) {
            checker.init({
                start: path.join(__dirname, '../')
            }, function (err, output) {
                Object.keys(output).map(function (key) {
                    return output[key];
                }).filter(function (dep) {
                    return dep.licenseFile !== undefined;
                }).forEach(function(dep) {
                    var expectedPath = path.join(__dirname, '../');
                    var actualPath = dep.licenseFile.substr(0, expectedPath.length);
                    assert.equal(actualPath, expectedPath);
                });
                done();
            });
        });

        it('as relative paths when using relativeLicensePath', function(done) {
            checker.init({
                start: path.join(__dirname, '../'),
                relativeLicensePath: true
            }, function (err, filtered) {
                Object.keys(filtered).map(function (key) {
                    return filtered[key];
                }).filter(function (dep) {
                    return dep.licenseFile !== undefined;
                }).forEach(function(dep) {
                    assert.notEqual(dep.licenseFile.substr(0, 1), "/");
                });
                done();
            });
        });
    });

    describe('should only list UNKNOWN or guessed licenses successful', function() {
        var output;
        before(function (done) {
            checker.init({
                start: path.join(__dirname, '../'),
                onlyunknown: true
            }, function (err, sorted) {
                output = sorted;
                done();
            });
        });

        it('so we check if there is no license with a star or UNKNOWN found', function() {
            var onlyStarsFound = true;
            Object.keys(output).forEach(function(item) {
                if (output[item].licenses && output[item].licenses.indexOf('UNKNOWN') !== -1) {
                    //Okay
                } else if (output[item].licenses && output[item].licenses.indexOf('*') !== -1) {
                    //Okay
                } else {
                    onlyStarsFound = false;
                }
            });
            assert.ok(onlyStarsFound);
        });
    });

    describe('should only list UNKNOWN or guessed licenses with errors (argument missing)', function() {
        var output;
        before(function (done) {
            checker.init({
                start: path.join(__dirname, '../'),
                production: true
            }, function (err, sorted) {
                output = sorted;
                done();
            });
        });

        it('so we check if there is no license with a star or UNKNOWN found', function() {
            var onlyStarsFound = true;
            Object.keys(output).forEach(function(item) {
                if (output[item].licenses && output[item].licenses.indexOf('UNKNOWN') !== -1) {
                    //Okay
                } else if (output[item].licenses && output[item].licenses.indexOf('*') !== -1) {
                    //Okay
                } else {
                    onlyStarsFound = false;
                }
            });
            assert.equal(onlyStarsFound, false);
        });
    });

    describe('should export', function() {

        it('print a tree', function() {
            var log = console.log;
            console.log = function(data) {
                assert.ok(data);
                assert.ok(data.indexOf('└─') > -1);
            };
            checker.print([{}]);
            console.log = log;
        });

        it('a tree', function() {
            var data = checker.asTree([{}]);
            assert.ok(data);
            assert.ok(data.indexOf('└─') > -1);
        });

        it('as csv', function() {
            var data = checker.asCSV({
                foo: {
                    licenses: 'MIT',
                    repository: '/path/to/foo'
                }
            });
            assert.ok(data);
            assert.ok(data.indexOf('"foo","MIT","/path/to/foo"') > -1);
        });

        it('as csv with partial data', function() {
            var data = checker.asCSV({
                foo: {
                }
            });
            assert.ok(data);
            assert.ok(data.indexOf('"foo","",""') > -1);
        });

        it('as markdown', function() {
            var data = checker.asMarkDown({
                foo: {
                    licenses: 'MIT',
                    repository: '/path/to/foo'
                }
            });
            assert.ok(data);
            assert.ok(data.indexOf('[foo](/path/to/foo) - MIT') > -1);
        });

    });

    describe('json parsing', function() {

        it('should parse json successfully (File exists + was json)', function() {
            var path = './tests/config/custom_format_correct.json';
            var json = checker.parseJson(path);
            assert.notEqual(json, undefined);
            assert.notEqual(json, null);
            assert.equal(json.licenseModified, 'no');
        });

        it('should parse json with errors (File exists + no json)', function() {
            var path = './tests/config/custom_format_broken.json';
            var json = checker.parseJson(path);
            assert.ok(json instanceof Error);
        });

        it('should parse json with errors (File not found)', function() {
            var path = './NotExitingFile.json';
            var json = checker.parseJson(path);
            assert.ok(json instanceof Error);
        });

        it('should parse json with errors (null passed)', function() {
            var json = checker.parseJson(null);
            assert.ok(json instanceof Error);
        });

    });

});
<commit_msg>fix tests<commit_after>var assert = require('assert'),
    path = require('path'),
    util = require('util'),
    checker = require('../lib/index'),
    args = require('../lib/args'),
    chalk = require('chalk'),
    fs = require('fs');

describe('main tests', function() {

    it('should load init', function() {
        assert.equal(typeof checker.init, 'function');
    });

    it('should load print', function() {
        assert.equal(typeof checker.print, 'function');
    });

    describe('should parse local with unknown', function(done) {
        var output;
        before(function(done) {
            checker.init({
                start: path.join(__dirname, '../')
            }, function (err, sorted) {
                output = sorted;
                done();
            });
        });

        it('and give us results', function () {
            assert.equal(Object.keys(output).length > 70, true);
            assert.equal(output['abbrev@1.0.9'].licenses, 'ISC');
        });

        it('and convert to CSV', function() {
            var str = checker.asCSV(output);
            assert.equal('"module name","license","repository"', str.split('\n')[0]);
            assert.equal('"abbrev@1.0.9","ISC","https://github.com/isaacs/abbrev-js"', str.split('\n')[1]);
        });
        it('and convert to MarkDown', function() {
            var str = checker.asMarkDown(output);
            assert.equal('[abbrev@1.0.9](https://github.com/isaacs/abbrev-js) - ISC', str.split('\n')[0]);
        });
    });

    describe('should parse local with unknown and custom format', function(done) {
        var output;
        before(function (done) {
            var format = {
                'name': '<<Default Name>>',
                'description': '<<Default Description>>',
                'pewpew': '<<Should Never be set>>'
            };

            checker.init({
                start: path.join(__dirname, '../'),
                customFormat: format
            }, function (err, sorted) {
                output = sorted;
                done();
            });
        });

        it('and give us results', function () {
            assert.ok(Object.keys(output).length > 70);
            assert.equal(output['abbrev@1.0.9'].description, 'Like ruby\'s abbrev module, but in js');
        });

        it('and convert to CSV', function() {
            var format = {
                'name': '<<Default Name>>',
                'description': '<<Default Description>>',
                'pewpew': '<<Should Never be set>>'
            };

            var str = checker.asCSV(output, format);
            assert.equal('"module name","name","description","pewpew"', str.split('\n')[0]);
            assert.equal('"abbrev@1.0.9","abbrev","Like ruby\'s abbrev module, but in js","<<Should Never be set>>"', str.split('\n')[1]);
        });

        it('and convert to MarkDown', function() {
            var format = {
                'name': '<<Default Name>>',
                'description': '<<Default Description>>',
                'pewpew': '<<Should Never be set>>'
            };

            var str = checker.asMarkDown(output, format);
            assert.equal(' - **[abbrev@1.0.9](https://github.com/isaacs/abbrev-js)**', str.split('\n')[0]);
        });
    });

    describe('should parse local without unknown', function() {
        var output;
        before(function(done) {
            checker.init({
                start: path.join(__dirname, '../'),
                unknown: true
            }, function (err, sorted) {
                output = sorted;
                done();
            });
        });

        it('should give us results', function () {
            assert.ok(output);
            assert.ok(Object.keys(output).length > 20);
        });
    });

    describe('should parse local with unknown and excludes', function() {
        var output;
        before(function (done) {
            checker.init({
                start: path.join(__dirname, '../'),
                exclude: "MIT, ISC"
            }, function (err, filtered) {
                output = filtered;
                done();
            });
        });

        it('should exclude MIT and ISC licensed modules from results', function () {
            var excluded = true;
            Object.keys(output).forEach(function(item) {
                if (output[item].licenses && (output[item].licenses == "MIT" || output[item].licenses == "ISC"))
                    excluded = false;
            });
            assert.ok(excluded);
        });
    });

    describe('error handler', function() {
        it('should init without errors', function(done) {
            checker.init({
                start: path.join(__dirname, '../'),
                development: true
            }, function (err) {
                assert.equal(err, null);
                done();
            });
        });

        it('should init with errors (npm packages not found)', function(done) {
            checker.init({
                start: 'C:\\'
            }, function (err) {
                assert.ok(util.isError(err));
                done();
            });
        });
    });

    describe('should parse with args', function() {
        var args = require('../lib/args.js');

        it('should handle undefined', function () {
            var result = args.defaults(undefined);
            assert.equal(result.color, chalk.supportsColor);
            assert.equal(result.start, path.resolve(path.join(__dirname, '../')));
        });

        it('should handle color undefined', function () {
            var result = args.defaults({color: undefined, start: path.resolve(path.join(__dirname, '../'))});
            assert.equal(result.color, chalk.supportsColor);
            assert.equal(result.start, path.resolve(path.join(__dirname, '../')));
        });

        ['json', 'markdown', 'csv'].forEach(function(type) {
            it('should disable color on ' + type, function () {
                var def = {
                    color: undefined,
                    start: path.resolve(path.join(__dirname, '../'))
                };
                def[type] = true;
                var result = args.defaults(def);
                assert.equal(result.color, false);
                assert.equal(result.start, path.resolve(path.join(__dirname, '../')));
            });
        });
    });

    describe('custom formats', function() {

        it('should create a custom format using customFormat successfully', function(done) {
            checker.init({
                start: path.join(__dirname, '../'),
                customFormat: {
                    'name': '<<Default Name>>',
                    'description': '<<Default Description>>',
                    'pewpew': '<<Should Never be set>>'
                }
            }, function (err, d) {
                Object.keys(d).forEach(function(item) {
                    assert.notEqual(d[item].name, undefined);
                    assert.notEqual(d[item].description, undefined);
                    assert.notEqual(d[item].pewpew, undefined);
                    assert.equal(d[item].pewpew, '<<Should Never be set>>');
                });
                done();
            });
        });

        it('should create a custom format using customPath', function(done) {
            process.argv.push('--customPath');
            process.argv.push('./customFormatExample.json');

            args = args.parse();
            args.start = path.join(__dirname, '../');

            process.argv.pop();
            process.argv.pop();

            checker.init(args, function (err, filtered) {
                var customFormatContent = fs.readFileSync(path.join(__dirname, './../customFormatExample.json'), 'utf8');

                assert.notEqual(customFormatContent, undefined);
                assert.notEqual(customFormatContent, null);

                var customJson = JSON.parse(customFormatContent);

                //Test dynamically with the file directly
                Object.keys(filtered).forEach(function(licenseItem) {
                    Object.keys(customJson).forEach(function(definedItem) {
                        assert.notEqual(filtered[licenseItem][definedItem], 'undefined');
                    });
                });
                done();
            });
        });

    });

    describe('should output the location of the license files', function() {

        it('as absolute paths', function (done) {
            checker.init({
                start: path.join(__dirname, '../')
            }, function (err, output) {
                Object.keys(output).map(function (key) {
                    return output[key];
                }).filter(function (dep) {
                    return dep.licenseFile !== undefined;
                }).forEach(function(dep) {
                    var expectedPath = path.join(__dirname, '../');
                    var actualPath = dep.licenseFile.substr(0, expectedPath.length);
                    assert.equal(actualPath, expectedPath);
                });
                done();
            });
        });

        it('as relative paths when using relativeLicensePath', function(done) {
            checker.init({
                start: path.join(__dirname, '../'),
                relativeLicensePath: true
            }, function (err, filtered) {
                Object.keys(filtered).map(function (key) {
                    return filtered[key];
                }).filter(function (dep) {
                    return dep.licenseFile !== undefined;
                }).forEach(function(dep) {
                    assert.notEqual(dep.licenseFile.substr(0, 1), "/");
                });
                done();
            });
        });
    });

    describe('should only list UNKNOWN or guessed licenses successful', function() {
        var output;
        before(function (done) {
            checker.init({
                start: path.join(__dirname, '../'),
                onlyunknown: true
            }, function (err, sorted) {
                output = sorted;
                done();
            });
        });

        it('so we check if there is no license with a star or UNKNOWN found', function() {
            var onlyStarsFound = true;
            Object.keys(output).forEach(function(item) {
                if (output[item].licenses && output[item].licenses.indexOf('UNKNOWN') !== -1) {
                    //Okay
                } else if (output[item].licenses && output[item].licenses.indexOf('*') !== -1) {
                    //Okay
                } else {
                    onlyStarsFound = false;
                }
            });
            assert.ok(onlyStarsFound);
        });
    });

    describe('should only list UNKNOWN or guessed licenses with errors (argument missing)', function() {
        var output;
        before(function (done) {
            checker.init({
                start: path.join(__dirname, '../'),
                production: true
            }, function (err, sorted) {
                output = sorted;
                done();
            });
        });

        it('so we check if there is no license with a star or UNKNOWN found', function() {
            var onlyStarsFound = true;
            Object.keys(output).forEach(function(item) {
                if (output[item].licenses && output[item].licenses.indexOf('UNKNOWN') !== -1) {
                    //Okay
                } else if (output[item].licenses && output[item].licenses.indexOf('*') !== -1) {
                    //Okay
                } else {
                    onlyStarsFound = false;
                }
            });
            assert.equal(onlyStarsFound, false);
        });
    });

    describe('should export', function() {

        it('print a tree', function() {
            var log = console.log;
            console.log = function(data) {
                assert.ok(data);
                assert.ok(data.indexOf('└─') > -1);
            };
            checker.print([{}]);
            console.log = log;
        });

        it('a tree', function() {
            var data = checker.asTree([{}]);
            assert.ok(data);
            assert.ok(data.indexOf('└─') > -1);
        });

        it('as csv', function() {
            var data = checker.asCSV({
                foo: {
                    licenses: 'MIT',
                    repository: '/path/to/foo'
                }
            });
            assert.ok(data);
            assert.ok(data.indexOf('"foo","MIT","/path/to/foo"') > -1);
        });

        it('as csv with partial data', function() {
            var data = checker.asCSV({
                foo: {
                }
            });
            assert.ok(data);
            assert.ok(data.indexOf('"foo","",""') > -1);
        });

        it('as markdown', function() {
            var data = checker.asMarkDown({
                foo: {
                    licenses: 'MIT',
                    repository: '/path/to/foo'
                }
            });
            assert.ok(data);
            assert.ok(data.indexOf('[foo](/path/to/foo) - MIT') > -1);
        });

    });

    describe('json parsing', function() {

        it('should parse json successfully (File exists + was json)', function() {
            var path = './tests/config/custom_format_correct.json';
            var json = checker.parseJson(path);
            assert.notEqual(json, undefined);
            assert.notEqual(json, null);
            assert.equal(json.licenseModified, 'no');
        });

        it('should parse json with errors (File exists + no json)', function() {
            var path = './tests/config/custom_format_broken.json';
            var json = checker.parseJson(path);
            assert.ok(json instanceof Error);
        });

        it('should parse json with errors (File not found)', function() {
            var path = './NotExitingFile.json';
            var json = checker.parseJson(path);
            assert.ok(json instanceof Error);
        });

        it('should parse json with errors (null passed)', function() {
            var json = checker.parseJson(null);
            assert.ok(json instanceof Error);
        });

    });

});
<|endoftext|>


<commit_before>import _ from 'lodash';
import { expect, assert } from 'chai';

import $forms from './data';

describe('Check validate() returns promise', () => {
  _.each($forms, (form, key) => it(`${key} validate() is promise`, () =>
    expect(form.validate()).to.be.a('promise')));
});

describe('Check values() returns object', () => {
  _.each($forms, (form, key) => it(`${key} values() is object`, () =>
    assert.isObject(form.values(), `${key}.values() is not object`)));
});

describe('Check errors() returns object', () => {
  _.each($forms, (form, key) => it(`${key} errors() is object`, () =>
    assert.isObject(form.errors(), `${key}.errors() is not object`)));
});

describe('Check eventsRunning() returns boolean', () => {
  _.each($forms, (form, key) => it(`${key} eventsRunning() is boolean`, () =>
    assert.isBoolean(form.eventsRunning(), `${key}.eventsRunning() is not boolean`)));
});

describe('Check hasError returns boolean', () => {
  _.each($forms, (form, key) => it(`${key} hasError is boolean`, () =>
    assert.isBoolean(form.hasError, `${key}.hasError is not boolean`)));
});

describe('Check isDirty returns boolean', () => {
  _.each($forms, (form, key) => it(`${key} isDirty is boolean`, () =>
    assert.isBoolean(form.isDirty, `${key}.isDirty is not boolean`)));
});

describe('Check isPristine returns boolean', () => {
  _.each($forms, (form, key) => it(`${key} isPristine is boolean`, () =>
    assert.isBoolean(form.isPristine, `${key}.isPristine is not boolean`)));
});

describe('Check isDefault returns boolean', () => {
  _.each($forms, (form, key) => it(`${key} isDefault is boolean`, () =>
    assert.isBoolean(form.isDefault, `${key}.isDefault is not boolean`)));
});

describe('Check isValid returns boolean', () => {
  _.each($forms, (form, key) => it(`${key} isValid is boolean`, () =>
    assert.isBoolean(form.isValid, `${key}.isValid is not boolean`)));
});

describe('Check isEmpty returns boolean', () => {
  _.each($forms, (form, key) => it(`${key} isEmpty is boolean`, () =>
    assert.isBoolean(form.isEmpty, `${key}.isEmpty is not boolean`)));
});
<commit_msg>nested-fields<commit_after>import _ from 'lodash';
import { expect, assert } from 'chai';

import $forms from './data';

describe('Check validate() returns promise', () => {
  _.each($forms, (form, key) => it(`${key} validate() is promise`, () =>
    expect(form.validate()).to.be.a('promise')));
});

describe('Check values() returns object', () => {
  _.each($forms, (form, key) => it(`${key} values() is object`, () =>
    assert.isObject(form.values(), `${key}.values() is not object`)));
});

describe('Check errors() returns object', () => {
  _.each($forms, (form, key) => it(`${key} errors() is object`, () =>
    assert.isObject(form.errors(), `${key}.errors() is not object`)));
});

describe('Check labels() returns object', () => {
  _.each($forms, (form, key) => it(`${key} labels() is object`, () =>
    assert.isObject(form.labels(), `${key}.labels() is not object`)));
});

describe('Check defaults() returns object', () => {
  _.each($forms, (form, key) => it(`${key} defaults() is object`, () =>
    assert.isObject(form.defaults(), `${key}.defaults() is not object`)));
});

describe('Check initials() returns object', () => {
  _.each($forms, (form, key) => it(`${key} initials() is object`, () =>
    assert.isObject(form.initials(), `${key}.initials() is not object`)));
});

describe('Check eventsRunning() returns boolean', () => {
  _.each($forms, (form, key) => it(`${key} eventsRunning() is boolean`, () =>
    assert.isBoolean(form.eventsRunning(), `${key}.eventsRunning() is not boolean`)));
});

describe('Check hasError returns boolean', () => {
  _.each($forms, (form, key) => it(`${key} hasError is boolean`, () =>
    assert.isBoolean(form.hasError, `${key}.hasError is not boolean`)));
});

describe('Check isDirty returns boolean', () => {
  _.each($forms, (form, key) => it(`${key} isDirty is boolean`, () =>
    assert.isBoolean(form.isDirty, `${key}.isDirty is not boolean`)));
});

describe('Check isPristine returns boolean', () => {
  _.each($forms, (form, key) => it(`${key} isPristine is boolean`, () =>
    assert.isBoolean(form.isPristine, `${key}.isPristine is not boolean`)));
});

describe('Check isDefault returns boolean', () => {
  _.each($forms, (form, key) => it(`${key} isDefault is boolean`, () =>
    assert.isBoolean(form.isDefault, `${key}.isDefault is not boolean`)));
});

describe('Check isValid returns boolean', () => {
  _.each($forms, (form, key) => it(`${key} isValid is boolean`, () =>
    assert.isBoolean(form.isValid, `${key}.isValid is not boolean`)));
});

describe('Check isEmpty returns boolean', () => {
  _.each($forms, (form, key) => it(`${key} isEmpty is boolean`, () =>
    assert.isBoolean(form.isEmpty, `${key}.isEmpty is not boolean`)));
});
<|endoftext|>


<commit_before>module('atom');

/* Inheritance tests */
test('B prototype should inherit all A attributes', function () {
    function A () {
        this.color = 'red';
        this.count = 10;
    }

    A.prototype.game = 'Super Mario';

    function B () { }

    B.inherits(A);
    equals((new B()).color, 'red');
    equals((new B()).count, 10);
    equals((new B()).game, 'Super Mario');
});

test('B prototype should inherit all A methods', function () {
    function A () {}
    A.extend({ getColor: function () { return 'red'; } });

    function B () {};
    B.inherits(A);

    equals((new B()).getColor(), 'red');
});

test('It should be possible to create simple key/val elements', function () {
    var selement = new atom.SimpleElement('key', 'val');
    equals(selement.toString(), '<key>val</key>');
});

test('It should be possible to extend simple elements', function () {
    var selement = new atom.SimpleElement('k', 'v');
    equals(selement.toString(), '<k>v</k>');
    selement.append(new atom.SimpleElement('sub', 'subv'));
    equals(selement.toString(), '<k>vsubv</k>');
});

test('Link objects can have href, title and rel attrs', function () {
    var link = new atom.Link();
    try {
        link.toString();
        ok(false, "should not be reached");
    } catch (e) {
        ok(true, "href attr is required");
    }

    link.setHref('http://gnome.org');

    equal(link.toString(), '<link href="http://gnome.org">');

    link.setTitle('Link Title');
    equal(link.toString(), '<link href="http://gnome.org" ' +
          'title="Link Title">');

    link.setRel('alternate');
    equal(link.toString(), '<link href="http://gnome.org" ' +
          'title="Link Title" rel="alternate">');
});

test('Content objects should have a type attr defined', function () {
    var ct = new atom.Content();
    try {
        ct.toString();
        ok(false, 'Not reached');
    } catch (e) {
        ok(true, 'type param is required');
    }
});

test('Content objects should not fill both src and content attrs', function () {
    var ct = new atom.Content('text/plain');
    ct.setSrc('http://gnu.org');
    ct.setContent('Blah');

    try {
        ct.toString();
        ok(false, 'Not reached');
    } catch (e) {
        ok(true, 'both src and content attrs cannot be filled');
    }
});

test('It should be possible to describe a person with name, email and an uri',
function () {
    var person = new atom.Person('Lincoln');
    equals(person.toString(), '<author><name>Lincoln</name></author>');

    person.setEmail('lincoln@comum.org');
    equals(person.toString(), '<author><name>Lincoln</name>' +
           '<email>lincoln@comum.org</email></author>');

    person.setIri('http://comum.org');
    equals(person.toString(), '<author><name>Lincoln</name>' +
           '<email>lincoln@comum.org</email>' +
           '<uri>http://comum.org</uri>' +
           '</author>');
});

test('It should be possible to describe categories with term, label and ' +
'schme attrs', function () {
    var cat = new atom.Category();
    try {
        cat.toString();
        ok(false, 'Not reached');
    } catch (e) {
        ok(true, "The `term' attribute is required");
    }

});
<commit_msg>Adding more tests to the Category object<commit_after>module('atom');

/* Inheritance tests */
test('B prototype should inherit all A attributes', function () {
    function A () {
        this.color = 'red';
        this.count = 10;
    }

    A.prototype.game = 'Super Mario';

    function B () { }

    B.inherits(A);
    equals((new B()).color, 'red');
    equals((new B()).count, 10);
    equals((new B()).game, 'Super Mario');
});

test('B prototype should inherit all A methods', function () {
    function A () {}
    A.extend({ getColor: function () { return 'red'; } });

    function B () {};
    B.inherits(A);

    equals((new B()).getColor(), 'red');
});

test('It should be possible to create simple key/val elements', function () {
    var selement = new atom.SimpleElement('key', 'val');
    equals(selement.toString(), '<key>val</key>');
});

test('It should be possible to extend simple elements', function () {
    var selement = new atom.SimpleElement('k', 'v');
    equals(selement.toString(), '<k>v</k>');
    selement.append(new atom.SimpleElement('sub', 'subv'));
    equals(selement.toString(), '<k>vsubv</k>');
});

test('Link objects can have href, title and rel attrs', function () {
    var link = new atom.Link();
    try {
        link.toString();
        ok(false, "should not be reached");
    } catch (e) {
        ok(true, "href attr is required");
    }

    link.setHref('http://gnome.org');

    equal(link.toString(), '<link href="http://gnome.org">');

    link.setTitle('Link Title');
    equal(link.toString(), '<link href="http://gnome.org" ' +
          'title="Link Title">');

    link.setRel('alternate');
    equal(link.toString(), '<link href="http://gnome.org" ' +
          'title="Link Title" rel="alternate">');
});

test('Content objects should have a type attr defined', function () {
    var ct = new atom.Content();
    try {
        ct.toString();
        ok(false, 'Not reached');
    } catch (e) {
        ok(true, 'type param is required');
    }
});

test('Content objects should not fill both src and content attrs', function () {
    var ct = new atom.Content('text/plain');
    ct.setSrc('http://gnu.org');
    ct.setContent('Blah');

    try {
        ct.toString();
        ok(false, 'Not reached');
    } catch (e) {
        ok(true, 'both src and content attrs cannot be filled');
    }
});

test('It should be possible to describe a person with name, email and an uri',
function () {
    var person = new atom.Person('Lincoln');
    equals(person.toString(), '<author><name>Lincoln</name></author>');

    person.setEmail('lincoln@comum.org');
    equals(person.toString(), '<author><name>Lincoln</name>' +
           '<email>lincoln@comum.org</email></author>');

    person.setIri('http://comum.org');
    equals(person.toString(), '<author><name>Lincoln</name>' +
           '<email>lincoln@comum.org</email>' +
           '<uri>http://comum.org</uri>' +
           '</author>');
});

test('It should be possible to describe categories with term, label and ' +
'schme attrs', function () {
    var cat = new atom.Category();
    try {
        cat.toString();
        ok(false, 'Not reached');
    } catch (e) {
        ok(true, "The `term' attribute is required");
    }

    cat.setTerm('myterm');
    equals(cat.toString(), '<category term="myterm"></category>');

    cat.setLabel('My Label');
    equals(cat.toString(), '<category term="myterm" label="My Label">' +
           '</category>');

    cat.setScheme('http://guake.org');
    equals(cat.toString(), '<category term="myterm" label="My Label" ' +
           'scheme="http://guake.org"></category>');
});
<|endoftext|>


<commit_before>/*global describe, it*/
'use strict';

var pollinate = require('../lib/index.js');
var assert = require('chai').assert;
var rimraf = require('rimraf');

describe('Test basic example', function () {
    it('GitHub with json string', function (done) {
        this.timeout(10000);
        pollinate({
            "inputs": [
                "howardroark/webapp",
                "{\"name\":\"newproject\",\"container\":\"alpine\"}"
            ],
            "options": {
                //..
            }
        }, function (err, result) {
            assert.isNull(err);
            assert.isObject(result);
            rimraf('newproject', done);
        });
    });
    it('GitHub with json file', function (done) {
        this.timeout(10000);
        pollinate({
            "inputs": [
                "howardroark/webapp",
                "tests/data.json"
            ],
            "options": {
                //..
            }
        }, function (err, result) {
            assert.isNull(err);
            assert.isObject(result);
            rimraf('newproject', done);
        });
    });
    it('GitHub with json url', function (done) {
        this.timeout(10000);
        pollinate({
            "inputs": [
                "howardroark/webapp",
                "https://raw.githubusercontent.com/howardroark/pollinate/develop/tests/data.json"
            ],
            "options": {
                //..
            }
        }, function (err, result) {
            assert.isNull(err);
            assert.isObject(result);
            rimraf('newproject', done);
        });
    });
    it('Git with json string', function (done) {
        this.timeout(10000);
        pollinate({
            "inputs": [
                "https://github.com/howardroark/webapp.git",
                "{\"name\":\"newproject\",\"container\":\"alpine\"}"
            ],
            "options": {
                //..
            }
        }, function (err, result) {
            assert.isNull(err);
            assert.isObject(result);
            rimraf('newproject', done);
        });
    });
    it('GitHub with options', function (done) {
        this.timeout(10000);
        pollinate({
            "inputs": [
                "howardroark/webapp"
            ],
            "options": {
                "name": "test",
                "container": "ubuntu"
            }
        }, function (err, result) {
            assert.isNull(err);
            assert.isObject(result);
            rimraf('test', done);
        });
    });
    it('Local path with json file', function (done) {
        this.timeout(10000);
        pollinate({
            "inputs": [
                "./tests/template",
                "tests/data.json"
            ],
            "options": {
                //..
            }
        }, function (err, result) {
            assert.isNull(err);
            assert.isObject(result);
            rimraf('newproject', done);
        });
    });
    it('Local path without template.json, json file with discard omitted', function (done) {
        this.timeout(10000);
        pollinate({
            "inputs": [
                "./tests/template-no-data/",
                "tests/data-no-discard.json"
            ],
            "options": {
                //
            }
        }, function (err, result) {
            assert.isNull(err);
            assert.isObject(result);
            rimraf('newproject', done);
        });
    });
    it('Local path without template.json, json file with parse set to all', function (done) {
        this.timeout(10000);
        pollinate({
            "inputs": [
                "./tests/template-no-data/",
                "tests/data-parse-all.json"
            ],
            "options": {
                //
            }
        }, function (err, result) {
            assert.isNull(err);
            assert.isObject(result);
            rimraf('newproject', done);
        });
    });
    it('Local path without template.json, json file with move omitted', function (done) {
        this.timeout(10000);
        pollinate({
            "inputs": [
                "./tests/template-no-data/",
                "tests/data-no-move.json"
            ],
            "options": {
                //
            }
        }, function (err, result) {
            assert.isNull(err);
            assert.isObject(result);
            rimraf('newproject', done);
        });
    });
    it('Local path without template.json, json file with complete', function (done) {
        this.timeout(10000);
        pollinate({
            "inputs": [
                "./tests/template-no-data/",
                "tests/data-complete.json"
            ],
            "options": {
                //
            }
        }, function (err, result) {
            assert.isNull(err);
            assert.isObject(result);
            rimraf('newproject', done);
        });
    });
});
<commit_msg>test(tests): test pollinate with refs<commit_after>/*global describe, it*/
'use strict';

var pollinate = require('../lib/index.js');
var assert = require('chai').assert;
var rimraf = require('rimraf');
var fs = require('fs');
var path = require('path');

describe('Test basic example', function () {
    it('GitHub with json string', function (done) {
        this.timeout(10000);
        pollinate({
            "inputs": [
                "howardroark/webapp",
                "{\"name\":\"newproject\",\"container\":\"alpine\"}"
            ],
            "options": {
                //..
            }
        }, function (err, result) {
            assert.isNull(err);
            assert.isObject(result);
            fs.readFile(path.join('newproject', 'README.md'), 'utf8', function (err, data) {
                assert.isNull(err);
                assert.notInclude(data, 'This branch is for testing `pollinate howardroark/webapp#test-branch`.');
                rimraf('newproject', done);
            });
        });
    });
    it('GitHub with json file', function (done) {
        this.timeout(10000);
        pollinate({
            "inputs": [
                "howardroark/webapp",
                "tests/data.json"
            ],
            "options": {
                //..
            }
        }, function (err, result) {
            assert.isNull(err);
            assert.isObject(result);
            rimraf('newproject', done);
        });
    });
    it('GitHub with json url', function (done) {
        this.timeout(10000);
        pollinate({
            "inputs": [
                "howardroark/webapp",
                "https://raw.githubusercontent.com/howardroark/pollinate/develop/tests/data.json"
            ],
            "options": {
                //..
            }
        }, function (err, result) {
            assert.isNull(err);
            assert.isObject(result);
            rimraf('newproject', done);
        });
    });
    it('Git with json string', function (done) {
        this.timeout(10000);
        pollinate({
            "inputs": [
                "https://github.com/howardroark/webapp.git",
                "{\"name\":\"newproject\",\"container\":\"alpine\"}"
            ],
            "options": {
                //..
            }
        }, function (err, result) {
            assert.isNull(err);
            assert.isObject(result);
            rimraf('newproject', done);
        });
    });
    it('GitHub with options', function (done) {
        this.timeout(10000);
        pollinate({
            "inputs": [
                "howardroark/webapp"
            ],
            "options": {
                "name": "test",
                "container": "ubuntu"
            }
        }, function (err, result) {
            assert.isNull(err);
            assert.isObject(result);
            rimraf('test', done);
        });
    });
    it('GitHub with ref', function (done) {
        this.timeout(10000);
        pollinate({
            "inputs": [
                "howardroark/webapp#test-branch",
                "{\"name\":\"newproject\",\"container\":\"alpine\"}"
            ],
            "options": {
                //..
            }
        }, function (err, result) {
            assert.isNull(err);
            assert.isObject(result);
            fs.readFile(path.join('newproject', 'README.md'), 'utf8', function (err, data) {
                assert.isNull(err);
                assert.include(data, 'This branch is for testing `pollinate howardroark/webapp#test-branch`.');
                rimraf('newproject', done);
            });
        });
    });
    it('Git with ref', function (done) {
        this.timeout(10000);
        pollinate({
            "inputs": [
                "https://github.com/howardroark/webapp.git#test-branch",
                "{\"name\":\"newproject\",\"container\":\"alpine\"}"
            ],
            "options": {
                //..
            }
        }, function (err, result) {
            assert.isNull(err);
            assert.isObject(result);
            fs.readFile(path.join('newproject', 'README.md'), 'utf8', function (err, data) {
                assert.isNull(err);
                assert.include(data, 'This branch is for testing `pollinate howardroark/webapp#test-branch`.');
                rimraf('newproject', done);
            });
        });
    });
    it('Local path with json file', function (done) {
        this.timeout(10000);
        pollinate({
            "inputs": [
                "./tests/template",
                "tests/data.json"
            ],
            "options": {
                //..
            }
        }, function (err, result) {
            assert.isNull(err);
            assert.isObject(result);
            rimraf('newproject', done);
        });
    });
    it('Local path without template.json, json file with discard omitted', function (done) {
        this.timeout(10000);
        pollinate({
            "inputs": [
                "./tests/template-no-data/",
                "tests/data-no-discard.json"
            ],
            "options": {
                //
            }
        }, function (err, result) {
            assert.isNull(err);
            assert.isObject(result);
            rimraf('newproject', done);
        });
    });
    it('Local path without template.json, json file with parse set to all', function (done) {
        this.timeout(10000);
        pollinate({
            "inputs": [
                "./tests/template-no-data/",
                "tests/data-parse-all.json"
            ],
            "options": {
                //
            }
        }, function (err, result) {
            assert.isNull(err);
            assert.isObject(result);
            rimraf('newproject', done);
        });
    });
    it('Local path without template.json, json file with move omitted', function (done) {
        this.timeout(10000);
        pollinate({
            "inputs": [
                "./tests/template-no-data/",
                "tests/data-no-move.json"
            ],
            "options": {
                //
            }
        }, function (err, result) {
            assert.isNull(err);
            assert.isObject(result);
            rimraf('newproject', done);
        });
    });
    it('Local path without template.json, json file with complete', function (done) {
        this.timeout(10000);
        pollinate({
            "inputs": [
                "./tests/template-no-data/",
                "tests/data-complete.json"
            ],
            "options": {
                //
            }
        }, function (err, result) {
            assert.isNull(err);
            assert.isObject(result);
            rimraf('newproject', done);
        });
    });
});
<|endoftext|>


<commit_before>/*jslint indent:2*/
/*global require: true, console: true */
var GoogleContacts = require('../').GoogleContacts;
var assert = require('assert');
var contactsTested = false;
var contactTested = false;
var contactCreated = false;

var c = new GoogleContacts({
  token: process.env.GOOGLE_TOKEN
});

c.getContacts(function (err, contacts) {
  if (err) throw err;
  assert.ok(typeof contacts === 'object', 'Contacts is not an object');
  console.log(contacts);
  contactsTested = true;
});

c.getContact(function (err, contact) {
  if (err) throw err;
  assert.ok(typeof contact === 'object', 'Contact is not an object');
  console.log(contact);
  contactTested = true;
}, {id: process.env.GOOGLE_CONTACT_ID});

var contactToCreate = {
  entry: {
    name: {
      fullName: 'foo bar'
    },
    email: [{
      primary: true,
      address: 'foobar@foo.bar',
      type: 'home'
    }],
    phoneNumber: [{
      type: 'work',
      phoneNumber: '555555555'
    }]
  }
};

c.createContact(function (err, contact) {
  if (err) throw err;
  assert.ok(typeof contact === 'object', 'Contact is not an object');
  contactCreated = true;
}, contactToCreate);

process.on('exit', function () {
  if (!contactsTested || !contactTested || !contactCreated) {
    throw new Error('contact test failed');
  }
});
<commit_msg>Enhancement: removing unnecesary console.logs<commit_after>/*jslint indent:2*/
/*global require: true, console: true */
var GoogleContacts = require('../').GoogleContacts;
var assert = require('assert');
var contactsTested = false;
var contactTested = false;
var contactCreated = false;

var c = new GoogleContacts({
  token: process.env.GOOGLE_TOKEN
});

c.getContacts(function (err, contacts) {
  if (err) throw err;
  assert.ok(typeof contacts === 'object', 'Contacts is not an object');
  contactsTested = true;
});

c.getContact(function (err, contact) {
  if (err) throw err;
  assert.ok(typeof contact === 'object', 'Contact is not an object');
  contactTested = true;
}, {id: process.env.GOOGLE_CONTACT_ID});

var contactToCreate = {
  entry: {
    name: {
      fullName: 'foo bar'
    },
    email: [{
      primary: true,
      address: 'foobar@foo.bar',
      type: 'home'
    }],
    phoneNumber: [{
      type: 'work',
      phoneNumber: '555555555'
    }]
  }
};

c.createContact(function (err, contact) {
  if (err) throw err;
  assert.ok(typeof contact === 'object', 'Contact is not an object');
  contactCreated = true;
}, contactToCreate);

process.on('exit', function () {
  if (!contactsTested || !contactTested || !contactCreated) {
    throw new Error('contact test failed');
  }

  console.log("all tests passed");
});
<|endoftext|>


<commit_before>const isPlainObj = require('is-plain-obj');
const eslint = require('eslint');
const find = require('lodash.find');
const baseConf = require('..');
const reactConf = require('../browser');
const workflowConf = require('../workflow');
const reactString = require('./react');
const reactTsString = require('./react-typescript.js');
const baseString = require('./base');
const workflowString = require('./workflow');

function runEslint(string, configuration, fileName) {
  const linter = new eslint.CLIEngine({
    useEslintrc: false,
    baseConfig: configuration,
  });

  return linter.executeOnText(string, fileName).results[0].messages;
}

describe('rules', () => {
  test('base', () => {
    expect(isPlainObj(baseConf)).toBeTruthy();
    expect(isPlainObj(baseConf.rules)).toBeDefined();

    const errors = runEslint(baseString(), baseConf);

    // Enabled
    expect(find(errors, { ruleId: 'no-var' })).toBeDefined();
    expect(find(errors, { ruleId: 'no-unused-vars' })).toBeDefined();
    expect(find(errors, { ruleId: 'unicorn/import-index' })).toBeUndefined();

    // Disabled
    expect(find(errors, { ruleId: 'no-param-reassign/sort-comp' })).toBeUndefined();
    expect(find(errors, { ruleId: 'prefer-destructuring' })).toBeUndefined();
    expect(find(errors, { ruleId: 'class-methods-use-this' })).toBeUndefined();
    expect(find(errors, { ruleId: 'no-plusplus' })).toBeUndefined();
    expect(find(errors, { ruleId: 'no-underscore-dangle' })).toBeUndefined();
    expect(find(errors, { ruleId: 'promise/avoid-new' })).toBeUndefined();
    expect(find(errors, { ruleId: 'unicorn/prefer-includes' })).toBeUndefined();
    expect(find(errors, { ruleId: 'unicorn/prefer-node-remove' })).toBeUndefined();
    expect(find(errors, { ruleId: 'unicorn/prefer-node-append' })).toBeUndefined();
    expect(find(errors, { ruleId: 'no-restricted-syntax' })).toBeUndefined();
    expect(find(errors, { ruleId: 'global-require' })).toBeUndefined();
  });

  test('react', () => {
    expect(isPlainObj(reactConf)).toBeDefined();
    expect(isPlainObj(reactConf.rules)).toBeDefined();

    const errors = runEslint(reactString(), reactConf);

    // Enabled
    expect(find(errors, { ruleId: 'react/forbid-prop-types' })).toBeDefined();

    // Disabled
    expect(find(errors, { ruleId: 'react/sort-comp' })).toBeUndefined();
    expect(find(errors, { ruleId: 'react/require-default-props' })).toBeUndefined();
    expect(find(errors, { ruleId: 'jsx-a11y/anchor-is-valid' })).toBeUndefined();
    expect(find(errors, { ruleId: 'unicorn/no-for-loop' })).toBeUndefined();
  });

  test('typescript', () => {
    const errors = runEslint(reactTsString(), reactConf, 'example.tsx');
    expect(find(errors, { ruleId: '@typescript-eslint/ban-types' })).toBeDefined();
    expect(find(errors, { ruleId: '@typescript-eslint/no-unused-vars' })).toBeDefined();
    expect(find(errors, { ruleId: 'react/prop-types' })).toBeUndefined();
    expect(find(errors, { ruleId: 'react/jsx-props-no-spreading' })).toBeUndefined();
  });

  test('workflow', () => {
    const errors = runEslint(workflowString(), workflowConf, 'example.tsx');

    expect(find(errors, { ruleId: 'import/no-unresolved' })).toBeUndefined();
  });
});
<commit_msg>test: add test for unicorn/prefer-math-trunc<commit_after>const isPlainObj = require('is-plain-obj');
const eslint = require('eslint');
const find = require('lodash.find');
const baseConf = require('..');
const reactConf = require('../browser');
const workflowConf = require('../workflow');
const reactString = require('./react');
const reactTsString = require('./react-typescript.js');
const baseString = require('./base');
const workflowString = require('./workflow');

function runEslint(string, configuration, fileName) {
  const linter = new eslint.CLIEngine({
    useEslintrc: false,
    baseConfig: configuration,
  });

  return linter.executeOnText(string, fileName).results[0].messages;
}

describe('rules', () => {
  test('base', () => {
    expect(isPlainObj(baseConf)).toBeTruthy();
    expect(isPlainObj(baseConf.rules)).toBeDefined();

    const errors = runEslint(baseString(), baseConf);

    // Enabled
    expect(find(errors, { ruleId: 'no-var' })).toBeDefined();
    expect(find(errors, { ruleId: 'no-unused-vars' })).toBeDefined();
    expect(find(errors, { ruleId: 'unicorn/import-index' })).toBeUndefined();

    // Disabled
    expect(find(errors, { ruleId: 'no-param-reassign/sort-comp' })).toBeUndefined();
    expect(find(errors, { ruleId: 'prefer-destructuring' })).toBeUndefined();
    expect(find(errors, { ruleId: 'class-methods-use-this' })).toBeUndefined();
    expect(find(errors, { ruleId: 'no-plusplus' })).toBeUndefined();
    expect(find(errors, { ruleId: 'no-underscore-dangle' })).toBeUndefined();
    expect(find(errors, { ruleId: 'promise/avoid-new' })).toBeUndefined();
    expect(find(errors, { ruleId: 'unicorn/prefer-includes' })).toBeUndefined();
    expect(find(errors, { ruleId: 'unicorn/prefer-node-remove' })).toBeUndefined();
    expect(find(errors, { ruleId: 'unicorn/prefer-node-append' })).toBeUndefined();
    expect(find(errors, { ruleId: 'unicorn/prefer-math-trunc' })).toBeUndefined();
    expect(find(errors, { ruleId: 'no-restricted-syntax' })).toBeUndefined();
    expect(find(errors, { ruleId: 'global-require' })).toBeUndefined();
  });

  test('react', () => {
    expect(isPlainObj(reactConf)).toBeDefined();
    expect(isPlainObj(reactConf.rules)).toBeDefined();

    const errors = runEslint(reactString(), reactConf);

    // Enabled
    expect(find(errors, { ruleId: 'react/forbid-prop-types' })).toBeDefined();

    // Disabled
    expect(find(errors, { ruleId: 'react/sort-comp' })).toBeUndefined();
    expect(find(errors, { ruleId: 'react/require-default-props' })).toBeUndefined();
    expect(find(errors, { ruleId: 'jsx-a11y/anchor-is-valid' })).toBeUndefined();
    expect(find(errors, { ruleId: 'unicorn/no-for-loop' })).toBeUndefined();
  });

  test('typescript', () => {
    const errors = runEslint(reactTsString(), reactConf, 'example.tsx');
    expect(find(errors, { ruleId: '@typescript-eslint/ban-types' })).toBeDefined();
    expect(find(errors, { ruleId: '@typescript-eslint/no-unused-vars' })).toBeDefined();
    expect(find(errors, { ruleId: 'react/prop-types' })).toBeUndefined();
    expect(find(errors, { ruleId: 'react/jsx-props-no-spreading' })).toBeUndefined();
  });

  test('workflow', () => {
    const errors = runEslint(workflowString(), workflowConf, 'example.tsx');

    expect(find(errors, { ruleId: 'import/no-unresolved' })).toBeUndefined();
  });
});
<|endoftext|>


<commit_before>'use strict';

const {expect} = require ('chai');
const {execSync} = require('child_process');

describe('cal',() => {
  describe('CLI', () => {
  xit('should handle the current momth', () => {
    const goal = execSync('cal').toString();
    const output = execSync('./cal.js').toString();

    expect(output).to.equal(goal);
    });
  });

  describe("Zeller's congruence", () => {
    const zellers = require('../lib/zellers.js')

    describe('.modified_month', () => {
      it('return 13 for January', () => {
        expect(zellers.modifiedMonth(1)).to.equal(13);
      });

      it('return 14 for February', () => {
        expect(zellers.modifiedMonth(2)).to.equal(14);
      });

      it('return 3 for March', () => {
        expect(zellers.modifiedMonth(3)).to.equal(3);
      });
    });

    describe('.modifiedYear', () => {
      it('returns 2015 for Jan 2015', () => {
        expect(zellers.modifiedYear(2015, 1)).to.equal(2014);
      });
      // 2016, 2 === 2015
      // 2017, 3 === 2017
    });

    describe('.getDay', () => {
      it('returns 2 (Tuesday) for March 1, 2016', () => {
        expect(zellers.getDay(2016, 3, 1)).to.equal(2);
      });
      // 2000, 3, 1 === 3
      // 2100, 3, 1 === 1
      // 2200, 3, 2 === 0
      // 2300, 3, 1 === 4
     })
   })
});
<commit_msg>Test code for modified year and get day passing<commit_after>'use strict';

const {expect} = require ('chai');
const {execSync} = require('child_process');

describe('cal',() => {
  describe('CLI', () => {
  xit('should handle the current momth', () => {
    const goal = execSync('cal').toString();
    const output = execSync('./cal.js').toString();

    expect(output).to.equal(goal);
    });
  });

  describe("Zeller's congruence", () => {
    const zellers = require('../lib/zellers.js')

    describe('.modified_month', () => {
      it('return 13 for January', () => {
        expect(zellers.modifiedMonth(1)).to.equal(13);
      });

      it('return 14 for February', () => {
        expect(zellers.modifiedMonth(2)).to.equal(14);
      });

      it('return 3 for March', () => {
        expect(zellers.modifiedMonth(3)).to.equal(3);
      });
    });

    describe('.modifiedYear', () => {
      it('returns 2015 for Jan 2015', () => {
        expect(zellers.modifiedYear(2015, 1)).to.equal(2014);
      });

       it('returns 2015 for Feb 2015', () => {
        expect(zellers.modifiedYear(2016, 2)).to.equal(2015);
      });

      it('returns 2017 for Mar 2017', () => {
        expect(zellers.modifiedYear(2017, 3)).to.equal(2017);
      });
    });

    describe('.getDay', () => {
      it('returns 2 (Tuesday) for March 1, 2016', () => {
        expect(zellers.getDay(2016, 3, 1)).to.equal(2);
      });

      it('returns 3 (Wednesday) for March 1, 2000', () => {
       expect(zellers.getDay(2000, 3, 1)).to.equal(3);
      });

      it('returns 1 (Monday) for March 1, 2100', () => {
       expect(zellers.getDay(2100, 3, 1)).to.equal(1);
      });

      it('returns 0 (Sunday) for March 2, 2200', () => {
       expect(zellers.getDay(2200, 3, 2)).to.equal(0);
      });

      it('returns 4 (Thursday) for March 1, 2300', () => {
       expect(zellers.getDay(2300, 3, 1)).to.equal(4);
      });

      // 2200, 3, 2 === 0
      // 2300, 3, 1 === 4
     })

     describe('get the current month', () => {
      const Output = require('../lib/month.js');
      it('should load the current month', () => {
        const calResult = execSync('cal').toString();
        expect(Output.currentMonth()).to.equal(calResult);
      });
    });
   })
});
<|endoftext|>


<commit_before>import fs                       from 'fs'
import { expect }               from 'chai'
import postcss                  from 'postcss'
import postcssSelectorNamespace from '../lib/plugin'

export function transform(input, options = {}, postcssOptions = {}) {
  return postcss()
    .use(postcssSelectorNamespace(options))
    .process(input, postcssOptions)
}

export function compareFixture(name, options, postcssOptions) {
  let { css } = transform(
    fs.readFileSync(`${__dirname}/fixtures/${name}`),
    options,
    postcssOptions
  )

  let expected = fs.readFileSync(`${__dirname}/expected/${name}`)

  expect(String(css)).to.equal(String(expected))
}

describe('Basic functionality', () => {
  it('should work', () => {
    compareFixture('basic.css', {
      selfSelector: /:--component/,
      namespace: '.namespaced'
    })
  })

  it('has a default namespace selector of :--namespace', () => {
    let { css } = transform(
      ':--namespace {}',
      { namespace: '.my-component' }
    )

    expect(String(css)).to.equal(String('.my-component {}'))
  })

  it('works with a regexp which matches multiple selectors', () => {
    compareFixture('multiself.css', {
      selfSelector: /&|:--component/,
      namespace: '.my-component'
    })
  })
})

describe(':root', () => {
  it('is configurable', () => {
    let { css } = transform(
      ':root .foo {}:global .foo {}',
      { namespace: '.my-component', rootSelector: ':global' }
    )

    expect(String(css)).to.equal(String('.my-component :root .foo {}.foo {}'))
  })

  it('does not namespace :root selectors', () => {
    compareFixture('root.css', {
      selfSelector: /:--component/,
      namespace: '.my-component'
    })
  })

  it('does namespace :root selectors if ignoreRoot is false', () => {
    let { css } = transform(
      ':root .foo {}',
      { namespace: '.my-component', ignoreRoot: false }
    )

    expect(String(css)).to.equal(String('.my-component :root .foo {}'))
  })

  it('does drop :root if dropRoot is true', () => {
    let { css } = transform(
      ':root .foo {}',
      { namespace: '.my-component', dropRoot: false }
    )

    expect(String(css)).to.equal(String(':root .foo {}'))
  })
})

describe('SCSS', function() {
  const syntax = require('postcss-scss')

  it('does transform basic nesting', () => {
    let { css } = transform(
      '& { .bar { color: red; } }\n' +
      '.foo { color: blue }',
      { selfSelector: '&', namespace: '.my-component' }
    )

    expect(String(css)).to.equal(
      String('.my-component { .bar { color: red; } }\n' +
             '.my-component .foo { color: blue }')
    )
  })

  it('does work with single line comments', () => {
    let { css } = transform(
      '& { .bar { color: red; } }\n' +
      '//.foo { color: blue }',
      { selfSelector: '&', namespace: '.my-component' },
      { syntax }
    )

    expect(String(css)).to.equal(
      String('.my-component { .bar { color: red; } }\n' +
             '//.foo { color: blue }')
    )
  })

  it('does work with rules nested in nested media queries', () => {
    compareFixture('nested-media-queries.scss',
      { namespace: '.my-component' },
      { syntax }
    )
  })
})
<commit_msg>Remove unnecessary string cast<commit_after>import fs                       from 'fs'
import { expect }               from 'chai'
import postcss                  from 'postcss'
import postcssSelectorNamespace from '../lib/plugin'

export function transform(input, options = {}, postcssOptions = {}) {
  return postcss()
    .use(postcssSelectorNamespace(options))
    .process(input, postcssOptions)
}

export function compareFixture(name, options, postcssOptions) {
  let { css } = transform(
    fs.readFileSync(`${__dirname}/fixtures/${name}`),
    options,
    postcssOptions
  )

  let expected = fs.readFileSync(`${__dirname}/expected/${name}`)

  expect(String(css)).to.equal(String(expected))
}

describe('Basic functionality', () => {
  it('should work', () => {
    compareFixture('basic.css', {
      selfSelector: /:--component/,
      namespace: '.namespaced'
    })
  })

  it('has a default namespace selector of :--namespace', () => {
    let { css } = transform(
      ':--namespace {}',
      { namespace: '.my-component' }
    )

    expect(String(css)).to.equal('.my-component {}')
  })

  it('works with a regexp which matches multiple selectors', () => {
    compareFixture('multiself.css', {
      selfSelector: /&|:--component/,
      namespace: '.my-component'
    })
  })
})

describe(':root', () => {
  it('is configurable', () => {
    let { css } = transform(
      ':root .foo {}:global .foo {}',
      { namespace: '.my-component', rootSelector: ':global' }
    )

    expect(String(css)).to.equal('.my-component :root .foo {}.foo {}')
  })

  it('does not namespace :root selectors', () => {
    compareFixture('root.css', {
      selfSelector: /:--component/,
      namespace: '.my-component'
    })
  })

  it('does namespace :root selectors if ignoreRoot is false', () => {
    let { css } = transform(
      ':root .foo {}',
      { namespace: '.my-component', ignoreRoot: false }
    )

    expect(String(css)).to.equal('.my-component :root .foo {}')
  })

  it('does drop :root if dropRoot is true', () => {
    let { css } = transform(
      ':root .foo {}',
      { namespace: '.my-component', dropRoot: false }
    )

    expect(String(css)).to.equal(':root .foo {}')
  })
})

describe('SCSS', function() {
  const syntax = require('postcss-scss')

  it('does transform basic nesting', () => {
    let { css } = transform(
      '& { .bar { color: red; } }\n' +
      '.foo { color: blue }',
      { selfSelector: '&', namespace: '.my-component' }
    )

    expect(String(css)).to.equal(
      '.my-component { .bar { color: red; } }\n' +
      '.my-component .foo { color: blue }'
    )
  })

  it('does work with single line comments', () => {
    let { css } = transform(
      '& { .bar { color: red; } }\n' +
      '//.foo { color: blue }',
      { selfSelector: '&', namespace: '.my-component' },
      { syntax }
    )

    expect(String(css)).to.equal(
      '.my-component { .bar { color: red; } }\n' +
      '//.foo { color: blue }'
    )
  })

  it('does work with rules nested in nested media queries', () => {
    compareFixture('nested-media-queries.scss',
      { namespace: '.my-component' },
      { syntax }
    )
  })
})
<|endoftext|>


<commit_before>import test from 'ava';
import utils from '../lib/utils';

test('Single Item - Pass', t => {
  const input = [
    {
      id: 'foo',
      type: 'bar',
    },
    {
      id: 'bar',
      type: 'baz',
    },
  ];

  const expected = {
    id: 'bar',
    type: 'baz',
  };

  const result = utils.singleItem('id', 'bar', input);

  t.deepEqual(result, expected, 'A single object is retrieved from array based on key/value');
});

test('Single Item - Fail', t => {
  const input = [
    {
      id: 'foo',
      type: 'bar',
    },
    {
      id: 'bar',
      type: 'baz',
    },
  ];

  const result = utils.singleItem('id', 'waldo', input);

  t.false(result, '`false` is returned if no item found');
});

test('ISO UTC Time', t => {
  const time = {
    date: '2016-05-27',
    time: '21:56',
    zone: 'America/New_York',
  };

  const expected = '2016-05-28T01:56:00.000Z';

  const result = utils.time.iso(time.date, time.time, time.zone);

  const badResult = utils.time.iso(time.date, time.time);

  t.is(result, expected, 'Date, Time, and Zone converted to ISO UTC Date Time');
  t.is(badResult, null, 'If an item is not included, `null` is returned');
});

test('Input Time', t => {
  const time = '2016-05-28T01:56:00.000Z';

  const expected = {
    date: '2016-05-27',
    time: '21:56',
    zone: 'America/New_York',
  };

  const expectedUTC = {
    date: '2016-05-28',
    time: '01:56',
    zone: 'UTC',
  };

  const result = utils.time.input(time, 'America/New_York');
  const resultUTC = utils.time.input(time);
  const badResult = utils.time.input('');

  t.deepEqual(result, expected, 'ISO Date Time converted to date, time, and zone');
  t.deepEqual(resultUTC, expectedUTC, 'ISO Date Time converted to UTC date, time, and zone');
  t.is(badResult, null, 'Returns `null` if empty string passed in');
});

test('Config', t => {
  const input = {
    'name--text': 'Waldo',
    'email--email': 'foo@bar.baz',
    'address--street': '100 My Street',
    'address--city': 'New York',
    'address--state': 'NY',
    'address--zip': 10108,
  };

  const expected = {
    name: {
      text: {
        value: 'Waldo',
      },
    },
    email: {
      email: {
        value: 'foo@bar.baz',
      },
    },
    address: {
      street: {
        value: '100 My Street',
      },
      city: {
        value: 'New York',
      },
      state: {
        value: 'NY',
      },
      zip: {
        value: 10108,
      },
    },
  };

  const result = utils.config(input);

  t.deepEqual(result, expected, 'Transforms input name:value in to object');
});

test('Request Format', t => {
  const input = {
    'sunset-date': '',
    'sunset-time': '',
    'sunrise-date': '2016-06-23',
    'sunrise-time': '00:00',
    'service-name--text--0': 'bar',
    'service-name--text--1': '',
    'service-email--email--0': 'foo@test.com',
    'service-email--email--1': '',
    'service-email--email--2': 'bar@test.com',
    'service-email--email--3': '',
  };

  const expected = {
    'sunset-date': { value: '' },
    'sunset-time': { value: '' },
    'sunrise-date': { value: '2016-06-23' },
    'sunrise-time': { value: '00:00' },
    'service-name': {
      text: { value: 'bar' },
    },
    'service-email': [
      {
        email: { 'value': 'foo@test.com' },
      },
      {
        email: { 'value': 'bar@test.com' },
      },
    ],
  };
  const result = utils.format(input);
  t.is(JSON.stringify(result), JSON.stringify(expected), 'A single object is retrieved from array based on key/value');
  t.deepEqual(result, expected, 'A single object is retrieved from array based on key/value');
});

<commit_msg>:white_check_mark: testing identifier getter<commit_after>import test from 'ava';
import utils from '../lib/utils';

test('Single Item - Pass', t => {
  const input = [
    {
      id: 'foo',
      type: 'bar',
    },
    {
      id: 'bar',
      type: 'baz',
    },
  ];

  const expected = {
    id: 'bar',
    type: 'baz',
  };

  const result = utils.singleItem('id', 'bar', input);

  t.deepEqual(result, expected, 'A single object is retrieved from array based on key/value');
});

test('Single Item - Fail', t => {
  const input = [
    {
      id: 'foo',
      type: 'bar',
    },
    {
      id: 'bar',
      type: 'baz',
    },
  ];

  const result = utils.singleItem('id', 'waldo', input);

  t.false(result, '`false` is returned if no item found');
});

test('ISO UTC Time', t => {
  const time = {
    date: '2016-05-27',
    time: '21:56',
    zone: 'America/New_York',
  };

  const expected = '2016-05-28T01:56:00.000Z';

  const result = utils.time.iso(time.date, time.time, time.zone);

  const badResult = utils.time.iso(time.date, time.time);

  t.is(result, expected, 'Date, Time, and Zone converted to ISO UTC Date Time');
  t.is(badResult, null, 'If an item is not included, `null` is returned');
});

test('Input Time', t => {
  const time = '2016-05-28T01:56:00.000Z';

  const expected = {
    date: '2016-05-27',
    time: '21:56',
    zone: 'America/New_York',
  };

  const expectedUTC = {
    date: '2016-05-28',
    time: '01:56',
    zone: 'UTC',
  };

  const result = utils.time.input(time, 'America/New_York');
  const resultUTC = utils.time.input(time);
  const badResult = utils.time.input('');

  t.deepEqual(result, expected, 'ISO Date Time converted to date, time, and zone');
  t.deepEqual(resultUTC, expectedUTC, 'ISO Date Time converted to UTC date, time, and zone');
  t.is(badResult, null, 'Returns `null` if empty string passed in');
});

test('Config', t => {
  const input = {
    'name--text': 'Waldo',
    'email--email': 'foo@bar.baz',
    'address--street': '100 My Street',
    'address--city': 'New York',
    'address--state': 'NY',
    'address--zip': 10108,
  };

  const expected = {
    name: {
      text: {
        value: 'Waldo',
      },
    },
    email: {
      email: {
        value: 'foo@bar.baz',
      },
    },
    address: {
      street: {
        value: '100 My Street',
      },
      city: {
        value: 'New York',
      },
      state: {
        value: 'NY',
      },
      zip: {
        value: 10108,
      },
    },
  };

  const result = utils.config(input);

  t.deepEqual(result, expected, 'Transforms input name:value in to object');
});

test('Request Format', t => {
  const input = {
    'sunset-date': '',
    'sunset-time': '',
    'sunrise-date': '2016-06-23',
    'sunrise-time': '00:00',
    'service-name--text--0': 'bar',
    'service-name--text--1': '',
    'service-email--email--0': 'foo@test.com',
    'service-email--email--1': '',
    'service-email--email--2': 'bar@test.com',
    'service-email--email--3': '',
  };

  const expected = {
    'sunset-date': { value: '' },
    'sunset-time': { value: '' },
    'sunrise-date': { value: '2016-06-23' },
    'sunrise-time': { value: '00:00' },
    'service-name': {
      text: { value: 'bar' },
    },
    'service-email': [
      {
        email: { 'value': 'foo@test.com' },
      },
      {
        email: { 'value': 'bar@test.com' },
      },
    ],
  };
  const result = utils.format(input);
  t.is(JSON.stringify(result), JSON.stringify(expected), 'A single object is retrieved from array based on key/value');
  t.deepEqual(result, expected, 'A single object is retrieved from array based on key/value');
});

test('Get identifier', t => {
  const rows = [
    {
      'value': {
	'service-name': {
	  'text': {
	    'value': 'This is the test title',
	  },
	},
      },
    },
  ];
  const type = {
    'identifier': 'service-name',
    'attributes':
    [
      {
	'name': 'Service Name',
	'description': 'Write a really cool name please.',
	'inputs': {
	  'text': {
	    'name': 'service-name--text',
	  },
	},
	'id': 'service-name',
	'type': 'text',
      },
    ],
  };
  const result = utils.routes.identifier(rows, type);
  t.is(result[0].identifier, 'This is the test title', 'Should have title as identifier');
});

test('Sad empty identifier value', t => {
  const rows = [
    {
      'value': {
	'service-name': {
	  'text': {
	    'value': '',
	  },
	},
      },
    },
  ];
  const type = {
    'identifier': 'service-name',
    'attributes':
    [
      {
	'name': 'Service Name',
	'description': 'Write a really cool name please.',
	'inputs': {
	  'text': {
	    'name': 'service-name--text',
	  },
	},
	'id': 'service-name',
	'type': 'text',
      },
    ],
  };
  const result = utils.routes.identifier(rows, type);
  t.is(result[0].identifier, '(No identifier available)', 'Should have title as identifier');
});
<|endoftext|>


<commit_before>var request = require('superagent'),
    Q = require('q');

var METHOD_MAP = {
  'create': 'post',
  'update': 'put',
  'delete': 'del',
  'read': 'get',
  'patch': 'patch'
};

var send = function (method, model, options, url, data, resolve, reject) {
  // Allow intercepting of the request object to inject sync-wide things like
  // an oAuth token.
  var req = request[METHOD_MAP[method]](url);
  module.exports.editRequest(req, method, model, options);
  // Inject POST/PUT data in body or GET data in querystring
  if (method == 'create' || method == 'update') {
    req.send(data);
  } else {
    req.query(data);
  }
  // Add common Backbone options like `headers`
  if (options.headers) {
    for(key in options.headers) req.set(key, options.headers[key]);
  }
  req.timeout(2000).end(function(err, res) {
    err ? error(options, err, reject) : success(options, res, resolve);
  });
}

var success = function(options, res, resolve) {
  options.res = { headers: res.headers };
  if (options.success) options.success(res.body);
  if (options.complete) options.complete(res.body);
  resolve(res.body);
}

var error = function(options, err, reject) {
  if (options.error) options.error(err);
  if (options.complete) options.complete(err);
  reject(err);
}

module.exports = function(method, model, options) {
  var url = (options.url ||
    (typeof model.url == 'function' ? model.url() : model.url));
  var data = (options.data ||
    (method === 'create' || method === 'update' ? model.toJSON() : {}));
  var cacheClient = module.exports.cacheClient;
  var cacheTime = options.cacheTime || module.exports.defaultCacheTime;
  var cacheKey = url + JSON.stringify(data);
  var cached = options.cache && cacheClient;
  return Q.promise(function(resolve, reject) {
    if (cached) {
      cacheClient.get(cacheKey, function(err, cachedJSON) {
        if (err) {
          error(options, err, reject);
        } else if (cachedJSON) {
          success(options, JSON.parse(cachedJSON), resolve);
        } else {
          send(method, model, options, url, data, resolve, reject);
        }
      });
    } else {
      send(method, model, options, url, data, resolve, reject);
    }
    model.trigger('request', model, {}, options);
    resolve();
  });
};

// Used to modify request objects mid-flight
module.exports.editRequest = function(req) {}

// When set will look for the cache: true option in requests and use this client
// to naively cache requests.
module.exports.cacheClient = null
module.exports.defaultCacheTime = 3600<commit_msg>latest<commit_after>var request = require('superagent'),
    Q = require('q');

var METHOD_MAP = {
  'create': 'post',
  'update': 'put',
  'delete': 'del',
  'read': 'get',
  'patch': 'patch'
};

var send = function (method, model, options, url, data, resolve, reject) {
  // Allow intercepting of the request object to inject sync-wide things like
  // an oAuth token.
  var req = request[METHOD_MAP[method]](url);
  module.exports.editRequest(req, method, model, options);
  // Inject POST/PUT data in body or GET data in querystring
  if (method == 'create' || method == 'update') {
    req.send(data);
  } else {
    req.query(data);
  }
  // Add common Backbone options like `headers`
  if (options.headers) {
    for(key in options.headers) req.set(key, options.headers[key]);
  }
  req.timeout(7000).end(function(err, res) {
    err ? error(options, err, reject) : success(options, res, resolve);
  });
}

var success = function(options, res, resolve) {
  options.res = { headers: res.headers };
  if (options.success) options.success(res.body);
  if (options.complete) options.complete(res.body);
  resolve(res.body);
}

var error = function(options, err, reject) {
  if (options.error) options.error(err);
  if (options.complete) options.complete(err);
  reject(err);
}

module.exports = function(method, model, options) {
  var url = (options.url ||
    (typeof model.url == 'function' ? model.url() : model.url));
  var data = (options.data ||
    (method === 'create' || method === 'update' ? model.toJSON() : {}));
  var cacheClient = module.exports.cacheClient;
  var cacheTime = options.cacheTime || module.exports.defaultCacheTime;
  var cacheKey = url + JSON.stringify(data);
  var cached = options.cache && cacheClient;
  return Q.promise(function(resolve, reject) {
    if (cached) {
      cacheClient.get(cacheKey, function(err, cachedJSON) {
        if (err) {
          error(options, err, reject);
        } else if (cachedJSON) {
          success(options, JSON.parse(cachedJSON), resolve);
        } else {
          send(method, model, options, url, data, resolve, reject);
        }
      });
    } else {
      send(method, model, options, url, data, resolve, reject);
    }
    model.trigger('request', model, {}, options);
    resolve();
  });
};

// Used to modify request objects mid-flight
module.exports.editRequest = function(req) {}

// When set will look for the cache: true option in requests and use this client
// to naively cache requests.
module.exports.cacheClient = null
module.exports.defaultCacheTime = 3600<|endoftext|>


<commit_before>import React from 'react'
import { bindActionCreators } from 'redux'
import { connect } from 'react-redux'
import { View, TextInput, TouchableOpacity, ActivityIndicator, Dimensions, Animated } from 'react-native'
import KeyboardComponent from './KeyboardComponent'
import * as actions from '../store/reducer/sendMoney'
import { openLoginForm } from '../store/reducer/login'
import merge from '../util/merge'
import { LOGIN_STATUSES } from '../store/reducer/login'
import DefaultText from './DefaultText'
import color from '../util/colors'
import { dimensions } from '../util/StyleUtils'

const Page = {
  Ready: 0,
  EnterAmount: 1,
  MakingPayment: 2,
  PaymentComplete: 3,
}

const { width } = Dimensions.get('window')
export const sectionHeight = 68

const styles = {
  button: {
    height: sectionHeight,
    flex: 1,
    justifyContent: 'center',
    alignItems: 'center',
  },
  buttonInnerContainer: {
    alignItems: 'center',
    flexDirection: 'row',
    backgroundColor: 'transparent'
  },
  textInput: {
    ...dimensions(width, sectionHeight),
    padding: 10,
    textAlign: 'center'
  },
  loadingSpinner: {
    backgroundColor: color.transparent,
    marginLeft: 20
  }
}

class InputComponent extends KeyboardComponent {
  getButtonColor() {
    const { input, invalidInput } = this.props
    if (input && input.value && invalidInput) {
      return color.offWhite
    }
    return color.bristolBlue
  }

  getButtonTextColor() {
    return this.getButtonColor() === color.offWhite ? 'black' : 'white'
  }

  render() {
    let { onButtonPress, buttonText, loading, input, invalidInput, accessibilityLabel } = this.props

    return <Animated.View style={{backgroundColor: 'white', bottom: input ? this.state.keyboardHeight : 0}} accessibilityLabel={accessibilityLabel}>
      <TouchableOpacity style={merge(styles.button, {backgroundColor: this.getButtonColor()})}
          onPress={() => invalidInput ? undefined : onButtonPress()}>
        <View style={styles.buttonInnerContainer}>
          <DefaultText style={{fontSize: 24, color: this.getButtonTextColor()}}>
            {buttonText}
          </DefaultText>

          { loading
            ? <ActivityIndicator size='small' style={styles.loadingSpinner}/>
            : undefined }
        </View>
      </TouchableOpacity>

      { input
        ? <TextInput style={styles.textInput}
              {...input}
              autoFocus={true}
              accessibilityLabel={input.placeholder} />
      : undefined }

    </Animated.View>
  }
}

class SendMoney extends React.Component {

  constructor() {
    super()
    this.state = {
      inputPage: Page.Ready,
    }
  }

  nextPage() {
    const nextPage = (this.state.inputPage + 1) % Object.keys(Page).length
    this.setState({ inputPage: nextPage })
    if (nextPage === Page.PaymentComplete) {
      setTimeout(() => {
        if (this.state.inputPage === Page.PaymentComplete) {
          this.nextPage()
        }
      }, 1800)
    }
  }

  componentDidUpdate(prevProps) {
    if (this.props.businessId !== prevProps.businessId) {
      this.props.updateAmount('')
      this.setState({ inputPage: Page.Ready })
    } else if (prevProps.loading && !this.props.loading && this.state.inputPage === 2) {
      this.nextPage()
    }
  }

  render() {
    let inputProps

    if (this.props.loggedIn) {
      switch (this.state.inputPage){
        case Page.Ready: // Initial state, ready to begin
          inputProps = {
            buttonText: 'Send Payment',
            onButtonPress: () => { this.props.updatePayee(this.props.payeeShortDisplay); this.nextPage() },
            accessibilityLabel: 'Ready',
          }
          break
        case Page.EnterAmount: // provide amount
          inputProps = {
            buttonText: 'Pay ' + this.props.payeeDisplay,
            onButtonPress: () => { this.props.sendTransaction(); this.nextPage() },
            input: {
              keyboardType: 'numeric',
              value: this.props.amount,
              placeholder: 'Amount',
              onChangeText: amt => this.props.updateAmount(amt),
            },
            invalidInput: isNaN(Number(this.props.amount)) || Number(this.props.amount) > this.props.balance || Number(this.props.amount) <= 0,
            accessibilityLabel: 'Enter Amount',
          }
          break
        case Page.MakingPayment: // in progress
          inputProps = {
            buttonText: 'Making Payment',
            loading: true,
            accessibilityLabel: 'Making Payment',
          }
          break
        case Page.PaymentComplete: // payment completed
          inputProps = {
            buttonText: this.props.message,
            onButtonPress: () => { this.props.resetForm(); this.nextPage() },
            accessibilityLabel: 'Payment complete',
          }
          break
      }
    } else {
      inputProps = {
        buttonText: 'Log in to make payment',
        onButtonPress: () => this.props.openLoginForm(true),
        accessibilityLabel: 'Log in to make payment',
      }
    }

    return <InputComponent {...inputProps} />
  }
}

const mapDispatchToProps = (dispatch) =>
  bindActionCreators({ ...actions, openLoginForm }, dispatch)

const mapStateToProps = (state) => ({
  ...state.sendMoney,
  balance: state.account.balance,
  loggedIn: state.login.loginStatus === LOGIN_STATUSES.LOGGED_IN
})

export default connect(mapStateToProps, mapDispatchToProps)(SendMoney)
<commit_msg>crop long name<commit_after>import React from 'react'
import { bindActionCreators } from 'redux'
import { connect } from 'react-redux'
import { View, TextInput, TouchableOpacity, ActivityIndicator, Dimensions, Animated } from 'react-native'
import KeyboardComponent from './KeyboardComponent'
import * as actions from '../store/reducer/sendMoney'
import { openLoginForm } from '../store/reducer/login'
import merge from '../util/merge'
import { LOGIN_STATUSES } from '../store/reducer/login'
import DefaultText from './DefaultText'
import color from '../util/colors'
import { dimensions } from '../util/StyleUtils'

const Page = {
  Ready: 0,
  EnterAmount: 1,
  MakingPayment: 2,
  PaymentComplete: 3,
}

const { width } = Dimensions.get('window')
export const sectionHeight = 68

const styles = {
  button: {
    height: sectionHeight,
    flex: 1,
    justifyContent: 'center',
    alignItems: 'center',
  },
  buttonInnerContainer: {
    alignItems: 'center',
    flexDirection: 'row',
    backgroundColor: 'transparent'
  },
  textInput: {
    ...dimensions(width, sectionHeight),
    padding: 10,
    textAlign: 'center'
  },
  loadingSpinner: {
    backgroundColor: color.transparent,
    marginLeft: 20
  }
}

class InputComponent extends KeyboardComponent {
  getButtonColor() {
    const { input, invalidInput } = this.props
    if (input && input.value && invalidInput) {
      return color.offWhite
    }
    return color.bristolBlue
  }

  getButtonTextColor() {
    return this.getButtonColor() === color.offWhite ? 'black' : 'white'
  }

  render() {
    let { onButtonPress, buttonText, loading, input, invalidInput, accessibilityLabel } = this.props

    return <Animated.View style={{backgroundColor: 'white', bottom: input ? this.state.keyboardHeight : 0}} accessibilityLabel={accessibilityLabel}>
      <TouchableOpacity style={merge(styles.button, {backgroundColor: this.getButtonColor()})}
          onPress={() => invalidInput ? undefined : onButtonPress()}>
        <View style={styles.buttonInnerContainer}>
          <DefaultText style={{fontSize: 24, color: this.getButtonTextColor(), textAlign: 'center', width: Dimensions.get('window').width - 20}}>
            {buttonText}
          </DefaultText>

          { loading
            ? <ActivityIndicator size='small' style={styles.loadingSpinner}/>
            : undefined }
        </View>
      </TouchableOpacity>

      { input
        ? <TextInput style={styles.textInput}
              {...input}
              autoFocus={true}
              accessibilityLabel={input.placeholder} />
      : undefined }

    </Animated.View>
  }
}

class SendMoney extends React.Component {

  constructor() {
    super()
    this.state = {
      inputPage: Page.Ready,
    }
  }

  nextPage() {
    const nextPage = (this.state.inputPage + 1) % Object.keys(Page).length
    this.setState({ inputPage: nextPage })
    if (nextPage === Page.PaymentComplete) {
      setTimeout(() => {
        if (this.state.inputPage === Page.PaymentComplete) {
          this.nextPage()
        }
      }, 1800)
    }
  }

  componentDidUpdate(prevProps) {
    if (this.props.businessId !== prevProps.businessId) {
      this.props.updateAmount('')
      this.setState({ inputPage: Page.Ready })
    } else if (prevProps.loading && !this.props.loading && this.state.inputPage === 2) {
      this.nextPage()
    }
  }

  render() {
    let inputProps

    if (this.props.loggedIn) {
      switch (this.state.inputPage){
        case Page.Ready: // Initial state, ready to begin
          inputProps = {
            buttonText: 'Send Payment',
            onButtonPress: () => { this.props.updatePayee(this.props.payeeShortDisplay); this.nextPage() },
            accessibilityLabel: 'Ready',
          }
          break
        case Page.EnterAmount: // provide amount
          inputProps = {
            buttonText: 'Pay ' + this.props.payeeDisplay,
            onButtonPress: () => { this.props.sendTransaction(); this.nextPage() },
            input: {
              keyboardType: 'numeric',
              value: this.props.amount,
              placeholder: 'Amount',
              onChangeText: amt => this.props.updateAmount(amt),
            },
            invalidInput: isNaN(Number(this.props.amount)) || Number(this.props.amount) > this.props.balance || Number(this.props.amount) <= 0,
            accessibilityLabel: 'Enter Amount',
          }
          break
        case Page.MakingPayment: // in progress
          inputProps = {
            buttonText: 'Making Payment',
            loading: true,
            accessibilityLabel: 'Making Payment',
          }
          break
        case Page.PaymentComplete: // payment completed
          inputProps = {
            buttonText: this.props.message,
            onButtonPress: () => { this.props.resetForm(); this.nextPage() },
            accessibilityLabel: 'Payment complete',
          }
          break
      }
    } else {
      inputProps = {
        buttonText: 'Log in to make payment',
        onButtonPress: () => this.props.openLoginForm(true),
        accessibilityLabel: 'Log in to make payment',
      }
    }

    return <InputComponent {...inputProps} />
  }
}

const mapDispatchToProps = (dispatch) =>
  bindActionCreators({ ...actions, openLoginForm }, dispatch)

const mapStateToProps = (state) => ({
  ...state.sendMoney,
  balance: state.account.balance,
  loggedIn: state.login.loginStatus === LOGIN_STATUSES.LOGGED_IN
})

export default connect(mapStateToProps, mapDispatchToProps)(SendMoney)
<|endoftext|>