<commit_before>var expect = require('chai').expect,
    sinon = require('sinon'),
    path = require('path'),
    ss = require('../index.js');

describe('static-template', function (argument) {
    it('should render on first try if no error', function(done) {
        var req = {
            originalUrl: 'someFile'
        };

        var render = function(url, opts, callback) {
            expect(url).to.equal(path.join('/path', 'someFile'));
            expect(opts).to.be.empty;
            callback(null, 'html');
        };

        var res = {
            render: render,
            end: function(text) {
                expect(text).to.equal('html');
                done();
            },
            writeHead: sinon.spy()
        };

        var middleware = ss.staticTemplate('/path', { otherOpts: 'opts' });
        middleware(req, res, function() { return; });
    });

    it('should render from template dir', function(done) {
        var req = {
            originalUrl: 'someFile'
        };

        var render = function(url, opts, callback) {
            expect(url).to.equal(path.join('/path', 'someFile'));
            expect(opts).to.equal('opts template');
            callback(null, 'html');
        };

        var res = {
            render: render,
            end: function(text) {
                expect(text).to.equal('html');
                done();
            },
            writeHead: sinon.spy()
        };

        var middleware = ss.staticTemplate('/path', { templateOpts: 'opts template' });
        middleware(req, res, function() { return; });

    });

    it('should try to render an index file if first render failed', function(done) {
        var req = {
            originalUrl: 'someDir'
        };

        var res = {
            render: function() {},
            end: function(text) {
                expect(text).to.equal('html render');
                // expect(text).to.equal('html render 2');
                done();
            },
            writeHead: sinon.spy()
        };

        sinon.stub(res, "render")
            .onFirstCall().callsArgWith(2, 'was a dir', null)
            .onSecondCall().callsArgWith(2, null, 'html render 2');

        var middleware = ss.staticTemplate('/path', { templateOpts: 'opts template' });
        middleware(req, res, function() { return; });
    });

    it('should call next if no file or dir', function(done) {
        var req = {
            originalUrl: 'someDir'
        };

        var res = {
            render: function() {},
            writeHead: sinon.spy()
        };

        sinon.stub(res, "render")
            .onFirstCall().callsArgWith(2, 'was a dir', null)
            .onSecondCall().callsArgWith(2, 'doesn\'t exist');

        var middleware = ss.staticTemplate('/path', { templateOpts: 'opts template' });
        middleware(req, res, function() { return done(); });
    });

    it('should call next if serveDirs is not true', function(done) {
        var req = {
            originalUrl: 'someDir'
        };

        var res = {
            render: function() {},
            writeHead: sinon.spy()
        };

        sinon.stub(res, "render")
            .onFirstCall().callsArgWith(2, 'was a dir', null)
            .onSecondCall().callsArgWith(2, 'doesn\'t exist');

        var middleware = ss.staticTemplate('/path', {
            templateOpts: 'opts template',
            serveDirs: false
        });

        middleware(req, res, function() { return done(); });
        expect(res.writeHead.called).to.be.false;
    });
});<commit_msg>Fixed broken unit test.<commit_after>var expect = require('chai').expect,
    sinon = require('sinon'),
    path = require('path'),
    ss = require('../index.js');

describe('static-template', function (argument) {
    it('should render on first try if no error', function(done) {
        var req = {
            originalUrl: 'someFile'
        };

        var render = function(url, opts, callback) {
            expect(url).to.equal(path.join('/path', 'someFile'));
            expect(opts).to.be.empty;
            callback(null, 'html');
        };

        var res = {
            render: render,
            end: function(text) {
                expect(text).to.equal('html');
                done();
            },
            writeHead: sinon.spy()
        };

        var middleware = ss.staticTemplate('/path', { otherOpts: 'opts' });
        middleware(req, res, function() { return; });
    });

    it('should render from template dir', function(done) {
        var req = {
            originalUrl: 'someFile'
        };

        var render = function(url, opts, callback) {
            expect(url).to.equal(path.join('/path', 'someFile'));
            expect(opts).to.equal('opts template');
            callback(null, 'html');
        };

        var res = {
            render: render,
            end: function(text) {
                expect(text).to.equal('html');
                done();
            },
            writeHead: sinon.spy()
        };

        var middleware = ss.staticTemplate('/path', { templateOpts: 'opts template' });
        middleware(req, res, function() { return; });

    });

    it('should try to render an index file if first render failed', function(done) {
        var req = {
            originalUrl: 'someDir'
        };

        var res = {
            render: function() {},
            end: function(text) {
                expect(text).to.equal('html render 2');
                done();
            },
            writeHead: sinon.spy()
        };

        sinon.stub(res, "render")
            .onFirstCall().callsArgWith(2, 'was a dir', null)
            .onSecondCall().callsArgWith(2, null, 'html render 2');

        var middleware = ss.staticTemplate('/path', { templateOpts: 'opts template' });
        middleware(req, res, function() { return; });
    });

    it('should call next if no file or dir', function(done) {
        var req = {
            originalUrl: 'someDir'
        };

        var res = {
            render: function() {},
            writeHead: sinon.spy()
        };

        sinon.stub(res, "render")
            .onFirstCall().callsArgWith(2, 'was a dir', null)
            .onSecondCall().callsArgWith(2, 'doesn\'t exist');

        var middleware = ss.staticTemplate('/path', { templateOpts: 'opts template' });
        middleware(req, res, function() { return done(); });
    });

    it('should call next if serveDirs is not true', function(done) {
        var req = {
            originalUrl: 'someDir'
        };

        var res = {
            render: function() {},
            writeHead: sinon.spy()
        };

        sinon.stub(res, "render")
            .onFirstCall().callsArgWith(2, 'was a dir', null)
            .onSecondCall().callsArgWith(2, 'doesn\'t exist');

        var middleware = ss.staticTemplate('/path', {
            templateOpts: 'opts template',
            serveDirs: false
        });

        middleware(req, res, function() { return done(); });
        expect(res.writeHead.called).to.be.false;
    });
});<|endoftext|>


