<commit_before>/**
 * Created by JiaHao on 18/8/15.
 */

var async = require('async');
var chai = require('chai');
var assert = chai.assert;

var phantomBase = require('./../lib/phantomBase');
var PhantomHigh = require('./../lib/PhantomHigh');

const testUrls = ['http://apple.com', 'https://www.facebook.com/', 'http://skewedlines.github.io/ajax-test-page/'];
const INVALID_URL = 'http://insdasjdlkas.com/';

describe('Testing base PhantomJS functions', function () {
    this.timeout(50000);
    it('Can open pages', function (done) {

        async.each(testUrls, function (testUrl, callback) {
            phantomBase.openPage(testUrl, function (error, page, ph) {
                ph.exit();
                callback(error);
            });
        }, function (error) {
            assert.notOk(error, 'No error should be received when opening pages');
            done(error);
        });
    });

    it('Can fail to open pages gracefully', function (done) {

        phantomBase.openPage(INVALID_URL, function (error, page, ph) {
            ph.exit();
            assert.ok(error, 'An error should be received when opening pages');
            done();
        });
    });
});

describe('Testing PhantomHigh Object', function () {
    this.timeout(30000);

    it('Can open pages (Node style callback)', function (done) {
        async.each(testUrls, function (testUrl, callback) {

            var browser = new PhantomHigh();
            browser.openPage(testUrl, function (error) {
                browser.done();
                callback(error);
            });

        }, function (error) {
            assert.notOk(error, 'No error should be received when opening a valid page.');
            done(error);
        })
    });

    it('Can do tasks sequentially and get a snapshot', function (done) {
        var browser = new PhantomHigh();
        var url = testUrls[0];
        browser
            .openPage(url)
            .then(function () {
                return browser.takeSnapshot();
            })
            .then(function (result) {
                assert.include(result, '', 'Snapshot results contain closing  tag');
                browser.done();
                done();
            }).fail(function (error) {
                browser.done();
                done(error);
            });
    });

    describe('Graceful failures', function () {
        describe('Error triggers if a page is not open', function () {

            it('Node style callback', function (done) {
                var browser = new PhantomHigh();

                browser.takeSnapshot(function (error) {
                    browser.done();
                    assert.ok(error, 'Error should say that a page is not open');
                    done();
                });
            });

            it('Promise', function (done) {
                var browser = new PhantomHigh();

                browser
                    .takeSnapshot()
                    .then(function (result) {
                        done('Error: Result callback should not be called, it is invalid');
                    }).fail(function (error) {
                        browser.done();
                        assert.ok(error, 'Error should say that a page is not open');
                        done();
                    });
            });
        });

        it('Promise Should propagate errors', function (done) {
            var browser = new PhantomHigh();

            // provide an invalid url, error should be sent in the callback at .openPage();
            var url = null;

            browser
                .openPage(url)
                .then(function () {
                    return browser.takeSnapshot();
                })
                .then(function (result) {
                    browser.done();
                    done('Error callback should have been triggered, not this.');
                }).fail(function (error) {
                    browser.done();
                    assert.ok(error, 'Error should say that an invalid url is provided');
                    done();
                }).fail(function (error) {
                    // this will be reached if an exception is thrown in the callback for .fail()
                    // as there are issues when throwing synchronous errors in the final callback
                    done(error);
                });
        });
    });

    it('Can wait for an element to appear and can get the innerHTML of the element', function (done) {
        var browser = new PhantomHigh();
        var url = testUrls[2];

        const SELECTOR = '#setTimeoutContent';
        browser.openPage(url);
        browser.waitForElement(SELECTOR);
        browser.getInnerHTML(SELECTOR, function (error, result) {
                assert.equal(result, 'BUBBLES', 'Awaited element innerHTML should be "BUBBLES"');
                browser.done();
                done(error);
            });
    });

    it('Can fill a form and query a form for its value', function (done) {
        var browser = new PhantomHigh();
        var url = testUrls[2];

        const USERNAME_SELECTOR = '#form-username';
        const PASSWORD_SELECTOR = '#form-password';

        const USERNAME = 'user123';

        browser
            .openPage(url)
            .then(function () {
                return browser.fillForm(USERNAME_SELECTOR, USERNAME);
            })
            .then(function () {
                return browser.getSelectorValue(USERNAME_SELECTOR);
            }).then(function (result) {
                assert.equal(result, USERNAME, 'Username should be equal to filled value');
                browser.done();
                done();
            }).fail(function (error) {
                done(error);
            });
    });
});<commit_msg>Reorganise tests for clarity<commit_after>/**
 * Created by JiaHao on 18/8/15.
 */

var async = require('async');
var chai = require('chai');
var assert = chai.assert;

var phantomBase = require('./../lib/phantomBase');
var PhantomHigh = require('./../lib/PhantomHigh');

const testUrls = ['http://apple.com', 'https://www.facebook.com/', 'http://skewedlines.github.io/ajax-test-page/'];
const INVALID_URL = 'http://insdasjdlkas.com/';

describe('Testing base PhantomJS functions', function () {
    this.timeout(50000);
    it('Can open pages', function (done) {

        async.each(testUrls, function (testUrl, callback) {
            phantomBase.openPage(testUrl, function (error, page, ph) {
                ph.exit();
                callback(error);
            });
        }, function (error) {
            assert.notOk(error, 'No error should be received when opening pages');
            done(error);
        });
    });

    it('Can fail to open pages gracefully', function (done) {

        phantomBase.openPage(INVALID_URL, function (error, page, ph) {
            ph.exit();
            assert.ok(error, 'An error should be received when opening pages');
            done();
        });
    });
});

describe('Testing PhantomHigh Object', function () {
    this.timeout(30000);

    describe('Basic tasks', function () {

        it('Can open pages (Node style callback)', function (done) {
            async.each(testUrls, function (testUrl, callback) {

                var browser = new PhantomHigh();
                browser.openPage(testUrl, function (error) {
                    browser.done();
                    callback(error);
                });

            }, function (error) {
                assert.notOk(error, 'No error should be received when opening a valid page.');
                done(error);
            });
        });

        it('Can do tasks sequentially and get a snapshot', function (done) {
            var browser = new PhantomHigh();
            var url = testUrls[0];
            browser
                .openPage(url)
                .then(function () {
                    return browser.takeSnapshot();
                })
                .then(function (result) {
                    assert.include(result, '', 'Snapshot results contain closing  tag');
                    browser.done();
                    done();
                }).fail(function (error) {
                    browser.done();
                    done(error);
                });
        });

        it('Can wait for an element to appear and can get the innerHTML of the element', function (done) {
            var browser = new PhantomHigh();
            var url = testUrls[2];

            const SELECTOR = '#setTimeoutContent';
            browser.openPage(url);
            browser.waitForElement(SELECTOR);
            browser.getInnerHTML(SELECTOR, function (error, result) {
                assert.equal(result, 'BUBBLES', 'Awaited element innerHTML should be "BUBBLES"');
                browser.done();
                done(error);
            });
        });

        it('Can fill a form and query a form for its value', function (done) {
            var browser = new PhantomHigh();
            var url = testUrls[2];

            const USERNAME_SELECTOR = '#form-username';
            const PASSWORD_SELECTOR = '#form-password';

            const USERNAME = 'user123';

            browser
                .openPage(url)
                .then(function () {
                    return browser.fillForm(USERNAME_SELECTOR, USERNAME);
                })
                .then(function () {
                    return browser.getSelectorValue(USERNAME_SELECTOR);
                }).then(function (result) {
                    assert.equal(result, USERNAME, 'Username should be equal to filled value');
                    browser.done();
                    done();
                }).fail(function (error) {
                    done(error);
                });
        });

    });

    describe('Graceful failures', function () {

        describe('Error triggers if a page is not open', function () {

            it('Node style callback', function (done) {
                var browser = new PhantomHigh();

                browser.takeSnapshot(function (error) {
                    browser.done();
                    assert.ok(error, 'Error should say that a page is not open');
                    done();
                });
            });

            it('Promise', function (done) {
                var browser = new PhantomHigh();

                browser
                    .takeSnapshot()
                    .then(function (result) {
                        done('Error: Result callback should not be called, it is invalid');
                    }).fail(function (error) {
                        browser.done();
                        assert.ok(error, 'Error should say that a page is not open');
                        done();
                    });
            });
        });

        it('Promise Should propagate errors', function (done) {
            var browser = new PhantomHigh();

            // provide an invalid url, error should be sent in the callback at .openPage();
            var url = null;

            browser
                .openPage(url)
                .then(function () {
                    return browser.takeSnapshot();
                })
                .then(function (result) {
                    browser.done();
                    done('Error callback should have been triggered, not this.');
                }).fail(function (error) {
                    browser.done();
                    assert.ok(error, 'Error should say that an invalid url is provided');
                    done();
                }).fail(function (error) {
                    // this will be reached if an exception is thrown in the callback for .fail()
                    // as there are issues when throwing synchronous errors in the final callback
                    done(error);
                });
        });
    });

});<|endoftext|>


