<commit_before>'use strict';
var expect = require('chai').expect;
var mockery = require('mockery');

describe('Modbus RTU buffered port', function() {
    var port;

    before(function() {
        var mock = require('./../mocks/SerialPortMock');
        mockery.resetCache();
        mockery.enable({warnOnReplace:false, useCleanCache:true, warnOnUnregistered:false});
        mockery.registerMock('serialport', mock);
        var RTUBufferedPort = require('./../../ports/rtubufferedport');
        port = new RTUBufferedPort('/dev/null', {});
    });

    after(function() {
        mockery.disable();
    });

    afterEach(function() {
        port.close();
    });

    describe('#isOpen', function() {
        it('should not be open before #open', function() {
           expect(port.isOpen()).to.be.false;
        });

        it('should be open after #open', function(done) {
            port.open(function() {
                expect(port.isOpen()).to.be.true;
                done();
            });
        });

        it('should not be open after #close', function(done) {
            port.open(function() {
                port.close(function() {
                    expect(port.isOpen()).to.be.false;
                    done();
                });
            });
        });
    });

    describe('data handler', function() {
        it('should return a valid Modbus RTU message', function(done) {
            port.once('data', function(data) {
                expect(data.toString('hex')).to.equal('110306ae415652434049ad');
                done();
            });
            port.open(function() {
                port.write(new Buffer('1103006B00037687', 'hex'));
                setTimeout(function() {
                    port._client.receive(new Buffer('11', 'hex'));
                    port._client.receive(new Buffer('03', 'hex'));
                    port._client.receive(new Buffer('06', 'hex'));
                    port._client.receive(new Buffer('ae', 'hex'));
                    port._client.receive(new Buffer('41', 'hex'));
                    port._client.receive(new Buffer('56', 'hex'));
                    port._client.receive(new Buffer('52', 'hex'));
                    port._client.receive(new Buffer('43', 'hex'));
                    port._client.receive(new Buffer('40', 'hex'));
                    port._client.receive(new Buffer('49', 'hex'));
                    port._client.receive(new Buffer('ad', 'hex'));
                });
            });
        });

        it('should return a valid Modbus RTU exception', function(done) {
            port.once('data', function(data) {
                expect(data.toString('hex')).to.equal('1183044136');
                done();
            });
            port.open(function() {
                port.write(new Buffer('1103006B00037687', 'hex'));
                setTimeout(function() {
                    port._client.receive(new Buffer('11', 'hex'));
                    port._client.receive(new Buffer('83', 'hex'));
                    port._client.receive(new Buffer('04', 'hex'));
                    port._client.receive(new Buffer('41', 'hex'));
                    port._client.receive(new Buffer('36', 'hex'));
                });
            });
        });
    });

    describe('#write', function() {
        it('should write a valid RTU message to the port', function() {
            port.write(new Buffer('1103006B00037687', 'hex'));
            expect(port._client._data.toString('hex')).to.equal('1103006b00037687');
        });
    });

});
<commit_msg>Extented buffer tests<commit_after>'use strict';
var expect = require('chai').expect;
var mockery = require('mockery');

describe('Modbus RTU buffered port', function() {
    var port;

    before(function() {
        var mock = require('./../mocks/SerialPortMock');
        mockery.resetCache();
        mockery.enable({warnOnReplace:false, useCleanCache:true, warnOnUnregistered:false});
        mockery.registerMock('serialport', mock);
        var RTUBufferedPort = require('./../../ports/rtubufferedport');
        port = new RTUBufferedPort('/dev/null', {});
    });

    after(function() {
        mockery.disable();
    });

    afterEach(function() {
        port.close();
    });

    describe('#isOpen', function() {
        it('should not be open before #open', function() {
           expect(port.isOpen()).to.be.false;
        });

        it('should be open after #open', function(done) {
            port.open(function() {
                expect(port.isOpen()).to.be.true;
                done();
            });
        });

        it('should not be open after #close', function(done) {
            port.open(function() {
                port.close(function() {
                    expect(port.isOpen()).to.be.false;
                    done();
                });
            });
        });
    });

    describe('data handler', function() {
        it('should return a valid Modbus RTU message', function(done) {
            port.once('data', function(data) {
                expect(data.toString('hex')).to.equal('110306ae415652434049ad');
                done();
            });
            port.open(function() {
                port.write(new Buffer('1103006B00037687', 'hex'));
                setTimeout(function() {
                    port._client.receive(new Buffer('11', 'hex'));
                    port._client.receive(new Buffer('03', 'hex'));
                    port._client.receive(new Buffer('06', 'hex'));
                    port._client.receive(new Buffer('ae', 'hex'));
                    port._client.receive(new Buffer('41', 'hex'));
                    port._client.receive(new Buffer('56', 'hex'));
                    port._client.receive(new Buffer('52', 'hex'));
                    port._client.receive(new Buffer('43', 'hex'));
                    port._client.receive(new Buffer('40', 'hex'));
                    port._client.receive(new Buffer('49', 'hex'));
                    port._client.receive(new Buffer('ad', 'hex'));
                });
            });
        });

        it('should return a valid Modbus RTU exception', function(done) {
            port.once('data', function(data) {
                expect(data.toString('hex')).to.equal('1183044136');
                done();
            });
            port.open(function() {
                port.write(new Buffer('1103006B00037687', 'hex'));
                setTimeout(function() {
                    port._client.receive(new Buffer('11', 'hex'));
                    port._client.receive(new Buffer('83', 'hex'));
                    port._client.receive(new Buffer('04', 'hex'));
                    port._client.receive(new Buffer('41', 'hex'));
                    port._client.receive(new Buffer('36', 'hex'));
                });
            });
        });

                it('Special data package, should return a valid Modbus RTU message', function(done) {
            port.once('data', function(data) {
                expect(data.toString('hex')).to.equal('010380018301830183018301830183018301830183018301830183018301830183018301830183018301830183018301830183018301830183018301830183018301830183018301830183018301830183018301830183018301830183018301830183018301830183018301830183018301830183018301830183018301830183018346e0');
                done();
            });
            port.open(function() {
                port.write(new Buffer('010300000040443A', 'hex'));
                setTimeout(function() {
                    port._client.receive(new Buffer('01', 'hex'));
                    port._client.receive(new Buffer('03', 'hex'));
                    port._client.receive(new Buffer('80', 'hex'));
                    port._client.receive(new Buffer('01', 'hex'));
                    port._client.receive(new Buffer('83', 'hex'));
                    port._client.receive(new Buffer('01', 'hex'));
                    port._client.receive(new Buffer('83', 'hex'));
                    port._client.receive(new Buffer('01', 'hex'));
                    port._client.receive(new Buffer('83', 'hex'));
                    port._client.receive(new Buffer('01', 'hex'));
                    port._client.receive(new Buffer('83', 'hex'));
                    port._client.receive(new Buffer('01', 'hex'));
                    port._client.receive(new Buffer('83', 'hex'));
                    port._client.receive(new Buffer('01', 'hex'));
                    port._client.receive(new Buffer('83', 'hex'));
                    port._client.receive(new Buffer('01', 'hex'));
                    port._client.receive(new Buffer('83', 'hex'));
                    port._client.receive(new Buffer('01', 'hex'));
                    port._client.receive(new Buffer('83', 'hex'));
                    port._client.receive(new Buffer('01', 'hex'));
                    port._client.receive(new Buffer('83', 'hex'));
                    port._client.receive(new Buffer('01', 'hex'));
                    port._client.receive(new Buffer('83', 'hex'));
                    port._client.receive(new Buffer('01', 'hex'));
                    port._client.receive(new Buffer('83', 'hex'));
                    port._client.receive(new Buffer('01', 'hex'));
                    port._client.receive(new Buffer('83', 'hex'));
                    port._client.receive(new Buffer('01', 'hex'));
                    port._client.receive(new Buffer('83', 'hex'));
                    port._client.receive(new Buffer('01', 'hex'));
                    port._client.receive(new Buffer('83', 'hex'));
                    port._client.receive(new Buffer('01', 'hex'));
                    port._client.receive(new Buffer('83', 'hex'));
                    port._client.receive(new Buffer('01', 'hex'));
                    port._client.receive(new Buffer('83', 'hex'));
                    port._client.receive(new Buffer('01', 'hex'));
                    port._client.receive(new Buffer('83', 'hex'));
                    port._client.receive(new Buffer('01', 'hex'));
                    port._client.receive(new Buffer('83', 'hex'));
                    port._client.receive(new Buffer('01', 'hex'));
                    port._client.receive(new Buffer('83', 'hex'));
                    port._client.receive(new Buffer('01', 'hex'));
                    port._client.receive(new Buffer('83', 'hex'));
                    port._client.receive(new Buffer('01', 'hex'));
                    port._client.receive(new Buffer('83', 'hex'));
                    port._client.receive(new Buffer('01', 'hex'));
                    port._client.receive(new Buffer('83', 'hex'));
                    port._client.receive(new Buffer('01', 'hex'));
                    port._client.receive(new Buffer('83', 'hex'));
                    port._client.receive(new Buffer('01', 'hex'));
                    port._client.receive(new Buffer('83', 'hex'));
                    port._client.receive(new Buffer('01', 'hex'));
                    port._client.receive(new Buffer('83', 'hex'));
                    port._client.receive(new Buffer('01', 'hex'));
                    port._client.receive(new Buffer('83', 'hex'));
                    port._client.receive(new Buffer('01', 'hex'));
                    port._client.receive(new Buffer('83', 'hex'));
                    port._client.receive(new Buffer('01', 'hex'));
                    port._client.receive(new Buffer('83', 'hex'));
                    port._client.receive(new Buffer('01', 'hex'));
                    port._client.receive(new Buffer('83', 'hex'));
                    port._client.receive(new Buffer('01', 'hex'));
                    port._client.receive(new Buffer('83', 'hex'));
                    port._client.receive(new Buffer('01', 'hex'));
                    port._client.receive(new Buffer('83', 'hex'));
                    port._client.receive(new Buffer('01', 'hex'));
                    port._client.receive(new Buffer('83', 'hex'));
                    port._client.receive(new Buffer('01', 'hex'));
                    port._client.receive(new Buffer('83', 'hex'));
                    port._client.receive(new Buffer('01', 'hex'));
                    port._client.receive(new Buffer('83', 'hex'));
                    port._client.receive(new Buffer('01', 'hex'));
                    port._client.receive(new Buffer('83', 'hex'));
                    port._client.receive(new Buffer('01', 'hex'));
                    port._client.receive(new Buffer('83', 'hex'));
                    port._client.receive(new Buffer('01', 'hex'));
                    port._client.receive(new Buffer('83', 'hex'));
                    port._client.receive(new Buffer('01', 'hex'));
                    port._client.receive(new Buffer('83', 'hex'));
                    port._client.receive(new Buffer('01', 'hex'));
                    port._client.receive(new Buffer('83', 'hex'));
                    port._client.receive(new Buffer('01', 'hex'));
                    port._client.receive(new Buffer('83', 'hex'));
                    port._client.receive(new Buffer('01', 'hex'));
                    port._client.receive(new Buffer('83', 'hex'));
                    port._client.receive(new Buffer('01', 'hex'));
                    port._client.receive(new Buffer('83', 'hex'));
                    port._client.receive(new Buffer('01', 'hex'));
                    port._client.receive(new Buffer('83', 'hex'));
                    port._client.receive(new Buffer('01', 'hex'));
                    port._client.receive(new Buffer('83', 'hex'));
                    port._client.receive(new Buffer('01', 'hex'));
                    port._client.receive(new Buffer('83', 'hex'));
                    port._client.receive(new Buffer('01', 'hex'));
                    port._client.receive(new Buffer('83', 'hex'));
                    port._client.receive(new Buffer('01', 'hex'));
                    port._client.receive(new Buffer('83', 'hex'));
                    port._client.receive(new Buffer('01', 'hex'));
                    port._client.receive(new Buffer('83', 'hex'));
                    port._client.receive(new Buffer('01', 'hex'));
                    port._client.receive(new Buffer('83', 'hex'));
                    port._client.receive(new Buffer('01', 'hex'));
                    port._client.receive(new Buffer('83', 'hex'));
                    port._client.receive(new Buffer('01', 'hex'));
                    port._client.receive(new Buffer('83', 'hex'));
                    port._client.receive(new Buffer('01', 'hex'));
                    port._client.receive(new Buffer('83', 'hex'));
                    port._client.receive(new Buffer('01', 'hex'));
                    port._client.receive(new Buffer('83', 'hex'));
                    port._client.receive(new Buffer('01', 'hex'));
                    port._client.receive(new Buffer('83', 'hex'));
                    port._client.receive(new Buffer('01', 'hex'));
                    port._client.receive(new Buffer('83', 'hex'));
                    port._client.receive(new Buffer('01', 'hex'));
                    port._client.receive(new Buffer('83', 'hex'));
                    port._client.receive(new Buffer('01', 'hex'));
                    port._client.receive(new Buffer('83', 'hex'));
                    port._client.receive(new Buffer('01', 'hex'));
                    port._client.receive(new Buffer('83', 'hex'));
                    port._client.receive(new Buffer('01', 'hex'));
                    port._client.receive(new Buffer('83', 'hex'));
                    port._client.receive(new Buffer('01', 'hex'));
                    port._client.receive(new Buffer('83', 'hex'));
                    port._client.receive(new Buffer('01', 'hex'));
                    port._client.receive(new Buffer('83', 'hex'));
                    port._client.receive(new Buffer('01', 'hex'));
                    port._client.receive(new Buffer('83', 'hex'));
                    port._client.receive(new Buffer('01', 'hex'));
                    port._client.receive(new Buffer('83', 'hex'));
                    port._client.receive(new Buffer('01', 'hex'));
                    port._client.receive(new Buffer('83', 'hex'));

                    port._client.receive(new Buffer('46', 'hex'));
                    port._client.receive(new Buffer('e0', 'hex'));
                });
            });
        });

        it('Illegal start chars, should synchronize to valid Modbus RTU message', function(done) {
            port.once('data', function(data) {
                expect(data.toString('hex')).to.equal('110306ae415652434049ad');
                done();
            });
            port.open(function() {
                port.write(new Buffer('1103006B00037687', 'hex'));
                setTimeout(function() {
                    port._client.receive(new Buffer('20', 'hex')); // illegal char
                    port._client.receive(new Buffer('54', 'hex')); // illegal char
                    port._client.receive(new Buffer('54', 'hex')); // illegal char
                    port._client.receive(new Buffer('ff', 'hex')); // illegal char
                    port._client.receive(new Buffer('11', 'hex'));
                    port._client.receive(new Buffer('03', 'hex'));
                    port._client.receive(new Buffer('06', 'hex'));
                    port._client.receive(new Buffer('ae', 'hex'));
                    port._client.receive(new Buffer('41', 'hex'));
                    port._client.receive(new Buffer('56', 'hex'));
                    port._client.receive(new Buffer('52', 'hex'));
                    port._client.receive(new Buffer('43', 'hex'));
                    port._client.receive(new Buffer('40', 'hex'));
                    port._client.receive(new Buffer('49', 'hex'));
                    port._client.receive(new Buffer('ad', 'hex'));
                });
            });
        });

        it('Illegal end chars, should return a valid Modbus RTU message', function(done) {
            port.once('data', function(data) {
                expect(data.toString('hex')).to.equal('110306ae415652434049ad');
                done();
            });
            port.open(function() {
                port.write(new Buffer('1103006B00037687', 'hex'));
                setTimeout(function() {
                    port._client.receive(new Buffer('11', 'hex'));
                    port._client.receive(new Buffer('03', 'hex'));
                    port._client.receive(new Buffer('06', 'hex'));
                    port._client.receive(new Buffer('ae', 'hex'));
                    port._client.receive(new Buffer('41', 'hex'));
                    port._client.receive(new Buffer('56', 'hex'));
                    port._client.receive(new Buffer('52', 'hex'));
                    port._client.receive(new Buffer('43', 'hex'));
                    port._client.receive(new Buffer('40', 'hex'));
                    port._client.receive(new Buffer('49', 'hex'));
                    port._client.receive(new Buffer('ad', 'hex'));
                    port._client.receive(new Buffer('20', 'hex')); // illegal char
                    port._client.receive(new Buffer('54', 'hex')); // illegal char
                    port._client.receive(new Buffer('54', 'hex')); // illegal char
                    port._client.receive(new Buffer('ff', 'hex')); // illegal char
                });
            });
        });

        it('should return a valid Modbus RTU message on illegal chars', function(done) {
            port.once('data', function(data) {
                expect(data.toString('hex')).to.equal('110306ae415652434049ad');
                done();
            });
            port.open(function() {
                port.write(new Buffer('1103006B00037687', 'hex'));
                setTimeout(function() {
                    port._client.receive(new Buffer('11', 'hex'));
                    port._client.receive(new Buffer('03', 'hex'));
                    port._client.receive(new Buffer('06', 'hex'));
                    port._client.receive(new Buffer('ae', 'hex'));
                    port._client.receive(new Buffer('41', 'hex'));
                    port._client.receive(new Buffer('56', 'hex'));
                    port._client.receive(new Buffer('52', 'hex'));
                    port._client.receive(new Buffer('43', 'hex'));
                    port._client.receive(new Buffer('40', 'hex'));
                    port._client.receive(new Buffer('49', 'hex'));
                    port._client.receive(new Buffer('ad', 'hex'));
                });
            });
        });
    });

    describe('#write', function() {
        it('should write a valid RTU message to the port', function() {
            port.write(new Buffer('1103006B00037687', 'hex'));
            expect(port._client._data.toString('hex')).to.equal('1103006b00037687');
        });
    });

});
<|endoftext|>