<commit_before>(function () {
    'use strict';

    angular
        .module('crowdsource.project.controllers')
        .controller('MyProjectController', MyProjectController);

    MyProjectController.$inject = ['$window', '$state', '$scope', '$mdToast', 'Project',
        '$filter', 'Authentication', '$mdDialog'];

    /**
     * @namespace MyProjectController
     */
    function MyProjectController($window, $state, $scope, $mdToast, Project,
                                 $filter, Authentication, $mdDialog) {
        var self = this;
        self.myProjects = [];
        self.createProject = createProject;
        self.navigateToTasks = navigateToTasks;
        self.statusToString = statusToString;
        self.updateStatus = updateStatus;
        self.openPreferences = openPreferences;
        self.discard = discard;
        self.edit = edit;
        self.fork = fork;
        self.sort = sort;
        self.editProject = editProject;
        self.getDate = getDate;
        self.getTaskNumber = getTaskNumber;
        self.deleteProject = deleteProject;
        self.projectToDelete = null;
        self.config = {
            order_by: "",
            order: ""
        };
        self.status = {
            STATUS_DRAFT: 1,
            STATUS_IN_PROGRESS: 3,
            STATUS_COMPLETED: 4,
            STATUS_PAUSED: 5
        };
        self.openActionsMenu = openActionsMenu;
        self.showPaused = showPaused;

        activate();
        function activate() {
            Project.getRequesterProjects().then(
                function success(response) {
                    self.myProjects = response[0];
                    initializeWebSocket();
                },
                function error(response) {
                    $mdToast.showSimple('Could not get requester projects.');
                }
            ).finally(function () {
            });
        }

        function initializeWebSocket() {
            $scope.$on('message', function (event, data) {
                callback(data);
            });
        }

        function callback(message) {
            if (message.hasOwnProperty('event') && (message.event == 'TASK_SUBMITTED' || message.event == 'TASK_APPROVED')) {
                var project = $filter('filter')(self.myProjects, {hash_id: message.project_key});
                if (project.length) {
                    refreshStats(project[0], message.event);
                }
            }
        }

        function refreshStats(project, event) {
            Project.status(project.id).then(
                function success(response) {
                    if (event == 'TASK_SUBMITTED') {
                        project.awaiting_review += 1;
                        project.in_progress -= 1;
                    }
                    else if (event == 'TASK_APPROVED') {
                        project.awaiting_review -= 1;
                        project.completed += 1;
                    }
                },
                function error(response) {
                }
            ).finally(function () {
            });
        }

        function sort(header) {
            var sortedData = $filter('orderBy')(self.myProjects, header, self.config.order === 'descending');
            self.config.order = (self.config.order === 'descending') ? 'ascending' : 'descending';
            self.config.order_by = header;
            self.myProjects = sortedData;
        }

        function createProject() {
            Project.create().then(
                function success(response) {
                    var project_pk = response[0].id;
                    $state.go('create_edit_project', {projectId: project_pk});
                },
                function error(response) {
                    $mdToast.showSimple('Could not get requester projects.');
                }
            ).finally(function () {
            });
        }

        function navigateToTasks(project_id) {
            $state.go('project_review', {projectId: project_id});
        }

        function statusToString(status, revisions) {
            if (status == self.status.STATUS_DRAFT && revisions.length == 1)
                return "Not yet launched";
            else if (status == self.status.STATUS_IN_PROGRESS) {
                return "Running";
            }
            else if (self.status.STATUS_PAUSED || (self.status.STATUS_DRAFT &&
                revisions.length > 1)) {
                return "Paused";
            }
            else if (status == self.status.STATUS_COMPLETED) {
                return "Completed";
            }
            return "";
        }

        function updateStatus(item, status) {
            Project.updateStatus(item.id, {status: status}).then(
                function success(response) {
                    $mdToast.showSimple('Updated ' + item.name + '!');
                    item.status = status;
                },
                function error(response) {
                    $mdToast.showSimple(response[0][0] + '. Open the project to edit it.');
                }
            ).finally(function () {
            });
        }

        function discard(item, $event) {
            var parent = angular.element(document.body);
            self.projectToDelete = item;
            $mdDialog.show({
                clickOutsideToClose: true,
                scope: $scope,
                preserveScope: true,
                parent: parent,
                targetEvent: $event,
                templateUrl: '/static/templates/project/delete.html',
                controller: DialogController
            });
        }

        function deleteProject() {
            Project.deleteInstance(self.projectToDelete.id).then(
                function success(response) {
                    self.myProjects.splice(self.myProjects.findIndex(function (element, index, array) {
                        return element.id == self.projectToDelete.id;
                    }), 1);
                    $mdToast.showSimple('Deleted ' + self.projectToDelete.name + '.');
                },
                function error(response) {
                    $mdToast.showSimple('Could not delete project.');
                }
            ).finally(function () {
            });
        }

        function edit(item) {
            $state.go('create_edit_project', {projectId: item.id});
        }

        function fork(item) {
            Project.fork(item.id).then(
                function success(response) {
                    $state.go('create_edit_project', {projectId: response[0].id});
                },
                function error(response) {
                    $mdToast.showSimple('Could not fork project.');
                }
            ).finally(function () {
            });
        }

        function openPreferences($event) {
            $mdDialog.show({
                clickOutsideToClose: true,
                scope: $scope,
                preserveScope: true,
                //parent: parent,
                targetEvent: $event,
                templateUrl: '/static/templates/project/preferences.html',
                controller: DialogController
            });
        }

        function openActionsMenu($mdOpenMenu, ev) {
            $mdOpenMenu(ev);
        }

        function editProject(project_id) {
            $state.go('create_edit_project', {projectId: project_id});
        }

        function showPaused(project) {
            return project.status == self.status.STATUS_PAUSED
                || (project.status == self.status.STATUS_DRAFT && project.revisions.length > 1);

        }

        function getDate(timestamp) {
            return new Date(timestamp).toLocaleString();
        }

        function getTaskNumber(rawNUmber, numberOfRevisions, status) {
            if (status == self.status.STATUS_DRAFT && numberOfRevisions == 1 && rawNUmber == 0) {
                return '-';
            }
            return rawNUmber;
        }

    }

    function DialogController($scope, $mdDialog) {
        $scope.hide = function () {
            $mdDialog.hide();
        };
        $scope.cancel = function () {
            $mdDialog.cancel();
        };
    }

})();
<commit_msg>use api response to update the stats for project list view<commit_after>(function () {
    'use strict';

    angular
        .module('crowdsource.project.controllers')
        .controller('MyProjectController', MyProjectController);

    MyProjectController.$inject = ['$window', '$state', '$scope', '$mdToast', 'Project',
        '$filter', 'Authentication', '$mdDialog'];

    /**
     * @namespace MyProjectController
     */
    function MyProjectController($window, $state, $scope, $mdToast, Project,
                                 $filter, Authentication, $mdDialog) {
        var self = this;
        self.myProjects = [];
        self.createProject = createProject;
        self.navigateToTasks = navigateToTasks;
        self.statusToString = statusToString;
        self.updateStatus = updateStatus;
        self.openPreferences = openPreferences;
        self.discard = discard;
        self.edit = edit;
        self.fork = fork;
        self.sort = sort;
        self.editProject = editProject;
        self.getDate = getDate;
        self.getTaskNumber = getTaskNumber;
        self.deleteProject = deleteProject;
        self.projectToDelete = null;
        self.config = {
            order_by: "",
            order: ""
        };
        self.status = {
            STATUS_DRAFT: 1,
            STATUS_IN_PROGRESS: 3,
            STATUS_COMPLETED: 4,
            STATUS_PAUSED: 5
        };
        self.openActionsMenu = openActionsMenu;
        self.showPaused = showPaused;

        activate();
        function activate() {
            Project.getRequesterProjects().then(
                function success(response) {
                    self.myProjects = response[0];
                    initializeWebSocket();
                },
                function error(response) {
                    $mdToast.showSimple('Could not get requester projects.');
                }
            ).finally(function () {
            });
        }

        function initializeWebSocket() {
            $scope.$on('message', function (event, data) {
                callback(data);
            });
        }

        function callback(message) {
            if (message.hasOwnProperty('event') && (message.event == 'TASK_SUBMITTED' || message.event == 'TASK_APPROVED')) {
                var project = $filter('filter')(self.myProjects, {hash_id: message.project_key});
                if (project.length) {
                    refreshStats(project[0], message.event);
                }
            }
        }

        function refreshStats(project, event) {
            Project.status(project.id).then(
                function success(response) {
                    if (event == 'TASK_SUBMITTED') {
                        project.awaiting_review = response[0].awaiting_review;
                        project.in_progress = response[0].in_progress;
                    }
                    else if (event == 'TASK_APPROVED') {
                        project.awaiting_review = response[0].awaiting_review;
                        project.completed = response[0].completed;
                    }
                },
                function error(response) {
                }
            ).finally(function () {
            });
        }

        function sort(header) {
            var sortedData = $filter('orderBy')(self.myProjects, header, self.config.order === 'descending');
            self.config.order = (self.config.order === 'descending') ? 'ascending' : 'descending';
            self.config.order_by = header;
            self.myProjects = sortedData;
        }

        function createProject() {
            Project.create().then(
                function success(response) {
                    var project_pk = response[0].id;
                    $state.go('create_edit_project', {projectId: project_pk});
                },
                function error(response) {
                    $mdToast.showSimple('Could not get requester projects.');
                }
            ).finally(function () {
            });
        }

        function navigateToTasks(project_id) {
            $state.go('project_review', {projectId: project_id});
        }

        function statusToString(status, revisions) {
            if (status == self.status.STATUS_DRAFT && revisions.length == 1)
                return "Not yet launched";
            else if (status == self.status.STATUS_IN_PROGRESS) {
                return "Running";
            }
            else if (self.status.STATUS_PAUSED || (self.status.STATUS_DRAFT &&
                revisions.length > 1)) {
                return "Paused";
            }
            else if (status == self.status.STATUS_COMPLETED) {
                return "Completed";
            }
            return "";
        }

        function updateStatus(item, status) {
            Project.updateStatus(item.id, {status: status}).then(
                function success(response) {
                    $mdToast.showSimple('Updated ' + item.name + '!');
                    item.status = status;
                },
                function error(response) {
                    $mdToast.showSimple(response[0][0] + '. Open the project to edit it.');
                }
            ).finally(function () {
            });
        }

        function discard(item, $event) {
            var parent = angular.element(document.body);
            self.projectToDelete = item;
            $mdDialog.show({
                clickOutsideToClose: true,
                scope: $scope,
                preserveScope: true,
                parent: parent,
                targetEvent: $event,
                templateUrl: '/static/templates/project/delete.html',
                controller: DialogController
            });
        }

        function deleteProject() {
            Project.deleteInstance(self.projectToDelete.id).then(
                function success(response) {
                    self.myProjects.splice(self.myProjects.findIndex(function (element, index, array) {
                        return element.id == self.projectToDelete.id;
                    }), 1);
                    $mdToast.showSimple('Deleted ' + self.projectToDelete.name + '.');
                },
                function error(response) {
                    $mdToast.showSimple('Could not delete project.');
                }
            ).finally(function () {
            });
        }

        function edit(item) {
            $state.go('create_edit_project', {projectId: item.id});
        }

        function fork(item) {
            Project.fork(item.id).then(
                function success(response) {
                    $state.go('create_edit_project', {projectId: response[0].id});
                },
                function error(response) {
                    $mdToast.showSimple('Could not fork project.');
                }
            ).finally(function () {
            });
        }

        function openPreferences($event) {
            $mdDialog.show({
                clickOutsideToClose: true,
                scope: $scope,
                preserveScope: true,
                //parent: parent,
                targetEvent: $event,
                templateUrl: '/static/templates/project/preferences.html',
                controller: DialogController
            });
        }

        function openActionsMenu($mdOpenMenu, ev) {
            $mdOpenMenu(ev);
        }

        function editProject(project_id) {
            $state.go('create_edit_project', {projectId: project_id});
        }

        function showPaused(project) {
            return project.status == self.status.STATUS_PAUSED
                || (project.status == self.status.STATUS_DRAFT && project.revisions.length > 1);

        }

        function getDate(timestamp) {
            return new Date(timestamp).toLocaleString();
        }

        function getTaskNumber(rawNUmber, numberOfRevisions, status) {
            if (status == self.status.STATUS_DRAFT && numberOfRevisions == 1 && rawNUmber == 0) {
                return '-';
            }
            return rawNUmber;
        }

    }

    function DialogController($scope, $mdDialog) {
        $scope.hide = function () {
            $mdDialog.hide();
        };
        $scope.cancel = function () {
            $mdDialog.cancel();
        };
    }

})();
<|endoftext|>


<commit_before>function test(name, path) {
    describe(name, function () {
        require(path);
    })
}

describe('#bateeq-module', function (done) {
    this.timeout(2 * 60000);
    // //auth
    // test('@AUTH/ACCOUNT-MANAGER', './auth/account-manager-test');
    // test('@AUTH/ROLE-MANAGER', './auth/role-manager-test');

    // //master
    // test('@MANAGER/MASTER/ITEM-MANAGER', './managers/master/item-manager-test');
    // test('@MANAGER/MASTER/MATERIAL-MANAGER', './managers/master/material-manager-test');
    // test('@MANAGER/MASTER/FINISHED-GOODS-MANAGER', './managers/master/finished-goods-manager-test');
    // test('@MANAGER/STORAGE-MANAGER', './managers/storage-manager-test');
    // test('@MANAGER/STORE-MANAGER', './managers/store-manager-test');
    // test('@MANAGER/SUPPLIER-MANAGER', './managers/supplier-manager-test');
    // test('@MANAGER/INVENTORY-MANAGER', './managers/inventory-manager-test');
    // test('@MANAGER/MODULE-MANAGER', './managers/module-manager-test');
    // test('@MANAGER/BANK-MANAGER', './managers/bank-manager-test');
    // test('@MANAGER/CARD-TYPE-MANAGER', './managers/card-type-manager-test');
    // test('@MANAGER/PROMO-MANAGER', './managers/promo-manager-test');
    // test('@MANAGER/RANGE-DISC-PRODUCT-MANAGER', './managers/range-disc-product-test');
    // test('@MANAGER/DESIGN-TRACKING-REASON-MANAGER', './managers/master/design-tracking-reason');

    // test('@ARTICLE/ARTICLE-MOTIF', './article/article-motif');
    // test('@ARTICLE/ARTICLE-COUNTER', './article/article-counter');
    // test('@ARTICLE/ARTICLE-SUB-COUNTER', './article/article-sub-counter');
    // test('@ARTICLE/ARTICLE-SEASON', './article/article-season');
    // test('@ARTICLE/ARTICLE-COLLECTION', './article/article-collection');
    // test('@ARTICLE/ARTICLE-SUB-COLLECTION', './article/article-sub-collection');
    // test('@ARTICLE/ARTICLE-MATERIAL', './article/article-material');
    // test('@ARTICLE/ARTICLE-MATERIAL-COMPOSITION', './article/article-material-composition');
    // test('@ARTICLE/ARTICLE-SUB-MATERIAL-COMPOSITION', './article/article-material-composition');
    // test('@ARTICLE/ARTICLE-PROCESS', './article/article-process');
    // test('@ARTICLE/ARTICLE-SUB-PROCESS', './article/article-sub-process');
    // test('@ARTICLE/ARTICLE-CATEGORY', './article/article-category');

    // //transaction
    // test('@MANAGER/TRANSFER-IN-DOC-MANAGER', './managers/transfer-in-doc-manager-test');
    // test('@MANAGER/TRANSFER-IN-STORE-BUSINESS', './business/store/transfer-in-store-business-test');
    // test('@MANAGER/TRANSFER-OUT-DOC-MANAGER', './managers/transfer-out-doc-manager-test');
    // test('@MANAGER/TRANSFER-IN-DOC-EXT-MANAGER', './managers/transfer-in-doc-ext-manager-test');
    // test('@MANAGER/EFR-TB-BJR-MANAGER', './managers/efr-tb-bjr-manager-test');
    // test('@MANAGER/EFR-TB-BRD-MANAGER', './managers/efr-tb-brd-manager-test');
    // test('@MANAGER/EFR-TB-BRT-MANAGER', './managers/efr-tb-brt-manager-test');
    // test('@MANAGER/SALES-MANAGER', './managers/sales-manager-test');
    // test('@MANAGER/SALES-RETURN-MANAGER', './managers/sales-return-manager-test');
    // test('@MANAGER/ADJUSTMENT-MANAGER', './managers/inventory/adjustment');
    // test('@MANAGER/STOCK-OPNAME-MANAGER', './managers/inventory/stock-opname');

    // //inventory
    // test('@MANAGERS/INVENTORY/REPORT-MANAGER', './managers/inventory/report-manager');
    // test('@MANAGER/MONTHLY-STOCK-MANAGER', './managers/inventory/monthly-stock-manager-test');

    // // manufacture
    // test('@MANAGERS/MANUFACTURE/DESIGN-TRACKING-BOARD-MANAGER', './managers/manufacture/design-tracking-board');
    // test('@MANAGERS/MANUFACTURE/DESIGN-TRACKING-STAGE-MANAGER', './managers/manufacture/design-tracking-stage');
    // test('@MANAGERS/MANUFACTURE/DESIGN-TRACKING-DESIGN-MANAGER', './managers/manufacture/design-tracking-design');
    // test('@MANAGERS/MANUFACTURE/DESIGN-TRACKING-ACTIVITY-MANAGER', './managers/manufacture/design-tracking-activity');

    //Purchasing
    test('@PURCHASING/PURCHASE REQUEST', './managers/purchasing/purchase-request');
    test('@PURCHASING/PURCHASE-ORDER', './managers/purchasing/purchase-order');
    // test('@PURCHASING/PURCHASE-ORDER-EXTERNAL', './managers/purchasing/purchase-order-external');
    // test('@PURCHASING/DELIVERY-ORDER', './managers/purchasing/delivery-order');
    // test('@PURCHASING/UNIT-RECEIPT-NOTE', './managers/purchasing/unit-receipt-note');
})<commit_msg>update index<commit_after>function test(name, path) {
    describe(name, function () {
        require(path);
    })
}