<commit_before>import BabelRootImportPlugin from '../plugin';

describe('Babel Root Import', () => {
  let babelRootImportPlugin, plugin;

  beforeEach(() => {
    plugin = BabelRootImportPlugin();
  });

  describe('Class', () => {
    it('returns the root path', () => {
      const rootByProcess = process.cwd();
      expect(plugin.root).to.equal(rootByProcess);
    });
  });

  describe('transformRelativeToRootPath', () => {
    it('returns a string', () => {
      const func = plugin.transformRelativeToRootPath();
      expect(func).to.be.a('string');
    });

    it('transforms given path relative root-path', () => {
      const rootPath = `${process.cwd()}/some/path`;
      const result = plugin.transformRelativeToRootPath('~/some/path');
      expect(result).to.equal(rootPath);
    });
  });

  describe('hasTildeInString', () => {
    it('returns a boolean', () => {
      const func = plugin.hasTildeInString();
      expect(func).to.be.a('boolean');
    });

    it('check if a "~/" is at the beginning of the string', () => {
      const withoutTilde = plugin.hasTildeInString('some/path');
      const withTilde = plugin.hasTildeInString('~/some/path');
      expect(withoutTilde).to.be.false;
      expect(withTilde).to.be.true;
    });

    it('returns false if no string is passed', () => {
      const nothingPassed = plugin.hasTildeInString();
      const wrongTypePassed = plugin.hasTildeInString([]);
      expect(nothingPassed).to.be.false;
      expect(wrongTypePassed).to.be.false;
    });
  });
});
<commit_msg>Update tests<commit_after>import BabelRootImportPlugin from '../plugin';

describe('Babel Root Import', () => {
  let babelRootImportPlugin, plugin;

  beforeEach(() => {
    plugin = BabelRootImportPlugin();
  });

  describe('Class', () => {
    it('returns the root path', () => {
      const rootByProcess = process.cwd();
      expect(plugin.root).to.equal(rootByProcess);
    });
  });

  describe('transformRelativeToRootPath', () => {
    it('returns a string', () => {
      const func = plugin.transformRelativeToRootPath('');
      expect(func).to.be.a('string');
    });

    it('transforms given path relative root-path', () => {
      const rootPath = `${process.cwd()}/some/path`;
      const result = plugin.transformRelativeToRootPath('~/some/path');
      expect(result).to.equal(rootPath);
    });

    it('throws error if no string is passed', () => {
      expect(() => {
        plugin.transformRelativeToRootPath();
      }).to.throw(Error);
    });
  });

  describe('hasTildeInString', () => {
    it('returns a boolean', () => {
      const func = plugin.hasTildeInString();
      expect(func).to.be.a('boolean');
    });

    it('check if a "~/" is at the beginning of the string', () => {
      const withoutTilde = plugin.hasTildeInString('some/path');
      const withTilde = plugin.hasTildeInString('~/some/path');
      expect(withoutTilde).to.be.false;
      expect(withTilde).to.be.true;
    });

    it('returns false if no string is passed', () => {
      const nothingPassed = plugin.hasTildeInString();
      const wrongTypePassed = plugin.hasTildeInString([]);
      expect(nothingPassed).to.be.false;
      expect(wrongTypePassed).to.be.false;
    });
  });
});
<|endoftext|>


<commit_before>/*globals it,describe,before,after*/
var path = require('path'),
    utils = require('./res/utils'),
    srcUtils = require('../src/utils'),
    assert = require('assert'),
    nop = require('nop'),
    fse = require('fs-extra'),
    exists = require('exists-file'),
    Logger = require('../src/Logger'),
    PluginManager = require(__dirname+'/../src/PluginManager'),
    rm_rf = require('rimraf'),
    _ = require('lodash');

var logger = new Logger(),
    manager = new PluginManager(logger),
    emitter = logger._emitter;

// Useful constants
var TMP_DIR = path.join(__dirname, '..', 'test-tmp'),
    WebGMEConfig = path.join('config', 'config.webgme.js'),
    PROJECT_DIR = path.join(TMP_DIR, 'ExamplePluginProject'),
    CONFIG_NAME = 'webgme-setup.json',
    CONFIG_PATH = path.join(PROJECT_DIR, CONFIG_NAME),
    OTHER_PROJECT = path.join(__dirname, 'res', 'OtherProject'),
    OTHER_PLUGIN = 'OtherPlugin',
    otherProject;

