<commit_before>"use strict";

var _ = require('lodash');
var expect = require('expect.js');
var dirInfo = require('..');
// var fsExtra = require('fs-extra');
var Promises = require('best-promise');
var fs = require('fs-promise');
var expectCalled = require('expect-called');
var Path = require('path');

var dirbase;

if(process.env.TRAVIS){
    dirbase = process.env.HOME;
}else if(process.env.APPVEYOR){
    dirbase = process.env.APPVEYOR_BUILD_FOLDER;
    console.log('APPVEYOR ============ DIR',dirbase);
    dirbase = 'C:\\Users\\appveyor\\AppData\\Local\\Temp';
}else{
    dirbase = process.env.TMP || process.env.TEMP || '/tmp';
}
dirbase+='/temp-dir-info';

var skip = { // provisional
    summary:true
}

describe('dir-info', function(){
    var paths=[{
        path:'simple-git',
        origin:null,
        branch:'master',
        isGit:true,
        modifieds:['only-one-staged.txt'],
        untrackeds:['another-un-staged-file.txt', 'un-staged-file.txt']
    },{
        skipped:'YES! THIS IS ONLY FOR A NON COMPRENSIVE TEST',
        path:'tree-git',
        origin:null,
        branch:'master',
        isGit:true,
        modifieds:['only-one-staged.txt'],
        untrackeds:['another-un-staged-file.txt', 'un-staged-file.txt']
    },{
        path:'auto-reference-github-unpushed',
        origin:'https://github.com/codenautas/dir-info.git',
        branch:'master',
        isGit:true,
        isGithub:true,
        untrackeds:['master', 'un-staged-file.txt'],
        pushPending:true,
        syncPending:true
    },{
        path:'auto-reference-github-unsynced',
        origin:'https://github.com/codenautas/dir-info.git',
        branch:'master',
        isGit:true,
        isGithub:true,
        deletes: ['test/test.js'],
        syncPending:true
    },{
        path:'simple-dir',
        origin:null
    },{
        path:'simple-dir/package.json',
        origin:null,
        isJson:true,
        isPackageJson:true
    },{
        path:'simple-dir/other.json',
        origin:null,
        isJson:true,
        hasError:true
    },{
        path:'auto-reference-github-unpushed/package.json',
        origin:null,
        isJson:true,
        isPackageJson:true,
        isOutdated:true
    },{
        path:'simple-git-with-newbranch',
        origin:null,
        branch:'newbranch',
        modifieds:['newbranch.txt'],
        isGit:true
    // },{ // ESTO HACE FALLAR LOS TESTS PORQUE pide usuario y password y no existe
        // path:'gitlab-private',
        // origin:'https://gitlab.com/pert/mangrullo.git',
        // branch:'master',
        // isGit:true,
        // isGitlab:true
    },{
        path:'gitlab-unpushed',
        origin:'https://gitlab.com/diegoefe/dir-info-check.git',
        branch:'master',
        isGit:true,
        isGitlab:true,
        pushPending:true
    },{
        path:'gitlab-unsynced',
        origin:'https://gitlab.com/diegoefe/dir-info-check.git',
        branch:'master',
        isGit:true,
        isGitlab:true,
        syncPending:true
    }];
    before(function(done){
        this.timeout(5000);
        Promises.start(function(){
            return fs.remove(dirbase);
        }).then(function(){
            return fs.copy('./test/fixtures', dirbase, {clobber:true});
        }).then(function(){
            return Promises.all(paths.map(function(path){
                if(path.isGit){
                    return fs.rename(dirbase+'/'+path.path+'/dot-git',dirbase+'/'+path.path+'/.git');
                }else{
                    return Promises.Promise.resolve();
                }
            }));
        }).then(function(){
            done();
        }).catch(function(err){
            console.log(err);
            done(_.isArray(err)?err[0]:err);
        });
    });
    describe('find gitdir tests', function(){
        var configOriginal;
        var envOriginal;
        var controlFsStat;
        beforeEach(function(){
            configOriginal = _.cloneDeep(dirInfo.config);
            envOriginal = process.env;
            controlFsStat = expectCalled.control(fs,'stat',{returns:[
                Promises.Promise.resolve({isDirectory: function(){ return true;}})
            ]});
        });
        afterEach(function(){
            dirInfo.config = configOriginal;
            process.env = envOriginal;
            controlFsStat.stopControl();
        });
        it('find git in dirInfo.config', function(done){
            var controlFsExists = expectCalled.control(fs,'exists',{returns:[
                Promises.Promise.resolve(false)
            ]});
            var fakeDirInConfig = "/usr/bin";
            dirInfo.config = {gitDir: fakeDirInConfig};
            dirInfo.findGitDir().then(function(git){
                expect(git).to.eql(fakeDirInConfig);
                expect(controlFsStat.calls).to.eql([
                    [fakeDirInConfig]
                ]);
                controlFsExists.stopControl();
                done();
            }).catch(function(done) {
                controlFsExists.stopControl();
            });
        });
        it('find git in local-config.yaml', function(done){
            var here=process.cwd();
            process.chdir(Path.normalize(dirbase+'/dir-with-yaml-conf'));
            dirInfo.findGitDir().then(function(git){
                expect(git).to.eql('/some/directory/containing/the/git/binary');
                process.chdir(here);
                done();
            }).catch(done);
        });
        it('find git in environment variable', function(done){
            var fakeEnvDir='c:\\directory\\containing\\git\\binary';
            process.env['GITDIR'] = fakeEnvDir;
            dirInfo.findGitDir().then(function(git){
                expect(git).to.eql(fakeEnvDir);
                expect(controlFsStat.calls).to.eql([ [fakeEnvDir] ]);
                done();
            }).catch(done);
        });
    });
    describe('simple tests', function(){
        this.timeout(5000);
        it('recognizes a git dir', function(done){
            dirInfo.getInfo(dirbase+'/simple-git').then(function(info){
                expect(info.isGit).to.be.ok();
                done();
            }).catch(done);
        });
        it('recognizes a github dir as "git"', function(done){
            dirInfo.getInfo(dirbase+'/auto-reference-github-unpushed').then(function(info){
                expect(info.isGit).to.be.ok();
                done();
            }).catch(done);
        });
        it('recognizes a github dir', function(done){
            dirInfo.getInfo(dirbase+'/auto-reference-github-unpushed', {cmd:true}).then(function(info){
                expect(info.isGithub).to.be.ok();
                done();
            }).catch(done);
        });
        it('run command for get more info', function(done){
            dirInfo.getInfo(dirbase+'/simple-git',{cmd:true}).then(function(info){
                expect(info.isGit).to.be.ok();
                expect(info.isGitSubdir).to.not.be.ok();
                done();
            }).catch(done);
        });
        it('tree-git must recognize git dir', function(done){
            dirInfo.getInfo(dirbase+'/tree-git/son/grandson',{cmd:true}).then(function(info){
                expect(info.isGit).to.not.be.ok();
                expect(info.isGitSubdir).to.be.ok();
                expect(info.addeds[0]).to.eql('.other-added-');
                info.addeds.sort();
                var addedsExpected=['nom français.txt','¡nombre español!.txt','.other-added-','littleson-chad/added.txt'];
                addedsExpected.sort();
                // prueba para #9:
                expect(info.addeds).to.eql(addedsExpected);
                info.modifieds.sort();
                // files in uppers dirs must not be included: EJ: ../../only-one-staged.txt
                // prueba para #10:
                expect(info.modifieds).to.eql(['littleson-chad/modified2.txt','modified.txt']);

                done();
            }).catch(done);
        });
        it('littleson-ok is a ok-dir inside modified git-dir', function(done){
            dirInfo.getInfo(dirbase+'/tree-git/son/grandson/littleson-ok',{cmd:true}).then(function(info){
                expect(info.isGit).to.not.be.ok();
                expect(info.isGitSubdir).to.be.ok();
                expect(info.deletes).to.not.be.ok();
                expect(info.addeds).to.not.be.ok();
                expect(info.modifieds).to.not.be.ok();
                done();
            }).catch(done);
        });
        it('littleson-chad has staged changes', function(done){
            dirInfo.getInfo(dirbase+'/tree-git/son/grandson/littleson-chad',{cmd:true}).then(function(info){
                expect(info.isGit).to.not.be.ok();
                expect(info.isGitSubdir).to.be.ok();
                expect(info.addeds).to.eql(['added.txt']);
                expect(info.modifieds).to.eql(['modified2.txt']);
                expect(info.deletes).to.eql(['deleted2.txt']);
                done();
            }).catch(done);
        });
        it('connect to the net for get more info', function(done){
            dirInfo.getInfo(dirbase+'/simple-git',{cmd:true, net:true}).then(function(info){
                expect(info.isGit).to.be.ok();
                done();
            }).catch(done);
        });
        it('accept files with spaces and ASII7 characters', function(done){
            //var expectedPath='grandson/nom français.txt';
            var expectedPath='grandson/¡nombre español!.txt';
            var inputFile=Path.normalize(dirbase+'/tree-git/son/'+expectedPath);
            dirInfo.getInfo(inputFile,{cmd:true}).then(function(info){
                //console.log(info);
                expect(info.name).to.eql(expectedPath);
                expect(info.origin).to.be.null;
                done();
            }).catch(done);
        });
        it('should fail if path is null', function(done){
            dirInfo.getInfo(null,null).then(function(info){
                done(info);
            }).catch(function(err){
                expect(err).to.match(/null path/);
                done();
            });
        });
        it('should fail if path does not exists', function(done){
            dirInfo.getInfo('/non existent path/',null).then(function(info){
                done(info);
            }).catch(function(err){
                expect(err).to.match(/does not exists/);
                done();
            });
        });
    });
    describe('tests with relative paths', function(){
        function checkWithRelativePath(relPath, done){
            var here=process.cwd();
            var db=dirbase+'/tree-git/son';
            try {
                process.chdir(relPath);
                var relPath = Path.relative(relPath, db);
                dirInfo.getInfo(relPath,{cmd:true}).then(function(info){
                    expect(info.isGit).to.not.be.ok();
                    expect(info.isGitSubdir).to.be.ok();
                    expect(info.addeds[0]).to.eql('grandson/.other-added-');
                    info.addeds.sort();
                    var addedsExpected=[
                        'grandson/nom français.txt',
                        'grandson/¡nombre español!.txt',
                        'grandson/.other-added-',
                        'grandson/littleson-chad/added.txt'];
                    expect(info.modifieds).to.eql(['grandson/littleson-chad/modified2.txt','grandson/modified.txt']);
                    // restore current working directory
                    process.chdir(here);
                    done();
                }).catch(function(err) {
                    done(err);
                });
            } catch (err) {
                done(err);
            }
        };
        it('should work with a relative path (issue #14)', function(done){
            checkWithRelativePath(dirbase+'/simple-dir', done);
        });
        it('should work with a relative path that lacks a package.json (issue #15)', function(done) {
            checkWithRelativePath(dirbase+'/simple-git', done);
        });
    });
    describe('comprehensive incomprehensible tests', function(){
        this.timeout(20000);
        var calls=[{
            opts:{cmd:false, net:false},
            resultMask:{origin:null},
            reconvert:function(info){
                if(info.isGithub){
                    delete info.isGithub;
                }
                if(info.isGitlab){
                    delete info.isGitlab;
                }
                if(info.isJson){
                    delete info.hasError;
                }
                if(info.isPackageJson) {
                    delete info.isOutdated;
                }
                delete info.modifieds;
                delete info.deletes;
                delete info.untrackeds;
                delete info.syncPending;
                delete info.pushPending;
                delete info.branch;
            }
        },{
            opts:{cmd:true, net:false},
            resultMask:{},
            reconvert:function(info) {
                if(info.isPackageJson) {
                    delete info.isOutdated;
                }
                delete info.syncPending;
                delete info.pushPending;
            }
        },{
            opts:{cmd:true, net:true},
            resultMask:{}
        }];
        paths.forEach(function(pathMayBeSkipped){
            if(pathMayBeSkipped.skipped) return;
            var path = _.clone(pathMayBeSkipped);
            delete path.skipped;
            calls.forEach(function(call){
                it('t: '+path.path+' of '+JSON.stringify(call.opts), function(done){
                    //console.log("call", call);
                    Promises.start(function(){
                        return dirInfo.getInfo(dirbase+'/'+path.path, call.opts);
                    }).then(function(info){
                        //console.log("ret info", info);
                        var expected = _.merge({}, path, call.resultMask);
                        (call.reconvert||function(){})(expected);
                        expected.name = path.path;
                        delete expected.path;
                        expect(info).to.eql(expected);
                        done();
                        /*
                    }).catch(function(err){
                        console.log('ERROR in case',path,call);
                        console.log(err);
                        console.log(err.stack);
                        throw err;
                        */
                    }).catch(done);
                });
            });
        });
    });
});
<commit_msg>Explico la exclusión del test<commit_after>"use strict";