describe('#bateeq-module', function (done) {
    this.timeout(2 * 60000);
    //auth
    test('@AUTH/ACCOUNT-MANAGER', './auth/account-manager-test');
    test('@AUTH/ROLE-MANAGER', './auth/role-manager-test');

    //master
    test('@MANAGER/MASTER/ITEM-MANAGER', './managers/master/item-manager-test');
    test('@MANAGER/MASTER/MATERIAL-MANAGER', './managers/master/material-manager-test');
    test('@MANAGER/MASTER/FINISHED-GOODS-MANAGER', './managers/master/finished-goods-manager-test');
    test('@MANAGER/STORAGE-MANAGER', './managers/storage-manager-test');
    test('@MANAGER/STORE-MANAGER', './managers/store-manager-test');
    test('@MANAGER/SUPPLIER-MANAGER', './managers/supplier-manager-test');
    test('@MANAGER/INVENTORY-MANAGER', './managers/inventory-manager-test');
    test('@MANAGER/MODULE-MANAGER', './managers/module-manager-test');
    test('@MANAGER/BANK-MANAGER', './managers/bank-manager-test');
    test('@MANAGER/CARD-TYPE-MANAGER', './managers/card-type-manager-test');
    test('@MANAGER/PROMO-MANAGER', './managers/promo-manager-test');
    test('@MANAGER/RANGE-DISC-PRODUCT-MANAGER', './managers/range-disc-product-test');
    test('@MANAGER/DESIGN-TRACKING-REASON-MANAGER', './managers/master/design-tracking-reason');

    test('@ARTICLE/ARTICLE-MOTIF', './article/article-motif');
    test('@ARTICLE/ARTICLE-COUNTER', './article/article-counter');
    test('@ARTICLE/ARTICLE-SUB-COUNTER', './article/article-sub-counter');
    test('@ARTICLE/ARTICLE-SEASON', './article/article-season');
    test('@ARTICLE/ARTICLE-COLLECTION', './article/article-collection');
    test('@ARTICLE/ARTICLE-SUB-COLLECTION', './article/article-sub-collection');
    test('@ARTICLE/ARTICLE-MATERIAL', './article/article-material');
    test('@ARTICLE/ARTICLE-MATERIAL-COMPOSITION', './article/article-material-composition');
    test('@ARTICLE/ARTICLE-SUB-MATERIAL-COMPOSITION', './article/article-material-composition');
    test('@ARTICLE/ARTICLE-PROCESS', './article/article-process');
    test('@ARTICLE/ARTICLE-SUB-PROCESS', './article/article-sub-process');
    test('@ARTICLE/ARTICLE-CATEGORY', './article/article-category');

    //transaction
    test('@MANAGER/TRANSFER-IN-DOC-MANAGER', './managers/transfer-in-doc-manager-test');
    test('@MANAGER/TRANSFER-IN-STORE-BUSINESS', './business/store/transfer-in-store-business-test');
    test('@MANAGER/TRANSFER-OUT-DOC-MANAGER', './managers/transfer-out-doc-manager-test');
    test('@MANAGER/TRANSFER-IN-DOC-EXT-MANAGER', './managers/transfer-in-doc-ext-manager-test');
    test('@MANAGER/EFR-TB-BJR-MANAGER', './managers/efr-tb-bjr-manager-test');
    test('@MANAGER/EFR-TB-BRD-MANAGER', './managers/efr-tb-brd-manager-test');
    test('@MANAGER/EFR-TB-BRT-MANAGER', './managers/efr-tb-brt-manager-test');
    test('@MANAGER/SALES-MANAGER', './managers/sales-manager-test');
    test('@MANAGER/SALES-RETURN-MANAGER', './managers/sales-return-manager-test');
    test('@MANAGER/ADJUSTMENT-MANAGER', './managers/inventory/adjustment');
    test('@MANAGER/STOCK-OPNAME-MANAGER', './managers/inventory/stock-opname');

    //inventory
    test('@MANAGERS/INVENTORY/REPORT-MANAGER', './managers/inventory/report-manager');
    test('@MANAGER/MONTHLY-STOCK-MANAGER', './managers/inventory/monthly-stock-manager-test');

    // manufacture
    test('@MANAGERS/MANUFACTURE/DESIGN-TRACKING-BOARD-MANAGER', './managers/manufacture/design-tracking-board');
    test('@MANAGERS/MANUFACTURE/DESIGN-TRACKING-STAGE-MANAGER', './managers/manufacture/design-tracking-stage');
    test('@MANAGERS/MANUFACTURE/DESIGN-TRACKING-DESIGN-MANAGER', './managers/manufacture/design-tracking-design');
    test('@MANAGERS/MANUFACTURE/DESIGN-TRACKING-ACTIVITY-MANAGER', './managers/manufacture/design-tracking-activity');

    //Purchasing
    test('@PURCHASING/PURCHASE REQUEST', './managers/purchasing/purchase-request');
    test('@PURCHASING/PURCHASE-ORDER', './managers/purchasing/purchase-order');
    // test('@PURCHASING/PURCHASE-ORDER-EXTERNAL', './managers/purchasing/purchase-order-external');
    // test('@PURCHASING/DELIVERY-ORDER', './managers/purchasing/delivery-order');
    // test('@PURCHASING/UNIT-RECEIPT-NOTE', './managers/purchasing/unit-receipt-note');
})<|endoftext|>


<commit_before>var assert = require('assert')

var index =  require('../')

describe('index', function(){
  it('should re-export stream api', function() {
    assert.strictEqual( index, require('stream') )
  })
  it('should export factory methods', function() {
    assert( typeof index.readable === 'function' )
    assert( typeof index.writable === 'function' )
    assert( typeof index.duplex === 'function' )
    assert( typeof index.transform === 'function' )
  })
})

describe('readable', function() {
  it('should create a readable stream with custom read', function() {
    var read = function(){}
      , opts = {objectMode:true}
      , rs = index.readable(read, opts)

    assert( rs instanceof index.Readable )
    assert.strictEqual( rs._read, read )
    assert( rs._readableState.objectMode, opts.objectMode )
  })
})

describe('writable', function() {
  it('should create a writable stream with custom write', function() {
    var write = function(){}
      , opts = {decodeStrings:true}
      , ws = index.writable(write, opts)

    assert( ws instanceof index.Writable )
    assert.strictEqual( ws._write, write )
    assert( ws._writableState.decodeStrings, opts.decodeStrings )
  })
})

describe('duplex', function() {
  it('should create a duplex stream with custom read and write', function() {
    var read = function(){}
      , write = function(){}
      , opts = {objectMode:true}
      , ds = index.duplex(read, write, opts)
    assert( ds instanceof index.Duplex )
    assert.strictEqual( ds._read, read )
    assert.strictEqual( ds._write, write )
    assert( ds._readableState.objectMode, opts.objectMode )
  })
})

describe('transform', function() {
  it('should create a transform stream with custom transform and flush', function() {
    var transform = function(){}
      , flush = function(){}
      , opts = {objectMode:true}
      , ts = index.transform(transform, opts, flush)
    assert( ts instanceof index.Transform )
    assert.strictEqual( ts._transform, transform )
    assert.strictEqual( ts._flush, flush )
    assert( ts._readableState.objectMode, opts.objectMode )
  })

  it('should create a transform stream with custom transform and no flush', function() {
    var transform = function(){}
      , opts = {objectMode:true}
      , ts = index.transform(transform, opts)
    assert( ts instanceof index.Transform )
    assert.strictEqual( ts._transform, transform )
    assert.equal( ts._flush, null )
    assert( ts._readableState.objectMode, opts.objectMode )
  })

  it('should create a transform stream with custom transform and flush without opts', function() {
    var transform = function(){}
      , flush = function(){}
      , ts = index.transform(transform, flush)
    assert( ts instanceof index.Transform )
    assert.strictEqual( ts._transform, transform )
    assert.strictEqual( ts._flush, flush )
  })
})<commit_msg>more tests<commit_after>var assert = require('assert')

var index =  require('../')

describe('index', function(){
  it('should re-export stream api', function() {
    assert.strictEqual( index, require('stream') )
  })
  it('should export factory methods', function() {
    assert( typeof index.readable === 'function' )
    assert( typeof index.writable === 'function' )
    assert( typeof index.duplex === 'function' )
    assert( typeof index.transform === 'function' )
  })
})