describe('Plugin tests', function() {
    'use strict';

    var PLUGIN_NAME = 'MyNewPlugin',
        PluginBasePath = path.join(PROJECT_DIR, 'src', 'plugins'),
        PLUGIN_SRC = path.join(PluginBasePath, PLUGIN_NAME, PLUGIN_NAME+'.js'),
        PLUGIN_TEST = path.join(PROJECT_DIR, 'test', 'plugins', PLUGIN_NAME, PLUGIN_NAME+'.spec.js');

    before(function(done) {
        utils.getCleanProject(PROJECT_DIR, done);
    });

    describe('new plugin', function() {
        before(function(done) {
            process.chdir(PROJECT_DIR);  // Start in different directory
            manager.new({pluginID: PLUGIN_NAME, meta: true}, done);
        });

        it('should not contain meta option', function() {
            manager._getOptions()
                .map(function(option) {
                    return option.name.substring(2);
                })
                .forEach(function(name) {
                    assert.equal(name.indexOf('meta'), -1);
                });
        });

        it('should create the plugin source file', function() {
            assert(fse.existsSync(PLUGIN_SRC));
        });

        it('should be valid js', function() {
            var content = fse.readFileSync(PLUGIN_SRC, 'utf8');
            assert(utils.isValidJs(content));
        });

        it('should not have desc (if none provided)', function() {
            var content = fse.readFileSync(PLUGIN_SRC, 'utf8');
            assert.equal(content.indexOf('getDescription'), -1);
        });

        it('should set pluginName to pluginId by default', function() {
            var content = fse.readFileSync(PLUGIN_SRC, 'utf8');
            assert.equal(content.indexOf('New Plugin'), -1);
        });

        it('should create the plugin\'s test file', function() {
            assert(fse.existsSync(PLUGIN_TEST));
        });

        it('should not create the plugin\'s meta file', function() {
            var metaPath = path.join(PluginBasePath, PLUGIN_NAME, 'meta.js');
            assert(!fse.existsSync(metaPath));
        });

        it('should add the plugin path to the config file', function() {
            var config = require(path.join(PROJECT_DIR, WebGMEConfig)),
                foundPath = utils.hasBasePath(config.plugin.basePaths, PluginBasePath);

            assert(foundPath);
        });

        it('should record the plugin in webgme-setup.json', function() {
            var config = require(CONFIG_PATH);
            assert.notEqual(config.components.plugins[PLUGIN_NAME], undefined);
        });

        describe('2nd plugin', function() {
            var secondPluginName = 'ABrandNewPlugin';
            before(function(done) {
                process.chdir(PROJECT_DIR);  // Start in different directory
                manager.new({
                    pluginID: secondPluginName,
                    templateType: 'Python'
                }, done);
            });

            it('should have both dirs in src/plugins', function() {
                [PLUGIN_NAME, secondPluginName]
                    .map(function(name) {
                        return path.join(PROJECT_DIR, 'src', 'plugins', name);
                    })
                    .forEach(function(pluginPath) {
                        assert(fse.existsSync(pluginPath));
                    });
            });

            it('should run "combine_templates"', function() {
                var templates;
                templates = path.join(
                    PROJECT_DIR,
                    'src',
                    'plugins',
                    secondPluginName,
                    'Templates',
                    'Templates.js'
                );
                assert(fse.existsSync(templates));
            });
        });

        describe('options', function() {
            var pyPlugin = 'PythonPlugin';
            before(function(done) {
                process.chdir(PROJECT_DIR);  // Start in different directory
                manager.new({
                    pluginID: pyPlugin,
                    language: 'Python'
                }, done);
            });

            it('should generate python entry point', function() {
                var runPluginPath = path.join(PROJECT_DIR, 'src', 'plugins', pyPlugin, 'run_plugin.py');

                assert(exists(runPluginPath), 'No python entry point!');
            });

            it('should update the package.json with webgme-bindings dependency', function() {
                var packageJSON = srcUtils.getPackageJSON(PROJECT_DIR);

                assert(typeof packageJSON.dependencies['webgme-bindings'] === 'string', 'Did not update package.json');
            });

            it('new python should not overwrite modified webgme-bindings version', function (done) {
                var packageJSON = srcUtils.getPackageJSON(PROJECT_DIR);
                packageJSON.dependencies['webgme-bindings'] = '^1.0.1';
                srcUtils.writePackageJSON(packageJSON, PROJECT_DIR);
                manager.new({
                    pluginID: 'anOtherPython',
                    language: 'Python'
                }, function (err) {
                    try {
                        assert(!err, err && err.message);
                        const newPackageJSON = srcUtils.getPackageJSON(PROJECT_DIR);
                        assert(packageJSON.dependencies['webgme-bindings'] === '^1.0.1',
                            'version overridden in package: ' + packageJSON.dependencies['webgme-bindings']);
                        done();
                    } catch (e) {
                        done(e);
                    }
                });
            });
        });

        describe('test file', function() {
            var PLUGIN_TEST = path.join(PROJECT_DIR, 'test', 'plugins',
                PLUGIN_NAME, PLUGIN_NAME+'.spec.js');

            it('should create test file in test/plugin', function() {
                assert(fse.existsSync(PLUGIN_TEST));
            });

            it('should have correct path for test fixtures', function() {
                var testContent = fse.readFileSync(PLUGIN_TEST, 'utf8'),
                    fixtureRegex = /require\('(.*)'\)/,
                    result = fixtureRegex.exec(testContent);
                assert(result[1] === '../../globals');
            });
        });

        describe('list plugins', function() {
            it('should list the new plugin', function(done) {
                manager.ls({}, function(err, plugins) {
                    assert.notEqual(-1, plugins.components.indexOf(PLUGIN_NAME));
                    done();
                });
            });

            it('should not list plugins in wrong directory ', function(done) {
                process.chdir(__dirname);
                manager.ls({}, function(err) {
                    assert(err);
                    process.chdir(PROJECT_DIR);
                    done();
                });
            });
        });
    });

    describe('rm plugin', function() {
        var PLUGIN_NAME = 'RemoveMe';
        before(function(done) {
            process.chdir(PROJECT_DIR);
            manager.rm({name: 'MyPlugin'}, done);
        });

        it('should remove plugin src directory', function() {
            var pluginPath = path.join(PROJECT_DIR, 'src', 'plugins', PLUGIN_NAME);
            assert.equal(fse.existsSync(pluginPath), false);
        });

        it('should remove plugin test directory', function() {
            var pluginPath = path.join(PROJECT_DIR, 'test', 'plugins', PLUGIN_NAME);
            assert.equal(fse.existsSync(pluginPath), false);
        });

        it('should remove plugin entry from '+CONFIG_NAME, function() {
            var config = require(CONFIG_PATH);
            assert.equal(config.components.plugins[PLUGIN_NAME], undefined);
        });
    });

    describe('import plugin', function() {

        describe('errors', function() {
            it('should not miss plugin or project', function(done) {
                emitter.once('error', done.bind(this, null));
                manager.import({name: OTHER_PLUGIN}, nop);
            });
        });

        describe('projects NOT created with webgme-setup-tool', function() {
            var previousDir, oldConfigPath;
            otherProject = path.join(__dirname+'res', 'NonCliProj');
            before(function(done) {
                this.timeout(10000);
                oldConfigPath = CONFIG_PATH;
                previousDir = PROJECT_DIR;
                PROJECT_DIR = path.join(PROJECT_DIR, 'NewProject');
                CONFIG_PATH = path.join(PROJECT_DIR, CONFIG_NAME),
                utils.getCleanProject(PROJECT_DIR, function() {
                    process.chdir(PROJECT_DIR);
                    manager.import({name: OTHER_PLUGIN,
                                 project: otherProject}, done);
                });
            });

            after(function() {
                PROJECT_DIR = previousDir;
                CONFIG_PATH = oldConfigPath;
            });

            it('should add the project to the package.json', function() {
                var pkg = require(path.join(PROJECT_DIR, 'package.json')),
                depName = otherProject.split(path.sep).pop().toLowerCase();
                assert.notEqual(pkg.dependencies[depName], undefined);
            });

            it('should add the project to the '+CONFIG_NAME, function() {
                var configText = fse.readFileSync(CONFIG_PATH),
                    config = JSON.parse(configText);
                assert.notEqual(config.dependencies.plugins[OTHER_PLUGIN], undefined);
            });

            it('should add the path to the webgme config', function() {
                var config = require(path.join(PROJECT_DIR, WebGMEConfig)),
                paths = config.plugin.basePaths.join(';');
                assert.notEqual(paths.indexOf(otherProject.split(path.sep)[1]), -1);
            });

            it('should add the relative path to the requirejsPaths webgme config', function() {
                var config = require(path.join(PROJECT_DIR, WebGMEConfig));

                assert.notEqual(config.requirejsPaths[OTHER_PLUGIN], undefined);
                assert.notEqual(config.requirejsPaths[OTHER_PLUGIN][0], '/');
            });

            describe('rm dependency plugin', function() {
                before(function(done) {
                    process.chdir(PROJECT_DIR);
                    manager.rm({name: OTHER_PLUGIN}, done);
                });

                it('should remove the path from the webgme config', function() {
                    var config = require(path.join(PROJECT_DIR, WebGMEConfig)),
                    paths = config.plugin.basePaths.join(';');
                    assert.equal(paths.indexOf(OTHER_PLUGIN), -1);
                });

                it('should remove plugin entry from '+CONFIG_NAME, function() {
                    var configText = fse.readFileSync(CONFIG_PATH),
                        config = JSON.parse(configText);
                    assert.equal(config.dependencies.plugins[OTHER_PLUGIN], undefined);
                });

                it.skip('should remove project from package.json', function() {
                    // TODO
                });

                it.skip('should not remove project from package.json if used', function() {
                    // TODO
                });
            });
        });

        describe('projects created with webgme-setup-tool', function() {
            otherProject = path.join(__dirname, 'res', 'OtherProject');
            before(function(done) {
                this.timeout(5000);
                process.chdir(PROJECT_DIR);
                manager.import({name: OTHER_PLUGIN,
                             project: otherProject}, function() {
                    utils.requireReload(
                        path.join(PROJECT_DIR, 'package.json')
                    );
                    done();
                });
            });

            it('should add the project to the package.json', function() {
                var pkg = require(path.join(PROJECT_DIR, 'package.json')),
                depName = otherProject.split(path.sep).pop().toLowerCase();
                assert.notEqual(pkg.dependencies[depName], undefined);
            });

            it('should add the project to the '+CONFIG_NAME, function() {
                var configText = fse.readFileSync(CONFIG_PATH),
                    config = JSON.parse(configText);
                assert.notEqual(config.dependencies.plugins[OTHER_PLUGIN], undefined);
            });

            it('should add the path to the webgme config', function() {
                var config = require(path.join(PROJECT_DIR, WebGMEConfig)),
                paths = config.plugin.basePaths.join(';');
                assert.notEqual(paths.indexOf(otherProject.split(path.sep)[1]), -1);
            });

            it('should add the project common requirejs path', function() {
                const config = require(path.join(PROJECT_DIR, WebGMEConfig));
                const otherAppName = path.basename(otherProject).toLowerCase();
                assert(config.requirejsPaths[otherAppName])
            });

            describe('rm dependency plugin', function() {
                before(function(done) {
                    process.chdir(PROJECT_DIR);
                    manager.rm({name: OTHER_PLUGIN}, done);
                });

                it('should remove the path from the webgme config', function() {
                    var config = require(path.join(PROJECT_DIR, WebGMEConfig)),
                    paths = config.plugin.basePaths.join(';');
                    assert.equal(paths.indexOf(OTHER_PLUGIN), -1);
                });

                it('should remove plugin entry from '+CONFIG_NAME, function() {
                    var configText = fse.readFileSync(CONFIG_PATH),
                        config = JSON.parse(configText);
                    assert.equal(config.dependencies.plugins[OTHER_PLUGIN], undefined);
                });

                it.skip('should remove project from package.json', function() {
                    // TODO
                });

                it.skip('should not remove project from package.json if used', function() {
                    // TODO
                });
            });
        });
    });

    // after(function(done) {
    //     if (fse.existsSync(PROJECT_DIR)) {
    //         rm_rf(PROJECT_DIR, done);
    //     } else {
    //         done();
    //     }
    // });
});
<commit_msg>WIP Remove outdated test<commit_after>/*globals it,describe,before,after*/
var path = require('path'),
    utils = require('./res/utils'),
    srcUtils = require('../src/utils'),
    assert = require('assert'),
    nop = require('nop'),
    fse = require('fs-extra'),
    exists = require('exists-file'),
    Logger = require('../src/Logger'),
    PluginManager = require(__dirname+'/../src/PluginManager'),
    rm_rf = require('rimraf'),
    _ = require('lodash');