<commit_before>/*jslint plusplus: true */
/*global hilary*/

hilary.register('gutentyp::toolbar', { init: function (config, dom, componentCollection) {
    "use strict";

    var build = function () {
        var components = componentCollection.components,
            i,
            formatEventSelector,
            buttonTemplate,
            groups = {},
            addWithDisplayHandler,
            addWithGroup,
            addGroup,
            add;

        formatEventSelector = function (component) {
            return config.selectors.toolbar + ' .' + component.cssClass + ':not(' + config.selectors.hasEvents + ')';
        };

        buttonTemplate = function (component, componentId) {
            var buttonClass, template;

            buttonClass = 'gutentyp-component ' + component.cssClass;

            if (componentId) {
                buttonClass += ' ' + componentId;
            }

            template = '<button type="button" class="' + buttonClass + '">'
                                + ''
                                + '' + component.title + ''
                            + '</button>';
            return template;
        };

        add = function (component) {
            dom.insertNewElementInto({
                markup: buttonTemplate(component)
            }, config.selectors.newToolbars);
            dom.attachEvent({
                primarySelector: formatEventSelector(component),
                eventType: 'click',
                eventHandler: component.execute
            });
        };

        addWithDisplayHandler = function (component) {
            dom.insertHtml(config.selectors.newToolbars, component.displayHandler());
            dom.attachEvent({
                primarySelector: formatEventSelector(component),
                eventType: 'click',
                eventHandler: component.execute
            });
        };

        addGroup = function (component) {
            var currentGroup = groups[component.group.name] = { components: [component] };
            currentGroup.toggleId = dom.getRandomString();// component.group.name + 'toggle';
            currentGroup.menuId = dom.getRandomString(); // component.group.name + 'menu';//dom.getRandomString();
            currentGroup.toggleSelector = '.' + currentGroup.toggleId;
            currentGroup.menuSelector = '.' + currentGroup.menuId;

            dom.insertNewElementInto({
                markup: buttonTemplate(component.group, currentGroup.toggleId)
            }, config.selectors.newToolbars);
            dom.insertNewElementInto({
                markup: '

'
            }, 'body'); //config.selectors.newToolbars);

            // toggle hidden
            dom.attachEvent({
                primarySelector: currentGroup.toggleSelector,
                eventType: 'click',
                eventHandler: function (event) {
	                var btnCoords = dom.getCoordinates(event.target, currentGroup.menuSelector),
	                    style;

	                // set the coordinates
	                style = 'left: ' + btnCoords.moveLeft + 'px';
	                style += '; top: ' + btnCoords.moveTop + 'px';
	                dom.setStyle(currentGroup.menuSelector, style);

	                // hide any other toolbars that might be open
	                dom.toggleClass('.gutentyp-toolbar-group.active:not(' + currentGroup.menuSelector + ')', 'active');
	                // show or hid this toolbar
	                dom.toggleClass(currentGroup.menuSelector, 'active');
                }
            });

            return currentGroup;
        };

        addWithGroup = function (component) {
            var componentId = dom.getRandomString(),
                componentSelector = '.' + componentId,
                currentGroup,
                execWrapper;

            if (!groups[component.group.name]) {
                currentGroup = addGroup(component);
            } else {
                currentGroup = groups[component.group.name];
                groups[component.group.name].components.push(component);
            }

            if (component.displayHandler) {
                dom.insertNewElementInto({
                    markup: '
' + component.displayHandler(componentId) + '
'
                }, currentGroup.menuSelector + ' ul');
            } else {
                dom.insertNewElementInto({
                    markup: '
' + buttonTemplate(component, componentId) + '
'
                }, currentGroup.menuSelector + ' ul');
            }

            execWrapper = function (event, input) {
                component.execute(event, input);
                dom.toggleClass(currentGroup.menuSelector, 'active');
            };

            dom.attachEvent({
                primarySelector: componentSelector,
                eventType: 'click',
                eventHandler: execWrapper
            });
        };

//        dom.insertNewElementBefore('div', config.selectors.newEditors, config.selectors.toolbar);

        for (i = 0; i < components.length; i++) {
            if (components[i].group !== undefined) {
                addWithGroup(components[i]);
            } else if (dom.isFunction(components[i].displayHandler)) {
                addWithDisplayHandler(components[i]);
            } else {
                add(components[i]);
            }
        }

        dom.addClass(config.selectors.newEditors, config.cssClasses.hasToolbar);
        dom.addClass(config.selectors.newToolbars, config.cssClasses.hasComponents);

        return;
    };

    return {
        build: build
    };

}});
<commit_msg>adds comments<commit_after>/*jslint plusplus: true */
/*global hilary*/