var _ = require('lodash');
var expect = require('expect.js');
var dirInfo = require('..');
// var fsExtra = require('fs-extra');
var Promises = require('best-promise');
var fs = require('fs-promise');
var expectCalled = require('expect-called');
var Path = require('path');

var dirbase;

if(process.env.TRAVIS){
    dirbase = process.env.HOME;
}else if(process.env.APPVEYOR){
    dirbase = process.env.APPVEYOR_BUILD_FOLDER;
    console.log('APPVEYOR ============ DIR',dirbase);
    dirbase = 'C:\\Users\\appveyor\\AppData\\Local\\Temp';
}else{
    dirbase = process.env.TMP || process.env.TEMP || '/tmp';
}
dirbase+='/temp-dir-info';

var skip = { // provisional
    summary:true
}

describe('dir-info', function(){
    var paths=[{
        path:'simple-git',
        origin:null,
        branch:'master',
        isGit:true,
        modifieds:['only-one-staged.txt'],
        untrackeds:['another-un-staged-file.txt', 'un-staged-file.txt']
    },{
        skipped:'YES! THIS IS ONLY FOR A NON COMPRENSIVE TEST',
        path:'tree-git',
        origin:null,
        branch:'master',
        isGit:true,
        modifieds:['only-one-staged.txt'],
        untrackeds:['another-un-staged-file.txt', 'un-staged-file.txt']
    },{
        path:'auto-reference-github-unpushed',
        origin:'https://github.com/codenautas/dir-info.git',
        branch:'master',
        isGit:true,
        isGithub:true,
        untrackeds:['master', 'un-staged-file.txt'],
        pushPending:true,
        syncPending:true
    },{
        path:'auto-reference-github-unsynced',
        origin:'https://github.com/codenautas/dir-info.git',
        branch:'master',
        isGit:true,
        isGithub:true,
        deletes: ['test/test.js'],
        syncPending:true
    },{
        path:'simple-dir',
        origin:null
    },{
        path:'simple-dir/package.json',
        origin:null,
        isJson:true,
        isPackageJson:true
    },{
        path:'simple-dir/other.json',
        origin:null,
        isJson:true,
        hasError:true
    },{
        path:'auto-reference-github-unpushed/package.json',
        origin:null,
        isJson:true,
        isPackageJson:true,
        isOutdated:true
    },{
        path:'simple-git-with-newbranch',
        origin:null,
        branch:'newbranch',
        modifieds:['newbranch.txt'],
        isGit:true
    // Este fixture está comentado porque:
    //   1. El repositorio es privado o inexistente
    //   2. Pide autenticación cuando opts.net == true, que corre comandos git que usan la red
    // Habría que remover el directorio test/fixtures/gitlab-private y este bloque comentado
    // },{
        // path:'gitlab-private',
        // origin:'https://gitlab.com/pert/mangrullo.git',
        // branch:'master',
        // isGit:true,
        // isGitlab:true
    },{
        path:'gitlab-unpushed',
        origin:'https://gitlab.com/diegoefe/dir-info-check.git',
        branch:'master',
        isGit:true,
        isGitlab:true,
        pushPending:true
    },{
        path:'gitlab-unsynced',
        origin:'https://gitlab.com/diegoefe/dir-info-check.git',
        branch:'master',
        isGit:true,
        isGitlab:true,
        syncPending:true
    }];
    before(function(done){
        this.timeout(5000);
        Promises.start(function(){
            return fs.remove(dirbase);
        }).then(function(){
            return fs.copy('./test/fixtures', dirbase, {clobber:true});
        }).then(function(){
            return Promises.all(paths.map(function(path){
                if(path.isGit){
                    return fs.rename(dirbase+'/'+path.path+'/dot-git',dirbase+'/'+path.path+'/.git');
                }else{
                    return Promises.Promise.resolve();
                }
            }));
        }).then(function(){
            done();
        }).catch(function(err){
            console.log(err);
            done(_.isArray(err)?err[0]:err);
        });
    });
    describe('find gitdir tests', function(){
        var configOriginal;
        var envOriginal;
        var controlFsStat;
        beforeEach(function(){
            configOriginal = _.cloneDeep(dirInfo.config);
            envOriginal = process.env;
            controlFsStat = expectCalled.control(fs,'stat',{returns:[
                Promises.Promise.resolve({isDirectory: function(){ return true;}})
            ]});
        });
        afterEach(function(){
            dirInfo.config = configOriginal;
            process.env = envOriginal;
            controlFsStat.stopControl();
        });
        it('find git in dirInfo.config', function(done){
            var controlFsExists = expectCalled.control(fs,'exists',{returns:[
                Promises.Promise.resolve(false)
            ]});
            var fakeDirInConfig = "/usr/bin";
            dirInfo.config = {gitDir: fakeDirInConfig};
            dirInfo.findGitDir().then(function(git){
                expect(git).to.eql(fakeDirInConfig);
                expect(controlFsStat.calls).to.eql([
                    [fakeDirInConfig]
                ]);
                controlFsExists.stopControl();
                done();
            }).catch(function(done) {
                controlFsExists.stopControl();
            });
        });
        it('find git in local-config.yaml', function(done){
            var here=process.cwd();
            process.chdir(Path.normalize(dirbase+'/dir-with-yaml-conf'));
            dirInfo.findGitDir().then(function(git){
                expect(git).to.eql('/some/directory/containing/the/git/binary');
                process.chdir(here);
                done();
            }).catch(done);
        });
        it('find git in environment variable', function(done){
            var fakeEnvDir='c:\\directory\\containing\\git\\binary';
            process.env['GITDIR'] = fakeEnvDir;
            dirInfo.findGitDir().then(function(git){
                expect(git).to.eql(fakeEnvDir);
                expect(controlFsStat.calls).to.eql([ [fakeEnvDir] ]);
                done();
            }).catch(done);
        });
    });
    describe('simple tests', function(){
        this.timeout(5000);
        it('recognizes a git dir', function(done){
            dirInfo.getInfo(dirbase+'/simple-git').then(function(info){
                expect(info.isGit).to.be.ok();
                done();
            }).catch(done);
        });
        it('recognizes a github dir as "git"', function(done){
            dirInfo.getInfo(dirbase+'/auto-reference-github-unpushed').then(function(info){
                expect(info.isGit).to.be.ok();
                done();
            }).catch(done);
        });
        it('recognizes a github dir', function(done){
            dirInfo.getInfo(dirbase+'/auto-reference-github-unpushed', {cmd:true}).then(function(info){
                expect(info.isGithub).to.be.ok();
                done();
            }).catch(done);
        });
        it('run command for get more info', function(done){
            dirInfo.getInfo(dirbase+'/simple-git',{cmd:true}).then(function(info){
                expect(info.isGit).to.be.ok();
                expect(info.isGitSubdir).to.not.be.ok();
                done();
            }).catch(done);
        });
        it('tree-git must recognize git dir', function(done){
            dirInfo.getInfo(dirbase+'/tree-git/son/grandson',{cmd:true}).then(function(info){
                expect(info.isGit).to.not.be.ok();
                expect(info.isGitSubdir).to.be.ok();
                expect(info.addeds[0]).to.eql('.other-added-');
                info.addeds.sort();
                var addedsExpected=['nom français.txt','¡nombre español!.txt','.other-added-','littleson-chad/added.txt'];
                addedsExpected.sort();
                // prueba para #9:
                expect(info.addeds).to.eql(addedsExpected);
                info.modifieds.sort();
                // files in uppers dirs must not be included: EJ: ../../only-one-staged.txt
                // prueba para #10:
                expect(info.modifieds).to.eql(['littleson-chad/modified2.txt','modified.txt']);

                done();
            }).catch(done);
        });
        it('littleson-ok is a ok-dir inside modified git-dir', function(done){
            dirInfo.getInfo(dirbase+'/tree-git/son/grandson/littleson-ok',{cmd:true}).then(function(info){
                expect(info.isGit).to.not.be.ok();
                expect(info.isGitSubdir).to.be.ok();
                expect(info.deletes).to.not.be.ok();
                expect(info.addeds).to.not.be.ok();
                expect(info.modifieds).to.not.be.ok();
                done();
            }).catch(done);
        });
        it('littleson-chad has staged changes', function(done){
            dirInfo.getInfo(dirbase+'/tree-git/son/grandson/littleson-chad',{cmd:true}).then(function(info){
                expect(info.isGit).to.not.be.ok();
                expect(info.isGitSubdir).to.be.ok();
                expect(info.addeds).to.eql(['added.txt']);
                expect(info.modifieds).to.eql(['modified2.txt']);
                expect(info.deletes).to.eql(['deleted2.txt']);
                done();
            }).catch(done);
        });
        it('connect to the net for get more info', function(done){
            dirInfo.getInfo(dirbase+'/simple-git',{cmd:true, net:true}).then(function(info){
                expect(info.isGit).to.be.ok();
                done();
            }).catch(done);
        });
        it('accept files with spaces and ASII7 characters', function(done){
            //var expectedPath='grandson/nom français.txt';
            var expectedPath='grandson/¡nombre español!.txt';
            var inputFile=Path.normalize(dirbase+'/tree-git/son/'+expectedPath);
            dirInfo.getInfo(inputFile,{cmd:true}).then(function(info){
                //console.log(info);
                expect(info.name).to.eql(expectedPath);
                expect(info.origin).to.be.null;
                done();
            }).catch(done);
        });
        it('should fail if path is null', function(done){
            dirInfo.getInfo(null,null).then(function(info){
                done(info);
            }).catch(function(err){
                expect(err).to.match(/null path/);
                done();
            });
        });
        it('should fail if path does not exists', function(done){
            dirInfo.getInfo('/non existent path/',null).then(function(info){
                done(info);
            }).catch(function(err){
                expect(err).to.match(/does not exists/);
                done();
            });
        });
    });
    describe('tests with relative paths', function(){
        function checkWithRelativePath(relPath, done){
            var here=process.cwd();
            var db=dirbase+'/tree-git/son';
            try {
                process.chdir(relPath);
                var relPath = Path.relative(relPath, db);
                dirInfo.getInfo(relPath,{cmd:true}).then(function(info){
                    expect(info.isGit).to.not.be.ok();
                    expect(info.isGitSubdir).to.be.ok();
                    expect(info.addeds[0]).to.eql('grandson/.other-added-');
                    info.addeds.sort();
                    var addedsExpected=[
                        'grandson/nom français.txt',
                        'grandson/¡nombre español!.txt',
                        'grandson/.other-added-',
                        'grandson/littleson-chad/added.txt'];
                    expect(info.modifieds).to.eql(['grandson/littleson-chad/modified2.txt','grandson/modified.txt']);
                    // restore current working directory
                    process.chdir(here);
                    done();
                }).catch(function(err) {
                    done(err);
                });
            } catch (err) {
                done(err);
            }
        };
        it('should work with a relative path (issue #14)', function(done){
            checkWithRelativePath(dirbase+'/simple-dir', done);
        });
        it('should work with a relative path that lacks a package.json (issue #15)', function(done) {
            checkWithRelativePath(dirbase+'/simple-git', done);
        });
    });
    describe('comprehensive incomprehensible tests', function(){
        this.timeout(20000);
        var calls=[{
            opts:{cmd:false, net:false},
            resultMask:{origin:null},
            reconvert:function(info){
                if(info.isGithub){
                    delete info.isGithub;
                }
                if(info.isGitlab){
                    delete info.isGitlab;
                }
                if(info.isJson){
                    delete info.hasError;
                }
                if(info.isPackageJson) {
                    delete info.isOutdated;
                }
                delete info.modifieds;
                delete info.deletes;
                delete info.untrackeds;
                delete info.syncPending;
                delete info.pushPending;
                delete info.branch;
            }
        },{
            opts:{cmd:true, net:false},
            resultMask:{},
            reconvert:function(info) {
                if(info.isPackageJson) {
                    delete info.isOutdated;
                }
                delete info.syncPending;
                delete info.pushPending;
            }
        },{
            opts:{cmd:true, net:true},
            resultMask:{}
        }];
        paths.forEach(function(pathMayBeSkipped){
            if(pathMayBeSkipped.skipped) return;
            var path = _.clone(pathMayBeSkipped);
            delete path.skipped;
            calls.forEach(function(call){
                it('t: '+path.path+' of '+JSON.stringify(call.opts), function(done){
                    //console.log("call", call);
                    Promises.start(function(){
                        return dirInfo.getInfo(dirbase+'/'+path.path, call.opts);
                    }).then(function(info){
                        //console.log("ret info", info);
                        var expected = _.merge({}, path, call.resultMask);
                        (call.reconvert||function(){})(expected);
                        expected.name = path.path;
                        delete expected.path;
                        expect(info).to.eql(expected);
                        done();
                        /*
                    }).catch(function(err){
                        console.log('ERROR in case',path,call);
                        console.log(err);
                        console.log(err.stack);
                        throw err;
                        */
                    }).catch(done);
                });
            });
        });
    });
});
<|endoftext|>