var logger = new Logger(),
    manager = new PluginManager(logger),
    emitter = logger._emitter;

// Useful constants
var TMP_DIR = path.join(__dirname, '..', 'test-tmp'),
    WebGMEConfig = path.join('config', 'config.webgme.js'),
    PROJECT_DIR = path.join(TMP_DIR, 'ExamplePluginProject'),
    CONFIG_NAME = 'webgme-setup.json',
    CONFIG_PATH = path.join(PROJECT_DIR, CONFIG_NAME),
    OTHER_PROJECT = path.join(__dirname, 'res', 'OtherProject'),
    OTHER_PLUGIN = 'OtherPlugin',
    otherProject;

describe('Plugin tests', function() {
    'use strict';

    var PLUGIN_NAME = 'MyNewPlugin',
        PluginBasePath = path.join(PROJECT_DIR, 'src', 'plugins'),
        PLUGIN_SRC = path.join(PluginBasePath, PLUGIN_NAME, PLUGIN_NAME+'.js'),
        PLUGIN_TEST = path.join(PROJECT_DIR, 'test', 'plugins', PLUGIN_NAME, PLUGIN_NAME+'.spec.js');

    before(function(done) {
        utils.getCleanProject(PROJECT_DIR, done);
    });

    describe('new plugin', function() {
        before(function(done) {
            process.chdir(PROJECT_DIR);  // Start in different directory
            manager.new({pluginID: PLUGIN_NAME, meta: true}, done);
        });

        it('should not contain meta option', function() {
            manager._getOptions()
                .map(function(option) {
                    return option.name.substring(2);
                })
                .forEach(function(name) {
                    assert.equal(name.indexOf('meta'), -1);
                });
        });

        it('should create the plugin source file', function() {
            assert(fse.existsSync(PLUGIN_SRC));
        });

        it('should be valid js', function() {
            var content = fse.readFileSync(PLUGIN_SRC, 'utf8');
            assert(utils.isValidJs(content));
        });

        it('should not have desc (if none provided)', function() {
            var content = fse.readFileSync(PLUGIN_SRC, 'utf8');
            assert.equal(content.indexOf('getDescription'), -1);
        });

        it('should set pluginName to pluginId by default', function() {
            var content = fse.readFileSync(PLUGIN_SRC, 'utf8');
            assert.equal(content.indexOf('New Plugin'), -1);
        });

        it('should create the plugin\'s test file', function() {
            assert(fse.existsSync(PLUGIN_TEST));
        });

        it('should not create the plugin\'s meta file', function() {
            var metaPath = path.join(PluginBasePath, PLUGIN_NAME, 'meta.js');
            assert(!fse.existsSync(metaPath));
        });

        it('should add the plugin path to the config file', function() {
            var config = require(path.join(PROJECT_DIR, WebGMEConfig)),
                foundPath = utils.hasBasePath(config.plugin.basePaths, PluginBasePath);

            assert(foundPath);
        });

        it('should record the plugin in webgme-setup.json', function() {
            var config = require(CONFIG_PATH);
            assert.notEqual(config.components.plugins[PLUGIN_NAME], undefined);
        });

        describe('2nd plugin', function() {
            var secondPluginName = 'ABrandNewPlugin';
            before(function(done) {
                process.chdir(PROJECT_DIR);  // Start in different directory
                manager.new({
                    pluginID: secondPluginName
                }, done);
            });

            it('should have both dirs in src/plugins', function() {
                [PLUGIN_NAME, secondPluginName]
                    .map(function(name) {
                        return path.join(PROJECT_DIR, 'src', 'plugins', name);
                    })
                    .forEach(function(pluginPath) {
                        assert(fse.existsSync(pluginPath));
                    });
            });
        });

        describe('options', function() {
            var pyPlugin = 'PythonPlugin';
            before(function(done) {
                process.chdir(PROJECT_DIR);  // Start in different directory
                manager.new({
                    pluginID: pyPlugin,
                    language: 'Python'
                }, done);
            });

            it('should generate python entry point', function() {
                var runPluginPath = path.join(PROJECT_DIR, 'src', 'plugins', pyPlugin, 'run_plugin.py');

                assert(exists(runPluginPath), 'No python entry point!');
            });

            it('should update the package.json with webgme-bindings dependency', function() {
                var packageJSON = srcUtils.getPackageJSON(PROJECT_DIR);

                assert(typeof packageJSON.dependencies['webgme-bindings'] === 'string', 'Did not update package.json');
            });

            it('new python should not overwrite modified webgme-bindings version', function (done) {
                var packageJSON = srcUtils.getPackageJSON(PROJECT_DIR);
                packageJSON.dependencies['webgme-bindings'] = '^1.0.1';
                srcUtils.writePackageJSON(packageJSON, PROJECT_DIR);
                manager.new({
                    pluginID: 'anOtherPython',
                    language: 'Python'
                }, function (err) {
                    try {
                        assert(!err, err && err.message);
                        const newPackageJSON = srcUtils.getPackageJSON(PROJECT_DIR);
                        assert(packageJSON.dependencies['webgme-bindings'] === '^1.0.1',
                            'version overridden in package: ' + packageJSON.dependencies['webgme-bindings']);
                        done();
                    } catch (e) {
                        done(e);
                    }
                });
            });
        });

        describe('test file', function() {
            var PLUGIN_TEST = path.join(PROJECT_DIR, 'test', 'plugins',
                PLUGIN_NAME, PLUGIN_NAME+'.spec.js');

            it('should create test file in test/plugin', function() {
                assert(fse.existsSync(PLUGIN_TEST));
            });

            it('should have correct path for test fixtures', function() {
                var testContent = fse.readFileSync(PLUGIN_TEST, 'utf8'),
                    fixtureRegex = /require\('(.*)'\)/,
                    result = fixtureRegex.exec(testContent);
                assert(result[1] === '../../globals');
            });
        });

        describe('list plugins', function() {
            it('should list the new plugin', function(done) {
                manager.ls({}, function(err, plugins) {
                    assert.notEqual(-1, plugins.components.indexOf(PLUGIN_NAME));
                    done();
                });
            });

            it('should not list plugins in wrong directory ', function(done) {
                process.chdir(__dirname);
                manager.ls({}, function(err) {
                    assert(err);
                    process.chdir(PROJECT_DIR);
                    done();
                });
            });
        });
    });

    describe('rm plugin', function() {
        var PLUGIN_NAME = 'RemoveMe';
        before(function(done) {
            process.chdir(PROJECT_DIR);
            manager.rm({name: 'MyPlugin'}, done);
        });

        it('should remove plugin src directory', function() {
            var pluginPath = path.join(PROJECT_DIR, 'src', 'plugins', PLUGIN_NAME);
            assert.equal(fse.existsSync(pluginPath), false);
        });

        it('should remove plugin test directory', function() {
            var pluginPath = path.join(PROJECT_DIR, 'test', 'plugins', PLUGIN_NAME);
            assert.equal(fse.existsSync(pluginPath), false);
        });

        it('should remove plugin entry from '+CONFIG_NAME, function() {
            var config = require(CONFIG_PATH);
            assert.equal(config.components.plugins[PLUGIN_NAME], undefined);
        });
    });

    describe('import plugin', function() {

        describe('errors', function() {
            it('should not miss plugin or project', function(done) {
                emitter.once('error', done.bind(this, null));
                manager.import({name: OTHER_PLUGIN}, nop);
            });
        });

        describe('projects NOT created with webgme-setup-tool', function() {
            var previousDir, oldConfigPath;
            otherProject = path.join(__dirname+'res', 'NonCliProj');
            before(function(done) {
                this.timeout(10000);
                oldConfigPath = CONFIG_PATH;
                previousDir = PROJECT_DIR;
                PROJECT_DIR = path.join(PROJECT_DIR, 'NewProject');
                CONFIG_PATH = path.join(PROJECT_DIR, CONFIG_NAME),
                utils.getCleanProject(PROJECT_DIR, function() {
                    process.chdir(PROJECT_DIR);
                    manager.import({name: OTHER_PLUGIN,
                                 project: otherProject}, done);
                });
            });

            after(function() {
                PROJECT_DIR = previousDir;
                CONFIG_PATH = oldConfigPath;
            });

            it('should add the project to the package.json', function() {
                var pkg = require(path.join(PROJECT_DIR, 'package.json')),
                depName = otherProject.split(path.sep).pop().toLowerCase();
                assert.notEqual(pkg.dependencies[depName], undefined);
            });

            it('should add the project to the '+CONFIG_NAME, function() {
                var configText = fse.readFileSync(CONFIG_PATH),
                    config = JSON.parse(configText);
                assert.notEqual(config.dependencies.plugins[OTHER_PLUGIN], undefined);
            });

            it('should add the path to the webgme config', function() {
                var config = require(path.join(PROJECT_DIR, WebGMEConfig)),
                paths = config.plugin.basePaths.join(';');
                assert.notEqual(paths.indexOf(otherProject.split(path.sep)[1]), -1);
            });

            it('should add the relative path to the requirejsPaths webgme config', function() {
                var config = require(path.join(PROJECT_DIR, WebGMEConfig));

                assert.notEqual(config.requirejsPaths[OTHER_PLUGIN], undefined);
                assert.notEqual(config.requirejsPaths[OTHER_PLUGIN][0], '/');
            });

            describe('rm dependency plugin', function() {
                before(function(done) {
                    process.chdir(PROJECT_DIR);
                    manager.rm({name: OTHER_PLUGIN}, done);
                });

                it('should remove the path from the webgme config', function() {
                    var config = require(path.join(PROJECT_DIR, WebGMEConfig)),
                    paths = config.plugin.basePaths.join(';');
                    assert.equal(paths.indexOf(OTHER_PLUGIN), -1);
                });

                it('should remove plugin entry from '+CONFIG_NAME, function() {
                    var configText = fse.readFileSync(CONFIG_PATH),
                        config = JSON.parse(configText);
                    assert.equal(config.dependencies.plugins[OTHER_PLUGIN], undefined);
                });

                it.skip('should remove project from package.json', function() {
                    // TODO
                });

                it.skip('should not remove project from package.json if used', function() {
                    // TODO
                });
            });
        });

        describe('projects created with webgme-setup-tool', function() {
            otherProject = path.join(__dirname, 'res', 'OtherProject');
            before(function(done) {
                this.timeout(5000);
                process.chdir(PROJECT_DIR);
                manager.import({name: OTHER_PLUGIN,
                             project: otherProject}, function() {
                    utils.requireReload(
                        path.join(PROJECT_DIR, 'package.json')
                    );
                    done();
                });
            });

            it('should add the project to the package.json', function() {
                var pkg = require(path.join(PROJECT_DIR, 'package.json')),
                depName = otherProject.split(path.sep).pop().toLowerCase();
                assert.notEqual(pkg.dependencies[depName], undefined);
            });

            it('should add the project to the '+CONFIG_NAME, function() {
                var configText = fse.readFileSync(CONFIG_PATH),
                    config = JSON.parse(configText);
                assert.notEqual(config.dependencies.plugins[OTHER_PLUGIN], undefined);
            });

            it('should add the path to the webgme config', function() {
                var config = require(path.join(PROJECT_DIR, WebGMEConfig)),
                paths = config.plugin.basePaths.join(';');
                assert.notEqual(paths.indexOf(otherProject.split(path.sep)[1]), -1);
            });

            it('should add the project common requirejs path', function() {
                const config = require(path.join(PROJECT_DIR, WebGMEConfig));
                const otherAppName = path.basename(otherProject).toLowerCase();
                assert(config.requirejsPaths[otherAppName])
            });

            describe('rm dependency plugin', function() {
                before(function(done) {
                    process.chdir(PROJECT_DIR);
                    manager.rm({name: OTHER_PLUGIN}, done);
                });

                it('should remove the path from the webgme config', function() {
                    var config = require(path.join(PROJECT_DIR, WebGMEConfig)),
                    paths = config.plugin.basePaths.join(';');
                    assert.equal(paths.indexOf(OTHER_PLUGIN), -1);
                });

                it('should remove plugin entry from '+CONFIG_NAME, function() {
                    var configText = fse.readFileSync(CONFIG_PATH),
                        config = JSON.parse(configText);
                    assert.equal(config.dependencies.plugins[OTHER_PLUGIN], undefined);
                });

                it.skip('should remove project from package.json', function() {
                    // TODO
                });

                it.skip('should not remove project from package.json if used', function() {
                    // TODO
                });
            });
        });
    });

    after(function(done) {
        if (fse.existsSync(PROJECT_DIR)) {
            rm_rf(PROJECT_DIR, done);
        } else {
            done();
        }
    });
});
<|endoftext|>