describe('readable', function() {
  it('should create a readable stream with custom read', function() {
    var read = function(){}
      , opts = {objectMode:true}
      , rs = index.readable(read, opts)

    assert( rs instanceof index.Readable )
    assert.strictEqual( rs._read, read )
    assert( rs._readableState.objectMode, opts.objectMode )
  })
})

describe('writable', function() {
  it('should create a writable stream with custom write', function() {
    var write = function(){}
      , opts = {decodeStrings:true}
      , ws = index.writable(write, opts)

    assert( ws instanceof index.Writable )
    assert.strictEqual( ws._write, write )
    assert( ws._writableState.decodeStrings, opts.decodeStrings )
  })
})

describe('duplex', function() {
  it('should create a duplex stream with custom read and write', function() {
    var read = function(){}
      , write = function(){}
      , opts = {objectMode:true}
      , ds = index.duplex(read, write, opts)
    assert( ds instanceof index.Duplex )
    assert.strictEqual( ds._read, read )
    assert.strictEqual( ds._write, write )
    assert( ds._readableState.objectMode, opts.objectMode )
  })
})

describe('transform', function() {
  it('should throw an error when transform is not provided', function() {
    assert.throws( function(){index.transform()}, TypeError )
  })

  it('should create a transform stream with custom transform and flush', function() {
    var transform = function(){}
      , flush = function(){}
      , opts = {objectMode:true}
      , ts = index.transform(transform, opts, flush)
    assert( ts instanceof index.Transform )
    assert.strictEqual( ts._transform, transform )
    assert.strictEqual( ts._flush, flush )
    assert( ts._readableState.objectMode, opts.objectMode )
  })

  it('should create a transform stream with custom transform and no flush', function() {
    var transform = function(){}
      , opts = {objectMode:true}
      , ts = index.transform(transform, opts)
    assert( ts instanceof index.Transform )
    assert.strictEqual( ts._transform, transform )
    assert.equal( ts._flush, null )
    assert( ts._readableState.objectMode, opts.objectMode )
  })

  it('should create a transform stream with custom transform and flush without opts', function() {
    var transform = function(){}
      , flush = function(){}
      , ts = index.transform(transform, flush)
    assert( ts instanceof index.Transform )
    assert.strictEqual( ts._transform, transform )
    assert.strictEqual( ts._flush, flush )
  })
})<|endoftext|>


<commit_before>// Dependencies
var JsonDb = require("../index")
  , Faker = require("faker")
  ;

// Create database instance
var MyDatabase = new JsonDb();

function generateFakeDataArray() {
    var docs = [];
    for (var i = 0; i < 30; ++i) {
        docs.push({
            name: Faker.Name.findName()
          , email: Faker.Internet.email()
          , age: Faker.Helpers.randomNumber(90)
        });
    }
    return docs;
}

// Create collection instance
var MyAwesomeCollection = MyDatabase.initCollection({
    inputFile: __dirname + "/docs-in.json"
  , outputFile: __dirname + "/docs-out.json"
  , uri: "mongodb://localhost:27017/test"
  , collection: "myCol"
  , autoInit: true
}, function (err) {

    // Handle error
    if (err) { throw err; }

    // Run a Mongo request
    MyAwesomeCollection.find({}).toArray(function (err, docs) {

        // Handle error
        if (err) { throw err; }

        // Output
        console.log("Documents: ", docs);

        // Insert
        MyAwesomeCollection.insert(generateFakeDataArray(), function (err, docs) {

            // Handle error
            if (err) { throw err; }

            console.log("Successfully inserted a new document: ", docs);
            console.log("Check out the content of the following file: ", MyAwesomeCollection._options.outputFile);

            // Close database
            MyAwesomeCollection.database.close();
        });
    });
});
<commit_msg>Updated variable name<commit_after>// Dependencies
var MongoSyncFiles = require("../index")
  , Faker = require("faker")
  ;

// Create database instance
var MyDatabase = new MongoSyncFiles();

function generateFakeDataArray() {
    var docs = [];
    for (var i = 0; i < 30; ++i) {
        docs.push({
            name: Faker.Name.findName()
          , email: Faker.Internet.email()
          , age: Faker.Helpers.randomNumber(90)
        });
    }
    return docs;
}

// Create collection instance
var MyAwesomeCollection = MyDatabase.initCollection({
    inputFile: __dirname + "/docs-in.json"
  , outputFile: __dirname + "/docs-out.json"
  , uri: "mongodb://localhost:27017/test"
  , collection: "myCol"
  , autoInit: true
}, function (err) {

    // Handle error
    if (err) { throw err; }

    // Run a Mongo request
    MyAwesomeCollection.find({}).toArray(function (err, docs) {

        // Handle error
        if (err) { throw err; }

        // Output
        console.log("Documents: ", docs);

        // Insert
        MyAwesomeCollection.insert(generateFakeDataArray(), function (err, docs) {

            // Handle error
            if (err) { throw err; }

            console.log("Successfully inserted a new document: ", docs);
            console.log("Check out the content of the following file: ", MyAwesomeCollection._options.outputFile);

            // Close database
            MyAwesomeCollection.database.close();
        });
    });
});
<|endoftext|>


<commit_before>import fs from "fs";
import path from "path";

import dox from "dox";
import originalDoxme from "doxme";
import test from "tape-catch";
import spigot from "stream-spigot";
import File from "vinyl";

import doxme from "../source/gulp-doxme";

var doxOutput = dox.parseComments(
  fs.readFileSync(path.resolve(__dirname, "fixtures/input.js")).toString()
  );
var doxOutputFile = new File(
  { cwd: "/"
  , base: "/base/"
  , path: "/base/anything.json"
  , contents: new Buffer(JSON.stringify(doxOutput))
  });

test("Processes file.data", (is) => {
  is.plan(3);

  var inputJSON = "[]";
  var inputFile = doxOutputFile.clone();
  inputFile.contents = new Buffer(inputJSON);
  inputFile.data = doxOutput;

  spigot({objectMode: true}, [inputFile])
    .pipe(doxme())
    .on("data", (outputFile) => {
      var output = outputFile.contents.toString();

      is.notEqual
        ( output
        , doxme(inputJSON)
        , "preferring file.data over JSON"
        );
      is.equal
        ( path.extname(outputFile.path)
        , ".md"
        , "outputting a markdown file"
        );
      is.equal
        ( output
        , originalDoxme(doxOutput)
        , "with the same content as doxme's output"
        );
      });
  });

test("Processes JSON output of gulp-dox", (is) => {
  is.skip("outputting a markdown file");
  is.skip("with the same content as doxme's output");
  is.end();
  });

test("Emits errors", (is) => {
  is.skip("when given broken file.data");
  is.skip("when given an invalid JSON file");
  is.end();
  });
<commit_msg>Test behavior with JSON files<commit_after>import fs from "fs";
import path from "path";

import dox from "dox";
import originalDoxme from "doxme";
import test from "tape-catch";
import spigot from "stream-spigot";
import File from "vinyl";

import doxme from "../source/gulp-doxme";

var doxOutput = dox.parseComments(
  fs.readFileSync(path.resolve(__dirname, "fixtures/input.js")).toString()
  );
var doxOutputFile = new File(
  { cwd: "/"
  , base: "/base/"
  , path: "/base/anything.json"
  , contents: new Buffer(JSON.stringify(doxOutput))
  });

test("Works with file.data", (is) => {
  is.plan(3);

  var inputJSON = "[]";
  var inputFile = doxOutputFile.clone();
  inputFile.contents = new Buffer(inputJSON);
  inputFile.data = doxOutput;

  spigot({objectMode: true}, [inputFile])
    .pipe(doxme())
    .on("data", (outputFile) => {
      var output = outputFile.contents.toString();

      is.notEqual
        ( output
        , doxme(inputJSON)
        , "preferring file.data over JSON"
        );
      is.equal
        ( path.extname(outputFile.path)
        , ".md"
        , "outputting a markdown file"
        );
      is.equal
        ( output
        , originalDoxme(doxOutput)
        , "with the same content as doxme's output"
        );
      })
    ;
  });

test("Works with a JSON file", (is) => {
  is.plan(2);

  spigot({objectMode: true}, [doxOutputFile.clone()])
    .pipe(doxme())
    .on("data", (outputFile) => {
      is.equal
        ( path.extname(outputFile.path)
        , ".md"
        , "outputting a markdown file"
        );
      is.equal
        ( outputFile.contents.toString()
        , originalDoxme(doxOutput)
        , "with the same content as doxme's output"
        );
      })
    ;
  });

test("Emits errors", (is) => {
  is.skip("when given broken file.data");
  is.skip("when given an invalid JSON file");
  is.end();
  });
<|endoftext|>


<commit_before>/**
	 * Requirements
	 */

	var chai = require('chai'),
	    assert = require('chai').assert,
	    chaiAsPromised = require('chai-as-promised');
	var resumePdfToJson = require('../index');

	chai.use(chaiAsPromised);

	/**
	 * Test Descriptions
	 */

	    var path = 'JohnBradley.pdf';
	    var output = 'JohnBradley.json';

	  /*var p = resumePdfToJson(path, {'output': output})
	        .then(function(data) {
	            return data;
	        });*/

	    var p = resumePdfToJson(path)
	        .then(function(data) {
	            return data;
	        });

<commit_msg>Update index.js<commit_after>/**
	 * Requirements
	 */

	var chai = require('chai'),
	    assert = require('chai').assert,
	    chaiAsPromised = require('chai-as-promised');
	var resumePdfToJson = require('../index');

	chai.use(chaiAsPromised);

	/**
	 * Test Descriptions
	 */

	    var path = 'JohnBradley.pdf';
	    var output = 'JohnBradley.json';

	    var p = resumePdfToJson(path, {'output': output})
	        .then(function(data) {
	            return data;
	        });

	   /*var p = resumePdfToJson(path)
	        .then(function(data) {
	            return data;
	        });*/
<|endoftext|>


<commit_before>var express = require('express');
var path = require('path');
var logger = require('morgan');

var me = require('../me');
var config = require('../config');
var Router = require('./routes/router');

var app = express();

app.set('json spaces', 4);
app.use(logger('dev'));
app.use(express.static(path.join(__dirname, 'public')));

// Allow Ajax GET calls
app.use(function (req, res, next) {
  res.setHeader('Access-Control-Allow-Origin', '*');
  res.setHeader('Access-Control-Allow-Methods', 'GET');
  res.setHeader('Access-Control-Allow-Headers', 'X-Requested-With,content-type');
  next();
});

app.use('/', (new Router(me, config.modules, config.settings)).router);

// catch 404 and forward to error handler
app.use(function(req, res, next) {
  var err = new Error('Not Found');
  err.status = 404;
  next(err);
});

// error handlers

// development error handler
// will print stacktrace
if (app.get('env') === 'development') {
  app.use(function(err, req, res, next) {
    res.status(err.status || 500);
    res.json({
      message: err.message,
      error: err
    });
  });
}