hilary.register('gutentyp::toolbar', { init: function (config, dom, componentCollection) {
    "use strict";

    var build = function () {
        var components = componentCollection.components,
            i,
            formatEventSelector,
            buttonTemplate,
            groups = {},
            addWithDisplayHandler,
            addWithGroup,
            addGroup,
            add;

        formatEventSelector = function (component) {
            return config.selectors.toolbar + ' .' + component.cssClass + ':not(' + config.selectors.hasEvents + ')';
        };

        buttonTemplate = function (component, componentId) {
            var buttonClass, template;

            buttonClass = 'gutentyp-component ' + component.cssClass;

            if (componentId) {
                buttonClass += ' ' + componentId;
            }

            template = '<button type="button" class="' + buttonClass + '">'
                                + ''
                                + '' + component.title + ''
                            + '</button>';
            return template;
        };

        add = function (component) {
            dom.insertNewElementInto({
                markup: buttonTemplate(component)
            }, config.selectors.newToolbars);
            dom.attachEvent({
                primarySelector: formatEventSelector(component),
                eventType: 'click',
                eventHandler: component.execute
            });
        };

        addWithDisplayHandler = function (component) {
            dom.insertHtml(config.selectors.newToolbars, component.displayHandler());
            dom.attachEvent({
                primarySelector: formatEventSelector(component),
                eventType: 'click',
                eventHandler: component.execute
            });
        };

        addGroup = function (component) {
            var currentGroup = groups[component.group.name] = { components: [component] };
            currentGroup.toggleId = dom.getRandomString();// component.group.name + 'toggle';
            currentGroup.menuId = dom.getRandomString(); // component.group.name + 'menu';//dom.getRandomString();
            currentGroup.toggleSelector = '.' + currentGroup.toggleId;
            currentGroup.menuSelector = '.' + currentGroup.menuId;

            dom.insertNewElementInto({
                markup: buttonTemplate(component.group, currentGroup.toggleId)
            }, config.selectors.newToolbars);
            dom.insertNewElementInto({
                markup: '

'
            }, 'body'); //config.selectors.newToolbars);

            // toggle hidden
            dom.attachEvent({
                primarySelector: currentGroup.toggleSelector,
                eventType: 'click',
                eventHandler: function (event) {
	                var btnCoords = dom.getCoordinates(event.target, currentGroup.menuSelector),
	                    style;

	                // set the coordinates
	                style = 'left: ' + btnCoords.moveLeft + 'px';
	                style += '; top: ' + btnCoords.moveTop + 'px';
	                dom.setStyle(currentGroup.menuSelector, style);

	                // hide any other toolbars that might be open
	                dom.toggleClass('.gutentyp-toolbar-group.active:not(' + currentGroup.menuSelector + ')', 'active');
	                // show or hid this toolbar
	                dom.toggleClass(currentGroup.menuSelector, 'active');
                }
            });

            return currentGroup;
        };

        addWithGroup = function (component) {
            var componentId = dom.getRandomString(),
                componentSelector = '.' + componentId,
                currentGroup,
                execWrapper;

            if (!groups[component.group.name]) {
                currentGroup = addGroup(component);
            } else {
                currentGroup = groups[component.group.name];
                groups[component.group.name].components.push(component);
            }

            if (component.displayHandler) {
                dom.insertNewElementInto({
                    markup: '
' + component.displayHandler(componentId) + '
'
                }, currentGroup.menuSelector + ' ul');
            } else {
                dom.insertNewElementInto({
                    markup: '
' + buttonTemplate(component, componentId) + '
'
                }, currentGroup.menuSelector + ' ul');
            }

            execWrapper = function (event, input) {
                component.execute(event, input);
                dom.toggleClass(currentGroup.menuSelector, 'active');
            };

            dom.attachEvent({
                primarySelector: componentSelector,
                eventType: 'click',
                eventHandler: execWrapper
            });
        };

// Add this back in, if we decide to not add the toolbar container when we render the editor.
// we might be able to just add a replaceWith call here.
//        dom.insertNewElementBefore('div', config.selectors.newEditors, config.selectors.toolbar);

        for (i = 0; i < components.length; i++) {
            if (components[i].group !== undefined) {
                addWithGroup(components[i]);
            } else if (dom.isFunction(components[i].displayHandler)) {
                addWithDisplayHandler(components[i]);
            } else {
                add(components[i]);
            }
        }

        dom.addClass(config.selectors.newEditors, config.cssClasses.hasToolbar);
        dom.addClass(config.selectors.newToolbars, config.cssClasses.hasComponents);

        return;
    };

    return {
        build: build
    };

}});
<|endoftext|>


<commit_before>var suite = new core.testrunner.Suite("Type/Function");

suite.test("debounce - END", function()
{
  var test = this;

  var counter = 0;
  var callback = function() {
    counter++;
  };

  var debounced = core.Function.debounce(callback);
  debounced();
  debounced();
  debounced();
  debounced();
  debounced();

  setTimeout(function() {
    test.isEqual(counter, 1);
    test.done();
  }, 200)
}, 1, 1000);

suite.test("debounce - ASAP", function()
{
  var counter = 0;
  var callback = function() {
    counter++;
  };

  var debounced = core.Function.debounce(callback, 100, true);
  debounced();
  debounced();
  debounced();
  debounced();
  debounced();

  this.isEqual(counter, 1);
});

suite.test("timeout", function()
{
  var ref = core.Function.timeout(function(arg1, arg2)
  {
    this.isEqual(arg1, "foo");
    this.isEqual(arg2, "bar");
    this.done();
  }, this, 100, "foo", "bar");

}, 2, 1000);

suite.test("interval", function()
{
  var ref = core.Function.interval(function(arg1, arg2)
  {
    this.isEqual(arg1, "foo");
    this.isEqual(arg2, "bar");

    // Using global method
    clearInterval(ref);

    this.done();
  }, this, 100, "foo", "bar");

}, 2, 1000);

suite.test("immediate", function()
{
  core.Function.immediate(function() {
    this.done();
  }, this);

}, 0, 1000);

suite.test("throttle", function()
{
  var counter = 0;
  var callback = function() {
    counter++;
  };

  var throttled = core.Function.throttle(callback, 100);

  setTimeout(throttled, 20);
  setTimeout(throttled, 50);
  setTimeout(throttled, 80);
  setTimeout(throttled, 110);
  setTimeout(throttled, 140);
  setTimeout(throttled, 170);
  setTimeout(throttled, 200);
  setTimeout(throttled, 230);
  setTimeout(throttled, 260);
  setTimeout(throttled, 290);

  var test = this;
  setTimeout(function() {
    test.isEqual(counter, 3);
    test.done();
  }, 500);

}, 1, 1000);

suite.test("bind", function()
{
  var test = this;

  var obj = new (new Function);

  var func1 = function() {
    test.isIdentical(this, obj);
  };
  var bound1 = core.Function.bind(func1, obj);
  var bound2 = core.Function.bind(func1, obj);

  this.isType(bound1, "Function");
  this.isIdentical(bound1, bound2);

  bound1();
  bound2();
});

suite.test("curry", function()
{
  var test = this;
  var obj = new (new Function);

  var param1 = "test";
  var param2 = 42;
  var param3 = null;
  var param4 = "own parameter";

  var func1 = function(a, b, c, d) {
    test.isIdentical(a, param1);
    test.isIdentical(b, param2);
    test.isIdentical(c, param3);
    test.isIdentical(d, param4);
  };
  var func2 = function(a, b, c, d) {
    test.isIdentical(this, obj);
    test.isIdentical(a, param1);
    test.isIdentical(b, param2);
    test.isIdentical(c, param3);
    test.isIdentical(d, param4);
  };

  // Curry 3 parameters to function
  var curryFunc1 = core.Function.curry(func1, param1, param2, param3);

  // Curry 3 parameters to function and test if context is not touched
  var curryFunc2 = core.Function.bind(core.Function.curry(func2, param1, param2, param3), obj);

  this.isType(curryFunc1, "Function");

  curryFunc1(param4);
  curryFunc2(param4);
});
<commit_msg>Fixed throttle test<commit_after>var suite = new core.testrunner.Suite("Type/Function");

suite.test("debounce - END", function()
{
  var test = this;

  var counter = 0;
  var callback = function() {
    counter++;
  };

  var debounced = core.Function.debounce(callback);
  debounced();
  debounced();
  debounced();
  debounced();
  debounced();

  setTimeout(function() {
    test.isEqual(counter, 1);
    test.done();
  }, 200)
}, 1, 1000);

suite.test("debounce - ASAP", function()
{
  var counter = 0;
  var callback = function() {
    counter++;
  };

  var debounced = core.Function.debounce(callback, 100, true);
  debounced();
  debounced();
  debounced();
  debounced();
  debounced();

  this.isEqual(counter, 1);
});

suite.test("timeout", function()
{
  var ref = core.Function.timeout(function(arg1, arg2)
  {
    this.isEqual(arg1, "foo");
    this.isEqual(arg2, "bar");
    this.done();
  }, this, 100, "foo", "bar");

}, 2, 1000);

suite.test("interval", function()
{
  var ref = core.Function.interval(function(arg1, arg2)
  {
    this.isEqual(arg1, "foo");
    this.isEqual(arg2, "bar");

    // Using global method
    clearInterval(ref);

    this.done();
  }, this, 100, "foo", "bar");

}, 2, 1000);

suite.test("immediate", function()
{
  core.Function.immediate(function() {
    this.done();
  }, this);

}, 0, 1000);

suite.test("throttle", function()
{
  var counter = 0;
  var callback = function() {
    counter++;
  };

  var throttled = core.Function.throttle(callback, 100);

  setTimeout(throttled, 20);
  setTimeout(throttled, 50);
  setTimeout(throttled, 80);
  setTimeout(throttled, 110);
  setTimeout(throttled, 140);
  setTimeout(throttled, 170);
  setTimeout(throttled, 200);
  setTimeout(throttled, 230);
  setTimeout(throttled, 260);
  setTimeout(throttled, 290);

  var test = this;
  setTimeout(function() {
    test.isTrue(counter<4);
    test.done();
  }, 500);

}, 1, 1000);