<commit_before>require('chai').should();
var expect = require('chai').expect;

var Plugin = require('../lib/plugin');
var HOOKS = require('../lib/hooks');
var configureLoaderPath = require('../lib/configurator/loader').LOADER_PATH;
var InMemoryCompiler = require('../lib/modules/MemoryCompiler');
var mergeConfig = require('webpack-config-merger');

function dummyCompiler(config) {
  var defaultConfig = {
    context: '/',

    output: {
      filename: '[name].js',
      path: '/build'
    }
  };

  var compiler = new InMemoryCompiler(
    mergeConfig(defaultConfig, config || {}),
    true,
    true
  );

  return compiler;
}

describe('Plugin', function () {

  describe('static props', function () {
    Plugin.should.have.property('HOOKS').and.be.a('object').and.eql(HOOKS);
  });

  describe('::extract()', function () {

    it('should exists', function () {
      Plugin.extract.should.exist.and.be.a('function');
    });

    it('should return path to configure loader', function () {
      Plugin.extract().should.contain(configureLoaderPath);
    });

    it('should return path with query params when options are presented', function () {
      var params = {qwe: 123};
      Plugin.extract({qwe: 123}).should.contain(JSON.stringify(params));
    });

  });

  describe('constructor', function () {

    it('should set initial config', function () {
      var plugin = new Plugin();
      plugin.should.have.property('config').and.be.a('object');
      plugin.config.should.have.property('loaders').and.be.a('array');
      plugin.should.have.property('extractors').and.be.a('object');
    });

  });

  describe('getConfig()', function () {

    it('should exist', function () {
      new Plugin().getConfig.should.exist;
    });

    it('should return initial config if no argument specified', function () {
      var plugin = new Plugin();
      plugin.getConfig().should.eql(plugin.config.initial);
    });

    describe('when plugin instantiated', function () {
      var plugin;
      var compiler;

      beforeEach(function () {
        plugin = new Plugin();
        compiler = dummyCompiler({
          module: {
            loaders: [
              {test: /\.qwe$/, loader: Plugin.extract({foo: 'bar'})}
            ]
          },
          plugins: [plugin]
        });
      });

      it('should return config provided in loaders', function (done) {
        compiler.run().then(function () {
          var config = plugin.getConfig('/tralala/test.qwe');
          config.should.have.property('foo');
          config.foo.should.be.eql('bar');
          done();
        });
      });

      it('should return initial config value if no param specified via loaders found', function (done) {
        compiler.run().then(function () {
          var config = plugin.getConfig('/tralala');
          config.should.be.eql(plugin.config.initial);
          done();
        });
      });

    });

  });

  describe('registerExtractor()', function () {

    it('should throw when extractor already registered', function (done) {
      var fakeExtractor = {
        getName: function () { return 'tralala' },
        extract: function () {},
        apply: function (compiler) {
          var extractor = this;

          compiler.plugin(HOOKS.CONFIGURE, function (plugin) {
            plugin.registerExtractor(extractor);
          })
        }
      };

      var plugin = new Plugin({ plugins: [fakeExtractor] });

      dummyCompiler({plugins: [plugin]}).run().then(function () {
        expect(function() {
          plugin.registerExtractor({
            getName: function() { return 'tralala' },
            extract: function() {}
          });

        }).to.throws(Error);

        done();
      })
    });

  });

});<commit_msg>Add few tests plugin tests<commit_after>var chai = require('chai');
var expect = chai.expect;
chai.should();