<commit_before>'use strict';

var _ = require('lodash');
var fs = require('fs');
var path = require('path');
var helpers = require('yeoman-generator').test;
var assert = _.extend({}, require('yeoman-generator').assert);

var run = function(components, done) {
  helpers.run(path.join( __dirname, '../app'))
    .inDir(path.join( __dirname, './tmp'))
    .withOptions({ 'skip-install': true })
    .withPrompt({ name: 'caribou-app' })
    .withPrompt({ components: components })
    .onEnd(done);
};

var projectFiles = [
  '.bowerrc',
  '.jshintrc',
  '.gitignore',
  'bower.json',
  'package.json',
  'gulpfile.js',
  'karma.conf.js'
];

var appFiles = [
  'app/media/caribou.png',
  'app/scripts/application.js',
  'app/scripts/vendor.json',
  'app/styles/application.scss',
  'app/styles/caribou.scss',
  'app/styles/vendor.scss',
  'app/index.html',
  'test/app_helper.js',
  'test/app/test.js',
  'test/fixtures/example.json'
];

var serverFiles = [
  'server/config/env/base.js',
  'server/config/env/development.js',
  'server/config/env/production.js',
  'server/config/env/staging.js',
  'server/config/index.js',
  'server/application.js',
  'test/server_helper.js',
  'test/server/test.js'
];

assert.fileMatches = function(file, fixture) {
  assert.textEqual(
    fs.readFileSync(file, 'utf8'),
    fs.readFileSync(fixture, 'utf8'));
};

describe('caribou', function() {
  describe('full-stack', function() {
    before(function(done) { run(['jquery', 'bootstrap', 'ember', 'server'], done); });

    it('creates expected files', function() {
      assert.file([].concat(projectFiles, appFiles, serverFiles));
      assert.noFile([]);
    });

    it('creates expected gulpfile.js', function() {
      assert.fileMatches('gulpfile.js', path.join(__dirname,
        'expected/gulpfile.full-stack.js'));
    });

    it('includes jquery', function() {
      assert.fileContent('bower.json', /jquery/);
      assert.fileContent('app/scripts/vendor.json', /jquery/);
    });

    it('includes bootstrap', function() {
      assert.fileContent('bower.json', /bootstrap/);
      assert.fileContent('app/scripts/vendor.json', /bootstrap/);
      assert.fileContent('app/styles/vendor.scss', /bootstrap/);
    });

    it('includes ember', function() {
      assert.fileContent('bower.json', /ember/);
      assert.fileContent('app/scripts/vendor.json', /ember/);
      assert.fileContent('test/app_helper.js', /ember/);
    });
  });

  describe('minimal', function() {
    before(function(done) { run([], done); });

    it('creates expected files', function() {
      assert.file([].concat(projectFiles, appFiles));
      assert.noFile([].concat(serverFiles));
    });

    it('does not include jquery');

    it('does not include bootstrap');

    it('does not include ember');
  });

  describe('ember-only', function() {
    before(function(done) { run(['jquery', 'ember'], done); });

    it('creates expected files', function() {
      assert.file([].concat(projectFiles, appFiles));
      assert.noFile([].concat(serverFiles));
    });

    it('does not include jquery');

    it('does not include bootstrap');

    it('does not include ember');
  });
});
<commit_msg>Fixed a few more tests.<commit_after>'use strict';

var _ = require('lodash');
var fs = require('fs');
var path = require('path');
var helpers = require('yeoman-generator').test;
var assert = _.extend({}, require('yeoman-generator').assert);

var run = function(components, done) {
  helpers.run(path.join( __dirname, '../app'))
    .inDir(path.join( __dirname, './tmp'))
    .withOptions({ 'skip-install': true })
    .withPrompt({ name: 'caribou-app' })
    .withPrompt({ components: components })
    .onEnd(done);
};

var projectFiles = [
  '.bowerrc',
  '.jshintrc',
  '.gitignore',
  'bower.json',
  'package.json',
  'gulpfile.js',
  'karma.conf.js'
];

var appFiles = [
  'app/media/caribou.png',
  'app/scripts/application.js',
  'app/scripts/vendor.json',
  'app/styles/application.scss',
  'app/styles/caribou.scss',
  'app/styles/vendor.scss',
  'app/index.html',
  'test/app_helper.js',
  'test/app/test.js',
  'test/fixtures/example.json'
];

var serverFiles = [
  'server/config/env/base.js',
  'server/config/env/development.js',
  'server/config/env/production.js',
  'server/config/env/staging.js',
  'server/config/index.js',
  'server/application.js',
  'test/server_helper.js',
  'test/server/test.js'
];

assert.fileMatches = function(file, fixture) {
  assert.textEqual(
    fs.readFileSync(file, 'utf8'),
    fs.readFileSync(fixture, 'utf8'));
};