// production error handler
// no stacktraces leaked to user
app.use(function(err, req, res, next) {
  res.status(err.status || 500);
  res.json({
    message: err.message,
    error: {}
  });
});

module.exports = app;
<commit_msg>Removing whitespace<commit_after>var express = require('express');
var path = require('path');
var logger = require('morgan');
var me = require('../me');
var config = require('../config');
var Router = require('./routes/router');
var app = express();

app.set('json spaces', 4);
app.use(logger('dev'));
app.use(express.static(path.join(__dirname, 'public')));

// Allow Ajax GET calls
app.use(function (req, res, next) {
  res.setHeader('Access-Control-Allow-Origin', '*');
  res.setHeader('Access-Control-Allow-Methods', 'GET');
  res.setHeader('Access-Control-Allow-Headers', 'X-Requested-With,content-type');
  next();
});

app.use('/', (new Router(me, config.modules, config.settings)).router);

// catch 404 and forward to error handler
app.use(function(req, res, next) {
  var err = new Error('Not Found');
  err.status = 404;
  next(err);
});

// error handlers

// development error handler
// will print stacktrace
if (app.get('env') === 'development') {
  app.use(function(err, req, res, next) {
    res.status(err.status || 500);
    res.json({
      message: err.message,
      error: err
    });
  });
}

// production error handler
// no stacktraces leaked to user
app.use(function(err, req, res, next) {
  res.status(err.status || 500);
  res.json({
    message: err.message,
    error: {}
  });
});

module.exports = app;
<|endoftext|>


<commit_before>'use strict';

let path = require('path');
let through2 = require('through2');
let File = require('vinyl');

let bemDepsOrder = require('../build');
let expect = require('chai').expect;
let collectStreamFiles = require('../lib/collect-stream-files');

function fillDeps(filename, stream) {
    let files = require(`./${filename}`);

    Object.keys(files).forEach(file => {
        let vinylFile = new File({
            path: path.resolve(__dirname, `${file}.deps.js`),
            contents: new Buffer(`(${JSON.stringify(files[file])})`)
        });

        stream.write(vinylFile);
    });

    stream.end();
}

function fillInputFiles(files, stream) {
    for (let file of files) {
        let vinylFile = new File({
            path: path.resolve(__dirname, `${file}.css`),
            contents: new Buffer('')
        });

        stream.write(vinylFile);
    }

    stream.end();
}

describe('gulp-order-bemdeps', () => {
    it('should not change order of files if no deps.js exist', () => {
        let stream = through2.obj();
        let myBemDepsOrder = bemDepsOrder(stream);

        // fill dependencies
        fillDeps('deps-empty', stream);

        // now pipe input files
        fillInputFiles(['block1', 'block2', 'block3'], myBemDepsOrder);

        return collectStreamFiles(myBemDepsOrder).then(files => {
            for (let file of files) {
                expect(file.isBuffer()).to.be.true;
            }

            // files number should stay the same
            expect(files).to.have.length(3);

            // files order should be the same
            expect(files[0].stem).to.equal('block1');
            expect(files[1].stem).to.equal('block2');
            expect(files[2].stem).to.equal('block3');
        });
    });

    it('should reorder files even if no deps.js are supported but files need this', () => {

    });

    it('should reorder files in accordance to blocks dependencies', () => {

    });

    it('should reorder files even if distance to root is different', () => {

    });

    it('should reorder files even if its dependency block is not listed inside source files', () => {

    });
});
<commit_msg>add first no-deps reorder test<commit_after>'use strict';

let path = require('path');
let through2 = require('through2');
let File = require('vinyl');

let bemDepsOrder = require('../build');
let expect = require('chai').expect;
let collectStreamFiles = require('../lib/collect-stream-files');

function fillDeps(filename, stream) {
    let files = require(`./${filename}`);

    Object.keys(files).forEach(file => {
        let vinylFile = new File({
            path: path.resolve(__dirname, `${file}.deps.js`),
            contents: new Buffer(`(${JSON.stringify(files[file])})`)
        });

        stream.write(vinylFile);
    });

    stream.end();
}

function fillInputFiles(files, stream) {
    for (let file of files) {
        let vinylFile = new File({
            path: path.resolve(__dirname, `${file}.css`),
            contents: new Buffer('')
        });

        stream.write(vinylFile);
    }

    stream.end();
}

describe('gulp-order-bemdeps', () => {
    it('should not change order of files if no deps.js exist', () => {
        let stream = through2.obj();
        let myBemDepsOrder = bemDepsOrder(stream);

        // fill dependencies
        fillDeps('deps-empty', stream);

        // now pipe input files
        fillInputFiles(['block1', 'block2', 'block3'], myBemDepsOrder);

        return collectStreamFiles(myBemDepsOrder).then(files => {
            for (let file of files) {
                expect(file.isBuffer()).to.be.true;
            }

            // files number should stay the same
            expect(files).to.have.length(3);

            // files order should be the same
            expect(files[0].stem).to.equal('block1');
            expect(files[1].stem).to.equal('block2');
            expect(files[2].stem).to.equal('block3');
        });
    });

    it('should reorder files even if no deps.js are supported but files need this', () => {
        let stream = through2.obj();
        let myBemDepsOrder = bemDepsOrder(stream);

        // fill dependencies
        fillDeps('deps-empty', stream);

        // now pipe input files
        fillInputFiles(['block1__elem', 'block1', 'block2'], myBemDepsOrder);

        return collectStreamFiles(myBemDepsOrder).then(files => {
            let blockIndex;
            let blockElemIndex;

            files.forEach((file, index) => {
                if (file.stem === 'block1') {
                    blockIndex = index;
                } else if (file.stem === 'block1__elem') {
                    blockElemIndex = index;
                }
            });

            expect(blockIndex).to.be.below(blockElemIndex);
        });
    });

    it('should reorder files in accordance to blocks dependencies', () => {

    });

    it('should reorder files even if distance to root is different', () => {

    });

    it('should reorder files even if its dependency block is not listed inside source files', () => {

    });
});
<|endoftext|>


<commit_before>/* @flow */

import { action, computed, observable } from "mobx";
import { createImmutableOutput } from "@nteract/commutable";
import { richestMimetype } from "@nteract/transforms";
import {
  escapeCarriageReturn,
  escapeCarriageReturnSafe
} from "escape-carriage";

import {
  transforms,
  displayOrder
} from "./../components/result-view/transforms";

import type { IObservableArray } from "mobx";
import type { ImmutableOutput } from "@nteract/commutable/lib/types";
import type { Output, StreamOutput } from "@nteract/commutable/lib/v4";

const outputTypes = ["execute_result", "display_data", "stream", "error"];

/**
 * https://github.com/nteract/hydrogen/issues/466#issuecomment-274822937
 * An output can be a stream of data that does not arrive at a single time. This
 * function handles the different types of outputs and accumulates the data
 * into a reduced output.
 *
 * @param {Array<Object>} outputs - Kernel output messages
 * @param {Object} output - Outputted to be reduced into list of outputs
 * @return {Array<Object>} updated-outputs - Outputs + Output
 */
export function reduceOutputs(
  outputs: Array<ImmutableOutput>,
  output: Output
): Array<any> {
  const last = outputs.length - 1;
  if (
    outputs.length > 0 &&
    output.output_type === "stream" &&
    outputs[last].get("output_type") === "stream"
  ) {
    const stream: StreamOutput = output;

    function appendText(previous: ImmutableOutput, next: StreamOutput) {
      return previous.update("text", text =>
        escapeCarriageReturnSafe(text + next.text)
      );
    }

    if (outputs[last].get("name") === stream.name) {
      outputs[last] = appendText(outputs[last], stream);
      return outputs;
    }

    if (outputs.length > 1 && outputs[last - 1].get("name") === stream.name) {
      outputs[last - 1] = appendText(outputs[last - 1], stream);
      return outputs;
    }
  }
  outputs.push(createImmutableOutput(output));
  return outputs;
}

function isSingeLine(text: string, availableSpace: number) {
  // If it turns out escapeCarriageReturn is a bottleneck, we should remove it.
  return (
    (text.indexOf("\n") === -1 || text.indexOf("\n") === text.length - 1) &&
    availableSpace > escapeCarriageReturn(text).length
  );
}

export default class OutputStore {
  outputs: IObservableArray<Object> = observable.shallowArray();
  @observable status: string = "running";
  @observable executionCount: ?number = null;
  @observable index: number = -1;
  @observable position = {
    lineHeight: 0,
    lineLength: 0,
    editorWidth: 0
  };

  @computed get isPlain(): boolean {
    if (this.outputs.length !== 1) return false;

    const availableSpace = this.position.editorWidth - this.position.lineLength;
    if (availableSpace <= 0) return false;

    const output = this.outputs[0];
    switch (output.get("output_type")) {
      case "execute_result":
      case "display_data": {
        const bundle = output.get("data");
        const mimetype = richestMimetype(bundle, displayOrder, transforms);
        return mimetype === "text/plain"
          ? isSingeLine(bundle.get(mimetype), availableSpace)
          : false;
      }
      case "stream": {
        return isSingeLine(output.get("text"), availableSpace);
      }
      default: {
        return false;
      }
    }
  }

  @action appendOutput(message: Object) {
    if (message.stream === "execution_count") {
      this.executionCount = message.data;
    } else if (message.stream === "status") {
      this.status = message.data;
    } else if (outputTypes.indexOf(message.output_type) > -1) {
      // $FlowFixMe
      this.outputs = reduceOutputs(this.outputs, message);
      this.setIndex(this.outputs.length - 1);
    }
  }

  @action updatePosition(position: {
    lineHeight?: number,
    lineLength?: number,
    editorWidth?: number
  }) {
    Object.assign(this.position, position);
  }

  @action setIndex = (index: number) => {
    this.index = index < this.outputs.length ? index : this.outputs.length - 1;
  };

  @action incrementIndex = () => {
    this.index = this.index < this.outputs.length - 1
      ? this.index + 1
      : this.outputs.length - 1;
  };

  @action decrementIndex = () => {
    this.index = this.index > 0 ? this.index - 1 : 0;
  };

  @action clear = () => {
    this.outputs.clear();
  };
}
<commit_msg>Fix clear output<commit_after>/* @flow */

import { action, computed, observable } from "mobx";
import { createImmutableOutput } from "@nteract/commutable";
import { richestMimetype } from "@nteract/transforms";
import {
  escapeCarriageReturn,
  escapeCarriageReturnSafe
} from "escape-carriage";

import {
  transforms,
  displayOrder
} from "./../components/result-view/transforms";

import type { IObservableArray } from "mobx";
import type { ImmutableOutput } from "@nteract/commutable/lib/types";
import type { Output, StreamOutput } from "@nteract/commutable/lib/v4";

const outputTypes = ["execute_result", "display_data", "stream", "error"];