suite.test("bind", function()
{
  var test = this;

  var obj = new (new Function);

  var func1 = function() {
    test.isIdentical(this, obj);
  };
  var bound1 = core.Function.bind(func1, obj);
  var bound2 = core.Function.bind(func1, obj);

  this.isType(bound1, "Function");
  this.isIdentical(bound1, bound2);

  bound1();
  bound2();
});

suite.test("curry", function()
{
  var test = this;
  var obj = new (new Function);

  var param1 = "test";
  var param2 = 42;
  var param3 = null;
  var param4 = "own parameter";

  var func1 = function(a, b, c, d) {
    test.isIdentical(a, param1);
    test.isIdentical(b, param2);
    test.isIdentical(c, param3);
    test.isIdentical(d, param4);
  };
  var func2 = function(a, b, c, d) {
    test.isIdentical(this, obj);
    test.isIdentical(a, param1);
    test.isIdentical(b, param2);
    test.isIdentical(c, param3);
    test.isIdentical(d, param4);
  };

  // Curry 3 parameters to function
  var curryFunc1 = core.Function.curry(func1, param1, param2, param3);

  // Curry 3 parameters to function and test if context is not touched
  var curryFunc2 = core.Function.bind(core.Function.curry(func2, param1, param2, param3), obj);

  this.isType(curryFunc1, "Function");

  curryFunc1(param4);
  curryFunc2(param4);
});
<|endoftext|>


<commit_before>var babel = require( 'babel-core' );
var fs = require( 'fs' );
var assert = require( 'assert' );
var getLocation = require( '../../utils/getLocation' );
var SourceMapConsumer = require( 'source-map' ).SourceMapConsumer;

module.exports = {
	description: 'preserves sourcemap chains when transforming',
	options: {
		plugins: [
			{
				load: function ( id ) {
					if ( id.endsWith( 'foo.js' ) ) {
						id = id.replace( /foo.js$/, 'bar.js' );
					} else if ( id.endsWith( 'bar.js' ) ) {
						id = id.replace( /bar.js$/, 'foo.js' );
					}

					var out = babel.transformFileSync( id, {
						blacklist: [ 'es6.modules' ],
						sourceMap: true,
						comments: false // misalign the columns
					});

					if ( id.endsWith( 'main.js' ) ) {
						delete out.map.sources;
					} else {
						const slash = out.map.sources[0].lastIndexOf( '/' ) + 1;
						out.map.sources = out.map.sources.map( source => '../' + source.slice( slash ) );
						out.map.sourceRoot = 'fake';
					}

					return { code: out.code, map: out.map };
				}
			}
		]
	},
	test: function ( code, map ) {
		var smc = new SourceMapConsumer( map );

		var generatedLoc = getLocation( code, code.indexOf( '22' ) );
		var originalLoc = smc.originalPositionFor( generatedLoc );

		assert.equal( originalLoc.source, '../foo.js' );
		assert.equal( originalLoc.line, 1 );
		assert.equal( originalLoc.column, 32 );

		var generatedLoc = getLocation( code, code.indexOf( '20' ) );
		var originalLoc = smc.originalPositionFor( generatedLoc );

		assert.equal( originalLoc.source, '../bar.js' );
		assert.equal( originalLoc.line, 1 );
		assert.equal( originalLoc.column, 37 );

		generatedLoc = getLocation( code, code.indexOf( 'log' ) );
		originalLoc = smc.originalPositionFor( generatedLoc );

		assert.equal( originalLoc.source, '../main.js' );
		assert.ok( /columns/.test( smc.sourceContentFor( '../main.js' ) ) );
		assert.equal( originalLoc.line, 4 );
		assert.equal( originalLoc.column, 19 );
	}
};
<commit_msg>Don't use endsWith. Will this fix the 0.12 build?<commit_after>var babel = require( 'babel-core' );
var fs = require( 'fs' );
var assert = require( 'assert' );
var getLocation = require( '../../utils/getLocation' );
var SourceMapConsumer = require( 'source-map' ).SourceMapConsumer;

module.exports = {
	description: 'preserves sourcemap chains when transforming',
	options: {
		plugins: [
			{
				load: function ( id ) {
					if ( /foo.js$/.test( id ) ) {
						id = id.replace( /foo.js$/, 'bar.js' );
					} else if ( /bar.js$/.test( id ) ) {
						id = id.replace( /bar.js$/, 'foo.js' );
					}

					var out = babel.transformFileSync( id, {
						blacklist: [ 'es6.modules' ],
						sourceMap: true,
						comments: false // misalign the columns
					});

					if ( /main.js$/.test( id ) ) {
						delete out.map.sources;
					} else {
						const slash = out.map.sources[0].lastIndexOf( '/' ) + 1;
						out.map.sources = out.map.sources.map( source => '../' + source.slice( slash ) );
						out.map.sourceRoot = 'fake';
					}

					return { code: out.code, map: out.map };
				}
			}
		]
	},
	test: function ( code, map ) {
		var smc = new SourceMapConsumer( map );

		var generatedLoc = getLocation( code, code.indexOf( '22' ) );
		var originalLoc = smc.originalPositionFor( generatedLoc );

		assert.equal( originalLoc.source, '../foo.js' );
		assert.equal( originalLoc.line, 1 );
		assert.equal( originalLoc.column, 32 );

		var generatedLoc = getLocation( code, code.indexOf( '20' ) );
		var originalLoc = smc.originalPositionFor( generatedLoc );

		assert.equal( originalLoc.source, '../bar.js' );
		assert.equal( originalLoc.line, 1 );
		assert.equal( originalLoc.column, 37 );

		generatedLoc = getLocation( code, code.indexOf( 'log' ) );
		originalLoc = smc.originalPositionFor( generatedLoc );

		assert.equal( originalLoc.source, '../main.js' );
		assert.ok( /columns/.test( smc.sourceContentFor( '../main.js' ) ) );
		assert.equal( originalLoc.line, 4 );
		assert.equal( originalLoc.column, 19 );
	}
};
<|endoftext|>


<commit_before>import Sync from '../../templates/classes/Sync.js'
import {expect} from '../../node_modules/chai/chai.js'
import {loadComponent} from './templates-fixture.js'

describe("Sync Tool",  () => {
  var that

  before("load", function(done){
    this.timeout(1000);
    loadComponent("lively-sync").then(c => {that = c; done()})
  })

  it("should load stored value", async () => {
    await that.storeValue("test_tmp_key", "hello");
    expect(await that.loadValue("test_tmp_key")).to.be.equal("hello");
  })

})

<commit_msg>SYNC  M test/templates/lively-sync-test.js;<commit_after>import Sync from '../../templates/classes/Sync.js'
import {expect} from '../../node_modules/chai/chai.js'
import {loadComponent} from './templates-fixture.js'

describe("Sync Tool",  function(){
  var that

    this.timeout(15000);

  before("load", function(done){
    loadComponent("lively-sync").then(c => {that = c; done()})
  })

  it("should load stored value", async () => {
    await that.storeValue("test_tmp_key", "hello");
    expect(await that.loadValue("test_tmp_key")).to.be.equal("hello");
  })

})

<|endoftext|>


<commit_before>const test = require('ava');
const NullSafeObject = require('..');
const srcObj = {
    key: 'value',
    deep: {
        property: {
            access: true
        }
    }
};

test('accessible exists key', t => {
    const obj = NullSafeObject.create(srcObj);
    t.is(obj.key, 'value');
    t.is(obj.deep.property.access, true);
});

<commit_msg>update test<commit_after>const test = require('ava');
const NullSafeObject = require('..');
const srcObj = {
    key: 'value',
    deep: {
        property: {
            access: true
        }
    }
};

test('accessible exists key', t => {
    const obj = NullSafeObject.create(srcObj);
    t.is(obj.key, 'value');
    t.is(obj.deep.property.access, true);
    t.truthy(obj.deep.other_property.access);
});

<|endoftext|>


<commit_before>'use strict';

var koa = require('koa'),
request = require('supertest');
require('should');

function create_app(){
	var app = koa();
	app.use(require('koa-body')());
	app.use(require('../lib/validate.js')());
	app.use(require('koa-router')(app));
	return app;
}

describe('koa-validate' , function(){
	it("bad uri decodeURIComponent should not to be ok" , function(done){
		var app = create_app();
		app.post('/decodeURIComponent',function*(){
			this.checkBody('uri').decodeURIComponent();
			if(this.errors) {
				this.status=500;
			}else{
				this.status=200;
			}
		});
		var req = request(app.listen());
		req.post('/decodeURIComponent')
		.send({uri:"%"})
		.expect(500 , done);
	});
	it("bad uri decodeURI should not to be ok" , function(done){
		var app = create_app();
		app.post('/decodeURI',function*(){
			this.checkBody('uri').decodeURI();
			if(this.errors) {
				this.status=500;
			}else{
				this.status=200;
			}
		});
		var req = request(app.listen());
		req.post('/decodeURI')
		.send({uri:"%"})
		.expect(500 , done);
	});
	it("bad base64 string should not to be ok" , function(done){
		var app = create_app();
		app.post('/decodeBase64',function*(){
			this.checkBody('base64').decodeURIComponent();
			if(this.errors) {
				this.status=500;
			}else{
				this.status=200;
			}
		});
		var req = request(app.listen());
		req.post('/decodeBase64')
		.send({base64:"%%"})
		.expect(500 , done);
	});
	it("bad int string should not to be ok" , function(done){
		var app = create_app();
		app.post('/toInt',function*(){
			this.checkBody('v').toInt();
			if(this.errors) {
				this.status=500;
			}else{
				this.status=200;
			}
		});
		var req = request(app.listen());
		req.post('/toInt')
		.send({v:"gg"})
		.expect(500 , done);
	});
});<commit_msg>add length test case.<commit_after>'use strict';

var koa = require('koa'),
request = require('supertest');
require('should');

function create_app(){
	var app = koa();
	app.use(require('koa-body')());
	app.use(require('../lib/validate.js')());
	app.use(require('koa-router')(app));
	return app;
}