describe('caribou', function() {
  describe('full-stack', function() {
    before(function(done) { run(['jquery', 'bootstrap', 'ember', 'server'], done); });

    it('creates expected files', function() {
      assert.file([].concat(projectFiles, appFiles, serverFiles));
      assert.noFile([]);
    });

    it('creates expected gulpfile.js', function() {
      assert.fileMatches('gulpfile.js', path.join(__dirname,
        'expected/gulpfile.full-stack.js'));
    });

    it('includes jquery', function() {
      assert.fileContent('bower.json', /jquery/);
      assert.fileContent('app/scripts/vendor.json', /jquery/);
    });

    it('includes bootstrap', function() {
      assert.fileContent('bower.json', /bootstrap/);
      assert.fileContent('app/scripts/vendor.json', /bootstrap/);
      assert.fileContent('app/styles/vendor.scss', /bootstrap/);
    });

    it('includes ember', function() {
      assert.fileContent('bower.json', /ember/);
      assert.fileContent('app/scripts/vendor.json', /ember/);
      assert.fileContent('test/app_helper.js', /ember/);
    });
  });

  describe('minimal', function() {
    before(function(done) { run([], done); });

    it('creates expected files', function() {
      assert.file([].concat(projectFiles, appFiles));
      assert.noFile([].concat(serverFiles));
    });

    it('does not include jquery', function() {
      assert.noFileContent('bower.json', /jquery/);
      assert.noFileContent('app/scripts/vendor.json', /jquery/);
    });

    it('does not include bootstrap', function() {
      assert.noFileContent('bower.json', /bootstrap/);
      assert.noFileContent('app/scripts/vendor.json', /bootstrap/);
    });

    it('does not include ember', function() {
      assert.noFileContent('bower.json', /ember/);
      assert.noFileContent('app/scripts/vendor.json', /ember/);
    });

    it('does not include server', function() {
      assert.noFileContent('gulpfile.js', /server/);
    });
  });

  describe('ember-only', function() {
    before(function(done) { run(['jquery', 'ember'], done); });

    it('creates expected files', function() {
      assert.file([].concat(projectFiles, appFiles));
      assert.noFile([].concat(serverFiles));
    });

    it('does not include bootstrap', function() {
      assert.noFileContent('bower.json', /bootstrap/);
      assert.noFileContent('app/scripts/vendor.json', /bootstrap/);
    });

    it('includes jquery', function() {
      assert.fileContent('bower.json', /jquery/);
      assert.fileContent('app/scripts/vendor.json', /jquery/);
    });

    it('includes ember', function() {
      assert.fileContent('bower.json', /ember/);
      assert.fileContent('app/scripts/vendor.json', /ember/);
    });
  });
});
<|endoftext|>


<commit_before><commit_msg>Revert "Revert "include es5 shim/sham""<commit_after><|endoftext|>