var Plugin = require('../lib/plugin');
var HOOKS = require('../lib/hooks');
var configureLoaderPath = require('../lib/configurator/loader').LOADER_PATH;
var InMemoryCompiler = require('../lib/modules/MemoryCompiler');
var mergeConfig = require('webpack-config-merger');
var Source = require('../lib/data/Source');

function inMemoryCompiler(config) {
  var defaultConfig = {
    context: '/',

    output: {
      filename: '[name].js',
      path: '/build'
    }
  };

  var compiler = new InMemoryCompiler(
    mergeConfig(defaultConfig, config || {}),
    true,
    true
  );

  return compiler;
}

describe('Plugin', function () {

  describe('static props', function () {
    Plugin.should.have.property('HOOKS').and.be.a('object').and.eql(HOOKS);
  });

  describe('::extract()', function () {

    it('should exist', function () {
      Plugin.extract.should.exist.and.be.a('function');
    });

    it('should return path to configure loader', function () {
      Plugin.extract().should.contain(configureLoaderPath);
    });

    it('should return path with query params when options are presented', function () {
      var params = {qwe: 123};
      Plugin.extract({qwe: 123}).should.contain(JSON.stringify(params));
    });

  });

  describe('constructor', function () {

    it('should set initial config', function () {
      var plugin = new Plugin();
      plugin.should.have.property('config').and.be.an('object');
      plugin.should.have.property('extractors').and.be.an('object');
      plugin.config.should.have.property('loaders').and.be.an('array');
    });

  });

  describe('getConfig()', function () {

    it('should exist', function () {
      new Plugin().getConfig.should.exist;
    });

    it('should return initial config if no argument specified', function () {
      var plugin = new Plugin();
      plugin.getConfig().should.eql(plugin.config.initial);
    });

    describe('when plugin instantiated', function () {
      var plugin;
      var compiler;

      beforeEach(function () {
        plugin = new Plugin();
        compiler = inMemoryCompiler({
          module: {
            loaders: [
              {test: /\.qwe$/, loader: Plugin.extract({foo: 'bar'})}
            ]
          },
          plugins: [plugin]
        });
      });

      it('should return config provided in loaders', function (done) {
        compiler.run().then(function () {
          var config = plugin.getConfig('/tralala/test.qwe');
          config.should.have.property('foo');
          config.foo.should.be.eql('bar');
          done();
        });
      });

      it('should return initial config value if no param specified via loaders found', function (done) {
        compiler.run().then(function () {
          var config = plugin.getConfig('/tralala');
          config.should.be.eql(plugin.config.initial);
          done();
        });
      });

    });

  });

  describe('registerExtractor()', function () {

    it('should throw if invalid extractor structure provided', function() {
      var extractor = {
        apply: function (compiler) {
          var extractor = this;

          compiler.plugin(HOOKS.CONFIGURE, function (plugin) {
            plugin.registerExtractor(extractor);
          })
        }
      };

      expect(function() {
        inMemoryCompiler({plugins: [ new Plugin(), extractor ]})
      }).to.throw();
    });

    it('should register extractor and throw when it already registered', function (done) {
      var extractorName = 'tralala';
      var extractor = {
        getName: function () { return extractorName },
        extract: function () {},
        apply: function (compiler) {
          var extractor = this;

          compiler.plugin(HOOKS.CONFIGURE, function (plugin) {
            plugin.registerExtractor(extractor);
          })
        }
      };

      var plugin = new Plugin();

      inMemoryCompiler({plugins: [plugin, extractor]}).run().then(function () {
        plugin.extractors.should.have.property(extractorName).and.be.eql(extractor);

        expect(function() {
          plugin.registerExtractor({
            getName: function() { return 'tralala' },
            extract: function() {}
          });

        }).to.throw();

        done();
      });

    });

  });

  describe('save()', function () {

    it('should save source', function() {
      var source = new Source({path: '/qwe', absolutePath: '/qwe', content: 'qwe'});
      var plugin = new Plugin();

      plugin.save(source);
      plugin.sources.should.include(source).and.to.have.lengthOf(1);

      plugin.save(source);
      plugin.sources.should.include(source).and.to.have.lengthOf(1);
    })

  });

  describe('readFile()', function () {

    it('should use the same filesystem as compiler', function() {
      var file = {
        path: '/test.txt',
        content: 'qwe'
      };

      var plugin = new Plugin();
      var compiler = inMemoryCompiler({plugins: [plugin]});

      compiler.inputFileSystem.writeFileSync(file.path, file.content, 'utf-8');
      plugin.readFile(file.path).then(function(content) {
        content.toString().should.eql(file.content);
      });
    })

  });

});<|endoftext|>


<commit_before>'use strict';

const HapiAutoRoute = require('../index.js');
const Hapi = require('hapi');

const { expect } = require('code');
const lab = exports.lab = require('lab').script();

lab.experiment('plugin', () => {

    lab.it('pluging.pkg should set with package.json', () => {

        const plugin = HapiAutoRoute.plugin;
        expect(plugin).to.not.undefined();
        expect(plugin.pkg).to.not.undefined();
        expect(plugin.pkg).include(['name', 'version', 'description']);
    });

    lab.it('Should have register function', () => {

        const plugin = HapiAutoRoute.plugin;
        expect(plugin.register).to.not.undefined();
        expect(plugin.register).to.be.function();
    });

    lab.it('Register route to the server', async () => {

        const server = Hapi.Server({ port: 3000 });
        await server.register({
            plugin: HapiAutoRoute,
            options: {
                routes_dir: 'test/fixtures/routes',
                pattern: '**/!(_)*.js'
            }
        });
        const result = await server.inject('/');
        expect(result.statusCode).to.be.equal(200);
    });

    lab.it('Apply default options', async () => {

        const server = Hapi.Server({ port: 3000 });
        await server.register({
            plugin: HapiAutoRoute,
            options: {
                routes_dir: 'test/fixtures/routes'
            }
        });
        const result = await server.inject('/');
        expect(result.statusCode).to.be.equal(200);
    });

    lab.it('Change route path if use_prefix is true', async () => {

        const server = Hapi.Server({ port: 3000 });
        await server.register({
            plugin: HapiAutoRoute,
            options: {
                routes_dir: 'test/fixtures/routes',
                use_prefix: true
            }
        });
        const result = await server.inject('/auth/login');
        expect(result.statusCode).to.be.equal(200);
    });
});
<commit_msg>Refactor tests<commit_after>'use strict';

const HapiAutoRoute = require('../index.js');
const Hapi = require('hapi');

const { expect } = require('code');
const lab = exports.lab = require('lab').script();