describe('koa-validate' , function(){
	it("bad uri decodeURIComponent should not to be ok" , function(done){
		var app = create_app();
		app.post('/decodeURIComponent',function*(){
			this.checkBody('uri').decodeURIComponent();
			if(this.errors) {
				this.status=500;
			}else{
				this.status=200;
			}
		});
		var req = request(app.listen());
		req.post('/decodeURIComponent')
		.send({uri:"%"})
		.expect(500 , done);
	});
	it("bad uri decodeURI should not to be ok" , function(done){
		var app = create_app();
		app.post('/decodeURI',function*(){
			this.checkBody('uri').decodeURI();
			if(this.errors) {
				this.status=500;
			}else{
				this.status=200;
			}
		});
		var req = request(app.listen());
		req.post('/decodeURI')
		.send({uri:"%"})
		.expect(500 , done);
	});
	it("bad base64 string should not to be ok" , function(done){
		var app = create_app();
		app.post('/decodeBase64',function*(){
			this.checkBody('base64').decodeURIComponent();
			if(this.errors) {
				this.status=500;
			}else{
				this.status=200;
			}
		});
		var req = request(app.listen());
		req.post('/decodeBase64')
		.send({base64:"%%"})
		.expect(500 , done);
	});
	it("bad int string should not to be ok" , function(done){
		var app = create_app();
		app.post('/toInt',function*(){
			this.checkBody('v').toInt();
			if(this.errors) {
				this.status=500;
			}else{
				this.status=200;
			}
		});
		var req = request(app.listen());
		req.post('/toInt')
		.send({v:"gg"})
		.expect(500 , done);
	});

	it("0 len should be ok" , function(done){
		var app = create_app();
		app.post('/len',function*(){
			this.checkBody('v').len(2);
			if(this.errors) {
				this.status=500;
			}else{
				this.status=200;
			}
		});
		var req = request(app.listen());
		req.post('/len')
		.send({v:"1"})
		.expect(200 , done);
	});
});<|endoftext|>


<commit_before>/* global describe, it */

var $require = require('proxyquire');
var expect = require('chai').expect;
var sinon = require('sinon');
var factory = require('../../../../com/token/http/grant/code');

describe('http/token/grant/code', function() {

  it('should be annotated', function() {
    expect(factory['@implements']).to.equal('http://i.authnomicon.org/oauth2/token/http/AuthorizationGrantExchange');
    expect(factory['@type']).to.equal('authorization_code');
  });

  it('should create exchange without response parameters', function(done) {
    var container = new Object();
    container.components = sinon.stub()
    container.components.withArgs('http://i.authnomicon.org/oauth2/token/http/ResponseParameters').returns([]);
    var logger = {
      error: function(){},
      warning: function(){},
      notice: function(){},
      info: function(){}
    };
    var acs = new Object();
    acs.verify = sinon.stub().yieldsAsync(null, {
      client: { id: 's6BhdRkqt3' },
      redirectURI: 'https://client.example.org/cb',
      user: { id: '248289761001' }
    });
    var ats = new Object();
    ats.issue = sinon.stub().yieldsAsync(null, '2YotnFZFEjr1zCsicMWpAA');

    var codeSpy = sinon.stub();
    var factory = $require('../../../../com/token/http/grant/code', {
      'oauth2orize': {
        exchange: { code: codeSpy }
      }
    });

    factory(ats, acs, logger, container)
      .then(function(exchange) {
        expect(codeSpy).to.be.calledOnce;
        done();
      })
      .catch(done);
  });

  describe('issue', function() {
    var container = new Object();
    container.components = sinon.stub()
    container.components.withArgs('http://i.authnomicon.org/oauth2/token/http/ResponseParameters').returns([]);
    var logger = {
      error: function(){},
      warning: function(){},
      notice: function(){},
      info: function(){}
    };
    var ats = new Object();
    ats.issue = sinon.stub().yieldsAsync(null, '2YotnFZFEjr1zCsicMWpAA');

    it('should issue access token with scope', function(done) {
      var codeSpy = sinon.stub();
      var factory = $require('../../../../com/token/http/grant/code', {
        'oauth2orize': { exchange: { code: codeSpy } }
      });

      var acs = new Object();
      acs.verify = sinon.stub().yieldsAsync(null, {
        client: { id: 's6BhdRkqt3' },
        redirectURI: 'https://client.example.org/cb',
        user: { id: '248289761001' },
        scope: [ 'profile', 'email' ]
      });

      factory(ats, acs, logger, container)
        .then(function(exchange) {

          var client = {
            id: 's6BhdRkqt3',
            name: 'Example Client',
            redirectURIs: [ 'https://client.example.org/cb' ]
          };

          var issue = codeSpy.getCall(0).args[0];
          issue(client, 'SplxlOBeZQQYbYS6WxSbIA', 'https://client.example.org/cb', {}, {}, function(err, token) {
            if (err) { return done(err); }

            expect(acs.verify).to.be.calledOnce;
            expect(acs.verify.getCall(0).args[0]).to.equal('SplxlOBeZQQYbYS6WxSbIA');
            expect(ats.issue).to.be.calledOnce;
            expect(ats.issue.getCall(0).args[0]).to.deep.equal({
              user: {
                id: '248289761001'
              },
              client: {
                id: 's6BhdRkqt3',
                name: 'Example Client',
                redirectURIs: [ 'https://client.example.org/cb' ]
              },
              scope: [ 'profile', 'email' ]
            });
            expect(token).to.equal('2YotnFZFEjr1zCsicMWpAA');
            done();
          });
        })
        .catch(done);
    }); // should issue access token with scope

  }); // creating exchange

});
<commit_msg>Add tests.<commit_after>/* global describe, it */

var $require = require('proxyquire');
var expect = require('chai').expect;
var sinon = require('sinon');
var factory = require('../../../../com/token/http/grant/code');

describe('http/token/grant/code', function() {

  it('should be annotated', function() {
    expect(factory['@implements']).to.equal('http://i.authnomicon.org/oauth2/token/http/AuthorizationGrantExchange');
    expect(factory['@type']).to.equal('authorization_code');
  });

  it('should create exchange without response parameters', function(done) {
    var container = new Object();
    container.components = sinon.stub()
    container.components.withArgs('http://i.authnomicon.org/oauth2/token/http/ResponseParameters').returns([]);
    var logger = {
      error: function(){},
      warning: function(){},
      notice: function(){},
      info: function(){}
    };
    var acs = new Object();
    acs.verify = sinon.stub().yieldsAsync(null, {
      client: { id: 's6BhdRkqt3' },
      redirectURI: 'https://client.example.org/cb',
      user: { id: '248289761001' }
    });
    var ats = new Object();
    ats.issue = sinon.stub().yieldsAsync(null, '2YotnFZFEjr1zCsicMWpAA');

    var codeSpy = sinon.stub();
    var factory = $require('../../../../com/token/http/grant/code', {
      'oauth2orize': {
        exchange: { code: codeSpy }
      }
    });

    factory(ats, acs, logger, container)
      .then(function(exchange) {
        expect(codeSpy).to.be.calledOnce;
        done();
      })
      .catch(done);
  });

  describe('issue', function() {
    var container = new Object();
    container.components = sinon.stub()
    container.components.withArgs('http://i.authnomicon.org/oauth2/token/http/ResponseParameters').returns([]);
    var logger = {
      error: function(){},
      warning: function(){},
      notice: function(){},
      info: function(){}
    };

    it('should issue access token with scope', function(done) {
      var codeSpy = sinon.stub();
      var factory = $require('../../../../com/token/http/grant/code', {
        'oauth2orize': { exchange: { code: codeSpy } }
      });

      var acs = new Object();
      acs.verify = sinon.stub().yieldsAsync(null, {
        client: { id: 's6BhdRkqt3' },
        redirectURI: 'https://client.example.org/cb',
        user: { id: '248289761001' },
        scope: [ 'profile', 'email' ]
      });
      var ats = new Object();
      ats.issue = sinon.stub().yieldsAsync(null, '2YotnFZFEjr1zCsicMWpAA');

      factory(ats, acs, logger, container)
        .then(function(exchange) {

          var client = {
            id: 's6BhdRkqt3',
            name: 'Example Client',
            redirectURIs: [ 'https://client.example.org/cb' ]
          };

          var issue = codeSpy.getCall(0).args[0];
          issue(client, 'SplxlOBeZQQYbYS6WxSbIA', 'https://client.example.org/cb', {}, {}, function(err, token) {
            if (err) { return done(err); }

            expect(acs.verify).to.be.calledOnce;
            expect(acs.verify.getCall(0).args[0]).to.equal('SplxlOBeZQQYbYS6WxSbIA');
            expect(ats.issue).to.be.calledOnce;
            expect(ats.issue.getCall(0).args[0]).to.deep.equal({
              user: {
                id: '248289761001'
              },
              client: {
                id: 's6BhdRkqt3',
                name: 'Example Client',
                redirectURIs: [ 'https://client.example.org/cb' ]
              },
              scope: [ 'profile', 'email' ]
            });
            expect(token).to.equal('2YotnFZFEjr1zCsicMWpAA');
            done();
          });
        })
        .catch(done);
    }); // should issue access token with scope

    it('should not issue access token when authorization code not issued to client', function(done) {
      var codeSpy = sinon.stub();
      var factory = $require('../../../../com/token/http/grant/code', {
        'oauth2orize': { exchange: { code: codeSpy } }
      });

      var acs = new Object();
      acs.verify = sinon.stub().yieldsAsync(null, {
        client: { id: 's6BhdRkqt3' },
        redirectURI: 'https://client.example.org/cb',
        user: { id: '248289761001' },
        scope: [ 'profile', 'email' ]
      });
      var ats = new Object();
      ats.issue = sinon.stub().yieldsAsync(null, '2YotnFZFEjr1zCsicMWpAA');

      factory(ats, acs, logger, container)
        .then(function(exchange) {

          var client = {
            id: 'XXXXXXXX',
            name: 'Example Client',
            redirectURIs: [ 'https://client.example.org/cb' ]
          };

          var issue = codeSpy.getCall(0).args[0];
          issue(client, 'SplxlOBeZQQYbYS6WxSbIA', 'https://client.example.org/cb', {}, {}, function(err, token) {
            if (err) { return done(err); }

            expect(acs.verify).to.be.calledOnce;
            expect(acs.verify.getCall(0).args[0]).to.equal('SplxlOBeZQQYbYS6WxSbIA');
            expect(ats.issue).to.not.be.called;
            expect(token).to.be.false;
            done();
          });
        })
        .catch(done);
    }); // should not issue access token when authorization code not issued to client

  }); // creating exchange

});
<|endoftext|>


<commit_before>var Vue = require('../../../src/vue')
var _ = require('../../../src/util')
var transition = require('../../../src/transition')