/**
 * https://github.com/nteract/hydrogen/issues/466#issuecomment-274822937
 * An output can be a stream of data that does not arrive at a single time. This
 * function handles the different types of outputs and accumulates the data
 * into a reduced output.
 *
 * @param {Array<Object>} outputs - Kernel output messages
 * @param {Object} output - Outputted to be reduced into list of outputs
 * @return {Array<Object>} updated-outputs - Outputs + Output
 */
export function reduceOutputs(
  outputs: Array<ImmutableOutput>,
  output: Output
): Array<any> {
  const last = outputs.length - 1;
  if (
    outputs.length > 0 &&
    output.output_type === "stream" &&
    outputs[last].get("output_type") === "stream"
  ) {
    const stream: StreamOutput = output;

    function appendText(previous: ImmutableOutput, next: StreamOutput) {
      return previous.update("text", text =>
        escapeCarriageReturnSafe(text + next.text)
      );
    }

    if (outputs[last].get("name") === stream.name) {
      outputs[last] = appendText(outputs[last], stream);
      return outputs;
    }

    if (outputs.length > 1 && outputs[last - 1].get("name") === stream.name) {
      outputs[last - 1] = appendText(outputs[last - 1], stream);
      return outputs;
    }
  }
  outputs.push(createImmutableOutput(output));
  return outputs;
}

function isSingeLine(text: string, availableSpace: number) {
  // If it turns out escapeCarriageReturn is a bottleneck, we should remove it.
  return (
    (text.indexOf("\n") === -1 || text.indexOf("\n") === text.length - 1) &&
    availableSpace > escapeCarriageReturn(text).length
  );
}

export default class OutputStore {
  outputs: IObservableArray<Object> = observable.shallowArray();
  @observable status: string = "running";
  @observable executionCount: ?number = null;
  @observable index: number = -1;
  @observable position = {
    lineHeight: 0,
    lineLength: 0,
    editorWidth: 0
  };

  @computed get isPlain(): boolean {
    if (this.outputs.length !== 1) return false;

    const availableSpace = this.position.editorWidth - this.position.lineLength;
    if (availableSpace <= 0) return false;

    const output = this.outputs[0];
    switch (output.get("output_type")) {
      case "execute_result":
      case "display_data": {
        const bundle = output.get("data");
        const mimetype = richestMimetype(bundle, displayOrder, transforms);
        return mimetype === "text/plain"
          ? isSingeLine(bundle.get(mimetype), availableSpace)
          : false;
      }
      case "stream": {
        return isSingeLine(output.get("text"), availableSpace);
      }
      default: {
        return false;
      }
    }
  }

  @action appendOutput(message: Object) {
    if (message.stream === "execution_count") {
      this.executionCount = message.data;
    } else if (message.stream === "status") {
      this.status = message.data;
    } else if (outputTypes.indexOf(message.output_type) > -1) {
      // $FlowFixMe
      this.outputs = reduceOutputs(this.outputs, message);
      this.setIndex(this.outputs.length - 1);
    }
  }

  @action updatePosition(position: {
    lineHeight?: number,
    lineLength?: number,
    editorWidth?: number
  }) {
    Object.assign(this.position, position);
  }

  @action setIndex = (index: number) => {
    this.index = index < this.outputs.length ? index : this.outputs.length - 1;
  };

  @action incrementIndex = () => {
    this.index = this.index < this.outputs.length - 1
      ? this.index + 1
      : this.outputs.length - 1;
  };

  @action decrementIndex = () => {
    this.index = this.index > 0 ? this.index - 1 : 0;
  };

  @action clear = () => {
    this.outputs.clear();
    this.index = -1;
  };
}
<|endoftext|>


<commit_before>(function(root) {
  var common = typeof module != 'undefined' && !!module.exports;
  var aok = common ? require('aok') : root.aok;
  var lap = common ? require('../src') : root.lap;
  var spy = surveil();
  if (![].some) aok.prototype.express = aok.info; // alert in ie8-

  /**
   * @param {{length:number}} stack
   * @param {string} type
   * @return {boolean}
   */
  function are(stack, type) {
    return !aok.fail(stack, function(v) {
      return typeof v === type;
    }, stack, 1);
  }

  /**
   * @param {*} o value to test
   * @param {!(number|Array)=} of expected length
   * @param {string=} type expected type for values
   * @return {boolean}
   */
  function isArray(o, of, type) {
    if (Array.isArray ? !Array.isArray(o) : !o) return false;
    if (o.length !== (of === +of ? of : isArray(of) ? of.length : +o.length)) return false;
    return !type || are(o, type);
  }

  /**
   * @param {Array} a
   * @return {boolean}
   */
  function ascends(a) {
    return a.join() === a.slice().sort().join();
  }

  function faster() {}
  function slower() {
    return +new Date;
  }

  /**
   * @param {Function=} fn
   * @return {Function}
   */
  function surveil(fn) {
    var did = 0, spy = function() {
      ++did;
      return !fn || fn.apply(this, arguments);
    };
    spy.reset = function(to) {
      did = to === +to ? to : 0;
    };
    spy.ran = function(expected) {
      return null == expected ? 0 < did : expected === did;
    };
    return spy;
  }

  /**
   * @param {string} method
   * @param {number} laps
   * @param {Array|Function} racers
   * @return {boolean}
   */
  function verify(method, laps, racers) {
    spy.reset();
    var field = typeof racers == 'function' ? 1 : racers.length;
    var output = lap[method](laps, racers);
    var bool = racers !== output && isArray(output, field, 'number') && spy.ran(laps*field);
    spy.reset();
    return bool;
  }

  aok('methods', !aok.fail(['timestamp', 'time', 'speed'], function(m) {
    return lap[m] && lap[m].sync && lap[m].async;
  }, aok, 1));

  aok('timestamp()', typeof lap.timestamp() == 'number' && lap.timestamp() > 0);
  aok('time(laps, fn)', verify('time', 1e3, spy));
  aok('time(laps, racers) ', verify('time', 1e3, [spy, spy]));
  aok('speed(laps, fn)', verify('speed', 1e3, spy));
  aok('speed(laps, racers)', verify('speed', 1e3, [spy, spy]));
  aok('ascends', ascends([0, 1, 1]) && ascends([0, 1]) && !ascends([2, 1]) && !ascends([1, 0, 1]));
  aok('logical times', ascends(lap.time(1e5, [faster, slower])));
  aok('logical speeds', ascends(lap.speed(1e5, [slower, faster])));

  lap.time.async(1e3, spy, function(err, result) {
    aok('async result', !err && isArray(result, 1, 'number'));
  });

  lap.time.async(1e3, function() {
    throw new Error;
  }, function(err) {
    aok('async error', !!err);
  });
}(this));<commit_msg>"logical" tests need hi-res accuracy in order to work over short timeframes<commit_after>(function(root) {
  var common = typeof module != 'undefined' && !!module.exports;
  var aok = common ? require('aok') : root.aok;
  var lap = common ? require('../src') : root.lap;
  var spy = surveil();
  var hires = lap.timestamp() < lap.timestamp(); // process.hrtime
  if (![].some) aok.prototype.express = aok.info; // alert in ie8-

  /**
   * @param {{length:number}} stack
   * @param {string} type
   * @return {boolean}
   */
  function are(stack, type) {
    return !aok.fail(stack, function(v) {
      return typeof v === type;
    }, stack, 1);
  }

  /**
   * @param {*} o value to test
   * @param {!(number|Array)=} of expected length
   * @param {string=} type expected type for values
   * @return {boolean}
   */
  function isArray(o, of, type) {
    if (Array.isArray ? !Array.isArray(o) : !o) return false;
    if (o.length !== (of === +of ? of : isArray(of) ? of.length : +o.length)) return false;
    return !type || are(o, type);
  }

  /**
   * @param {Array} a
   * @return {boolean}
   */
  function ascends(a) {
    return a.join() === a.slice().sort().join();
  }

  /**
   * @param {Function=} fn
   * @return {Function}
   */
  function surveil(fn) {
    var did = 0, spy = function() {
      ++did;
      return !fn || fn.apply(this, arguments);
    };
    spy.reset = function(to) {
      did = to === +to ? to : 0;
    };
    spy.ran = function(expected) {
      return null == expected ? 0 < did : expected === did;
    };
    return spy;
  }

  /**
   * @param {string} method
   * @param {number} laps
   * @param {Array|Function} racers
   * @return {boolean}
   */
  function verify(method, laps, racers) {
    spy.reset();
    var field = typeof racers == 'function' ? 1 : racers.length;
    var output = lap[method](laps, racers);
    var bool = racers !== output && isArray(output, field, 'number') && spy.ran(laps*field);
    spy.reset();
    return bool;
  }

  /**
   * @param {string} method
   * @param {number} laps
   * @param {Array|Function} racers
   * @param {Function} test
   * @return {boolean}
   */
  function tends(method, laps, racers, test) {
    var samples = 64, i = samples, enough = samples - Math.sqrt(samples), tally = 0;
    while (i--) if (test(lap[method](laps, racers)) && ++tally >= enough) return true;
    return false;
  }

  aok('methods', !aok.fail(['timestamp', 'time', 'speed'], function(m) {
    return lap[m] && lap[m].sync && lap[m].async;
  }, aok, 1));

  aok('timestamp()', typeof lap.timestamp() == 'number' && lap.timestamp() > 0);
  aok('time(laps, fn)', verify('time', 1e3, spy));
  aok('time(laps, racers) ', verify('time', 1e3, [spy, spy]));
  aok('speed(laps, fn)', verify('speed', 1e3, spy));
  aok('speed(laps, racers)', verify('speed', 1e3, [spy, spy]));
  aok('ascends', ascends([0, 1, 1]) && ascends([0, 1]) && !ascends([2, 1]) && !ascends([1, 0, 1]));

  hires && setTimeout(function() {
    function faster() {}
    function slower() {
      return [+new Date].concat(1);
    }
    aok('logical times', tends('time', 1e4, [faster, slower], ascends));
    aok('logical speeds', tends('speed', 1e4, [slower, faster], ascends));
  }, 0);

  lap.time.async(1e3, spy, function(err, result) {
    aok('async result', !err && isArray(result, 1, 'number'));
  });

  lap.time.async(1e3, function() {
    throw new Error;
  }, function(err) {
    aok('async error', !!err);
  });
}(this));<|endoftext|>


<commit_before>'use strict'
var _ = require('lodash')
var assert = require('assert')
var final = require('..')
var http = require('http')
var sinon = require('sinon')