lab.experiment('plugin', () => {

    let server = null;
    let plugin = null;
    let hapiAutoRouteOptions = null;

    lab.beforeEach(() => {

        server = Hapi.Server({ port: 3000 });
        plugin = HapiAutoRoute.plugin;
        hapiAutoRouteOptions = {
            routes_dir: 'test/fixtures/routes',
            pattern: '**/*.js',
            use_prefix: true
        };
    });

    lab.afterEach(() => {

        server = null;
    });

    lab.it('pluging.pkg should set with package.json', () => {

        expect(plugin).to.not.undefined();
        expect(plugin.pkg).to.not.undefined();
        expect(plugin.pkg).include(['name', 'version', 'description']);
    });

    lab.it('Should have register function', () => {

        expect(plugin.register).to.not.undefined();
        expect(plugin.register).to.be.function();
    });

    lab.it('Register route to the server', async () => {

        hapiAutoRouteOptions.use_prefix = false;
        await server.register({
            plugin: HapiAutoRoute,
            options: hapiAutoRouteOptions
        });
        const result = await server.inject('/');
        expect(result.statusCode).to.be.equal(200);
    });

    lab.it('Apply default options', async () => {

        delete hapiAutoRouteOptions.use_prefix;
        delete hapiAutoRouteOptions.pattern;
        await server.register({
            plugin: HapiAutoRoute,
            options: hapiAutoRouteOptions
        });
        const result = await server.inject('/');
        expect(result.statusCode).to.be.equal(200);
    });

    lab.it('Change route path if use_prefix is true', async () => {

        await server.register({
            plugin: HapiAutoRoute,
            options: hapiAutoRouteOptions
        });
        const result = await server.inject('/auth/login');
        expect(result.statusCode).to.be.equal(200);
    });
});
<|endoftext|>


<commit_before>amqp = require('amqp');
nconf = require('nconf');
nconf.env().file({
    "file": "./config/epp-config.json"
});
var uuid = require('node-uuid');
var rabbitmqConfig = nconf.get('rabbitmq');
var chai = require('chai');
var expect = chai.expect,
should = chai.should;

describe('RabbitMQ operation', function() {
    var amqpConnection, exchange;
    before(function(done) {
        amqpConnection = amqp.createConnection(rabbitmqConfig.connection);
        amqpConnection.on('ready', function() {
            exchange = amqpConnection.exchange('eppTest');
            exchange.on('open', function() {
                done();
            });
        });
    });
    describe('test one-way queues',function() {
        var eppQueue, backendQueue;
        before(function(done) {
            eppQueue = amqpConnection.queue('eppQueue', function(queue) {
                eppQueue.bind(exchange, 'test-epp');
                done();
            });
        });
        before(function(done) {
            backendQueue = amqpConnection.queue('eppResponse', function(queue) {
                backendQueue.bind(exchange, 'test-epp2');
                done();
            });
        });
        it('should send multiple commands', function(done) {
            var counter = 1;
            eppQueue.subscribe({
                "ack": true
            },
            function(msg, headers, deliveryInfo, messageObject) {
                try {
                    expect(msg.command).to.equal('checkDomain');
                    if (counter == 1) expect(msg.data).to.have.deep.property('name', 'test-1-domain.com');
                    else expect(msg.data).to.have.deep.property('name', 'test-2-domain.com');

                    messageObject.acknowledge(true);
                    if (counter == 2) {
                        done();
                    }
                    counter = counter + 1;
                } catch(e) {
                    done(e);
                }
            });
            exchange.publish('test-epp', {
                "command": "checkDomain",
                "data": {
                    "name": "test-1-domain.com"
                }
            });
            exchange.publish('test-epp', {
                "command": "checkDomain",
                "data": {
                    "name": "test-2-domain.com"
                }
            });
        });

        it('should pass a message to another consumer', function(done) {
            backendQueue.subscribe({
                "ack": true
            },
            function(msg) {
                try {
                    expect(msg.testResponse).to.equal('successful');
                    done();
                }
                catch(e) {
                    done(e);
                }
            });
            exchange.publish('test-epp2', {
                "testResponse": "successful"
            });
        });
    });
    describe('RPC test', function () {
        var serverQueue, clientQueue;
        before(function(done) {
            serverQueue = amqpConnection.queue('serverQueue',  function (queue) {
                serverQueue.bind(exchange, 'serverQueue');
                done();
            } );
        });
        before(function(done) {
            clientQueue = amqpConnection.queue('clientQueue', {"exclusive": true}, function (queue) {
                clientQueue.bind(exchange, 'clientQueue');
                done();
            } );
        });
        it('should create an rpc queue', function(done) {
            serverQueue.subscribe( function(msg, headers, deliveryInfo, msgObject) {
                expect(msg).to.have.deep.property('data.name', 'test-me.com');
                exchange.publish(deliveryInfo.replyTo, {"response": "successful"}, {"correlationId": deliveryInfo.correlationId});
            });
            var corrId = uuid.v4();
            clientQueue.subscribe(function(msg, headers, deliveryInfo, msgObject) {
                try {
                    if (deliveryInfo.correlationId && deliveryInfo.correlationId == corrId) {
                        expect(msg).to.have.deep.property('response', 'successful');
                        done();
                    }
                } catch (e) {
                    /* handle error */
                    done(e);
                }
            });

            exchange.publish('serverQueue', {
                "command": "infoDomain", "data": {"name": "test-me.com"}
            }, {"replyTo": "clientQueue", "correlationId": corrId } );

        });
    });

    after(function() {
        amqpConnection.disconnect();

    });
});

<commit_msg>whitespace<commit_after>amqp = require('amqp');
nconf = require('nconf');
nconf.env().file({
    "file": "./config/epp-config.json"
});
var uuid = require('node-uuid');
var rabbitmqConfig = nconf.get('rabbitmq');
var chai = require('chai');
var expect = chai.expect,
should = chai.should;

describe('RabbitMQ operation', function() {
    var amqpConnection, exchange;
    before(function(done) {
        amqpConnection = amqp.createConnection(rabbitmqConfig.connection);
        amqpConnection.on('ready', function() {
            exchange = amqpConnection.exchange('eppTest');
            exchange.on('open', function() {
                done();
            });
        });
    });
    describe('test one-way queues', function() {
        var eppQueue, backendQueue;
        before(function(done) {
            eppQueue = amqpConnection.queue('eppQueue', function(queue) {
                eppQueue.bind(exchange, 'test-epp');
                done();
            });
        });
        before(function(done) {
            backendQueue = amqpConnection.queue('eppResponse', function(queue) {
                backendQueue.bind(exchange, 'test-epp2');
                done();
            });
        });
        it('should send multiple commands', function(done) {
            var counter = 1;
            eppQueue.subscribe({
                "ack": true
            },
            function(msg, headers, deliveryInfo, messageObject) {
                try {
                    expect(msg.command).to.equal('checkDomain');
                    if (counter == 1) expect(msg.data).to.have.deep.property('name', 'test-1-domain.com');
                    else expect(msg.data).to.have.deep.property('name', 'test-2-domain.com');

                    messageObject.acknowledge(true);
                    if (counter == 2) {
                        done();
                    }
                    counter = counter + 1;
                } catch(e) {
                    done(e);
                }
            });
            exchange.publish('test-epp', {
                "command": "checkDomain",
                "data": {
                    "name": "test-1-domain.com"
                }
            });
            exchange.publish('test-epp', {
                "command": "checkDomain",
                "data": {
                    "name": "test-2-domain.com"
                }
            });
        });

        it('should pass a message to another consumer', function(done) {
            backendQueue.subscribe({
                "ack": true
            },
            function(msg) {
                try {
                    expect(msg.testResponse).to.equal('successful');
                    done();
                }
                catch(e) {
                    done(e);
                }
            });
            exchange.publish('test-epp2', {
                "testResponse": "successful"
            });
        });
    });
    describe('RPC test', function() {
        var serverQueue, clientQueue;
        before(function(done) {
            serverQueue = amqpConnection.queue('serverQueue', function(queue) {
                serverQueue.bind(exchange, 'serverQueue');
                done();
            });
        });
        before(function(done) {
            clientQueue = amqpConnection.queue('clientQueue', {
                "exclusive": true
            },
            function(queue) {
                clientQueue.bind(exchange, 'clientQueue');
                done();
            });
        });
        it('should create an rpc queue', function(done) {
            serverQueue.subscribe(function(msg, headers, deliveryInfo, msgObject) {
                expect(msg).to.have.deep.property('data.name', 'test-me.com');
                exchange.publish(deliveryInfo.replyTo, {
                    "response": "successful"
                },
                {
                    "correlationId": deliveryInfo.correlationId
                });
            });
            var corrId = uuid.v4();
            clientQueue.subscribe(function(msg, headers, deliveryInfo, msgObject) {
                try {
                    if (deliveryInfo.correlationId && deliveryInfo.correlationId == corrId) {
                        expect(msg).to.have.deep.property('response', 'successful');
                        done();
                    }
                } catch(e) {
                    /* handle error */
                    done(e);
                }
            });

            exchange.publish('serverQueue', {
                "command": "infoDomain",
                "data": {
                    "name": "test-me.com"
                }
            },
            {
                "replyTo": "clientQueue",
                "correlationId": corrId
            });

        });
    });

    after(function() {
        amqpConnection.disconnect();

    });
});