if (_.inBrowser && !_.isIE9) {
  describe('Transition', function () {

    describe('Wrapper methods', function () {

      var spy, el, target, parent, vm
      beforeEach(function () {
        el = document.createElement('div')
        target = document.createElement('div')
        parent = document.createElement('div')
        parent.appendChild(target)
        spy = jasmine.createSpy('transition skip')
        vm = new Vue()
        spyOn(transition, 'apply')
      })

      it('append', function () {
        transition.append(el, parent, vm, spy)
        expect(parent.lastChild).toBe(el)
        expect(spy).toHaveBeenCalled()
      })

      it('before', function () {
        transition.before(el, target, vm, spy)
        expect(parent.firstChild).toBe(el)
        expect(el.nextSibling).toBe(target)
        expect(spy).toHaveBeenCalled()
      })

      it('remove', function () {
        transition.remove(target, vm, spy)
        expect(parent.childNodes.length).toBe(0)
        expect(spy).toHaveBeenCalled()
      })

      it('removeThenAppend', function () {
        transition.removeThenAppend(target, el, vm, spy)
        expect(parent.childNodes.length).toBe(0)
        expect(el.firstChild).toBe(target)
        expect(spy).toHaveBeenCalled()
      })

    })

    describe('Skipping', function () {

      var el, vm, op, cb
      beforeEach(function () {
        el = document.createElement('div')
        op = jasmine.createSpy('transition skip op')
        cb = jasmine.createSpy('transition skip cb')
        vm = new Vue()
      })

      it('skip el with no transition data', function () {
        transition.apply(el, 1, op, vm, cb)
        expect(op).toHaveBeenCalled()
        expect(cb).toHaveBeenCalled()
      })

      it('skip vm still being compiled', function () {
        el.__v_trans = { id: 'test' }
        transition.apply(el, 1, op, vm, cb)
        expect(op).toHaveBeenCalled()
        expect(cb).toHaveBeenCalled()
      })

      it('skip vm with parent still being compiled', function () {
        el.__v_trans = { id: 'test' }
        var child = vm.$addChild({
          el: el
        })
        expect(child._isCompiled).toBe(true)
        transition.apply(el, 1, op, child, cb)
        expect(op).toHaveBeenCalled()
        expect(cb).toHaveBeenCalled()
      })

      it('skip when no transition available', function () {
        var e = _.transitionEndEvent
        _.transitionEndEvent = null
        el.__v_trans = { id: 'test' }
        vm.$mount(el)
        transition.apply(el, 1, op, vm, cb)
        expect(op).toHaveBeenCalled()
        expect(cb).toHaveBeenCalled()
        _.transitionEndEvent = e
      })

    })

    describe('CSS transitions', function () {

      var duration = '50ms'

      // insert a test css
      function insertCSS (text) {
        var cssEl = document.createElement('style')
        cssEl.textContent = text
        document.head.appendChild(cssEl)
      }

      insertCSS(
        '.test {\
          transition: opacity ' + duration + ' ease;\
          -webkit-transition: opacity ' + duration + ' ease;}'
      )
      insertCSS('.test-enter, .test-leave { opacity: 0; }')
      insertCSS(
        '.test-anim-enter {\
          animation: test-enter ' + duration + ';\
          -webkit-animation: test-enter ' + duration + ';}\
        .test-anim-leave {\
          animation: test-leave ' + duration + ';\
          -webkit-animation: test-leave ' + duration + ';}\
        @keyframes test-enter {\
          from { opacity: 0 }\
          to { opacity: 1 }}\
        @-webkit-keyframes test-enter {\
          from { opacity: 0 }\
          to { opacity: 1 }}\
        @keyframes test-leave {\
          from { opacity: 1 }\
          to { opacity: 0 }}\
        @-webkit-keyframes test-leave {\
          from { opacity: 1 }\
          to { opacity: 0 }}'
      )

      var vm, el, op, cb
      beforeEach(function (done) {
        el = document.createElement('div')
        el.__v_trans = {}
        vm = new Vue({ el: el })
        op = jasmine.createSpy('css op')
        cb = jasmine.createSpy('css cb')
        document.body.appendChild(el)
        // !IMPORTANT!
        // this ensures we force a layout for every test.
        _.nextTick(done)
        spyOn(window, 'getComputedStyle').and.callThrough()
      })

      afterEach(function () {
        document.body.removeChild(el)
      })

      it('skip on 0s duration', function () {
        el.__v_trans.id = 'test'
        el.style.transition =
        el.style.WebkitTransition = 'opacity 0s ease'
        transition.apply(el, 1, op, vm, cb)
        expect(op).toHaveBeenCalled()
        expect(cb).toHaveBeenCalled()
        expect(el.classList.contains('test-enter')).toBe(false)
        transition.apply(el, -1, op, vm, cb)
        expect(op.calls.count()).toBe(2)
        expect(cb.calls.count()).toBe(2)
        expect(el.classList.contains('test-leave')).toBe(false)
      })

      it('skip when no transition available', function () {
        el.__v_trans.id = 'test-no-trans'
        transition.apply(el, 1, op, vm, cb)
        expect(op).toHaveBeenCalled()
        expect(cb).toHaveBeenCalled()
        expect(el.classList.contains('test-no-trans-enter')).toBe(false)
        transition.apply(el, -1, op, vm, cb)
        expect(op.calls.count()).toBe(2)
        expect(cb.calls.count()).toBe(2)
        expect(el.classList.contains('test-no-trans-leave')).toBe(false)
      })

      it('transition enter', function (done) {
        document.body.removeChild(el)
        el.__v_trans.id = 'test'
        // inline style
        el.style.transition =
        el.style.WebkitTransition = 'opacity ' + duration + ' ease'
        transition.apply(el, 1, function () {
          document.body.appendChild(el)
          op()
        }, vm, cb)
        expect(op).toHaveBeenCalled()
        expect(cb).not.toHaveBeenCalled()
        _.nextTick(function () {
          expect(el.classList.contains('test-enter')).toBe(false)
          _.on(el, _.transitionEndEvent, function () {
            expect(cb).toHaveBeenCalled()
            done()
          })
        })
      })

      it('transition leave', function (done) {
        el.__v_trans.id = 'test'
        // cascaded class style
        el.classList.add('test')
        transition.apply(el, -1, op, vm, cb)
        expect(op).not.toHaveBeenCalled()
        expect(cb).not.toHaveBeenCalled()
        expect(el.classList.contains('test-leave')).toBe(false)
        _.nextTick(function () {
          expect(el.classList.contains('test-leave')).toBe(true)
          _.on(el, _.transitionEndEvent, function () {
            expect(op).toHaveBeenCalled()
            expect(cb).toHaveBeenCalled()
            expect(el.classList.contains('test-leave')).toBe(false)
            done()
          })
        })
      })

      it('animation enter', function (done) {
        document.body.removeChild(el)
        el.__v_trans.id = 'test-anim'
        transition.apply(el, 1, function () {
          document.body.appendChild(el)
          op()
        }, vm, cb)
        expect(op).toHaveBeenCalled()
        expect(cb).not.toHaveBeenCalled()
        expect(el.classList.contains('test-anim-enter')).toBe(true)
        _.on(el, _.animationEndEvent, function () {
          expect(el.classList.contains('test-anim-enter')).toBe(false)
          expect(cb).toHaveBeenCalled()
          done()
        })
      })

      it('animation leave', function (done) {
        el.__v_trans.id = 'test-anim'
        transition.apply(el, -1, op, vm, cb)
        expect(op).not.toHaveBeenCalled()
        expect(cb).not.toHaveBeenCalled()
        expect(el.classList.contains('test-anim-leave')).toBe(true)
        _.on(el, _.animationEndEvent, function () {
          expect(op).toHaveBeenCalled()
          expect(cb).toHaveBeenCalled()
          expect(el.classList.contains('test-anim-leave')).toBe(false)
          done()
        })
      })

      it('clean up unfinished callback', function (done) {
        el.__v_trans.id = 'test'
        el.classList.add('test')
        transition.apply(el, -1, function () {
          document.body.removeChild(el)
        }, vm, cb)
        expect(el.__v_trans.callback).toBeTruthy()
        // cancel early
        _.nextTick(function () {
          expect(el.classList.contains('test-leave')).toBe(true)
          transition.apply(el, 1, function () {
            document.body.appendChild(el)
          }, vm)
          expect(cb).not.toHaveBeenCalled()
          expect(el.classList.contains('test-leave')).toBe(false)
          expect(el.__v_trans.callback).toBeNull()
          done()
        })
      })

      it('cache transition sniff results', function () {
        el.__v_trans.id = 'test'
        el.classList.add('test')
        transition.apply(el, 1, op, vm)
        expect(window.getComputedStyle.calls.count()).toBe(1)
        transition.apply(el, 1, op, vm)
        expect(window.getComputedStyle.calls.count()).toBe(1)
      })

    })

    describe('JavaScript transitions', function () {

      var el, vm, op, cb, def, emitter
      beforeEach(function () {
        emitter = {}
        el = document.createElement('div')
        el.__v_trans = { id: 'test' }
        document.body.appendChild(el)
        op = jasmine.createSpy('js transition op')
        cb = jasmine.createSpy('js transition cb')
        def = {}
        vm = new Vue({
          el: el,
          transitions: {
            test: def
          }
        })
      })

      afterEach(function () {
        document.body.removeChild(el)
      })

      it('beforeEnter', function () {
        def.beforeEnter = jasmine.createSpy('js transition beforeEnter')
        transition.apply(el, 1, op, vm, cb)
        expect(def.beforeEnter).toHaveBeenCalledWith(el)
      })

      it('enter', function () {
        var spy = jasmine.createSpy('js enter')
        def.enter = function (e, done) {
          expect(e).toBe(el)
          expect(op).toHaveBeenCalled()
          done()
          expect(cb).toHaveBeenCalled()
          spy()
        }
        transition.apply(el, 1, op, vm, cb)
        expect(spy).toHaveBeenCalled()
      })

      it('leave', function () {
        var spy = jasmine.createSpy('js leave')
        def.leave = function (e, done) {
          expect(e).toBe(el)
          done()
          expect(op).toHaveBeenCalled()
          expect(cb).toHaveBeenCalled()
          spy()
        }
        transition.apply(el, -1, op, vm, cb)
        expect(spy).toHaveBeenCalled()
      })

      it('no def', function () {
        transition.apply(el, 1, op, vm, cb)
        expect(op).toHaveBeenCalled()
        expect(cb).toHaveBeenCalled()
        transition.apply(el, -1, op, vm, cb)
        expect(op.calls.count()).toBe(2)
        expect(cb.calls.count()).toBe(2)
      })

      it('optional cleanup callback', function (done) {
        var cleanupSpy = jasmine.createSpy('js cleanup')
        var leaveSpy = jasmine.createSpy('js leave')
        def.enter = function (el, done) {
          var to = setTimeout(done, 30)
          return function () {
            clearTimeout(to)
            cleanupSpy()
          }
        }
        def.leave = function (el, done) {
          expect(cleanupSpy).toHaveBeenCalled()
          leaveSpy()
          done()
        }
        transition.apply(el, 1, op, vm, cb)
        setTimeout(function () {
          transition.apply(el, -1, op, vm)
          expect(leaveSpy).toHaveBeenCalled()
          setTimeout(function () {
            expect(cb).not.toHaveBeenCalled()
            done()
          }, 30)
        }, 15)
      })

    })

  })
}<commit_msg>make tests pass on Chrome 37.0 Android<commit_after>var Vue = require('../../../src/vue')
var _ = require('../../../src/util')
var transition = require('../../../src/transition')