describe('final', () => {
  var commandCore = (options) => {
    return _.parseInt(options.first) + (_.parseInt(options.second) || 0)
  }

  var commandOptions = {
    first: {
      description: 'first number to add',
      required: true
    },
    second: {
      description: 'second number to add'
    }
  }

  var command = new final.Command(commandCore, commandOptions)

  var options = { first: 1, second: 2 }
  var stringOptions = _.mapValues(options, String)

  describe('Command', () => {
    var greeting = 'Hello, world!'
    var simpleCommandCore = () => greeting
    var simpleCommand = new final.Command(simpleCommandCore)

    describe('constructor', () => {
      context('for a command without options', () => {
        it('uses the given core', () => {
          assert.strictEqual(simpleCommand.core, simpleCommandCore)
        })

        it('doesn\'t use any options', () => {
          assert.strictEqual(simpleCommand.options, undefined)
        })
      })

      context('for a command with required and optional options', () => {
        it('uses the given core', () => {
          assert.strictEqual(command.core, commandCore)
        })

        it('uses the given options', () => {
          assert.deepStrictEqual(command.options, commandOptions)
        })
      })
    })

    describe('#run()', () => {
      context('for a command without options', () => {
        context('given empty options', () => {
          it('returns a String result', () => {
            assert.strictEqual(simpleCommand.run({}), greeting)
          })
        })

        context('given any option', () => {
          it('returns a String result', () => {
            assert.strictEqual(simpleCommand.run({ extra: true }), greeting)
          })
        })
      })

      context('for a command with required and optional options', () => {
        context('given empty options', () => {
          it('throws a ValidationError', () => {
            assert.throws(() => command.run({}), final.ValidationError)
          })
        })

        context('given only the required option', () => {
          it('returns a String result', () => {
            assert.strictEqual(command.run({ first: 1 }), '1')
          })
        })

        context('given only the optional option', () => {
          it('throws a ValidationError', () => {
            assert.throws(() => command.run({ second: 2 }), final.ValidationError)
          })
        })

        context('given both options', () => {
          it('returns a String result', () => {
            assert.strictEqual(command.run(options), '3')
          })
        })

        context('given an invalid option', () => {
          it('throws a ValidationError', () => {
            assert.throws(() => command.run({ first: 1, invalid: true }), final.ValidationError)
          })
        })
      })
    })

    describe('#validate()', () => {
      context('for a command without options', () => {
        context('given empty options', () => {
          it('returns no errors', () => {
            assert.deepStrictEqual(simpleCommand.validate(new Set([])), new Set([]))
          })
        })

        context('given any option', () => {
          it('returns no errors', () => {
            assert.deepStrictEqual(simpleCommand.validate(new Set(['extra'])), new Set([]))
          })
        })
      })

      context('for a command with required and optional options', () => {
        context('given empty options', () => {
          it('returns a MissingOptionError', () => {
            assert.deepStrictEqual(command.validate(new Set([])), new Set([new final.MissingOptionError('first')]))
          })
        })

        context('given only the required option', () => {
          it('returns no errors', () => {
            assert.deepStrictEqual(command.validate(new Set(['first'])), new Set([]))
          })
        })

        context('given only the optional option', () => {
          it('returns a MissingOptionError', () => {
            assert.deepStrictEqual(command.validate(new Set(['second'])), new Set([new final.MissingOptionError('first')]))
          })
        })

        context('given both options', () => {
          it('returns no errors', () => {
            assert.deepStrictEqual(command.validate(new Set(['first', 'second'])), new Set([]))
          })
        })

        context('given the required option and an invalid option', () => {
          it('returns an InvalidOptionError', () => {
            assert.deepStrictEqual(command.validate(new Set(['first', 'invalid'])), new Set([new final.InvalidOptionError('invalid')]))
          })
        })
      })
    })
  })

  describe('Runner', () => {
    describe('constructor', () => {
      it('uses the given command', () => {
        assert.strictEqual(new final.Runner(command).command, command)
      })
    })
  })

  describe('API', () => {
    var api = new final.API(command)

    var req = new http.IncomingMessage()
    req.url = 'http://localhost:3000?first=1&second=2'

    after(() => api.close())

    describe('constructor', () => {
      it('creates a server', () => {
        assert(api.server instanceof http.Server)
      })
    })

    describe('#callback()', () => {
      it('is a function', () => {
        assert(api.callback instanceof Function)
      })

      it('takes a request and a response', () => {
        assert.strictEqual(api.callback.length, 2)
      })
    })

    describe('#close()', () => {
      it('closes the server', (done) => {
        api.close()

        http.get('http://localhost:3000', () =>
          done('Error: API server should be closed')
        ).on('error', () => done())
      })
    })

    describe('.options()', () => {
      it('returns options from the given request', () => {
        assert.deepStrictEqual(final.API.options(req), stringOptions)
      })
    })

    describe('#run()', () => {
      var res

      function run (done) {
        api.run()
        http.get(req.url, (thisRes) => {
          res = thisRes
          done()
        }).on('error', done)
      }

      it('runs its server for the given command', run)

      describe('response', () => {
        before(run)

        it('has a 200 status code', () => {
          assert.strictEqual(res.statusCode, 200)
        })

        it('has a text/plain content type', () => {
          assert.strictEqual(res.headers['content-type'], 'text/plain')
        })

        it('has a body with a result', (done) => {
          res.on('data', (chunk) => {
            assert.strictEqual(chunk.toString('utf8'), '3\n')
            done()
          })
        })
      })
    })
  })

  describe('CLI', () => {
    var args
    var cli = new final.CLI(command)

    before(() => { args = 'node cli.js --first 1 --second 2' })
    beforeEach(() => { process.argv = args.split(' ') })

    describe('#help()', () => {
      it('returns formatted help text', () => {
        var expected = [
          'Usage: cli [options]',
          '',
          'Options:',
          '',
          '  --help               output usage information',
          '  --first              first number to add',
          '  --second             second number to add'
        ].join('\n')

        assert.strictEqual(cli.help(), expected)
      })
    })

    describe('.options()', () => {
      it('returns options from argv', () => {
        assert.deepStrictEqual(final.CLI.options(), options)
      })
    })

    describe('#run()', () => {
      context('without the help flag', () => {
        it('runs a cli for the given command that prints a result', sinon.test(function () {
          this.stub(console, 'log')
          cli.run()

          sinon.assert.calledOnce(console.log)
          sinon.assert.calledWithExactly(console.log, '3')
        }))
      })

      context('with the help flag', () => {
        before(() => { args = 'node cli.js --help' })

        it('runs a cli for the given command that prints usage information')
      })
    })
  })
})
<commit_msg>Fix a comparison<commit_after>'use strict'
var _ = require('lodash')
var assert = require('assert')
var final = require('..')
var http = require('http')
var sinon = require('sinon')

describe('final', () => {
  var commandCore = (options) => {
    return _.parseInt(options.first) + (_.parseInt(options.second) || 0)
  }

  var commandOptions = {
    first: {
      description: 'first number to add',
      required: true
    },
    second: {
      description: 'second number to add'
    }
  }

  var command = new final.Command(commandCore, commandOptions)

  var options = { first: 1, second: 2 }
  var stringOptions = _.mapValues(options, String)

  describe('Command', () => {
    var greeting = 'Hello, world!'
    var simpleCommandCore = () => greeting
    var simpleCommand = new final.Command(simpleCommandCore)

    describe('constructor', () => {
      context('for a command without options', () => {
        it('uses the given core', () => {
          assert.strictEqual(simpleCommand.core, simpleCommandCore)
        })

        it('doesn\'t use any options', () => {
          assert.strictEqual(simpleCommand.options, undefined)
        })
      })

      context('for a command with required and optional options', () => {
        it('uses the given core', () => {
          assert.strictEqual(command.core, commandCore)
        })

        it('uses the given options', () => {
          assert.deepStrictEqual(command.options, commandOptions)
        })
      })
    })

    describe('#run()', () => {
      context('for a command without options', () => {
        context('given empty options', () => {
          it('returns a String result', () => {
            assert.strictEqual(simpleCommand.run({}), greeting)
          })
        })

        context('given any option', () => {
          it('returns a String result', () => {
            assert.strictEqual(simpleCommand.run({ extra: true }), greeting)
          })
        })
      })

      context('for a command with required and optional options', () => {
        context('given empty options', () => {
          it('throws a ValidationError', () => {
            assert.throws(() => command.run({}), final.ValidationError)
          })
        })

        context('given only the required option', () => {
          it('returns a String result', () => {
            assert.strictEqual(command.run({ first: 1 }), '1')
          })
        })

        context('given only the optional option', () => {
          it('throws a ValidationError', () => {
            assert.throws(() => command.run({ second: 2 }), final.ValidationError)
          })
        })

        context('given both options', () => {
          it('returns a String result', () => {
            assert.strictEqual(command.run(options), '3')
          })
        })

        context('given an invalid option', () => {
          it('throws a ValidationError', () => {
            assert.throws(() => command.run({ first: 1, invalid: true }), final.ValidationError)
          })
        })
      })
    })

    describe('#validate()', () => {
      context('for a command without options', () => {
        context('given empty options', () => {
          it('returns no errors', () => {
            assert.deepStrictEqual(simpleCommand.validate(new Set([])), new Set([]))
          })
        })

        context('given any option', () => {
          it('returns no errors', () => {
            assert.deepStrictEqual(simpleCommand.validate(new Set(['extra'])), new Set([]))
          })
        })
      })

      context('for a command with required and optional options', () => {
        context('given empty options', () => {
          it('returns a MissingOptionError', () => {
            assert.deepStrictEqual(command.validate(new Set([])), new Set([new final.MissingOptionError('first')]))
          })
        })

        context('given only the required option', () => {
          it('returns no errors', () => {
            assert.deepStrictEqual(command.validate(new Set(['first'])), new Set([]))
          })
        })

        context('given only the optional option', () => {
          it('returns a MissingOptionError', () => {
            assert.deepStrictEqual(command.validate(new Set(['second'])), new Set([new final.MissingOptionError('first')]))
          })
        })

        context('given both options', () => {
          it('returns no errors', () => {
            assert.deepStrictEqual(command.validate(new Set(['first', 'second'])), new Set([]))
          })
        })

        context('given the required option and an invalid option', () => {
          it('returns an InvalidOptionError', () => {
            assert.deepStrictEqual(command.validate(new Set(['first', 'invalid'])), new Set([new final.InvalidOptionError('invalid')]))
          })
        })
      })
    })
  })

  describe('Runner', () => {
    describe('constructor', () => {
      it('uses the given command', () => {
        assert.strictEqual(new final.Runner(command).command, command)
      })
    })
  })

  describe('API', () => {
    var api = new final.API(command)

    var req = new http.IncomingMessage()
    req.url = 'http://localhost:3000?first=1&second=2'

    after(() => api.close())

    describe('constructor', () => {
      it('creates a server', () => {
        assert(api.server instanceof http.Server)
      })
    })

    describe('#callback()', () => {
      it('is a function', () => {
        assert(api.callback instanceof Function)
      })

      it('takes a request and a response', () => {
        assert.strictEqual(api.callback.length, 2)
      })
    })

    describe('#close()', () => {
      it('closes the server', (done) => {
        api.close()

        http.get('http://localhost:3000', () =>
          done('Error: API server should be closed')
        ).on('error', () => done())
      })
    })

    describe('.options()', () => {
      it('returns options from the given request', () => {
        assert.deepEqual(final.API.options(req), stringOptions)
      })
    })

    describe('#run()', () => {
      var res

      function run (done) {
        api.run()
        http.get(req.url, (thisRes) => {
          res = thisRes
          done()
        }).on('error', done)
      }

      it('runs its server for the given command', run)

      describe('response', () => {
        before(run)

        it('has a 200 status code', () => {
          assert.strictEqual(res.statusCode, 200)
        })

        it('has a text/plain content type', () => {
          assert.strictEqual(res.headers['content-type'], 'text/plain')
        })

        it('has a body with a result', (done) => {
          res.on('data', (chunk) => {
            assert.strictEqual(chunk.toString('utf8'), '3\n')
            done()
          })
        })
      })
    })
  })

  describe('CLI', () => {
    var args
    var cli = new final.CLI(command)

    before(() => { args = 'node cli.js --first 1 --second 2' })
    beforeEach(() => { process.argv = args.split(' ') })

    describe('#help()', () => {
      it('returns formatted help text', () => {
        var expected = [
          'Usage: cli [options]',
          '',
          'Options:',
          '',
          '  --help               output usage information',
          '  --first              first number to add',
          '  --second             second number to add'
        ].join('\n')

        assert.strictEqual(cli.help(), expected)
      })
    })

    describe('.options()', () => {
      it('returns options from argv', () => {
        assert.deepStrictEqual(final.CLI.options(), options)
      })
    })

    describe('#run()', () => {
      context('without the help flag', () => {
        it('runs a cli for the given command that prints a result', sinon.test(function () {
          this.stub(console, 'log')
          cli.run()

          sinon.assert.calledOnce(console.log)
          sinon.assert.calledWithExactly(console.log, '3')
        }))
      })

      context('with the help flag', () => {
        before(() => { args = 'node cli.js --help' })

        it('runs a cli for the given command that prints usage information')
      })
    })
  })
})
<|endoftext|>