<commit_before>window.initializeCtxScript = function(config, options){
console.log("Initializing context script...");
var VERSION = "0.0.0";
var context = {
  location: {
    href: window.location.href,
    host: window.location.host
  }
};
var history = [];
System.import("jquery@2.1").then(function(jQuery) {
var $ = jQuery;
$(function(){
var $mainContainer = $(options.container);
var createContextScriptAPI = function(extras){
  var __resolveResult;
  var resultPromise = new Promise(function(resolveResult){
    __resolveResult = resolveResult;
  });
  return $.extend({
    config: config,
    apiPost: function(path, options){
      var newOptions = $.extend({}, options, {
        user: config.user
      });
      // Forcing https because firefox is having trouble with x-origin http requests.
      return $.post(config.url.replace(/(.{0,6}\/\/)/, "https://") + path, newOptions);
    },
    setResult: function(value){
      __resolveResult(value);
      var $resultContainer = this.$el.find('.ctxscript-result');
      if($resultContainer.length > 0) {
        $resultContainer.append('
Result:
');
        if($.type(value) === "string") {
          $resultContainer.append($('<textarea readonly=true>').text(value));
        } else {
          //TODO: Display result with JSON tree viewer.
          $resultContainer.append($('<textarea readonly=true>')
            .text(JSON.stringify(value, 0, 2)));
        }
      }
    },
    getPrevHistItem: function(){
      if(!this.history || history.length === 0) return null;
      return this.history.slice(-1)[0];
    },
    getPrevResultPromise: function(){
      var prevHistItem = this.getPrevHistItem();
      if(prevHistItem) return prevHistItem.resultPromise;
      return null;
    },
    getPrevEvaledCtxScript: function(){
      var prevHistItem = this.getPrevHistItem();
      if(prevHistItem) return prevHistItem.evaledCtxScript;
      return null;
    },
    resultPromise: resultPromise
  }, extras);
};
var createBox = function(output){
  var $box = $('
');
  $box.append(output);
  $mainContainer.find('#ctxscript-out').append($box);
  return $box;
};
$mainContainer.on('click', '.ctxscript-search-btn', function ( e ) {
  doSearch($(e.target).text());
});
//Preload:
System.import("handlebars");
System.import("github:nathanathan/fuzzyTemplateMatcher@gh-pages/fuzzyTemplateMatcher");
var evalContextScript = function(result, cxsAPI, extraArgs){
//TODO: Use polyfill.
Promise.all([
  System.import("handlebars"),
  System.import("github:nathanathan/fuzzyTemplateMatcher@gh-pages/fuzzyTemplateMatcher")
])
.then(function(imports){
  var handlebars = imports[0];
  var ftm = imports[1];
  if(cxsAPI.currentHistoryItem) {
    cxsAPI.currentHistoryItem.evaledCtxScript = result;
  }
  cxsAPI.$el.addClass("ctxscript-bar");
  cxsAPI.args = $.extend({}, extraArgs, {});
  var chosenQItem;
  var q = result._source.context.q;
  if(!$.isArray(q)) q = [q];
  var requestQ;
  if(cxsAPI.context) requestQ = cxsAPI.context.q;
  if(requestQ) {
    var bestMatch;
    q.forEach(function(qItem){
      var ftmResult = ftm(requestQ, qItem);
      if(!bestMatch || ftmResult.adjustedLd < bestMatch.adjustedLd) {
        chosenQItem = qItem;
        bestMatch = ftmResult;
      }
    });
    var newArgs = {};
    bestMatch.vars.forEach(function(v){
      newArgs[v.vName] = v.value;
    });
    cxsAPI.args = $.extend(newArgs, cxsAPI.args);
  } else {
    // If there is not a request q, use any user supplied args to
    // choose the best matching qItem.
    var bestCount;
    q.forEach(function(qItem){
      var matchingKeys = ftm("", qItem).vars.reduce(function(sofar, cur){
        return sofar + (cur.vName in cxsAPI.args ? 1 : 0);
      }, 0);
      if(!bestCount || matchingKeys > bestCount) {
        chosenQItem = qItem;
        bestCount = matchingKeys;
      }
    });
  }

  cxsAPI.qItem = chosenQItem;
  var quotedArgContext = {};
  Object.keys(cxsAPI.args).forEach(function(argName){
    quotedArgContext[argName] = "{{" + cxsAPI.args[argName] + "}}";
  });
  var title = handlebars.compile(chosenQItem)(quotedArgContext);
  cxsAPI.$el.append(
    $('
')
      .text(title)
      .append('')
  );
  var $controls = $('
');
  $controls.append(
    //TODO: Hook this button up.
    $('Alternative Scripts'),
    $('Show Source').prop({
      href: cxsAPI.config.url + '/contextscripts/' + result._id,
    })
  );
  $controls.hide();
  cxsAPI.$el.append($controls);

  cxsAPI.$el.find('.ctxscript-open-menu').click(function(){
    $controls.toggle();
  });
  cxsAPI.$el = createBox();
  cxsAPI.$el.append('

');
  eval(
    traceur.Compiler.script(result._source.script)
  );
  //Cause the side pane to scroll down to show the input box.
  //TODO: this doesn't quite work...
  $mainContainer.scrollTop($mainContainer[0].scrollHeight);
});
};
var doSearch = function(q){
  var currentContext = Object.create(context);
  currentContext.q = q;
  //Beware that the result might not be present.
  var historyItem = {
    searchContext: currentContext
  };
  createBox('>' + q)
    .addClass("ctxscript-prev");
  var cxsAPI = createContextScriptAPI({
    $el: createBox('Loading...'),
    history: history,
    context: currentContext,
    currentHistoryItem: historyItem
  });
  historyItem.resultPromise = cxsAPI.resultPromise;

  cxsAPI.apiPost("/v0/search", {
    context: currentContext
  }).success(function(resp){
    historyItem.response = resp;
    cxsAPI.$el.empty();
    if (resp.hits.length === 0) {
      cxsAPI.$el.append(
        '
No scripts found
' +
        '<button class="ctxscript-btn ctxscript-search-btn">Create a script for this context</button>' +
        '<button class="ctxscript-btn ctxscript-search-btn">Request a script for this context</button>'
      );
    } else if (resp.hits.length === 1) {
      evalContextScript(resp.hits[0], cxsAPI);
    } else {
      // If there is one hit with a much higher score than the others
      // that will be shown instead of the multiple result list.
      var hitsAboveThreshold = resp.hits.filter(function(hit){
        return hit._score > (resp.max_score / 2);
      });
      if(hitsAboveThreshold.length == 1) {
          evalContextScript(hitsAboveThreshold[0], cxsAPI);
          return;
      }
      //TODO Add more meta-data
      cxsAPI.$el.append("
Multiple results:
");
      var $results = $("
");
      resp.hits.forEach(function(result){
        var $row = $('
');
        var $button = $('<button class="ctxscript-btn ctxscript-item-btn">')
          .text(result._source.context.q)
          .click(function(){
            cxsAPI.$el.empty();
            evalContextScript(result, cxsAPI);
          });
        $row.append(
          $button,
          $('
').text(
            "Last Modified: " +
            (new Date(result._source.lastModified)).toDateString()
          ),
          $('View Source').prop({
            href: cxsAPI.config.url + '/contextscripts/' + result._id
          })
        );
        $results.append($row);
      });
      cxsAPI.$el.append($results);
    }
  }).fail(function(error, msg){
    console.log(error);
    cxsAPI.$el.html(
        '
Error
' +
        '
' +
          error.status + ": " + error.statusText +
        '
'
    );
  });
  //Create new history array so that this context isn't included in the history
  //passed to the script.
  history = history.concat(historyItem);
};
$mainContainer.on('click', '.ctxscript-invoke', function ( e ) {
  var $q = $mainContainer.find('#ctxscript-q');
  doSearch($q.val());
  $q.val('');
});
$mainContainer.on('click', '.ctxscript-settings-btn', function ( e ) {
  $mainContainer.find('.ctxscript-settings').toggle();
});
$mainContainer.on('click', '.ctxscript-close', function ( e ) {
  $mainContainer.hide();
});
$mainContainer.on('click', '.ctxscript-about', function ( e ) {
  //The injection script could go out of sync with this one,
  //so it is versioned separately.
  //TODO: Make ctxscript alerts that allow copy/paste
  alert(
    "Version: " + VERSION + '-' + config.version +
    "\nUser Id: " + (config.user && config.user.id) +
    "\nServer URL: " + config.url
  );
});
//TODO: Go though command history with up/down arrows
$mainContainer.on('keypress', '#ctxscript-q', function(e) {
  if(e.which == 13) {
    var $q = $mainContainer.find('#ctxscript-q');
    doSearch($q.val());
    $q.val('');
  }
});
$mainContainer.find('.ctxscript-invoke').prop('disabled', false);
$mainContainer.find('.ctxscript-settings-btn').prop('disabled', false);
//TODO: Create suggestions box
//var $suggestions = $('
');
//$suggestions.append('suggestions:');
//$mainContainer.append($suggestions);
if(options.scriptId) {
  var currentContext = Object.create(context);
  var historyItem = {
    searchContext: currentContext
  };
  var cxsAPI = createContextScriptAPI({
    $el: createBox('Loading...'),
    history: history,
    context: currentContext,
    currentHistoryItem: historyItem
  });
  historyItem.resultPromise = cxsAPI.resultPromise;
  $.getJSON(config.url + '/v0/contextscripts/' + options.scriptId)
  .success(function(result){
    historyItem.response = result;
    cxsAPI.$el.empty();
    evalContextScript(result, cxsAPI, options.args);
  });
  history = history.concat(historyItem);
}
});
});
};
<commit_msg>Fixes location not being updated on sites with hash urls<commit_after>window.initializeCtxScript = function(config, options){
console.log("Initializing context script...");
var VERSION = "0.0.0";
var createContext = function(){
  return {
    location: {
      href: window.location.href,
      host: window.location.host
    }
  };
};
var history = [];
System.import("jquery@2.1").then(function(jQuery) {
var $ = jQuery;
$(function(){
var $mainContainer = $(options.container);
var createContextScriptAPI = function(extras){
  var __resolveResult;
  var resultPromise = new Promise(function(resolveResult){
    __resolveResult = resolveResult;
  });
  return $.extend({
    config: config,
    apiPost: function(path, options){
      var newOptions = $.extend({}, options, {
        user: config.user
      });
      // Forcing https because firefox is having trouble with x-origin http requests.
      return $.post(config.url.replace(/(.{0,6}\/\/)/, "https://") + path, newOptions);
    },
    setResult: function(value){
      __resolveResult(value);
      var $resultContainer = this.$el.find('.ctxscript-result');
      if($resultContainer.length > 0) {
        $resultContainer.append('
Result:
');
        if($.type(value) === "string") {
          $resultContainer.append($('<textarea readonly=true>').text(value));
        } else {
          //TODO: Display result with JSON tree viewer.
          $resultContainer.append($('<textarea readonly=true>')
            .text(JSON.stringify(value, 0, 2)));
        }
      }
    },
    getPrevHistItem: function(){
      if(!this.history || history.length === 0) return null;
      return this.history.slice(-1)[0];
    },
    getPrevResultPromise: function(){
      var prevHistItem = this.getPrevHistItem();
      if(prevHistItem) return prevHistItem.resultPromise;
      return null;
    },
    getPrevEvaledCtxScript: function(){
      var prevHistItem = this.getPrevHistItem();
      if(prevHistItem) return prevHistItem.evaledCtxScript;
      return null;
    },
    resultPromise: resultPromise
  }, extras);
};
var createBox = function(output){
  var $box = $('
');
  $box.append(output);
  $mainContainer.find('#ctxscript-out').append($box);
  return $box;
};
$mainContainer.on('click', '.ctxscript-search-btn', function ( e ) {
  doSearch($(e.target).text());
});
//Preload:
System.import("handlebars");
System.import("github:nathanathan/fuzzyTemplateMatcher@gh-pages/fuzzyTemplateMatcher");
var evalContextScript = function(result, cxsAPI, extraArgs){
//TODO: Use polyfill.
Promise.all([
  System.import("handlebars"),
  System.import("github:nathanathan/fuzzyTemplateMatcher@gh-pages/fuzzyTemplateMatcher")
])
.then(function(imports){
  var handlebars = imports[0];
  var ftm = imports[1];
  if(cxsAPI.currentHistoryItem) {
    cxsAPI.currentHistoryItem.evaledCtxScript = result;
  }
  cxsAPI.$el.addClass("ctxscript-bar");
  cxsAPI.args = $.extend({}, extraArgs, {});
  var chosenQItem;
  var q = result._source.context.q;
  if(!$.isArray(q)) q = [q];
  var requestQ;
  if(cxsAPI.context) requestQ = cxsAPI.context.q;
  if(requestQ) {
    var bestMatch;
    q.forEach(function(qItem){
      var ftmResult = ftm(requestQ, qItem);
      if(!bestMatch || ftmResult.adjustedLd < bestMatch.adjustedLd) {
        chosenQItem = qItem;
        bestMatch = ftmResult;
      }
    });
    var newArgs = {};
    bestMatch.vars.forEach(function(v){
      newArgs[v.vName] = v.value;
    });
    cxsAPI.args = $.extend(newArgs, cxsAPI.args);
  } else {
    // If there is not a request q, use any user supplied args to
    // choose the best matching qItem.
    var bestCount;
    q.forEach(function(qItem){
      var matchingKeys = ftm("", qItem).vars.reduce(function(sofar, cur){
        return sofar + (cur.vName in cxsAPI.args ? 1 : 0);
      }, 0);
      if(!bestCount || matchingKeys > bestCount) {
        chosenQItem = qItem;
        bestCount = matchingKeys;
      }
    });
  }

  cxsAPI.qItem = chosenQItem;
  var quotedArgContext = {};
  Object.keys(cxsAPI.args).forEach(function(argName){
    quotedArgContext[argName] = "{{" + cxsAPI.args[argName] + "}}";
  });
  var title = handlebars.compile(chosenQItem)(quotedArgContext);
  cxsAPI.$el.append(
    $('
')
      .text(title)
      .append('')
  );
  var $controls = $('
');
  $controls.append(
    //TODO: Hook this button up.
    $('Alternative Scripts'),
    $('Show Source').prop({
      href: cxsAPI.config.url + '/contextscripts/' + result._id,
    })
  );
  $controls.hide();
  cxsAPI.$el.append($controls);

  cxsAPI.$el.find('.ctxscript-open-menu').click(function(){
    $controls.toggle();
  });
  cxsAPI.$el = createBox();
  cxsAPI.$el.append('

');
  eval(
    traceur.Compiler.script(result._source.script)
  );
  //Cause the side pane to scroll down to show the input box.
  //TODO: this doesn't quite work...
  $mainContainer.scrollTop($mainContainer[0].scrollHeight);
});
};
var doSearch = function(q){
  var currentContext = createContext();
  currentContext.q = q;
  //Beware that the result might not be present.
  var historyItem = {
    searchContext: currentContext
  };
  createBox('>' + q)
    .addClass("ctxscript-prev");
  var cxsAPI = createContextScriptAPI({
    $el: createBox('Loading...'),
    history: history,
    context: currentContext,
    currentHistoryItem: historyItem
  });
  historyItem.resultPromise = cxsAPI.resultPromise;

  cxsAPI.apiPost("/v0/search", {
    context: currentContext
  }).success(function(resp){
    historyItem.response = resp;
    cxsAPI.$el.empty();
    if (resp.hits.length === 0) {
      cxsAPI.$el.append(
        '
No scripts found
' +
        '<button class="ctxscript-btn ctxscript-search-btn">Create a script for this context</button>' +
        '<button class="ctxscript-btn ctxscript-search-btn">Request a script for this context</button>'
      );
    } else if (resp.hits.length === 1) {
      evalContextScript(resp.hits[0], cxsAPI);
    } else {
      // If there is one hit with a much higher score than the others
      // that will be shown instead of the multiple result list.
      var hitsAboveThreshold = resp.hits.filter(function(hit){
        return hit._score > (resp.max_score / 2);
      });
      if(hitsAboveThreshold.length == 1) {
          evalContextScript(hitsAboveThreshold[0], cxsAPI);
          return;
      }
      //TODO Add more meta-data
      cxsAPI.$el.append("
Multiple results:
");
      var $results = $("
");
      resp.hits.forEach(function(result){
        var $row = $('
');
        var $button = $('<button class="ctxscript-btn ctxscript-item-btn">')
          .text(result._source.context.q)
          .click(function(){
            cxsAPI.$el.empty();
            evalContextScript(result, cxsAPI);
          });
        $row.append(
          $button,
          $('
').text(
            "Last Modified: " +
            (new Date(result._source.lastModified)).toDateString()
          ),
          $('View Source').prop({
            href: cxsAPI.config.url + '/contextscripts/' + result._id
          })
        );
        $results.append($row);
      });
      cxsAPI.$el.append($results);
    }
  }).fail(function(error, msg){
    console.log(error);
    cxsAPI.$el.html(
        '
Error
' +
        '
' +
          error.status + ": " + error.statusText +
        '
'
    );
  });
  //Create new history array so that this context isn't included in the history
  //passed to the script.
  history = history.concat(historyItem);
};
$mainContainer.on('click', '.ctxscript-invoke', function ( e ) {
  var $q = $mainContainer.find('#ctxscript-q');
  doSearch($q.val());
  $q.val('');
});
$mainContainer.on('click', '.ctxscript-settings-btn', function ( e ) {
  $mainContainer.find('.ctxscript-settings').toggle();
});
$mainContainer.on('click', '.ctxscript-close', function ( e ) {
  $mainContainer.hide();
});
$mainContainer.on('click', '.ctxscript-about', function ( e ) {
  //The injection script could go out of sync with this one,
  //so it is versioned separately.
  //TODO: Make ctxscript alerts that allow copy/paste
  alert(
    "Version: " + VERSION + '-' + config.version +
    "\nUser Id: " + (config.user && config.user.id) +
    "\nServer URL: " + config.url
  );
});
//TODO: Go though command history with up/down arrows
$mainContainer.on('keypress', '#ctxscript-q', function(e) {
  if(e.which == 13) {
    var $q = $mainContainer.find('#ctxscript-q');
    doSearch($q.val());
    $q.val('');
  }
});
$mainContainer.find('.ctxscript-invoke').prop('disabled', false);
$mainContainer.find('.ctxscript-settings-btn').prop('disabled', false);
//TODO: Create suggestions box
//var $suggestions = $('
');
//$suggestions.append('suggestions:');
//$mainContainer.append($suggestions);
if(options.scriptId) {
  var currentContext = Object.create(context);
  var historyItem = {
    searchContext: currentContext
  };
  var cxsAPI = createContextScriptAPI({
    $el: createBox('Loading...'),
    history: history,
    context: currentContext,
    currentHistoryItem: historyItem
  });
  historyItem.resultPromise = cxsAPI.resultPromise;
  $.getJSON(config.url + '/v0/contextscripts/' + options.scriptId)
  .success(function(result){
    historyItem.response = result;
    cxsAPI.$el.empty();
    evalContextScript(result, cxsAPI, options.args);
  });
  history = history.concat(historyItem);
}
});
});
};
<|endoftext|>


<commit_before>var ipfsd = require('../index.js')
var assert = require('assert')
var ipfsApi = require('ipfs-api')
var run = require('comandante')

describe('disposable node with local api', function () {
  this.timeout(20000)
  var ipfs
  before(function (done) {
    ipfsd.disposable(function (err, node) {
      if (err) throw err
      node.startDaemon(function (err, ignore) {
        if (err) throw err
        ipfs = ipfsApi(node.apiAddr)
        done()
      })
    })
  })

  it('should have started the daemon and returned an api', function () {
    assert(ipfs)
    assert(ipfs.id)
  })

  var store, retrieve

  before(function (done) {
    var blorb = Buffer('blorb')
    ipfs.block.put(blorb, function (err, res) {
      if (err) throw err
      store = res.Key

      ipfs.block.get(res.Key, function (err, res) {
        if (err) throw err
        var buf = ''
        res
          .on('data', function (data) { buf += data })
          .on('end', function () {
            retrieve = buf
            done()
          })
      })
    })
  })
  it('should be able to store objects', function () {
    assert.equal(store, 'QmPv52ekjS75L4JmHpXVeuJ5uX2ecSfSZo88NSyxwA3rAQ')
  })
  it('should be able to retrieve objects', function () {
    assert.equal(retrieve, 'blorb')
  })
})

describe('disposableApi node', function () {
  this.timeout(20000)
  var ipfs
  before(function (done) {
    ipfsd.disposableApi(function (err, api) {
      if (err) throw err
      ipfs = api
      done()
    })
  })

  it('should have started the daemon and returned an api', function () {
    assert(ipfs)
    assert(ipfs.id)
  })

  var store, retrieve

  before(function (done) {
    var blorb = Buffer('blorb')
    ipfs.block.put(blorb, function (err, res) {
      if (err) throw err
      store = res.Key

      ipfs.block.get(res.Key, function (err, res) {
        if (err) throw err
        var buf = ''
        res
          .on('data', function (data) { buf += data })
          .on('end', function () {
            retrieve = buf
            done()
          })
      })
    })
  })
  it('should be able to store objects', function () {
    assert.equal(store, 'QmPv52ekjS75L4JmHpXVeuJ5uX2ecSfSZo88NSyxwA3rAQ')
  })
  it('should be able to retrieve objects', function () {
    assert.equal(retrieve, 'blorb')
  })
})

describe('starting and stopping', function () {
  this.timeout(10000)
  var node

  describe('init', function () {
    before(function (done) {
      ipfsd.disposable(function (err, res) {
        node = res
        done()
      })
    })

    it('should returned a node', function () {
      assert(node)
    })

    it('daemon should not be running', function () {
      assert(!node.daemonPid())
    })
  })

  var pid

  describe('starting', function () {
    var ipfs
    before(function (done) {
      node.startDaemon(function (err, res) {
        if (err) throw err

        pid = node.daemonPid()
        ipfs = res

        // actually running?
        run('kill', ['-0', pid])
          .on(err, function (err) { throw err })
          .on('end', function () { done() })
      })
    })

    it('should be running', function () {
      assert(ipfs.id)
    })
  })

  describe('stopping', function () {
    before(function (done) {
      node.stopDaemon()
      // make sure it's not still running
      var poll = setInterval(function () {
        run('kill', ['-0', pid])
          .on('error', function () {
            clearInterval(poll)
            done()
          })
      }, 100)
    })

    it('should be stopped', function () {
      assert(!node.daemonPid())
    })
  })
})
<commit_msg>test that daemon callback was called back<commit_after>var ipfsd = require('../index.js')
var assert = require('assert')
var ipfsApi = require('ipfs-api')
var run = require('comandante')

describe('disposable node with local api', function () {
  this.timeout(20000)
  var ipfs
  before(function (done) {
    ipfsd.disposable(function (err, node) {
      if (err) throw err
      node.startDaemon(function (err, ignore) {
        if (err) throw err
        ipfs = ipfsApi(node.apiAddr)
        done()
      })
    })
  })

  it('should have started the daemon and returned an api', function () {
    assert(ipfs)
    assert(ipfs.id)
  })

  var store, retrieve

  before(function (done) {
    var blorb = Buffer('blorb')
    ipfs.block.put(blorb, function (err, res) {
      if (err) throw err
      store = res.Key

      ipfs.block.get(res.Key, function (err, res) {
        if (err) throw err
        var buf = ''
        res
          .on('data', function (data) { buf += data })
          .on('end', function () {
            retrieve = buf
            done()
          })
      })
    })
  })
  it('should be able to store objects', function () {
    assert.equal(store, 'QmPv52ekjS75L4JmHpXVeuJ5uX2ecSfSZo88NSyxwA3rAQ')
  })
  it('should be able to retrieve objects', function () {
    assert.equal(retrieve, 'blorb')
  })
})

describe('disposableApi node', function () {
  this.timeout(20000)
  var ipfs
  before(function (done) {
    ipfsd.disposableApi(function (err, api) {
      if (err) throw err
      ipfs = api
      done()
    })
  })

  it('should have started the daemon and returned an api', function () {
    assert(ipfs)
    assert(ipfs.id)
  })

  var store, retrieve

  before(function (done) {
    var blorb = Buffer('blorb')
    ipfs.block.put(blorb, function (err, res) {
      if (err) throw err
      store = res.Key

      ipfs.block.get(res.Key, function (err, res) {
        if (err) throw err
        var buf = ''
        res
          .on('data', function (data) { buf += data })
          .on('end', function () {
            retrieve = buf
            done()
          })
      })
    })
  })
  it('should be able to store objects', function () {
    assert.equal(store, 'QmPv52ekjS75L4JmHpXVeuJ5uX2ecSfSZo88NSyxwA3rAQ')
  })
  it('should be able to retrieve objects', function () {
    assert.equal(retrieve, 'blorb')
  })
})

describe('starting and stopping', function () {
  this.timeout(10000)
  var node

  describe('init', function () {
    before(function (done) {
      ipfsd.disposable(function (err, res) {
        node = res
        done()
      })
    })

    it('should returned a node', function () {
      assert(node)
    })

    it('daemon should not be running', function () {
      assert(!node.daemonPid())
    })
  })

  var pid

  describe('starting', function () {
    var ipfs
    before(function (done) {
      node.startDaemon(function (err, res) {
        if (err) throw err

        pid = node.daemonPid()
        ipfs = res

        // actually running?
        run('kill', ['-0', pid])
          .on(err, function (err) { throw err })
          .on('end', function () { done() })
      })
    })

    it('should be running', function () {
      assert(ipfs.id)
    })
  })

  var stopped = false
  describe('stopping', function () {
    before(function (done) {
      node.stopDaemon(function (err) {
        if (err) throw err
        stopped = true;
      })
      // make sure it's not still running
      var poll = setInterval(function () {
        run('kill', ['-0', pid])
          .on('error', function () {
            clearInterval(poll)
            done()
          })
      }, 100)
    })

    it('should be stopped', function () {
      assert(!node.daemonPid())
      assert(stopped)
    })
  })
})
<|endoftext|>


<commit_before>'use strict';

import chai, {expect} from 'src/external/chai.js';
import sinon from 'src/external/sinon-3.2.1.js';
import sinonChai from 'src/external/sinon-chai.js';
chai.use(sinonChai);

import { aexpr, check, clearDefaultActiveExpressions } from '../../active-expression-convention/active-expression-ticking.js';

describe('Ticking Active Expressions', () => {
    it("runs a basic aexpr", () => {
        let obj = {a: 2, b: 3},
            spy = sinon.spy();

        aexpr(() => obj.a).onChange(spy);

        check();
        expect(spy.called).to.be.false;

        obj.a = 42;

        check();
        expect(spy.calledOnce).to.be.true;
    });

    it("recognize changes to local variables", () => {
        let val = 17,
            spy = sinon.spy();

        aexpr(() => val).onChange(spy);

        val = 42;

        check();
        expect(spy.calledOnce).to.be.true;
    });

    it("provide the new value of the expression to the callback", () => {
        let val = 17,
            spy = sinon.spy();

        aexpr(() => val).onChange(spy);

        val = 42;

        check();
        expect(spy.withArgs(42).calledOnce).to.be.true;
    });

    it("provide additional information (e.g. the last value of the expression) to the callback", () => {
        let val = 17,
            spy = sinon.spy();

        aexpr(() => val).onChange(spy);

        val = 42;

        check();
        expect(spy).to.have.been.calledOnce;
        expect(spy.getCall(0).args[0]).to.equal(42);
        expect(spy.getCall(0).args[1]).to.have.property('lastValue', 17);
    });

    describe('check', () => {
        it("run multiple checks only invokes the callback once", () => {
            let val = 17,
                spy = sinon.spy();

            aexpr(() => val).onChange(spy);

            val = 42;

            check();
            check();

            expect(spy.calledOnce).to.be.true;
        });

        it("check all active expressions if not specified further", () => {
            let val1 = 17,
                val2 = 33,
                spy1 = sinon.spy(),
                spy2 = sinon.spy();

            aexpr(() => val1).onChange(spy1);
            aexpr(() => val2).onChange(spy2);

            val1 = 42;
            val2 = 51;

            check();

            expect(spy1.calledOnce).to.be.true;
            expect(spy2.calledOnce).to.be.true;
        });

        it("check all active expressions provided by an iterator", () => {
            let val = 17,
                spy1 = sinon.spy(),
                spy2 = sinon.spy(),
                spy3 = sinon.spy(),
                aexpr1 = aexpr(() => val).onChange(spy1),
                aexpr2 = aexpr(() => val).onChange(spy2),
                aexpr3 = aexpr(() => val).onChange(spy3);

            val = 42;

            check([aexpr1, aexpr2]);

            expect(spy1.calledOnce).to.be.true;
            expect(spy2.calledOnce).to.be.true;
            expect(spy3.called).to.be.false;
        });

        // TODO: should this really be part of the API?
        it("check a single active expressions", () => {
            let val = 17,
                spy = sinon.spy(),
                expr = aexpr(() => val).onChange(spy);

            val = 42;
            expr.checkAndNotify();

            expect(spy.calledOnce).to.be.true;
        });
    });

    describe('parametrizable aexprs', () => {
        it("handle aexprs with one single instance-bindong", () => {
            let obj = { val: 17 },
                spy = sinon.spy();

            aexpr(o => o.val, { params: [obj] }).onChange(spy);

            expect(spy).not.to.be.called;

            obj.val = 42;

            check();

            expect(spy).to.be.calledOnce;
        });

        it("handle aexprs with one instance-binding with multiple variables", () => {
            let obj1 = { val: 1 },
                obj2 = { val: 2 },
                obj3 = { val: 3 },
                spy = sinon.spy();

            aexpr((o1, o2, o3) => o1.val + o2.val + o3.val, { params: [obj1, obj2, obj3] }).onChange(spy);

            expect(spy).not.to.be.called;

            obj1.val = 10;
            check();

            expect(spy.withArgs(15)).to.be.calledOnce;

            obj2.val = 20;
            check();

            expect(spy.withArgs(33)).to.be.calledOnce;
        });

        it("handle aexprs with multiple instance-bindings", () => {
            let obj1 = { val: 1 },
                obj2 = { val: 2 },
                obj3 = { val: 3 },
                spy12 = sinon.spy(),
                spy23 = sinon.spy(),
                expr = (o1, o2) => o1.val + o2.val;

            aexpr(expr, { params: [obj1, obj2] }).onChange(spy12);
            aexpr(expr, { params: [obj2, obj3] }).onChange(spy23);

            expect(spy12).not.to.be.called;
            expect(spy23).not.to.be.called;

            obj1.val = 10;
            check();

            expect(spy12.withArgs(12)).to.be.calledOnce;
            expect(spy23).not.to.be.called;

            obj2.val = 20;
            check();

            expect(spy12.withArgs(30)).to.be.calledOnce;
            expect(spy23.withArgs(23)).to.be.calledOnce;

            obj3.val = 30;
            check();

            expect(spy12.withArgs(30)).to.be.calledOnce;
            expect(spy23.withArgs(50)).to.be.calledOnce;
        });
    });

        // TODO: is this useful?
    describe('disable and re-enable', () => {
        it("disabled aexprs do not fire notify the callback", () => {
            let val = 17,
                spy = sinon.spy();

            aexpr(() => val)
                .onChange(spy)
                .disable();

            val = 33;
            check();

            expect(spy.called).to.be.false;
        });

        it("disabled aexprs do nothing when explicitly listed to be checked", () => {
            let val = 17,
                spy = sinon.spy(),
                expr = aexpr(() => val)
                    .onChange(spy)
                    .disable();

            val = 33;
            check([expr]);

            expect(spy.called).to.be.false;
        });

        it("disabled aexprs do nothing when explicitly listed to be checked", () => {
            let val = 17,
                spy = sinon.spy(),
                expr = aexpr(() => val)
                    .onChange(spy)
                    .disable();

            val = 33;
            check();

            expect(spy.called).to.be.false;

            expr.enable();

            val = 33;
            check();

            expect(spy.calledOnce).to.be.true;

        });
    });

    describe('clearDefaultActiveExpressions', () => {
        it("clear global fallback set of active expressions", () => {
            let val = 17,
                spy = sinon.spy();

            let expr = aexpr(() => val)
                .onChange(spy);

            val = 33;

            clearDefaultActiveExpressions();

            check();

            expect(spy.called).to.be.false;

            check([expr]);

            expect(spy.called).to.be.true;
        });
    });
});<commit_msg>AUTO-COMMIT src/client/reactive/test/active-expression-convention/active-expression-ticking.spec.js<commit_after>'use strict';

import chai, {expect} from 'src/external/chai.js';
import sinon from 'src/external/sinon-3.2.1.js';
import sinonChai from 'src/external/sinon-chai.js';
chai.use(sinonChai);

import { aexpr, check, clearDefaultActiveExpressions } from '../../active-expression-convention/active-expression-ticking.js';

describe('Ticking Active Expressions', () => {
    it("runs a basic aexpr", () => {
        let obj = {a: 2, b: 3},
            spy = sinon.spy();

        aexpr(() => obj.a).onChange(spy);

        check();
        expect(spy.called).to.be.false;

        obj.a = 42;

        check();
        expect(spy.calledOnce).to.be.true;
    });

    it("recognize changes to local variables", () => {
        let val = 17,
            spy = sinon.spy();

        aexpr(() => val).onChange(spy);

        val = 42;

        check();
        expect(spy.calledOnce).to.be.true;
    });

    it("provide the new value of the expression to the callback", () => {
        let val = 17,
            spy = sinon.spy();

        aexpr(() => val).onChange(spy);

        val = 42;

        check();
        expect(spy.withArgs(42).calledOnce).to.be.true;
    });

    it("provide additional information (e.g. the last value of the expression) to the callback", () => {
        let val = 17,
            spy = sinon.spy();

        aexpr(() => val).onChange(spy);

        val = 42;

        check();
        expect(spy).to.have.been.calledOnce;
        expect(spy.getCall(0).args[0]).to.equal(42);
        expect(spy.getCall(0).args[1]).to.have.property('lastValue', 17);
    });

    describe('check', () => {
        it("run multiple checks only invokes the callback once", () => {
            let val = 17,
                spy = sinon.spy();

            aexpr(() => val).onChange(spy);

            val = 42;

            check();
            check();

            expect(spy.calledOnce).to.be.true;
        });

        it("check all active expressions if not specified further", () => {
            let val1 = 17,
                val2 = 33,
                spy1 = sinon.spy(),
                spy2 = sinon.spy();

            aexpr(() => val1).onChange(spy1);
            aexpr(() => val2).onChange(spy2);

            val1 = 42;
            val2 = 51;

            check();

            expect(spy1.calledOnce).to.be.true;
            expect(spy2.calledOnce).to.be.true;
        });

        it("check all active expressions provided by an iterator", () => {
            let val = 17,
                spy1 = sinon.spy(),
                spy2 = sinon.spy(),
                spy3 = sinon.spy(),
                aexpr1 = aexpr(() => val).onChange(spy1),
                aexpr2 = aexpr(() => val).onChange(spy2),
                aexpr3 = aexpr(() => val).onChange(spy3);

            val = 42;

            check([aexpr1, aexpr2]);

            expect(spy1.calledOnce).to.be.true;
            expect(spy2.calledOnce).to.be.true;
            expect(spy3.called).to.be.false;
        });

        // TODO: should this really be part of the API?
        it("check a single active expressions", () => {
            let val = 17,
                spy = sinon.spy(),
                expr = aexpr(() => val).onChange(spy);

            val = 42;
            expr.checkAndNotify();

            expect(spy.calledOnce).to.be.true;
        });
    });

    describe('parametrizable aexprs', () => {
        it("handle aexprs with one single instance-bindong", () => {
            let obj = { val: 17 },
                spy = sinon.spy();

            aexpr(o => o.val, { params: [obj] }).onChange(spy);

            expect(spy).not.to.be.called;

            obj.val = 42;

            check();

            expect(spy).to.be.calledOnce;
        });

        it("handle aexprs with one instance-binding with multiple variables", () => {
            let obj1 = { val: 1 },
                obj2 = { val: 2 },
                obj3 = { val: 3 },
                spy = sinon.spy();

            aexpr((o1, o2, o3) => o1.val + o2.val + o3.val, { params: [obj1, obj2, obj3] }).onChange(spy);

            expect(spy).not.to.be.called;

            obj1.val = 10;
            check();

            expect(spy.withArgs(15)).to.be.calledOnce;

            obj2.val = 20;
            check();

            expect(spy.withArgs(33)).to.be.calledOnce;
        });

        it("handle aexprs with multiple instance-bindings", () => {
            let obj1 = { val: 1 },
                obj2 = { val: 2 },
                obj3 = { val: 3 },
                spy12 = sinon.spy(),
                spy23 = sinon.spy(),
                expr = (o1, o2) => o1.val + o2.val;

            aexpr(expr, { params: [obj1, obj2] }).onChange(spy12);
            aexpr(expr, { params: [obj2, obj3] }).onChange(spy23);

            expect(spy12).not.to.be.called;
            expect(spy23).not.to.be.called;

            obj1.val = 10;
            check();

            expect(spy12.withArgs(12)).to.be.calledOnce;
            expect(spy23).not.to.be.called;

            obj2.val = 20;
            check();

            expect(spy12.withArgs(30)).to.be.calledOnce;
            expect(spy23.withArgs(23)).to.be.calledOnce;

            obj3.val = 30;
            check();

            expect(spy12.withArgs(30)).to.be.calledOnce;
            expect(spy23.withArgs(50)).to.be.calledOnce;
        });
    });

        // TODO: is this useful?
    describe('disable and re-enable', () => {
        it("disabled aexprs do not fire notify the callback", () => {
            let val = 17,
                spy = sinon.spy();

            aexpr(() => val)
                .onChange(spy)
                .disable();

            val = 33;
            check();

            expect(spy.called).to.be.false;
        });

        it("disabled aexprs do nothing when explicitly listed to be checked", () => {
            let val = 17,
                spy = sinon.spy(),
                expr = aexpr(() => val)
                    .onChange(spy)
                    .disable();

            val = 33;
            check([expr]);

            expect(spy.called).to.be.false;
        });

        it("disabled aexprs do nothing when explicitly listed to be checked", () => {
            let val = 17,
                spy = sinon.spy(),
                expr = aexpr(() => val)
                    .onChange(spy)
                    .disable();

            val = 33;
            check();

            expect(spy.called).to.be.false;

            expr.enable();

            val = 33;
            check();

            expect(spy.calledOnce).to.be.true;

        });
    });

    describe('clearDefaultActiveExpressions', () => {
        it("clear global fallback set of active expressions", () => {
            let val = 17,
                spy = sinon.spy();

            let expr = aexpr(() => val)
                .onChange(spy);

            val = 33;

            clearDefaultActiveExpressions();

            check();

            expect(spy.called).to.be.false;

            check([expr]);

            expect(spy.called).to.be.true;
        });
    });
});
<|endoftext|>


<commit_before>
'use strict';

const test = require('tape');
const co = require('co');
const path = require('path');
const MrRogers = require('../index');
const Store = require('kevin-johnson');
require('dotenv').config({path: path.resolve('./test/test.env')});
const opts = {
  appName: process.env.APP_NAME,
  dbUrl: process.env.DATABASE_URL
};

const errorFunc = (err) => {
  throw err;
};

test('clean text returns false', (t) => {
  co(function*() {
    const text = 'Here is some clean text #obama';
    const store = yield Store(opts);
    const mrRogers = yield MrRogers({ store });
    yield mrRogers.useDefaults();
    const hasProfanity = yield mrRogers.detect(text);
    t.equal(hasProfanity, false, 'the clean text returns false');
    yield store.destroy();
    t.end();
  })
  .catch((err) => console.error(err));
});

test('dirty text returns true', (t) => {
  co(function*() {
    const text = 'Here is some dirty fucking text';
    const store = yield Store(opts);
    const mrRogers = yield MrRogers({ store });
    yield mrRogers.useDefaults();
    const hasProfanity = yield mrRogers.detect(text);
    t.equal(hasProfanity, true, 'the dirty text returns true');
    yield store.destroy();
    t.end();
  })
  .catch((err) => console.error(err));
});

test('forbid a clean word', (t) => {
  co(function*() {
    const text = 'blah blah obama trump';
    const word = 'obama';
    const store = yield Store(opts);
    const mrRogers = yield MrRogers({ store });
    yield mrRogers.useDefaults();
    let hasProfanity = yield mrRogers.detect(text);
    t.equal(hasProfanity, false, 'no trigger before forbid');
    yield mrRogers.forbid([ word ]);
    hasProfanity = yield mrRogers.detect(text);
    t.equal(hasProfanity, true, 'trigger after forbid');
    yield store.destroy();
    t.end();
  })
  .catch((err) => console.error(err));
});

test('allow a dirty word', (t) => {
  co(function*() {
    const text = 'blah blah obama trump';
    const word = 'fuck';
    const store = yield Store(opts);
    const mrRogers = yield MrRogers({ store });
    yield mrRogers.useDefaults();
    let hasProfanity = yield mrRogers.detect(word);
    t.equal(hasProfanity, true, 'detects the bad word before allow');
    yield mrRogers.allow(word);
    hasProfanity = yield mrRogers.detect(word);
    t.equal(hasProfanity, false, 'does not detect the bad word after allowing');
    yield store.destroy();
    t.end();
  })
  .catch((err) => console.error(err));
});

test('do not detect pattern within words', (t) => {
  co(function*() {
    const text = 'Here is some dirtyfuckingtext';
    const word = 'fuck';
    const store = yield Store(opts);
    const mrRogers = yield MrRogers({ store });
    yield mrRogers.useDefaults();
    const hasProfanity = yield mrRogers.detect(text);
    t.equal(hasProfanity, false, 'it didn\'t detect the bad word');
    yield store.destroy();
    t.end();
  })
  .catch((err) => console.error(err));
});

test('detect pattern at the beginning of a string', (t) => {
  co(function*() {
    const text = 'ass Here is some';
    const word = 'fuck';
    const store = yield Store(opts);
    const mrRogers = yield MrRogers({ store });
    yield mrRogers.useDefaults();
    const hasProfanity = yield mrRogers.detect(text);
    t.equal(hasProfanity, true, 'detects a bad word at the beginning');
    yield store.destroy();
    t.end();
  })
  .catch((err) => console.error(err));
});

test('detect pattern at the end of a string', (t) => {
  co(function*() {
    const text = 'Here is the word shit.';
    const word = 'fuck';
    const store = yield Store(opts);
    const mrRogers = yield MrRogers({ store });
    yield mrRogers.useDefaults();
    const hasProfanity = yield mrRogers.detect(text);
    t.equal(hasProfanity, true, 'detects bad word at the end');
    yield store.destroy();
    t.end();
  })
  .catch((err) => console.error(err));
});

// test('cleanup', (t) => {
//   t.end();
//   process.exit();
// });
<commit_msg>remove unnecessary exit code from tests<commit_after>
'use strict';

const test = require('tape');
const co = require('co');
const path = require('path');
const MrRogers = require('../index');
const Store = require('kevin-johnson');
require('dotenv').config({path: path.resolve('./test/test.env')});
const opts = {
  appName: process.env.APP_NAME,
  dbUrl: process.env.DATABASE_URL
};

const errorFunc = (err) => {
  throw err;
};

test('clean text returns false', (t) => {
  co(function*() {
    const text = 'Here is some clean text #obama';
    const store = yield Store(opts);
    const mrRogers = yield MrRogers({ store });
    yield mrRogers.useDefaults();
    const hasProfanity = yield mrRogers.detect(text);
    t.equal(hasProfanity, false, 'the clean text returns false');
    yield store.destroy();
    t.end();
  })
  .catch((err) => console.error(err));
});

test('dirty text returns true', (t) => {
  co(function*() {
    const text = 'Here is some dirty fucking text';
    const store = yield Store(opts);
    const mrRogers = yield MrRogers({ store });
    yield mrRogers.useDefaults();
    const hasProfanity = yield mrRogers.detect(text);
    t.equal(hasProfanity, true, 'the dirty text returns true');
    yield store.destroy();
    t.end();
  })
  .catch((err) => console.error(err));
});

test('forbid a clean word', (t) => {
  co(function*() {
    const text = 'blah blah obama trump';
    const word = 'obama';
    const store = yield Store(opts);
    const mrRogers = yield MrRogers({ store });
    yield mrRogers.useDefaults();
    let hasProfanity = yield mrRogers.detect(text);
    t.equal(hasProfanity, false, 'no trigger before forbid');
    yield mrRogers.forbid([ word ]);
    hasProfanity = yield mrRogers.detect(text);
    t.equal(hasProfanity, true, 'trigger after forbid');
    yield store.destroy();
    t.end();
  })
  .catch((err) => console.error(err));
});

test('allow a dirty word', (t) => {
  co(function*() {
    const text = 'blah blah obama trump';
    const word = 'fuck';
    const store = yield Store(opts);
    const mrRogers = yield MrRogers({ store });
    yield mrRogers.useDefaults();
    let hasProfanity = yield mrRogers.detect(word);
    t.equal(hasProfanity, true, 'detects the bad word before allow');
    yield mrRogers.allow(word);
    hasProfanity = yield mrRogers.detect(word);
    t.equal(hasProfanity, false, 'does not detect the bad word after allowing');
    yield store.destroy();
    t.end();
  })
  .catch((err) => console.error(err));
});

test('do not detect pattern within words', (t) => {
  co(function*() {
    const text = 'Here is some dirtyfuckingtext';
    const word = 'fuck';
    const store = yield Store(opts);
    const mrRogers = yield MrRogers({ store });
    yield mrRogers.useDefaults();
    const hasProfanity = yield mrRogers.detect(text);
    t.equal(hasProfanity, false, 'it didn\'t detect the bad word');
    yield store.destroy();
    t.end();
  })
  .catch((err) => console.error(err));
});

test('detect pattern at the beginning of a string', (t) => {
  co(function*() {
    const text = 'ass Here is some';
    const word = 'fuck';
    const store = yield Store(opts);
    const mrRogers = yield MrRogers({ store });
    yield mrRogers.useDefaults();
    const hasProfanity = yield mrRogers.detect(text);
    t.equal(hasProfanity, true, 'detects a bad word at the beginning');
    yield store.destroy();
    t.end();
  })
  .catch((err) => console.error(err));
});

test('detect pattern at the end of a string', (t) => {
  co(function*() {
    const text = 'Here is the word shit.';
    const word = 'fuck';
    const store = yield Store(opts);
    const mrRogers = yield MrRogers({ store });
    yield mrRogers.useDefaults();
    const hasProfanity = yield mrRogers.detect(text);
    t.equal(hasProfanity, true, 'detects bad word at the end');
    yield store.destroy();
    t.end();
  })
  .catch((err) => console.error(err));
});

<|endoftext|>


<commit_before>'use strict';

// stdlib
import React from 'react';
import createReactClass from 'create-react-class';
import PropTypes from 'prop-types';

// third party lib
import { Input } from '../../../../libs/bootstrap/form';
import ModalComponent from '../../../../libs/bootstrap/modal';

/**
 * Modal to confirm before deleting an evidence.
 */

let ConfirmDelete = createReactClass({
    propTypes: {
        evidence: PropTypes.object,     // Selected evidence row to be deleted
        deleteEvidence: PropTypes.func  // Function to call to delete the evidence row
    },

    handleModalClose() {
        this.confirm.closeModal();
    },

    cancel() {
        this.handleModalClose();
    },

    clickConfirm() {
        this.props.deleteEvidence(this.props.evidence);
        this.handleModalClose();
    },

    render() {
        return (
            <ModalComponent
                    modalTitle="Confirm evidence deletion"
                    modalClass="modal-default"
                    modalWrapperClass="confirm-interpretation-delete-evidence pull-right"
                    bootstrapBtnClass="btn btn-danger "
                    actuatorClass="interpretation-delete-evidence-btn"
                    actuatorTitle={"Delete"}
                    onRef={ref => (this.confirm = ref)}
                >

                            Are you sure you want to delete this evidence?

                        <Input type="button" inputClassName="btn-primary btn-inline-spacer" clickHandler={this.clickConfirm} title="Confirm" />
                        <Input type="button" inputClassName="btn-default btn-inline-spacer" clickHandler={this.cancel} title="Cancel" />

            </ModalComponent>
        );
    }
});

module.exports = {
    ConfirmDelete: ConfirmDelete
}

<commit_msg>#1893: Small style changes<commit_after>'use strict';

// stdlib
import React from 'react';
import createReactClass from 'create-react-class';
import PropTypes from 'prop-types';

// third party lib
import { Input } from '../../../../libs/bootstrap/form';
import ModalComponent from '../../../../libs/bootstrap/modal';

/**
 * Modal to confirm before deleting an evidence.
 */

let ConfirmDelete = createReactClass({
    propTypes: {
        evidence: PropTypes.object,     // Selected evidence row to be deleted
        deleteEvidence: PropTypes.func  // Function to call to delete the evidence row
    },

    handleModalClose() {
        this.confirm.closeModal();
    },

    cancel() {
        this.handleModalClose();
    },

    clickConfirm() {
        this.props.deleteEvidence(this.props.evidence);
        this.handleModalClose();
    },

    render() {
        return (
            <ModalComponent
                    modalTitle="Confirm evidence deletion"
                    modalClass="modal-default"
                    modalWrapperClass="confirm-interpretation-delete-evidence pull-right"
                    bootstrapBtnClass="btn btn-danger "
                    actuatorClass="interpretation-delete-evidence-btn"
                    actuatorTitle="Delete"
                    onRef={ref => (this.confirm = ref)}
                >

                            Are you sure you want to delete this evidence?

                        <Input type="button" inputClassName="btn-primary btn-inline-spacer" clickHandler={this.clickConfirm} title="Confirm" />
                        <Input type="button" inputClassName="btn-default btn-inline-spacer" clickHandler={this.cancel} title="Cancel" />

            </ModalComponent>
        );
    }
});

module.exports = {
    ConfirmDelete: ConfirmDelete
}

<|endoftext|>