if (_.inBrowser && !_.isIE9) {
  describe('Transition', function () {

    describe('Wrapper methods', function () {

      var spy, el, target, parent, vm
      beforeEach(function () {
        el = document.createElement('div')
        target = document.createElement('div')
        parent = document.createElement('div')
        parent.appendChild(target)
        spy = jasmine.createSpy('transition skip')
        vm = new Vue()
        spyOn(transition, 'apply')
      })

      it('append', function () {
        transition.append(el, parent, vm, spy)
        expect(parent.lastChild).toBe(el)
        expect(spy).toHaveBeenCalled()
      })

      it('before', function () {
        transition.before(el, target, vm, spy)
        expect(parent.firstChild).toBe(el)
        expect(el.nextSibling).toBe(target)
        expect(spy).toHaveBeenCalled()
      })

      it('remove', function () {
        transition.remove(target, vm, spy)
        expect(parent.childNodes.length).toBe(0)
        expect(spy).toHaveBeenCalled()
      })

      it('removeThenAppend', function () {
        transition.removeThenAppend(target, el, vm, spy)
        expect(parent.childNodes.length).toBe(0)
        expect(el.firstChild).toBe(target)
        expect(spy).toHaveBeenCalled()
      })

    })

    describe('Skipping', function () {

      var el, vm, op, cb
      beforeEach(function () {
        el = document.createElement('div')
        op = jasmine.createSpy('transition skip op')
        cb = jasmine.createSpy('transition skip cb')
        vm = new Vue()
      })

      it('skip el with no transition data', function () {
        transition.apply(el, 1, op, vm, cb)
        expect(op).toHaveBeenCalled()
        expect(cb).toHaveBeenCalled()
      })

      it('skip vm still being compiled', function () {
        el.__v_trans = { id: 'test' }
        transition.apply(el, 1, op, vm, cb)
        expect(op).toHaveBeenCalled()
        expect(cb).toHaveBeenCalled()
      })

      it('skip vm with parent still being compiled', function () {
        el.__v_trans = { id: 'test' }
        var child = vm.$addChild({
          el: el
        })
        expect(child._isCompiled).toBe(true)
        transition.apply(el, 1, op, child, cb)
        expect(op).toHaveBeenCalled()
        expect(cb).toHaveBeenCalled()
      })

      it('skip when no transition available', function () {
        var e = _.transitionEndEvent
        _.transitionEndEvent = null
        el.__v_trans = { id: 'test' }
        vm.$mount(el)
        transition.apply(el, 1, op, vm, cb)
        expect(op).toHaveBeenCalled()
        expect(cb).toHaveBeenCalled()
        _.transitionEndEvent = e
      })

    })

    describe('CSS transitions', function () {

      var duration = '50ms'

      // insert a test css
      function insertCSS (text) {
        var cssEl = document.createElement('style')
        cssEl.textContent = text
        document.head.appendChild(cssEl)
      }

      insertCSS(
        '.test {\
          transition: opacity ' + duration + ' ease;\
          -webkit-transition: opacity ' + duration + ' ease;}'
      )
      insertCSS('.test-enter, .test-leave { opacity: 0; }')
      insertCSS(
        '.test-anim-enter {\
          animation: test-enter ' + duration + ';\
          -webkit-animation: test-enter ' + duration + ';}\
        .test-anim-leave {\
          animation: test-leave ' + duration + ';\
          -webkit-animation: test-leave ' + duration + ';}\
        @keyframes test-enter {\
          from { opacity: 0 }\
          to { opacity: 1 }}\
        @-webkit-keyframes test-enter {\
          from { opacity: 0 }\
          to { opacity: 1 }}\
        @keyframes test-leave {\
          from { opacity: 1 }\
          to { opacity: 0 }}\
        @-webkit-keyframes test-leave {\
          from { opacity: 1 }\
          to { opacity: 0 }}'
      )

      var vm, el, op, cb
      beforeEach(function (done) {
        el = document.createElement('div')
        el.__v_trans = {}
        vm = new Vue({ el: el })
        op = jasmine.createSpy('css op')
        cb = jasmine.createSpy('css cb')
        document.body.appendChild(el)
        // !IMPORTANT!
        // this ensures we force a layout for every test.
        _.nextTick(done)
        spyOn(window, 'getComputedStyle').and.callThrough()
      })

      afterEach(function () {
        document.body.removeChild(el)
      })

      it('skip on 0s duration', function () {
        el.__v_trans.id = 'test'
        el.style.transition =
        el.style.WebkitTransition = 'opacity 0s ease'
        transition.apply(el, 1, op, vm, cb)
        expect(op).toHaveBeenCalled()
        expect(cb).toHaveBeenCalled()
        expect(el.classList.contains('test-enter')).toBe(false)
        transition.apply(el, -1, op, vm, cb)
        expect(op.calls.count()).toBe(2)
        expect(cb.calls.count()).toBe(2)
        expect(el.classList.contains('test-leave')).toBe(false)
      })

      it('skip when no transition available', function () {
        el.__v_trans.id = 'test-no-trans'
        transition.apply(el, 1, op, vm, cb)
        expect(op).toHaveBeenCalled()
        expect(cb).toHaveBeenCalled()
        expect(el.classList.contains('test-no-trans-enter')).toBe(false)
        transition.apply(el, -1, op, vm, cb)
        expect(op.calls.count()).toBe(2)
        expect(cb.calls.count()).toBe(2)
        expect(el.classList.contains('test-no-trans-leave')).toBe(false)
      })

      it('transition enter', function (done) {
        document.body.removeChild(el)
        el.__v_trans.id = 'test'
        // inline style
        el.style.transition =
        el.style.WebkitTransition = 'opacity ' + duration + ' ease'
        transition.apply(el, 1, function () {
          document.body.appendChild(el)
          op()
        }, vm, cb)
        expect(op).toHaveBeenCalled()
        expect(cb).not.toHaveBeenCalled()
        _.nextTick(function () {
          expect(el.classList.contains('test-enter')).toBe(false)
          _.on(el, _.transitionEndEvent, function () {
            expect(cb).toHaveBeenCalled()
            done()
          })
        })
      })

      it('transition leave', function (done) {
        el.__v_trans.id = 'test'
        // cascaded class style
        el.classList.add('test')
        // wait a frame: Chrome Android 37 doesn't trigger
        // transition if we apply the leave class in the
        // same frame.
        _.nextTick(function () {
          transition.apply(el, -1, op, vm, cb)
          expect(op).not.toHaveBeenCalled()
          expect(cb).not.toHaveBeenCalled()
          expect(el.classList.contains('test-leave')).toBe(false)
          _.nextTick(function () {
            expect(el.classList.contains('test-leave')).toBe(true)
            _.on(el, _.transitionEndEvent, function () {
              expect(op).toHaveBeenCalled()
              expect(cb).toHaveBeenCalled()
              expect(el.classList.contains('test-leave')).toBe(false)
              done()
            })
          })
        })
      })

      it('animation enter', function (done) {
        document.body.removeChild(el)
        el.__v_trans.id = 'test-anim'
        transition.apply(el, 1, function () {
          document.body.appendChild(el)
          op()
        }, vm, cb)
        expect(op).toHaveBeenCalled()
        expect(cb).not.toHaveBeenCalled()
        expect(el.classList.contains('test-anim-enter')).toBe(true)
        _.on(el, _.animationEndEvent, function () {
          expect(el.classList.contains('test-anim-enter')).toBe(false)
          expect(cb).toHaveBeenCalled()
          done()
        })
      })

      it('animation leave', function (done) {
        el.__v_trans.id = 'test-anim'
        transition.apply(el, -1, op, vm, cb)
        expect(op).not.toHaveBeenCalled()
        expect(cb).not.toHaveBeenCalled()
        expect(el.classList.contains('test-anim-leave')).toBe(true)
        _.on(el, _.animationEndEvent, function () {
          expect(op).toHaveBeenCalled()
          expect(cb).toHaveBeenCalled()
          expect(el.classList.contains('test-anim-leave')).toBe(false)
          done()
        })
      })

      it('clean up unfinished callback', function (done) {
        el.__v_trans.id = 'test'
        el.classList.add('test')
        transition.apply(el, -1, function () {
          document.body.removeChild(el)
        }, vm, cb)
        expect(el.__v_trans.callback).toBeTruthy()
        // cancel early
        _.nextTick(function () {
          expect(el.classList.contains('test-leave')).toBe(true)
          transition.apply(el, 1, function () {
            document.body.appendChild(el)
          }, vm)
          expect(cb).not.toHaveBeenCalled()
          expect(el.classList.contains('test-leave')).toBe(false)
          expect(el.__v_trans.callback).toBeNull()
          done()
        })
      })

      it('cache transition sniff results', function () {
        el.__v_trans.id = 'test'
        el.classList.add('test')
        transition.apply(el, 1, op, vm)
        expect(window.getComputedStyle.calls.count()).toBe(1)
        transition.apply(el, 1, op, vm)
        expect(window.getComputedStyle.calls.count()).toBe(1)
      })

    })

    describe('JavaScript transitions', function () {

      var el, vm, op, cb, def, emitter
      beforeEach(function () {
        emitter = {}
        el = document.createElement('div')
        el.__v_trans = { id: 'test' }
        document.body.appendChild(el)
        op = jasmine.createSpy('js transition op')
        cb = jasmine.createSpy('js transition cb')
        def = {}
        vm = new Vue({
          el: el,
          transitions: {
            test: def
          }
        })
      })

      afterEach(function () {
        document.body.removeChild(el)
      })

      it('beforeEnter', function () {
        def.beforeEnter = jasmine.createSpy('js transition beforeEnter')
        transition.apply(el, 1, op, vm, cb)
        expect(def.beforeEnter).toHaveBeenCalledWith(el)
      })

      it('enter', function () {
        var spy = jasmine.createSpy('js enter')
        def.enter = function (e, done) {
          expect(e).toBe(el)
          expect(op).toHaveBeenCalled()
          done()
          expect(cb).toHaveBeenCalled()
          spy()
        }
        transition.apply(el, 1, op, vm, cb)
        expect(spy).toHaveBeenCalled()
      })

      it('leave', function () {
        var spy = jasmine.createSpy('js leave')
        def.leave = function (e, done) {
          expect(e).toBe(el)
          done()
          expect(op).toHaveBeenCalled()
          expect(cb).toHaveBeenCalled()
          spy()
        }
        transition.apply(el, -1, op, vm, cb)
        expect(spy).toHaveBeenCalled()
      })

      it('no def', function () {
        transition.apply(el, 1, op, vm, cb)
        expect(op).toHaveBeenCalled()
        expect(cb).toHaveBeenCalled()
        transition.apply(el, -1, op, vm, cb)
        expect(op.calls.count()).toBe(2)
        expect(cb.calls.count()).toBe(2)
      })

      it('optional cleanup callback', function (done) {
        var cleanupSpy = jasmine.createSpy('js cleanup')
        var leaveSpy = jasmine.createSpy('js leave')
        def.enter = function (el, done) {
          var to = setTimeout(done, 30)
          return function () {
            clearTimeout(to)
            cleanupSpy()
          }
        }
        def.leave = function (el, done) {
          expect(cleanupSpy).toHaveBeenCalled()
          leaveSpy()
          done()
        }
        transition.apply(el, 1, op, vm, cb)
        setTimeout(function () {
          transition.apply(el, -1, op, vm)
          expect(leaveSpy).toHaveBeenCalled()
          setTimeout(function () {
            expect(cb).not.toHaveBeenCalled()
            done()
          }, 30)
        }, 15)
      })

    })

  })
}<|endoftext|>