<|endoftext|>


<commit_before>var chai = require("chai");
var chaiAsPromised = require("chai-as-promised");
var sinon = require('sinon');
var sinonChai = require("sinon-chai");
var util = require('util');

var Q = require('q');
var Item = require('../models/item').Item;
var ItemStates = require('../models/item').ItemStates;
var ItemTypeIcons = require('../models/item').ItemTypeIcons;

var config = require('../config');
var itemRoutes = require('../routes/item');
var torrenter = require('../jobs/torrenter');

chai.should();
chai.use(chaiAsPromised);
chai.use(sinonChai);

var staticConfig = config.get();

config.get = function() {
	return staticConfig;
}

describe('routes.item', function() {
	var item;
	var res;

	beforeEach(function () {
		item =  { type : 'movie' };
		Item.setupMethods(item);
		item.save = sinon.spy(item.save);
		item.planNextCheck = sinon.spy(item.planNextCheck);
		Item.findById = function(id) {
			return id === 123 ? Q(item) : Q(undefined);
		};
		Item.save = sinon.stub().returns(Q(this));
		Item.removeById = sinon.stub().returns(Q(undefined));
		torrenter.removeTorrent = sinon.stub().returns(Q(undefined));
		res = {
			render : sinon.spy(),
			redirect : sinon.spy()
		};
		util.error = sinon.spy();
	});

	it('should add item', function() {
		return itemRoutes.add({query : { name : 'Test', type : 'movie', year : 2015, externalId : 'tt000000' } }, res).should.be.fulfilled.then(function() {
			return Item.save.should.have.been.called;
		}).then(function() {
			var newItem = Item.save.getCall(0).args[0];
			newItem.name.should.equal('Test');
			return newItem.state.should.equal(ItemStates.wanted);
		}).then(function() {
			return res.redirect.should.have.been.calledWith('/');
		});
	});

	it('should change item', function() {
		return itemRoutes.changeState({query : { id : 123, state : ItemStates.downloaded } }, res).should.be.fulfilled.then(function() {
			return item.planNextCheck.should.have.been.called;
		}).then(function() {
			return item.save.should.have.been.called;
		}).then(function() {
			return item.state.should.equal(ItemStates.downloaded);
		}).then(function() {
			return res.redirect.should.have.been.calledWith('/');
		});
	});

	it('should remove item', function() {
		return itemRoutes.remove({query : {id : 123} }, res).should.be.fulfilled.then(function() {
			return Item.removeById.should.have.been.calledWith(123);
		}).then(function() {
			return torrenter.removeTorrent.should.have.been.calledWith(item, true);
		}).then(function() {
			return res.redirect.should.have.been.calledWith('/');
		});
	});

	it('should not fail from invalid item', function() {
		return itemRoutes.remove({query : {id : 0} }, res).should.be.fulfilled.then(function() {
			return Item.removeById.should.not.have.been.called;
		}).then(function() {
			return torrenter.removeTorrent.should.not.have.been.called;
		}).then(function() {
			return util.error.should.not.have.been.called;
		}).then(function() {
			return res.redirect.should.have.been.calledWith('/');
		});
	});

	it('should not fail from torrent removal inability', function() {
		torrenter.removeTorrent = function() { return Q.fcall(function() { throw new Error('Unable to connect'); }); };

		return itemRoutes.remove({query : {id : 123} }, res).should.be.fulfilled.then(function() {
			return Item.removeById.should.have.been.calledWith(123);
		}).then(function() {
			return util.error.should.have.been.called;
		}).then(function() {
			return res.redirect.should.have.been.calledWith('/');
		});
	});
});<commit_msg>Use sinon matching tests.<commit_after>var chai = require("chai");
var chaiAsPromised = require("chai-as-promised");
var sinon = require('sinon');
var sinonChai = require("sinon-chai");
var util = require('util');

var Q = require('q');
var Item = require('../models/item').Item;
var ItemStates = require('../models/item').ItemStates;
var ItemTypeIcons = require('../models/item').ItemTypeIcons;

var config = require('../config');
var itemRoutes = require('../routes/item');
var torrenter = require('../jobs/torrenter');

chai.should();
chai.use(chaiAsPromised);
chai.use(sinonChai);

var staticConfig = config.get();

config.get = function() {
	return staticConfig;
}

describe('routes.item', function() {
	var item;
	var res;

	beforeEach(function () {
		item =  { type : 'movie' };
		Item.setupMethods(item);
		item.save = sinon.spy(item.save);
		item.planNextCheck = sinon.spy(item.planNextCheck);
		Item.findById = function(id) {
			return id === 123 ? Q(item) : Q(undefined);
		};
		Item.save = sinon.stub().returns(Q(this));
		Item.removeById = sinon.stub().returns(Q(undefined));
		torrenter.removeTorrent = sinon.stub().returns(Q(undefined));
		res = {
			render : sinon.spy(),
			redirect : sinon.spy()
		};
		util.error = sinon.spy();
	});

	it('should add item', function() {
		return itemRoutes.add({query : { name : 'Test', type : 'movie', year : 2015, externalId : 'tt000000' } }, res).should.be.fulfilled.then(function() {
			return Item.save.should.have.been.calledWithMatch({ name : 'Test', state : ItemStates.wanted });
		}).then(function() {
			return res.redirect.should.have.been.calledWith('/');
		});
	});

	it('should change item', function() {
		return itemRoutes.changeState({query : { id : 123, state : ItemStates.downloaded } }, res).should.be.fulfilled.then(function() {
			return item.planNextCheck.should.have.been.called;
		}).then(function() {
			return Item.save.should.have.been.calledWithMatch({ state : ItemStates.downloaded });
		}).then(function() {
			return res.redirect.should.have.been.calledWith('/');
		});
	});

	it('should remove item', function() {
		return itemRoutes.remove({query : {id : 123} }, res).should.be.fulfilled.then(function() {
			return Item.removeById.should.have.been.calledWith(123);
		}).then(function() {
			return torrenter.removeTorrent.should.have.been.calledWith(item, true);
		}).then(function() {
			return res.redirect.should.have.been.calledWith('/');
		});
	});

	it('should not fail from invalid item', function() {
		return itemRoutes.remove({query : {id : 0} }, res).should.be.fulfilled.then(function() {
			return Item.removeById.should.not.have.been.called;
		}).then(function() {
			return torrenter.removeTorrent.should.not.have.been.called;
		}).then(function() {
			return util.error.should.not.have.been.called;
		}).then(function() {
			return res.redirect.should.have.been.calledWith('/');
		});
	});

	it('should not fail from torrent removal inability', function() {
		torrenter.removeTorrent = function() { return Q.fcall(function() { throw new Error('Unable to connect'); }); };

		return itemRoutes.remove({query : {id : 123} }, res).should.be.fulfilled.then(function() {
			return Item.removeById.should.have.been.calledWith(123);
		}).then(function() {
			return util.error.should.have.been.called;
		}).then(function() {
			return res.redirect.should.have.been.calledWith('/');
		});
	});
});<|endoftext|>