<commit_before>require('should');
var debug = require('debug')('register-handlers')
var registerHandlers = require('../index');
var sinon = require('sinon');

var bus = {
  listen: sinon.spy(),
  subscribe: sinon.spy()
};

var mockbus = {
  listen: function (key, event) {
    this.queues[key] = {
      listening: false,
      on: function () {}
    };
    bus.listen(key, event);
  },
  on: function () {},
  subscribe: function (key, event) {
    this.pubsubqueues[key] = {
      listening: false,
      on: function () {}
    };
    bus.subscribe(key, event);
  },
  queues: {},
  pubsubqueues: {},
  correlationId: function () {}
}

var mockMessage = {
  fields: {
    queueName: 'queue',
    routingKey: 'r.k'
  },
  properties: {
    correlationId: '1'
  }
}

var mockMsg = {
  handle: {
    ack: function () {}
  }
}

describe('register-handlers', function () {
  it('should register simple listen', function () {

    var registered = registerHandlers({
      bus: mockbus,
      handlers: [ {
        listen: function () {}
      }]
    });

  });

  it('should register simple subscribe', function () {

    var registered = registerHandlers({
      bus: mockbus,
      handlers: [ {
        subscribe: function () {}
      }]
    });

  });

  it('should register entire folder', function () {
    var registered = registerHandlers({
      bus: mockbus,
      path: './test/support'
    });

    registered.pipelines.should.have.property('one');
    registered.pipelines['one'].should.have.property('size', 2);

    registered.pipelines.should.have.property('two.*');
    registered.pipelines['two.*'].should.have.property('size', 1);

    registered.pipelines.should.have.property('four-five');
    registered.pipelines['four-five'].should.have.property('size', 2);

  });

  it('should register globbed folders', function () {
    var registered = registerHandlers({
      bus: mockbus,
      path: './test/support/**/*'
    });

    registered.pipelines.should.have.property('one');
    registered.pipelines['one'].should.have.property('size', 2);

    registered.pipelines.should.have.property('two.*');
    registered.pipelines['two.*'].should.have.property('size', 1);

    registered.pipelines.should.have.property('four-five');
    registered.pipelines['four-five'].should.have.property('size', 2);

    registered.pipelines.should.have.property('six');
    registered.pipelines['six'].should.have.property('size', 1);

  });

  it('simplified api should map to correct values and default ack to true', function () {
    var registered = registerHandlers({
      bus: mockbus,
      path: './test/support/api'
    });

    registered.pipelines.should.have.property('domain.command');
    registered.pipelines['domain.command'].should.have.property('queueName', 'domain.command');
    registered.pipelines['domain.command'].should.have.property('size', 1);

    registered.pipelines.should.have.property('domain.event');
    registered.pipelines['domain.event'].should.have.property('routingKey', 'domain.event');
    registered.pipelines['domain.event'].should.have.property('size', 1);
  });

  it('Handler constructor options', () => {
    var routingKeyHandler = new registerHandlers.Handler({
      routingKey: 'r.k',
      subscribe: function(){}
    })
    routingKeyHandler.should.have.property('routingKey', 'r.k')
    routingKeyHandler.should.have.property('ack', undefined)

    var eventHandler = new registerHandlers.Handler({
      event: 'r.k',
      subscribe: function(){}
    })
    eventHandler.should.have.property('routingKey', 'r.k')
    eventHandler.should.have.property('ack', true)

    var queueNameHandler = new registerHandlers.Handler({
      queueName: 'q.n',
      listen: function(){}
    })
    queueNameHandler.should.have.property('queueName', 'q.n')
    queueNameHandler.should.have.property('ack', undefined)

    var commandHandler = new registerHandlers.Handler({
      command: 'q.n',
      listen: function(){}
    })
    commandHandler.should.have.property('queueName', 'q.n')
    commandHandler.should.have.property('ack', true)
  })

  it('exposes the bus, queueName, routingKey, and correlationId to the handler', (done) => {
    var registered = registerHandlers({
      bus: mockbus,
      handlers: [ {
        listen: function () {
          this.should.have.property('bus')
          this.should.have.property('queueName', mockMessage.fields.queueName)
          this.should.have.property('routingKey', mockMessage.fields.routingKey)
          this.should.have.property('correlationId', mockMessage.properties.correlationId)
          done()
        }
      }]
    });

    // handleIncomingMessage calls listen when bound to a context
    registered.pipelines[undefined].handleIncomingMessage(mockMsg, mockMessage)
  })

});<commit_msg>test: should be able to call publish from handler<commit_after>require('should');
var debug = require('debug')('register-handlers')
var registerHandlers = require('../index');
var sinon = require('sinon');

var bus = {
  listen: sinon.spy(),
  subscribe: sinon.spy()
};

var mockbus = {
  listen: function (key, event) {
    this.queues[key] = {
      listening: false,
      on: function () {}
    };
    bus.listen(key, event);
  },
  on: function () {},
  subscribe: function (key, event) {
    this.pubsubqueues[key] = {
      listening: false,
      on: function () {}
    };
    bus.subscribe(key, event);
  },
  queues: {},
  pubsubqueues: {},
  correlationId: function () {},
  publish: function (key, event, done) {
    done()
  }
}

var mockMessage = {
  fields: {
    queueName: 'queue',
    routingKey: 'r.k'
  },
  properties: {
    correlationId: '1'
  }
}

var mockMsg = {
  handle: {
    ack: function () {}
  }
}

describe('register-handlers', function () {
  it('should register simple listen', function () {

    var registered = registerHandlers({
      bus: mockbus,
      handlers: [ {
        listen: function () {}
      }]
    });

  });

  it('should register simple subscribe', function () {

    var registered = registerHandlers({
      bus: mockbus,
      handlers: [ {
        subscribe: function () {}
      }]
    });

  });

  it('should register entire folder', function () {
    var registered = registerHandlers({
      bus: mockbus,
      path: './test/support'
    });

    registered.pipelines.should.have.property('one');
    registered.pipelines['one'].should.have.property('size', 2);

    registered.pipelines.should.have.property('two.*');
    registered.pipelines['two.*'].should.have.property('size', 1);

    registered.pipelines.should.have.property('four-five');
    registered.pipelines['four-five'].should.have.property('size', 2);

  });

  it('should register globbed folders', function () {
    var registered = registerHandlers({
      bus: mockbus,
      path: './test/support/**/*'
    });

    registered.pipelines.should.have.property('one');
    registered.pipelines['one'].should.have.property('size', 2);

    registered.pipelines.should.have.property('two.*');
    registered.pipelines['two.*'].should.have.property('size', 1);

    registered.pipelines.should.have.property('four-five');
    registered.pipelines['four-five'].should.have.property('size', 2);

    registered.pipelines.should.have.property('six');
    registered.pipelines['six'].should.have.property('size', 1);

  });

  it('simplified api should map to correct values and default ack to true', function () {
    var registered = registerHandlers({
      bus: mockbus,
      path: './test/support/api'
    });

    registered.pipelines.should.have.property('domain.command');
    registered.pipelines['domain.command'].should.have.property('queueName', 'domain.command');
    registered.pipelines['domain.command'].should.have.property('size', 1);

    registered.pipelines.should.have.property('domain.event');
    registered.pipelines['domain.event'].should.have.property('routingKey', 'domain.event');
    registered.pipelines['domain.event'].should.have.property('size', 1);
  });

  it('Handler constructor options', () => {
    var routingKeyHandler = new registerHandlers.Handler({
      routingKey: 'r.k',
      subscribe: function(){}
    })
    routingKeyHandler.should.have.property('routingKey', 'r.k')
    routingKeyHandler.should.have.property('ack', undefined)

    var eventHandler = new registerHandlers.Handler({
      event: 'r.k',
      subscribe: function(){}
    })
    eventHandler.should.have.property('routingKey', 'r.k')
    eventHandler.should.have.property('ack', true)

    var queueNameHandler = new registerHandlers.Handler({
      queueName: 'q.n',
      listen: function(){}
    })
    queueNameHandler.should.have.property('queueName', 'q.n')
    queueNameHandler.should.have.property('ack', undefined)

    var commandHandler = new registerHandlers.Handler({
      command: 'q.n',
      listen: function(){}
    })
    commandHandler.should.have.property('queueName', 'q.n')
    commandHandler.should.have.property('ack', true)
  })

  it('exposes the bus, queueName, routingKey, and correlationId to the handler, and can call bus.publish', (done) => {
    var registered = registerHandlers({
      bus: mockbus,
      handlers: [ {
        listen: function () {
          this.should.have.property('bus')
          this.should.have.property('queueName', mockMessage.fields.queueName)
          this.should.have.property('routingKey', mockMessage.fields.routingKey)
          this.should.have.property('correlationId', mockMessage.properties.correlationId)

          this.bus.publish(null,null,done)
        }
      }]
    });

    // handleIncomingMessage calls listen when bound to a context
    registered.pipelines[undefined].handleIncomingMessage(mockMsg, mockMessage)
  })

});<|endoftext|>