<commit_before>/*eslint-env jasmine*/

"use strict";

let wsdotRouteUtils = require("../index");
let RouteDescription = wsdotRouteUtils.default;
let getRouteParts = wsdotRouteUtils.getRouteParts;

describe("RouteDescription", () => {
    it("won't parse invalidly formatted routes", () => {
        let srid = "005AAA";
        expect(() => { let thing = new RouteDescription(srid); }).toThrowError();
    });
    it("can parse mainline routes", () => {
        const srid = "005";
        let desc = new RouteDescription(srid);
        expect(desc.sr).toEqual(srid);
        expect(desc.rrt).toBeNull();
        expect(desc.rrq).toBeNull();
        expect(desc.mainlineConnectionMP).toBeNull();
        expect(desc.rrqDescription).toBeNull();
        expect(desc.rrqDescription).toBeNull();
        expect(desc.toString()).toEqual(srid);
    });
    it("can parse route with RRT && RRQ", () => {
        const srid = "101COABERDN";
        let [sr, rrt, rrq] = getRouteParts(srid);
        let desc = new RouteDescription(srid);
        expect(desc.sr).toEqual(sr);
        expect(desc.rrt).toEqual(rrt);
        expect(desc.rrq).toEqual(rrq);
        expect(desc.rrtDescription).toEqual("Couplet");
        expect(desc.rrqDescription).toEqual("Aberdeen");
        expect(desc.mainlineConnectionMP).toBeNull();
    });
    it("can parse MP from ramp ID", () => {
        const srid = "005R109958";
        let desc = new RouteDescription(srid);
        expect(desc.mainlineConnectionMP).toEqual(99.58);
    });

    it('can optionally support direction', function() {
        const withDirId = "529SPEVERETd";
        const nonDirId = "005Q516479";

        let withDirDesc = new RouteDescription(withDirId, true);
        let nonDirDesc = new RouteDescription(nonDirId, false);
        let incDesc = new RouteDescription(nonDirId, true);
        expect(withDirDesc.isDecrease).toEqual(true);
        expect(nonDirDesc.isDecrease).toEqual(null);
        expect(incDesc.isDecrease).toEqual(false);
        expect(() => {
            let desc = new RouteDescription(withDirId, false);
        }).toThrowError();
    });

});

<commit_msg>Jasmine test: replaced let and const with var for old node compatibility<commit_after>/*eslint-env jasmine*/

"use strict";

var wsdotRouteUtils = require("../index");
var RouteDescription = wsdotRouteUtils.default;
var getRouteParts = wsdotRouteUtils.getRouteParts;

describe("RouteDescription", () => {
    it("won't parse invalidly formatted routes", () => {
        var srid = "005AAA";
        expect(() => { var thing = new RouteDescription(srid); }).toThrowError();
    });
    it("can parse mainline routes", () => {
        var srid = "005";
        var desc = new RouteDescription(srid);
        expect(desc.sr).toEqual(srid);
        expect(desc.rrt).toBeNull();
        expect(desc.rrq).toBeNull();
        expect(desc.mainlineConnectionMP).toBeNull();
        expect(desc.rrqDescription).toBeNull();
        expect(desc.rrqDescription).toBeNull();
        expect(desc.toString()).toEqual(srid);
    });
    it("can parse route with RRT && RRQ", () => {
        var srid = "101COABERDN";
        var [sr, rrt, rrq] = getRouteParts(srid);
        var desc = new RouteDescription(srid);
        expect(desc.sr).toEqual(sr);
        expect(desc.rrt).toEqual(rrt);
        expect(desc.rrq).toEqual(rrq);
        expect(desc.rrtDescription).toEqual("Coupvar");
        expect(desc.rrqDescription).toEqual("Aberdeen");
        expect(desc.mainlineConnectionMP).toBeNull();
    });
    it("can parse MP from ramp ID", () => {
        var srid = "005R109958";
        var desc = new RouteDescription(srid);
        expect(desc.mainlineConnectionMP).toEqual(99.58);
    });

    it('can optionally support direction', function() {
        var withDirId = "529SPEVERETd";
        var nonDirId = "005Q516479";

        var withDirDesc = new RouteDescription(withDirId, true);
        var nonDirDesc = new RouteDescription(nonDirId, false);
        var incDesc = new RouteDescription(nonDirId, true);
        expect(withDirDesc.isDecrease).toEqual(true);
        expect(nonDirDesc.isDecrease).toEqual(null);
        expect(incDesc.isDecrease).toEqual(false);
        expect(() => {
            var desc = new RouteDescription(withDirId, false);
        }).toThrowError();
    });

});

<|endoftext|>


<commit_before>/* global beforeEach, describe, expect, it, jasmine, spyOn */
describe('Page', function() {
  function setCurrentScope(scope) {
    document.body.dataset.page = scope;
  }

  beforeEach(function() {
    this.page = new window.Page();
  });

  it('runs the initializer block for the given scope', function() {
    var block = jasmine.createSpy();
    this.page.at('a-scope', block);

    setCurrentScope('a-scope');
    this.page.dispatch();
    expect(block).toHaveBeenCalled();
  });

  it('sends the current scope as an argument', function() {
    var arg;
    this.page.at('the-scope', function(scope) { arg = scope; });

    setCurrentScope('the-scope');
    this.page.dispatch();

    expect(arg).toEqual('the-scope');
  });

  it('always run the before and after block', function() {
    var beforeBlock = jasmine.createSpy(),
        afterBlock = jasmine.createSpy();
    this.page.at(':before', beforeBlock);
    this.page.at(':after', afterBlock);

    setCurrentScope('scope-without-blocks');
    this.page.dispatch();

    expect(beforeBlock).toHaveBeenCalled();
    expect(afterBlock).toHaveBeenCalled();
  });

  it('runs multiple blocks for the given scope', function() {
    var sequence = [];
    this.page.at('multiple', function() { sequence.push(1); });
    this.page.at('multiple', function() { sequence.push(2); });

    setCurrentScope('multiple');
    this.page.dispatch();

    expect(sequence).toEqual([1,2]);
  });

  it('halts the chain if a block returns false', function() {
    var block = jasmine.createSpy();
    this.page.at('halting', function() { return false; });
    this.page.at('halting', block);

    setCurrentScope('halting');
    this.page.dispatch();

    expect(block).not.toHaveBeenCalled();
  });

  it("runs the chain on the following order - 'before', initializers, and 'after'", function() {
    var sequence = [];
    this.page.at('chain',   function() { sequence.push('initializer'); });
    this.page.at(':before', function() { sequence.push(':before'); });
    this.page.at(':after',  function() { sequence.push(':after'); });

    setCurrentScope('chain');
    this.page.dispatch();

    expect(sequence).toEqual([':before', 'initializer', ':after']);
  });

  it('stores the same block for more than one scope', function() {
    var called = 0;
    this.page.at('one two', function() { called += 1; });

    setCurrentScope('one');
    this.page.dispatch();

    setCurrentScope('two');
    this.page.dispatch();

    expect(called).toEqual(2);
  });

  it('detects the current scope if none is given to the run', function() {
    spyOn(this.page, 'recognize');

    this.page.dispatch();
    expect(this.page.recognize).toHaveBeenCalled();
  });
});
<commit_msg>Fix Jasmine output.<commit_after>/* global beforeEach, describe, expect, it, jasmine, spyOn */
describe('Page', function() {
  function setCurrentScope(scope) {
    document.body.dataset.page = scope;
  }

  beforeEach(function() {
    this.page = new window.Page();
  });

  it('runs the initializer block for the given scope', function() {
    var block = jasmine.createSpy();
    this.page.at('a-scope', block);

    setCurrentScope('a-scope');
    this.page.dispatch();
    expect(block).toHaveBeenCalled();
  });

  it('sends the current scope as an argument', function() {
    var arg;
    this.page.at('the-scope', function(scope) { arg = scope; });

    setCurrentScope('the-scope');
    this.page.dispatch();

    expect(arg).toEqual('the-scope');
  });

  it('always run the before and after block', function() {
    var beforeBlock = jasmine.createSpy(),
        afterBlock = jasmine.createSpy();
    this.page.at(':before', beforeBlock);
    this.page.at(':after', afterBlock);

    setCurrentScope('scope-without-blocks');
    this.page.dispatch();

    expect(beforeBlock).toHaveBeenCalled();
    expect(afterBlock).toHaveBeenCalled();
  });

  it('runs multiple blocks for the given scope', function() {
    var sequence = [];
    this.page.at('multiple', function() { sequence.push(1); });
    this.page.at('multiple', function() { sequence.push(2); });

    setCurrentScope('multiple');
    this.page.dispatch();

    expect(sequence).toEqual([1,2]);
  });

  it('halts the chain if a block returns false', function() {
    var block = jasmine.createSpy();
    this.page.at('halting', function() { return false; });
    this.page.at('halting', block);

    setCurrentScope('halting');
    this.page.dispatch();

    expect(block).not.toHaveBeenCalled();
  });

  it("runs the chain on the following order: 'before', initializers, and 'after'", function() {
    var sequence = [];
    this.page.at('chain',   function() { sequence.push('initializer'); });
    this.page.at(':before', function() { sequence.push(':before'); });
    this.page.at(':after',  function() { sequence.push(':after'); });

    setCurrentScope('chain');
    this.page.dispatch();

    expect(sequence).toEqual([':before', 'initializer', ':after']);
  });

  it('stores the same block for more than one scope', function() {
    var called = 0;
    this.page.at('one two', function() { called += 1; });

    setCurrentScope('one');
    this.page.dispatch();

    setCurrentScope('two');
    this.page.dispatch();

    expect(called).toEqual(2);
  });

  it('detects the current scope if none is given to the run', function() {
    spyOn(this.page, 'recognize');

    this.page.dispatch();
    expect(this.page.recognize).toHaveBeenCalled();
  });
});
<|endoftext|>