<commit_before>function random(min, max) {
    return Math.floor(Math.random()*(max-min+1)+min);
}

var HomePage = function() {
    this.meetingName = 'test' + random(1000,2000);

    this.meetingInput = element(by.model('meetingName')),
    this.createMeetingButton = element(by.buttonText('Create a Meeting!')),

    this.get = function() {
        browser.get('http://localhost:5000/');
    }

    this.createMeeting = function() {
        this.meetingInput.sendKeys(this.meetingName);
        this.createMeetingButton.click();
    }

    this.getMeetingName = function() {
        return this.meetingName;
    }
};

describe('lean coffee', function(){

    var homePage = new HomePage();
    homePage.get();
    homePage.createMeeting();

    describe('meeting', function(){

        it('should display my user name', function(){
            var userElement = element(by.binding('user'));
            expect(userElement.getText()).toMatch(/You are: [\s\w]+/);
        });

        xit('should display the meeting particpants', function(){

        });

        it('should show the name of the meeting', function(){
            browser.debugger();

            var meetingNameElement = $('.meeting-list'); // element(by.model('meeting.name'));
            expect(meetingNameElement.getText()).toContain(homePage.getMeetingName());
        });

        xit('should show who the host is', function(){

        });

        xit('should show me if I am the host', function(){

        });

        xit('should allow transition to the next meeting phase', function(){

        });

        xit('should show a timer', function(){

        });

        describe('sumbit phase', function(){

            xit('should allow us submit a topic', function(){

            });

            xit('should show all topics', function(){

            });

            xit('should show the remaining time for the phase', function(){
            x
            });

            xit('should show the name of the person who submitted the topic', function(){

            });

            describe('timer expiration', function(){

                xit('(maybe?) should advance automatically to the merge phase', function(){

                });

                xit('(maybe?) should disable submission, but not automaticallly transition to merge phase', function(){

                });
            });
        });

        describe('merge phase', function(){

            xit('(maybe?) should allow merging of 2+ topics', function(){

            });

            xit('should allow us to merge two topics', function(){

            });

            describe('merge ownership', function(){

                xit('(maybe?) should show all owners for a merged topic', function(){

                });

                xit('(maybe?) should show the original topic owner', function(){

                });
            });

            describe('merge text', function(){

                xit('(maybe?) should merge text when topics are merged', function(){

                });

                xit('(maybe?) should show original text when topics are merged', function(){

                });
            });

            describe('timer expiration', function(){

                xit('(maybe?) should advance automatically to the vote phase', function(){

                });

                xit('(maybe?) should disable merging, but not automaticallly transition to voting phase', function(){

                });
            });
        });

        describe('voting phase', function(){

            xit('should start the timer when the phase begins', function(){

            });

            xit('should show the remaining time for the phase', function(){

            });

            xit('should display an icon to vote with', function(){

            });

            xit('should allow a user to vote', function(){

            });

            xit('should allow a user to vote up to 3 times', function(){

            });

            xit('should allow a user to vote on up to 3 topics', function(){

            });

            xit('should allow a user to vote 3 times on a single topic', function(){

            });

            xit('should not allow a user to vote 4 or more times', function(){

            });

            xit('should display the number of votes the user has remaining', function(){

            });

            xit('(maybe?) should display total number of remaining votes across all users', function(){

            });

            xit('(maybe?) should allow a user to change their votes', function(){

            });

            describe('timer expiration', function(){

                xit('(maybe?) should advance automatically to the discuss phase', function(){

                });

                xit('(maybe?) should disable voting, but not automatically move to the discuss phase', function(){

                });
            });
        });

        describe('discuss phase', function(){

            xit('should order the topics by number of votes', function(){

            });

            xit('should show the active topic', function(){

            });

            xit('should show the remaining time to discuss the active topic', function(){

            });

            xit('should allow the host to advance to the topic forcibly', function(){

            });

            describe('all topics discussed', function(){
                xit('(maybe?) should show star guy', function(){

                });

                xit('(maybe?) should show a summary of topics discussed', function(){

                });

                xit('should have no active topic', function(){

                });

                xit('should hide any remaining timers', function(){

                });

                xit('(maybe?) should prompt for email', function(){

                });

                xit('(maybe?) should move the user to the landing page and delete the meeting', function(){

                });
            });

            describe('timer expiration', function(){

                xit('(maybe?) should allow you to vote to continue discussing this topic', function(){

                });

                xit('(maybe?) should allow you to vote to continue discussing this topic 15 seconds prior to expiration', function(){

                });

                describe('vote is to stop talking about the current topic' , function(){

                    xit('(maybe?) automatically move to the next topic', function(){

                    });

                    xit('(maybe?) should do nothing', function(){

                    });

                    xit('(maybe?) it allows manual movement to the next topic (by host, or by user)', function(){

                    });

                });

                describe('vote is to continue talking' , function(){

                    xit('(maybe?) automatically reset the timer to 3 minutes', function(){

                    });

                    xit('(maybe?) should do nothing', function(){

                    });

                    xit('(maybe?) it allows manual reset of the timer', function(){

                    });

                });

                describe('the vote to continue is tied or no one votes', function(){
                    xit('(maybe?) host breaks the tie', function(){

                    });

                    xit('(maybe?) tie goes stop', function(){

                    });
                });

            });

            describe('tie breakers', function(){
                xit('(maybe?) should sort ties by timestamp', function(){

                });

                xit('(maybe?) should randomize ties', function(){

                });

                xit('(maybe?) should sort ties alphabetically', function(){

                });
            });

            describe('(maybe?) notes', function(){

                xit('(maybe?> allow host to take notes on active topic', function(){

                });

                xit('(maybe?) should allow participants to take personal notes', function(){

                });

                xit('(maybe?) should allow collaborative note taking', function(){

                });

                xit('(maybe?) should display the all notes to all participants', function(){

                });

                xit('(maybe?) should only allow the Chinese swear words from Firefly', function(){

                });
            });

            describe('email', function(){
                xit('(maybe?) should allow "subscribing" to each topic', function(){

                });

                xit('(maybe?) should populate an email subject and body', function(){

                });

                xit('should be optional', function(){

                });

                describe('body', function(){
                    xit('(maybe?) should contain all the topics discussed', function(){

                    });

                    xit('(maybe?) should contain only the topics "subscribed" to', function(){

                    });

                    xit('(maybe?) should contain the notes for each topic', function(){

                    });
                });
            });
        });
    });

});
<commit_msg>added page object for meeting<commit_after>function random(min, max) {
    return Math.floor(Math.random()*(max-min+1)+min);
}

var HomePage = function() {
    this.meetingName = 'test' + random(1000,2000);

    this.meetingInput = element(by.model('meetingName')),
    this.createMeetingButton = element(by.buttonText('Create a Meeting!')),

    this.get = function() {
        browser.get('http://localhost:5000/');
    }

    this.createMeeting = function() {
        this.meetingInput.sendKeys(this.meetingName);
        this.createMeetingButton.click();
    }

    this.getMeetingName = function() {
        return this.meetingName;
    }
};

var MeetingPage = function() {
    this.userGreeting = function() {
        return element(by.binding('user'));
    }
};

describe('lean coffee', function(){

    var homePage = new HomePage();
    homePage.get();
    homePage.createMeeting();

    describe('meeting', function(){
        var meetingPage = new MeetingPage();

        it('should display my user name', function(){
            expect(meetingPage.userGreeting().getText()).toMatch(/You are: [\s\w]+/);
        });

        xit('should display the meeting particpants', function(){

        });

        it('should show the name of the meeting', function(){
            browser.debugger();

            var meetingNameElement = $('.meeting-list'); // element(by.model('meeting.name'));
            expect(meetingNameElement.getText()).toContain(homePage.getMeetingName());
        });

        xit('should show who the host is', function(){

        });

        xit('should show me if I am the host', function(){

        });

        xit('should allow transition to the next meeting phase', function(){

        });

        xit('should show a timer', function(){

        });

        describe('sumbit phase', function(){

            xit('should allow us submit a topic', function(){

            });

            xit('should show all topics', function(){

            });

            xit('should show the remaining time for the phase', function(){
            x
            });

            xit('should show the name of the person who submitted the topic', function(){

            });

            describe('timer expiration', function(){

                xit('(maybe?) should advance automatically to the merge phase', function(){

                });

                xit('(maybe?) should disable submission, but not automaticallly transition to merge phase', function(){

                });
            });
        });

        describe('merge phase', function(){

            xit('(maybe?) should allow merging of 2+ topics', function(){

            });

            xit('should allow us to merge two topics', function(){

            });

            describe('merge ownership', function(){

                xit('(maybe?) should show all owners for a merged topic', function(){

                });

                xit('(maybe?) should show the original topic owner', function(){

                });
            });

            describe('merge text', function(){

                xit('(maybe?) should merge text when topics are merged', function(){

                });

                xit('(maybe?) should show original text when topics are merged', function(){

                });
            });

            describe('timer expiration', function(){

                xit('(maybe?) should advance automatically to the vote phase', function(){

                });

                xit('(maybe?) should disable merging, but not automaticallly transition to voting phase', function(){

                });
            });
        });

        describe('voting phase', function(){

            xit('should start the timer when the phase begins', function(){

            });

            xit('should show the remaining time for the phase', function(){

            });

            xit('should display an icon to vote with', function(){

            });

            xit('should allow a user to vote', function(){

            });

            xit('should allow a user to vote up to 3 times', function(){

            });

            xit('should allow a user to vote on up to 3 topics', function(){

            });

            xit('should allow a user to vote 3 times on a single topic', function(){

            });

            xit('should not allow a user to vote 4 or more times', function(){

            });

            xit('should display the number of votes the user has remaining', function(){

            });

            xit('(maybe?) should display total number of remaining votes across all users', function(){

            });

            xit('(maybe?) should allow a user to change their votes', function(){

            });

            describe('timer expiration', function(){

                xit('(maybe?) should advance automatically to the discuss phase', function(){

                });

                xit('(maybe?) should disable voting, but not automatically move to the discuss phase', function(){

                });
            });
        });

        describe('discuss phase', function(){

            xit('should order the topics by number of votes', function(){

            });

            xit('should show the active topic', function(){

            });

            xit('should show the remaining time to discuss the active topic', function(){

            });

            xit('should allow the host to advance to the topic forcibly', function(){

            });

            describe('all topics discussed', function(){
                xit('(maybe?) should show star guy', function(){

                });

                xit('(maybe?) should show a summary of topics discussed', function(){

                });

                xit('should have no active topic', function(){

                });

                xit('should hide any remaining timers', function(){

                });

                xit('(maybe?) should prompt for email', function(){

                });

                xit('(maybe?) should move the user to the landing page and delete the meeting', function(){

                });
            });

            describe('timer expiration', function(){

                xit('(maybe?) should allow you to vote to continue discussing this topic', function(){

                });

                xit('(maybe?) should allow you to vote to continue discussing this topic 15 seconds prior to expiration', function(){

                });

                describe('vote is to stop talking about the current topic' , function(){

                    xit('(maybe?) automatically move to the next topic', function(){

                    });

                    xit('(maybe?) should do nothing', function(){

                    });

                    xit('(maybe?) it allows manual movement to the next topic (by host, or by user)', function(){

                    });

                });

                describe('vote is to continue talking' , function(){

                    xit('(maybe?) automatically reset the timer to 3 minutes', function(){

                    });

                    xit('(maybe?) should do nothing', function(){

                    });

                    xit('(maybe?) it allows manual reset of the timer', function(){

                    });

                });

                describe('the vote to continue is tied or no one votes', function(){
                    xit('(maybe?) host breaks the tie', function(){

                    });

                    xit('(maybe?) tie goes stop', function(){

                    });
                });

            });

            describe('tie breakers', function(){
                xit('(maybe?) should sort ties by timestamp', function(){

                });

                xit('(maybe?) should randomize ties', function(){

                });

                xit('(maybe?) should sort ties alphabetically', function(){

                });
            });

            describe('(maybe?) notes', function(){

                xit('(maybe?> allow host to take notes on active topic', function(){

                });

                xit('(maybe?) should allow participants to take personal notes', function(){

                });

                xit('(maybe?) should allow collaborative note taking', function(){

                });

                xit('(maybe?) should display the all notes to all participants', function(){

                });

                xit('(maybe?) should only allow the Chinese swear words from Firefly', function(){

                });
            });

            describe('email', function(){
                xit('(maybe?) should allow "subscribing" to each topic', function(){

                });

                xit('(maybe?) should populate an email subject and body', function(){

                });

                xit('should be optional', function(){

                });

                describe('body', function(){
                    xit('(maybe?) should contain all the topics discussed', function(){

                    });

                    xit('(maybe?) should contain only the topics "subscribed" to', function(){

                    });

                    xit('(maybe?) should contain the notes for each topic', function(){

                    });
                });
            });
        });
    });

});
<|endoftext|>


<commit_before>/*global define*/
define([
        './ImageryState',
        './TileState'
    ], function(
        ImageryState,
        TileState) {
    "use strict";

    /**
     * A priority queue of tiles to be replaced, if necessary, to make room for new tiles.  The queue
     * is implemented as a linked list.
     *
     * @alias TileReplacementQueue
     * @private
     */
    var TileReplacementQueue = function TileReplacementQueue() {
        this.head = undefined;
        this.tail = undefined;
        this.count = 0;
        this._lastBeforeStartOfFrame = undefined;
    };

    /**
     * Marks the start of the render frame.  Tiles before (closer to the head) this tile in the
     * list were used last frame and must not be unloaded.
     */
    TileReplacementQueue.prototype.markStartOfRenderFrame = function() {
        this._lastBeforeStartOfFrame = this.head;
    };

    /**
     * Reduces the size of the queue to a specified size by unloading the least-recently used
     * tiles.  Tiles that were used last frame will not be unloaded, even if that puts the number
     * of tiles above the specified maximum.
     *
     * @memberof TileReplacementQueue
     *
     * @param {Number} maximumTiles The maximum number of tiles in the queue.
     */
    TileReplacementQueue.prototype.trimTiles = function(maximumTiles) {
        var tileToTrim = this.tail;
        var keepTrimming = true;
        while (keepTrimming &&
               typeof this._lastBeforeStartOfFrame !== 'undefined' &&
               this.count > maximumTiles &&
               typeof tileToTrim !== 'undefined') {
            // Stop trimming after we process the last tile not used in the
            // current frame.
            keepTrimming = tileToTrim !== this._lastBeforeStartOfFrame;

            var previous = tileToTrim.replacementPrevious;

            // Do not remove tiles that are transitioning or that have
            // imagery that is transitioning.
            var removeTile = tileToTrim.state !== TileState.TRANSITIONING;
            var imagery = tileToTrim.imagery;
            for (var i = 0, len = imagery.length; removeTile && i < len; ++i) {
                var tileImagery = imagery[i];
                removeTile = tileImagery.imagery.state !== ImageryState.TRANSITIONING;
            }

            if (removeTile) {
                tileToTrim.freeResources();
                this._remove(tileToTrim);
            }

            tileToTrim = previous;
        }
    };

    TileReplacementQueue.prototype._remove = function(item) {
        var previous = item.replacementPrevious;
        var next = item.replacementNext;

        if (item === this._lastBeforeStartOfFrame) {
            this._lastBeforeStartOfFrame = next;
        }

        if (item === this.head) {
            this.head = next;
        } else {
            previous.replacementNext = next;
        }

        if (item === this.tail) {
            this.tail = previous;
        } else {
            next.replacementPrevious = previous;
        }

        item.replacementPrevious = undefined;
        item.replacementNext = undefined;

        --this.count;
    };

    /**
     * Marks a tile as rendered this frame and moves it before the first tile that was not rendered
     * this frame.
     *
     * @memberof TileReplacementQueue
     *
     * @param {TileReplacementQueue} item The tile that was rendered.
     */
    TileReplacementQueue.prototype.markTileRendered = function(item) {
        var head = this.head;
        if (head === item) {
            if (item === this._lastBeforeStartOfFrame) {
                this._lastBeforeStartOfFrame = item.replacementNext;
            }
            return;
        }

        ++this.count;

        if (typeof head === 'undefined') {
            // no other tiles in the list
            item.replacementPrevious = undefined;
            item.replacementNext = undefined;
            this.head = item;
            this.tail = item;
            return;
        }

        if (typeof item.replacementPrevious !== 'undefined' || typeof item.replacementNext !== 'undefined') {
            // tile already in the list, remove from its current location
            this._remove(item);
        }

        item.replacementPrevious = undefined;
        item.replacementNext = head;
        head.replacementPrevious = item;

        this.head = item;
    };

    return TileReplacementQueue;
});
<commit_msg>Rename removeTile to shouldRemoveTile.<commit_after>/*global define*/
define([
        './ImageryState',
        './TileState'
    ], function(
        ImageryState,
        TileState) {
    "use strict";

    /**
     * A priority queue of tiles to be replaced, if necessary, to make room for new tiles.  The queue
     * is implemented as a linked list.
     *
     * @alias TileReplacementQueue
     * @private
     */
    var TileReplacementQueue = function TileReplacementQueue() {
        this.head = undefined;
        this.tail = undefined;
        this.count = 0;
        this._lastBeforeStartOfFrame = undefined;
    };

    /**
     * Marks the start of the render frame.  Tiles before (closer to the head) this tile in the
     * list were used last frame and must not be unloaded.
     */
    TileReplacementQueue.prototype.markStartOfRenderFrame = function() {
        this._lastBeforeStartOfFrame = this.head;
    };

    /**
     * Reduces the size of the queue to a specified size by unloading the least-recently used
     * tiles.  Tiles that were used last frame will not be unloaded, even if that puts the number
     * of tiles above the specified maximum.
     *
     * @memberof TileReplacementQueue
     *
     * @param {Number} maximumTiles The maximum number of tiles in the queue.
     */
    TileReplacementQueue.prototype.trimTiles = function(maximumTiles) {
        var tileToTrim = this.tail;
        var keepTrimming = true;
        while (keepTrimming &&
               typeof this._lastBeforeStartOfFrame !== 'undefined' &&
               this.count > maximumTiles &&
               typeof tileToTrim !== 'undefined') {
            // Stop trimming after we process the last tile not used in the
            // current frame.
            keepTrimming = tileToTrim !== this._lastBeforeStartOfFrame;

            var previous = tileToTrim.replacementPrevious;

            // Do not remove tiles that are transitioning or that have
            // imagery that is transitioning.
            var shouldRemoveTile = tileToTrim.state !== TileState.TRANSITIONING;
            var imagery = tileToTrim.imagery;
            for (var i = 0, len = imagery.length; shouldRemoveTile && i < len; ++i) {
                var tileImagery = imagery[i];
                shouldRemoveTile = tileImagery.imagery.state !== ImageryState.TRANSITIONING;
            }

            if (shouldRemoveTile) {
                tileToTrim.freeResources();
                this._remove(tileToTrim);
            }

            tileToTrim = previous;
        }
    };

    TileReplacementQueue.prototype._remove = function(item) {
        var previous = item.replacementPrevious;
        var next = item.replacementNext;

        if (item === this._lastBeforeStartOfFrame) {
            this._lastBeforeStartOfFrame = next;
        }

        if (item === this.head) {
            this.head = next;
        } else {
            previous.replacementNext = next;
        }

        if (item === this.tail) {
            this.tail = previous;
        } else {
            next.replacementPrevious = previous;
        }

        item.replacementPrevious = undefined;
        item.replacementNext = undefined;

        --this.count;
    };

    /**
     * Marks a tile as rendered this frame and moves it before the first tile that was not rendered
     * this frame.
     *
     * @memberof TileReplacementQueue
     *
     * @param {TileReplacementQueue} item The tile that was rendered.
     */
    TileReplacementQueue.prototype.markTileRendered = function(item) {
        var head = this.head;
        if (head === item) {
            if (item === this._lastBeforeStartOfFrame) {
                this._lastBeforeStartOfFrame = item.replacementNext;
            }
            return;
        }

        ++this.count;

        if (typeof head === 'undefined') {
            // no other tiles in the list
            item.replacementPrevious = undefined;
            item.replacementNext = undefined;
            this.head = item;
            this.tail = item;
            return;
        }

        if (typeof item.replacementPrevious !== 'undefined' || typeof item.replacementNext !== 'undefined') {
            // tile already in the list, remove from its current location
            this._remove(item);
        }

        item.replacementPrevious = undefined;
        item.replacementNext = head;
        head.replacementPrevious = item;

        this.head = item;
    };

    return TileReplacementQueue;
});
<|endoftext|>


<commit_before>/** Breadcrumb management. */
Ext.define('devilry_extjsextras.Breadcrumbs', {
    extend: 'Ext.Component',
    alias: 'widget.breadcrumbs',
    cls: 'breadcrumb-component',

    home: {
        url: '',
        text: 'Dashboard'
    },

    tpl: [
        '
',
            '
',
                gettext('You are here'),
            ':
',
            '<tpl for="breadcrumbs">',
                '<tpl if="xindex != xcount">',
                    '
',
                        '{text}/',
                    '
',
                '</tpl>',
                '<tpl if="xindex == xcount">',
                    '
{text}
',
                '</tpl>',
            '</tpl>',
        '
'
    ],

    /**
     * @cfg
     *
     */
    defaultBreadcrumbs: undefined,

    initComponent: function() {
        this.clear();
        this.callParent(arguments);
        this.draw();
    },

    /** Set the breadcrumbs.
     *
     * Example:
     *
     *      set([{
     *          url: '/hello',
     *          text: 'Hello'
     *      }, {
     *          url: '/hello/cruel',
     *          text: 'Cruel'
     *      }], 'World');
     * */
    set: function(breadcrumbs, current) {
        this.clear();
        if(this.defaultBreadcrumbs) {
            this.addMany(this.defaultBreadcrumbs);
        }
        this.addMany(breadcrumbs);
        this.add('', current)
        this.draw();
    },

    addMany: function(breadcrumbs) {
        Ext.Array.each(breadcrumbs, function(breadcrumb) {
            this.add(breadcrumb.url, breadcrumb.text);
        }, this);
    },

    add: function(url, text) {
        this.breadcrumbs.push({
            url: url,
            text: text
        });
    },

    clear: function() {
        this.breadcrumbs = [];
        //this.add(this.home.url, this.home.text);
    },

    draw: function() {
        if(this.breadcrumbs.length === 0) {
            this.hide();
        } else {
            this.show();
            this.update({
                breadcrumbs: this.breadcrumbs
            });
        }
    },

    setHome: function() {
        this.clear();
        this.draw();
    }
});
<commit_msg>devilry_extjsextras...Breadcrumbs: No "You are here".<commit_after>/** Breadcrumb management. */
Ext.define('devilry_extjsextras.Breadcrumbs', {
    extend: 'Ext.Component',
    alias: 'widget.breadcrumbs',
    cls: 'breadcrumb-component',

    home: {
        url: '',
        text: 'Dashboard'
    },

    tpl: [
        '
',
            '<tpl for="breadcrumbs">',
                '<tpl if="xindex != xcount">',
                    '
',
                        '{text}/',
                    '
',
                '</tpl>',
                '<tpl if="xindex == xcount">',
                    '
{text}
',
                '</tpl>',
            '</tpl>',
        '
'
    ],

    /**
     * @cfg
     *
     */
    defaultBreadcrumbs: undefined,

    initComponent: function() {
        this.clear();
        this.callParent(arguments);
        this.draw();
    },

    /** Set the breadcrumbs.
     *
     * Example:
     *
     *      set([{
     *          url: '/hello',
     *          text: 'Hello'
     *      }, {
     *          url: '/hello/cruel',
     *          text: 'Cruel'
     *      }], 'World');
     * */
    set: function(breadcrumbs, current) {
        this.clear();
        if(this.defaultBreadcrumbs) {
            this.addMany(this.defaultBreadcrumbs);
        }
        this.addMany(breadcrumbs);
        this.add('', current)
        this.draw();
    },

    addMany: function(breadcrumbs) {
        Ext.Array.each(breadcrumbs, function(breadcrumb) {
            this.add(breadcrumb.url, breadcrumb.text);
        }, this);
    },

    add: function(url, text) {
        this.breadcrumbs.push({
            url: url,
            text: text
        });
    },

    clear: function() {
        this.breadcrumbs = [];
        //this.add(this.home.url, this.home.text);
    },

    draw: function() {
        if(this.breadcrumbs.length === 0) {
            this.hide();
        } else {
            this.show();
            this.update({
                breadcrumbs: this.breadcrumbs
            });
        }
    },

    setHome: function() {
        this.clear();
        this.draw();
    }
});
<|endoftext|>


<commit_before>import chai from 'chai'
import chaiThings from 'chai-things'
import fs from 'fs'
import { Element, Beat } from '../dist/bundle'
import fixtures from './fixtures'

const should = chai.should()

chai.use(chaiThings)

describe('Element', () => {
  describe('value', () => {
    it('should return the first input of the element instance/atom', () => {
      const data = fixtures.fast.json.data[0][0].notes
      const elem = new Element(data)

      elem.value.should.equal(elem.inputs[0])
    })
  })

  describe('inputs', () => {
    it('should return the arguments object of the element instance/atom', () => {
      const data = fixtures.fast.json.data[0][0].notes
      const elem = new Element(data)

      elem.inputs.should.equal(data.atom.init['arguments'])
    })
  })

  describe('kind', () => {
    describe('explicit', () => {

    })

    describe('implicit', () => {

    })
  })

  describe('identify', () => {
    describe('note', () => {

    })

    describe('scale', () => {

    })

    describe('chord', () => {

    })
  })
})

describe('Beat', () => {
  describe('duration', () => {

  })

  describe('items', () => {

  })

  describe('empty', () => {

  })

  describe('exists', () => {

  })

  describe('from', () => {

  })
})
<commit_msg>:microscope: :construction: added pending tests for element.kind<commit_after>import chai from 'chai'
import chaiThings from 'chai-things'
import fs from 'fs'
import { Element, Beat } from '../dist/bundle'
import fixtures from './fixtures'

const should = chai.should()

chai.use(chaiThings)

describe('Element', () => {
  describe('value', () => {
    it('should return the first input of the element instance/atom', () => {
      const data = fixtures.fast.json.data[0][0].notes
      const elem = new Element(data)

      elem.value.should.equal(elem.inputs[0])
    })
  })

  describe('inputs', () => {
    it('should return the arguments object of the element instance/atom', () => {
      const data = fixtures.fast.json.data[0][0].notes
      const elem = new Element(data)

      elem.inputs.should.equal(data.atom.init['arguments'])
    })
  })

  describe('kind', () => {
    describe('explicit', () => {

    })

    describe('implicit', () => {

    })
  })

  describe('identify', () => {
    describe('note', () => {
      it('should return `"note"` for Note elements', () => {
        const elem = new Element({
          atom: {
            init: {
              'arguments': ['C2']
            }
          }
        })

        elem.identify(elem).should.equal('note')
      })
    })

    // FIXME
    xdescribe('scale', () => {
      it('should return `"scale"` for Scale elements', () => {
        const elem = new Element({
          atom: {
            init: {
              'arguments': ['C2 Major']
            }
          }
        })

        elem.identify(elem).should.equal('scale')
      })
    })

    // FIXME
    xdescribe('chord', () => {
      it('should return `"chord"` for Chord elements', () => {
        const elem = new Element({
          atom: {
            init: {
              'arguments': ['C2maj7']
            }
          }
        })

        elem.identify(elem).should.equal('chord')
      })

    })
  })
})

describe('Beat', () => {
  describe('duration', () => {

  })

  describe('items', () => {

  })

  describe('empty', () => {

  })

  describe('exists', () => {

  })

  describe('from', () => {

  })
})
<|endoftext|>


<commit_before>'use strict'

var server = require('./server')
  , request = require('../index')
  , util = require('util')
  , tape = require('tape')

var s = server.createServer()

s.on('/redirect/from', function(req, res) {
  res.writeHead(301, {
    location : '/redirect/to'
  })
  res.end()
})

s.on('/redirect/to', function(req, res) {
  res.end('ok')
})

tape('setup', function(t) {
  s.listen(s.port, function() {
    t.end()
  })
})

function runTest(name, path, requestObj, serverAssertFn) {
  tape(name, function(t) {
    s.on('/' + path, function(req, res) {
      serverAssertFn(t, req, res)
      res.writeHead(200)
      res.end()
    })
    requestObj.url = s.url + '/' + path
    request(requestObj, function(err, res, body) {
      t.equal(err, null)
      t.equal(res.statusCode, 200)
      t.end()
    })
  })
}

runTest(
  '#125: headers.cookie with no cookie jar',
  'no-jar',
  {headers: {cookie: 'foo=bar'}},
  function(t, req, res) {
    t.equal(req.headers.cookie, 'foo=bar')
  })

var jar = request.jar()
jar.setCookie('quux=baz', s.url)
runTest(
  '#125: headers.cookie + cookie jar',
  'header-and-jar',
  {jar: jar, headers: {cookie: 'foo=bar'}},
  function(t, req, res) {
    t.equal(req.headers.cookie, 'foo=bar; quux=baz')
  })

var jar2 = request.jar()
jar2.setCookie('quux=baz; Domain=foo.bar.com', s.url, {ignoreError: true})
runTest(
  '#794: ignore cookie parsing and domain errors',
  'ignore-errors',
  {jar: jar2, headers: {cookie: 'foo=bar'}},
  function(t, req, res) {
    t.equal(req.headers.cookie, 'foo=bar')
  })

runTest(
  '#784: override content-type when json is used',
  'json',
  {
    json: true,
    method: 'POST',
    headers: { 'content-type': 'application/json; charset=UTF-8' },
    body: { hello: 'my friend' }},
  function(t, req, res) {
    t.equal(req.headers['content-type'], 'application/json; charset=UTF-8')
  }
)

runTest(
  'neither headers.cookie nor a cookie jar is specified',
  'no-cookie',
  {},
  function(t, req, res) {
    t.equal(req.headers.cookie, undefined)
  })

tape('upper-case Host header and redirect', function(t) {
  // Horrible hack to observe the raw data coming to the server (before Node
  // core lower-cases the headers)
  var rawData = ''
  s.on('connection', function(socket) {
    socket.on('data', function(d) {
      rawData += d
    })
  })

  function checkHostHeader(host) {
    t.ok(
      new RegExp('^Host: ' + host + '$', 'm').test(rawData),
      util.format(
        'Expected "Host: %s" in data "%s"',
        host, rawData.trim().replace(/\r?\n/g, '\\n')))
    rawData = ''
  }

  var redirects = 0
  request({
    url : s.url + '/redirect/from',
    headers : { Host : '127.0.0.1' }
  }, function(err, res, body) {
    t.equal(err, null)
    t.equal(res.statusCode, 200)
    t.equal(body, 'ok')
    t.equal(redirects, 1)
    // XXX should the host header change like this after a redirect?
    checkHostHeader('localhost:' + s.port)
    t.end()
  }).on('redirect', function() {
    redirects++
    t.equal(this.uri.href, s.url + '/redirect/to')
    checkHostHeader('127.0.0.1')
  })
})

tape('cleanup', function(t) {
  s.close(function() {
    t.end()
  })
})
<commit_msg>Fixing to work again on 0.10's broken stream implementation.<commit_after>'use strict'

var server = require('./server')
  , request = require('../index')
  , util = require('util')
  , tape = require('tape')

var s = server.createServer()

s.on('/redirect/from', function(req, res) {
  res.writeHead(301, {
    location : '/redirect/to'
  })
  res.end()
})

s.on('/redirect/to', function(req, res) {
  res.end('ok')
})

tape('setup', function(t) {
  s.listen(s.port, function() {
    t.end()
  })
})

function runTest(name, path, requestObj, serverAssertFn) {
  tape(name, function(t) {
    s.on('/' + path, function(req, res) {
      serverAssertFn(t, req, res)
      res.writeHead(200)
      res.end()
    })
    requestObj.url = s.url + '/' + path
    request(requestObj, function(err, res, body) {
      t.equal(err, null)
      t.equal(res.statusCode, 200)
      t.end()
    })
  })
}

runTest(
  '#125: headers.cookie with no cookie jar',
  'no-jar',
  {headers: {cookie: 'foo=bar'}},
  function(t, req, res) {
    t.equal(req.headers.cookie, 'foo=bar')
  })

var jar = request.jar()
jar.setCookie('quux=baz', s.url)
runTest(
  '#125: headers.cookie + cookie jar',
  'header-and-jar',
  {jar: jar, headers: {cookie: 'foo=bar'}},
  function(t, req, res) {
    t.equal(req.headers.cookie, 'foo=bar; quux=baz')
  })

var jar2 = request.jar()
jar2.setCookie('quux=baz; Domain=foo.bar.com', s.url, {ignoreError: true})
runTest(
  '#794: ignore cookie parsing and domain errors',
  'ignore-errors',
  {jar: jar2, headers: {cookie: 'foo=bar'}},
  function(t, req, res) {
    t.equal(req.headers.cookie, 'foo=bar')
  })

runTest(
  '#784: override content-type when json is used',
  'json',
  {
    json: true,
    method: 'POST',
    headers: { 'content-type': 'application/json; charset=UTF-8' },
    body: { hello: 'my friend' }},
  function(t, req, res) {
    t.equal(req.headers['content-type'], 'application/json; charset=UTF-8')
  }
)

runTest(
  'neither headers.cookie nor a cookie jar is specified',
  'no-cookie',
  {},
  function(t, req, res) {
    t.equal(req.headers.cookie, undefined)
  })

tape('upper-case Host header and redirect', function(t) {
  // Horrible hack to observe the raw data coming to the server (before Node
  // core lower-cases the headers)
  var rawData = ''

  s.on('connection', function(socket) {
    if (socket.ondata) {
      var ondata = socket.ondata
    }
    function handledata (d, start, end) {
      if (ondata) {
        rawData += d.slice(start, end).toString()
        return ondata.apply(this, arguments)
      } else {
        rawData += d
      }
    }
    socket.on('data', handledata)
    socket.ondata = handledata
  })

  function checkHostHeader(host) {
    t.ok(
      new RegExp('^Host: ' + host + '$', 'm').test(rawData),
      util.format(
        'Expected "Host: %s" in data "%s"',
        host, rawData.trim().replace(/\r?\n/g, '\\n')))
    rawData = ''
  }

  var redirects = 0
  request({
    url : s.url + '/redirect/from',
    headers : { Host : '127.0.0.1' }
  }, function(err, res, body) {
    t.equal(err, null)
    t.equal(res.statusCode, 200)
    t.equal(body, 'ok')
    t.equal(redirects, 1)
    // XXX should the host header change like this after a redirect?
    checkHostHeader('localhost:' + s.port)
    t.end()
  }).on('redirect', function() {
    redirects++
    t.equal(this.uri.href, s.url + '/redirect/to')
    checkHostHeader('127.0.0.1')
  })
})

tape('cleanup', function(t) {
  s.close(function() {
    t.end()
  })
})
<|endoftext|>


<commit_before>

var maple = require('../treeRouter.js')
   , tree = new maple.RouteTree()
   , assert = require('assert')

//the purpose of this test is to make sure similar routes don't interfere with one another. I made this because I had an early bug where routes differing by 1 letter would sometimes match
function a(){}
function b(){}
function c(){}

tree.define('/trees.e/', a)
tree.define('/trees/', b)
tree.define('/tree/', c)

//taken straight from problem with tako
tree.define('/file/js', function() {
})
tree.define('/files/*', function () {
   console.log('wildcard')
})

var matcher = tree.match('/files/hello')
assert(matcher.perfect)

matcher = tree.match('/files/hello.js')
assert(matcher.perfect)

matcher = tree.match('/file/js')
assert(matcher.perfect)

matcher = tree.match('/trees.e')
assert(matcher.fn === a)

matcher = tree.match('/trees')
assert(matcher.fn === b)

matcher = tree.match('/tree')
assert(matcher.fn === c)

<commit_msg>removed quesion mark regex match from the final slash because routes that were identical but off by one letter would match one another<commit_after>

var maple = require('../treeRouter.js')
   , tree = new maple.RouteTree()
   , assert = require('assert')

//the purpose of this test is to make sure similar routes don't interfere with one another. I made this because I had an early bug where routes differing by 1 letter would sometimes match
function a(){}
function b(){}
function c(){}
function d(){}
function e(){}

tree.define('/trees.e/', a)
tree.define('/trees/', b)
tree.define('/tree/', c)

//taken straight from problem with tako
tree.define('/file/js', d)
tree.define('/files/*', e)

var matcher = tree.match('/files/hello')
assert(matcher.perfect)
assert(matcher.fn === e)

matcher = tree.match('/files/hello.js')
assert(matcher.perfect)
assert(matcher.fn === e)

matcher = tree.match('/file/js')
assert(matcher.perfect)
assert(matcher.fn === d)

matcher = tree.match('/trees.e')
assert(matcher.fn === a)

matcher = tree.match('/trees')
assert(matcher.fn === b)

matcher = tree.match('/tree')
assert(matcher.fn === c)

<|endoftext|>


<commit_before>'use strict';

var express = require('express');
var request = require('supertest')
var scale = require('..');
var sharp = require('sharp');
var should = require('should');

var app = express();
app.use('/my-scale', scale({baseHost: 'localhost'}));
app.use('/images', express.static('test/images'));

var imgUrl = function(path) {
  var port = app.listen().address().port;
  return encodeURIComponent('http://localhost:' + port + path)
}

describe('GET /my-scale/resize', function() {
  it('should respond with 404', function(done) {
    request(app).get('/my-scale/resize').expect(404, done);
  });

  it('should respond with 400', function(done) {
    request(app).get('/my-scale/resize/100').expect(400, done);
  });

  it('should respond with original image', function(done) {
    request(app)
      .get('/images/a.jpg')
      .expect('Content-Length', 1970087)
      .expect(200, done);
  });

  it('should resize /images/a.jpg to 100px', function(done) {
    request(app)
      .get('/my-scale/resize/100?url=' + imgUrl('/images/a.jpg'))
      .expect(function(res) {
        res.body.byteLength.should.be.exactly(3641);
        sharp(res.body).metadata(function(err, metadata) {
          metadata.width.should.be.exactly(100);
        });
      })
      .expect(200, done);
  });

  it('should resize /images/a.jpg to 110px, 50% quality', function(done) {
    request(app)
      .get('/my-scale/resize/110?quality=50&url=' + imgUrl('/images/a.jpg'))
      .expect(function(res) {
        res.body.byteLength.should.be.exactly(2472);
        sharp(res.body).metadata(function(err, metadata) {
          should(metadata.width).be.exactly(1110)
          console.log('!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!');
        });
      })
      .expect(200, done);
  });
});
<commit_msg>cleanup<commit_after>'use strict';

var express = require('express');
var request = require('supertest')
var scale = require('..');
var sharp = require('sharp');
var should = require('should');

var app = express();
app.use('/my-scale', scale({baseHost: 'localhost'}));
app.use('/images', express.static('test/images'));

var imgUrl = function(path) {
  var port = app.listen().address().port;
  return encodeURIComponent('http://localhost:' + port + path)
}

describe('GET /my-scale/resize', function() {
  it('should respond with 404', function(done) {
    request(app).get('/my-scale/resize').expect(404, done);
  });

  it('should respond with 400', function(done) {
    request(app).get('/my-scale/resize/100').expect(400, done);
  });

  it('should respond with original image', function(done) {
    request(app)
      .get('/images/a.jpg')
      .expect('Content-Length', 1970087)
      .expect(200, done);
  });

  it('should resize /images/a.jpg to 100px', function(done) {
    request(app)
      .get('/my-scale/resize/100?url=' + imgUrl('/images/a.jpg'))
      .expect(function(res) {
        res.body.byteLength.should.be.exactly(3641);
        sharp(res.body).metadata(function(err, metadata) {
          metadata.width.should.be.exactly(100);
        });
      })
      .expect(200, done);
  });

  it('should resize /images/a.jpg to 110px, 50% quality', function(done) {
    request(app)
      .get('/my-scale/resize/110?quality=50&url=' + imgUrl('/images/a.jpg'))
      .expect(function(res) {
        res.body.byteLength.should.be.exactly(2472);
        sharp(res.body).metadata(function(err, metadata) {
          should(metadata.width).be.exactly(1110)
        });
      })
      .expect(200, done);
  });
});
<|endoftext|>


<commit_before>var chai = require('chai');
var assert = chai.assert;
var Game = require('../lib/gametime');

describe('Game', function() {
  context('with default attributes', function() {
    var game = new Game({}, {});

    it('should be a function', function() {
      assert.isFunction(Game);
    });

    it('should have a canvas property', function() {
      assert.property(game, 'canvas');
    });

    it('should have a context property', function () {
      assert.property(game, 'context');
    });

    it('should have a paddle property', function () {
      assert.property(game, 'paddle');
    });

    it('should have a score property', function () {
      assert.property(game, 'score');
    });

    it('should have a ball property', function () {
      assert.property(game, 'ball');
    });

    it('should have a default gameMode of 0', function () {
      assert.property(game.gameMode, 0);
    });

    it('should have a default rightPressed value of 0', function () {
      assert.equal(game.rightPressed, false);
    });

    it('should have a default leftPressed value of 0', function () {
      assert.equal(game.leftPressed, false);
    });

    it('should have an empty brickArray by default', function () {
      assert.equal(game.brickArray, []);
    });

    it('should have 4 brickRows by default', function () {
      assert.equal(game.brickRows, 4);
    });

    it('should have 6 brickColumns by default', function () {
      assert.equal(game.brickColumns, 6);
    });

    it('should have a brickWidth of 100 by default', function () {
      assert.equal(game.brickWidth, 100);
    });

    it('should have a brickHeight of 25 by default', function () {
      assert.equal(game.brickHeight, 25);
    });
  });
});

describe(' ', function() {
  context('on ballRectCollision (ball hitting brick)', function() {
    var game = new Game({}, {});

    it('should not change bricksDestroyed, brickAlive, or playerLive values if brick is missed', function() {
      game.ballRectCollision();

    });

    it('should change bricksDestroyed, brickAlive, or playerLive values if brick is hit', function() {
      game.ballRectCollision();

    });
  });
});

describe(' ', function() {
  context('on drawBricks', function() {
    var game = new Game({}, {});

    it('should add a column if the number of columns is less than brickColumns', function() {

    });

    it('should add a row if the number of rows is less than brickRows', function() {

    });
  });
});

describe(' ', function() {
  context('on populateBrickArray', function() {
    var game = new Game({}, {});

    it('should have a brickPad of 10 by default', function () {
      game.populateBrickArray();

    });

    it('should have a brickWidth of 100 by default', function () {
      game.populateBrickArray();

    });

    it('should have a brickHeight of 25 by default', function () {
      game.populateBrickArray();

    });
  });
});

describe(' ', function() {
  context('on gameMode functions', function() {
    var game = new Game({}, {});

  });
});
<commit_msg>Finish game test skeleton<commit_after>var chai = require('chai');
var assert = chai.assert;
var Game = require('../lib/gametime');

describe('Game', function() {
  context('with default attributes', function() {
    var game = new Game({}, {});

    it('should be a function', function() {
      assert.isFunction(Game);
    });

    it('should have a canvas property', function() {
      assert.property(game, 'canvas');
    });

    it('should have a context property', function () {
      assert.property(game, 'context');
    });

    it('should have a paddle property', function () {
      assert.property(game, 'paddle');
    });

    it('should have a score property', function () {
      assert.property(game, 'score');
    });

    it('should have a ball property', function () {
      assert.property(game, 'ball');
    });

    it('should have a default gameMode of 0', function () {
      assert.property(game.gameMode, 0);
    });

    it('should have a default rightPressed value of 0', function () {
      assert.equal(game.rightPressed, false);
    });

    it('should have a default leftPressed value of 0', function () {
      assert.equal(game.leftPressed, false);
    });

    it('should have an empty brickArray by default', function () {
      assert.equal(game.brickArray, []);
    });

    it('should have 4 brickRows by default', function () {
      assert.equal(game.brickRows, 4);
    });

    it('should have 6 brickColumns by default', function () {
      assert.equal(game.brickColumns, 6);
    });

    it('should have a brickWidth of 100 by default', function () {
      assert.equal(game.brickWidth, 100);
    });

    it('should have a brickHeight of 25 by default', function () {
      assert.equal(game.brickHeight, 25);
    });
  });

  context('on ballRectCollision (ball hitting brick)', function() {
    var game = new Game({}, {});

    it('should not change bricksDestroyed, brickAlive, or playerLive values if brick is missed', function() {
      game.ballRectCollision();

    });

    it('should change bricksDestroyed, brickAlive, or playerLive values if brick is hit', function() {
      game.ballRectCollision();

    });
  });

  context('on drawBricks', function() {
    var game = new Game({}, {});

    it('should add a column if the number of columns is less than brickColumns', function() {
      game.drawBricks();

    });

    it('should add a row if the number of rows is less than brickRows', function() {
      game.drawBricks();

    });
  });

  context('on populateBrickArray', function() {
    var game = new Game({}, {});

    it('should have a brickPad of 10 by default', function () {
      game.populateBrickArray();

    });

    it('should have a brickWidth of 100 by default', function () {
      game.populateBrickArray();

    });

    it('should have a brickHeight of 25 by default', function () {
      game.populateBrickArray();

    });
  });

  context('on passedBall functions', function() {
    var game = new Game({}, {});

    it('', function () {
      game.passedBall();

    });

    it('', function () {
      game.passedBall();

    });
  });

  context('on gameMode functions', function() {
    var game = new Game({}, {});

    it('', function () {

    });

    it('', function () {

    });

    it('', function () {

    });

    it('', function () {

    });

    it('', function () {

    });

    it('', function () {

    });

  });
});
<|endoftext|>


<commit_before>/**
 * @copyright Copyright 2016 Kevin Locke <kevin@kevinlocke.name>
 * @license MIT
 */

'use strict';

const assert = require('assert');
const path = require('path');

const gitBranchIs = require('..');

const assertMatch = require('../test-lib/assert-match');
const constants = require('../test-lib/constants');

// Local copy of shared constants
const {
  BRANCH_CURRENT,
  BRANCH_NON_EXISTENT,
  BRANCH_SAME_COMMIT,
  SUBDIR_NAME,
  TEST_REPO_PATH,
} = constants;

describe('gitBranchIs', () => {
  it('callback true for current branch name', (done) => {
    gitBranchIs(BRANCH_CURRENT, (err, result) => {
      assert.ifError(err);
      assert.strictEqual(result, true);
      done();
    });
  });

  it('callback false for non-existent branch name', (done) => {
    gitBranchIs(BRANCH_NON_EXISTENT, (err, result) => {
      assert.ifError(err);
      assert.strictEqual(result, false);
      done();
    });
  });

  it('callback false for different branch, same commit', (done) => {
    gitBranchIs(BRANCH_SAME_COMMIT, (err, result) => {
      assert.ifError(err);
      assert.strictEqual(result, false);
      done();
    });
  });

  it('callback true for same branch name in subdir', (done) => {
    gitBranchIs(BRANCH_CURRENT, { cwd: SUBDIR_NAME }, (err, result) => {
      assert.ifError(err);
      assert.strictEqual(result, true);
      done();
    });
  });

  it('callback true for function comparing branch name', (done) => {
    function checkBranchName(branchName) {
      return branchName === BRANCH_CURRENT;
    }
    gitBranchIs(checkBranchName, (err, result) => {
      assert.ifError(err);
      assert.strictEqual(result, true);
      done();
    });
  });

  it('callback false for function returning false', (done) => {
    function returnsFalse(branchName) {
      return false;
    }
    gitBranchIs(returnsFalse, (err, result) => {
      assert.ifError(err);
      assert.strictEqual(result, false);
      done();
    });
  });

  it('callback propagates error from function which throws', (done) => {
    const errTest = new Error('test');
    function throwsErr(branchName) { throw errTest; }
    gitBranchIs(throwsErr, (err, result) => {
      assert.strictEqual(err, errTest);
      assert(result === undefined || result === null);
      done();
    });
  });

  it('can specify additional git arguments', (done) => {
    const options = {
      cwd: '..',
      gitArgs: ['-C', TEST_REPO_PATH],
    };
    gitBranchIs(BRANCH_CURRENT, options, (err, result) => {
      assert.ifError(err);
      assert.strictEqual(result, true);
      done();
    });
  });

  it('null gitArgs is ignored', (done) => {
    gitBranchIs(BRANCH_CURRENT, { gitArgs: null }, (err, result) => {
      assert.ifError(err);
      assert.strictEqual(result, true);
      done();
    });
  });

  it('gitArgs takes precedence over gitDir', (done) => {
    const options = {
      gitArgs: ['--git-dir=.git'],
      gitDir: 'invalid',
    };
    gitBranchIs(BRANCH_CURRENT, options, (err, result) => {
      assert.ifError(err);
      assert.strictEqual(result, true);
      done();
    });
  });

  it('can specify git executable and args', (done) => {
    const options = {
      gitArgs: [path.join('..', 'test-bin', 'echo-surprise.js')],
      gitPath: process.execPath,
    };
    gitBranchIs('surprise', options, (err, result) => {
      assert.ifError(err);
      assert.strictEqual(result, true);
      done();
    });
  });

  it('callback Error outside of git repo', (done) => {
    gitBranchIs(BRANCH_CURRENT, { cwd: '/' }, (err, result) => {
      assert(err instanceof Error);
      assert(result === undefined || result === null);
      done();
    });
  });

  it('callback Error if cwd doesn\'t exist', (done) => {
    gitBranchIs(BRANCH_CURRENT, { cwd: 'invalid' }, (err, result) => {
      assert(err instanceof Error);
      assert(result === undefined || result === null);
      done();
    });
  });

  it('callback Error if git is not executable', (done) => {
    const badGitPath = path.join(__dirname, '..', 'package.json');
    gitBranchIs(BRANCH_CURRENT, { gitPath: badGitPath }, (err, result) => {
      assert(err instanceof Error);
      assert(result === undefined || result === null);
      done();
    });
  });

  it('callback Error if gitDir is not a git repo', (done) => {
    gitBranchIs(BRANCH_CURRENT, { gitDir: SUBDIR_NAME }, (err, result) => {
      assert(err instanceof Error);
      assert(result === undefined || result === null);
      done();
    });
  });

  // Just like git -C and --git-dir
  it('gitDir is relative to cwd', (done) => {
    const options = {
      cwd: SUBDIR_NAME,
      gitDir: path.join('..', '.git'),
    };
    gitBranchIs(BRANCH_CURRENT, options, (err, result) => {
      assert.ifError(err);
      assert.strictEqual(result, true);
      done();
    });
  });

  it('gitPath is relative to cwd', (done) => {
    const options = {
      cwd: SUBDIR_NAME,
      gitArgs: [path.join('..', '..', 'test-bin', 'echo-surprise.js')],
      gitPath: path.relative(SUBDIR_NAME, process.execPath),
    };
    gitBranchIs('surprise', options, (err, result) => {
      assert.ifError(err);
      assert.strictEqual(result, true);
      done();
    });
  });

  describe('.getBranch()', () => {
    it('gets the branch name', (done) => {
      gitBranchIs.getBranch((err, result) => {
        assert.ifError(err);
        assert.strictEqual(result, BRANCH_CURRENT);
        done();
      });
    });
  });

  it('Promise resolves true for same branch name', () => {
    const promise = gitBranchIs(BRANCH_CURRENT);
    assert(promise instanceof global.Promise);
    return promise.then((result) => {
      assert.strictEqual(result, true);
    });
  });

  it('Promise resolves false for different branch name', () => {
    const promise = gitBranchIs('invalid');
    assert(promise instanceof global.Promise);
    return promise.then((result) => {
      assert.strictEqual(result, false);
    });
  });

  it('Promise rejects on Error', () => {
    const promise = gitBranchIs(BRANCH_CURRENT, 'opts');
    assert(promise instanceof global.Promise);
    return promise.then(
      (result) => { throw new Error('expecting Error'); },
      (err) => {
        assert(err instanceof TypeError);
        assertMatch(err.message, /\boptions\b/);
      },
    );
  });

  it('Promise flattens for function returning Promise', () => {
    function checkBranchName(branchName) {
      return global.Promise.resolve(branchName === BRANCH_CURRENT);
    }
    const promise = gitBranchIs(checkBranchName);
    assert(promise instanceof global.Promise);
    return promise.then((result) => {
      assert.strictEqual(result, true);
    });
  });

  it('Promise rejects for function returning Promise', () => {
    // Note: reject with non-Error to ensure no special handling
    function checkBranchName(branchName) {
      return global.Promise.reject(branchName === BRANCH_CURRENT);
    }
    const promise = gitBranchIs(checkBranchName);
    assert(promise instanceof global.Promise);
    return promise.then(
      (result) => { throw new Error('expecting rejection'); },
      (err) => {
        assert.strictEqual(err, true);
      },
    );
  });

  it('Promise rejects for function throwing Error', () => {
    const errTest = new Error('test');
    function checkBranchName(branchName) { throw errTest; }
    const promise = gitBranchIs(checkBranchName);
    assert(promise instanceof global.Promise);
    return promise.then(
      (result) => { throw new Error('expecting rejection'); },
      (err) => { assert.strictEqual(err, errTest); },
    );
  });

  describe('.getBranch()', () => {
    it('resolves to the branch name', () => {
      const promise = gitBranchIs.getBranch();
      assert(promise instanceof global.Promise);
      return promise.then((result) => {
        assert.strictEqual(result, BRANCH_CURRENT);
      });
    });

    it('rejects on Error', () => {
      const promise = gitBranchIs.getBranch(BRANCH_CURRENT);
      assert(promise instanceof global.Promise);
      return promise.then(
        (result) => { throw new Error('expecting Error'); },
        (err) => {
          assert(err instanceof TypeError);
          assertMatch(err.message, /\boptions\b/);
        },
      );
    });
  });
});
<commit_msg>Selectively disable unicorn/consistent-function-scoping<commit_after>/**
 * @copyright Copyright 2016 Kevin Locke <kevin@kevinlocke.name>
 * @license MIT
 */

'use strict';

const assert = require('assert');
const path = require('path');

const gitBranchIs = require('..');

const assertMatch = require('../test-lib/assert-match');
const constants = require('../test-lib/constants');

// Local copy of shared constants
const {
  BRANCH_CURRENT,
  BRANCH_NON_EXISTENT,
  BRANCH_SAME_COMMIT,
  SUBDIR_NAME,
  TEST_REPO_PATH,
} = constants;

describe('gitBranchIs', () => {
  it('callback true for current branch name', (done) => {
    gitBranchIs(BRANCH_CURRENT, (err, result) => {
      assert.ifError(err);
      assert.strictEqual(result, true);
      done();
    });
  });

  it('callback false for non-existent branch name', (done) => {
    gitBranchIs(BRANCH_NON_EXISTENT, (err, result) => {
      assert.ifError(err);
      assert.strictEqual(result, false);
      done();
    });
  });

  it('callback false for different branch, same commit', (done) => {
    gitBranchIs(BRANCH_SAME_COMMIT, (err, result) => {
      assert.ifError(err);
      assert.strictEqual(result, false);
      done();
    });
  });

  it('callback true for same branch name in subdir', (done) => {
    gitBranchIs(BRANCH_CURRENT, { cwd: SUBDIR_NAME }, (err, result) => {
      assert.ifError(err);
      assert.strictEqual(result, true);
      done();
    });
  });

  it('callback true for function comparing branch name', (done) => {
    // eslint-disable-next-line unicorn/consistent-function-scoping
    function checkBranchName(branchName) {
      return branchName === BRANCH_CURRENT;
    }
    gitBranchIs(checkBranchName, (err, result) => {
      assert.ifError(err);
      assert.strictEqual(result, true);
      done();
    });
  });

  it('callback false for function returning false', (done) => {
    // eslint-disable-next-line unicorn/consistent-function-scoping
    function returnsFalse(branchName) {
      return false;
    }
    gitBranchIs(returnsFalse, (err, result) => {
      assert.ifError(err);
      assert.strictEqual(result, false);
      done();
    });
  });

  it('callback propagates error from function which throws', (done) => {
    const errTest = new Error('test');
    function throwsErr(branchName) { throw errTest; }
    gitBranchIs(throwsErr, (err, result) => {
      assert.strictEqual(err, errTest);
      assert(result === undefined || result === null);
      done();
    });
  });

  it('can specify additional git arguments', (done) => {
    const options = {
      cwd: '..',
      gitArgs: ['-C', TEST_REPO_PATH],
    };
    gitBranchIs(BRANCH_CURRENT, options, (err, result) => {
      assert.ifError(err);
      assert.strictEqual(result, true);
      done();
    });
  });

  it('null gitArgs is ignored', (done) => {
    gitBranchIs(BRANCH_CURRENT, { gitArgs: null }, (err, result) => {
      assert.ifError(err);
      assert.strictEqual(result, true);
      done();
    });
  });

  it('gitArgs takes precedence over gitDir', (done) => {
    const options = {
      gitArgs: ['--git-dir=.git'],
      gitDir: 'invalid',
    };
    gitBranchIs(BRANCH_CURRENT, options, (err, result) => {
      assert.ifError(err);
      assert.strictEqual(result, true);
      done();
    });
  });

  it('can specify git executable and args', (done) => {
    const options = {
      gitArgs: [path.join('..', 'test-bin', 'echo-surprise.js')],
      gitPath: process.execPath,
    };
    gitBranchIs('surprise', options, (err, result) => {
      assert.ifError(err);
      assert.strictEqual(result, true);
      done();
    });
  });

  it('callback Error outside of git repo', (done) => {
    gitBranchIs(BRANCH_CURRENT, { cwd: '/' }, (err, result) => {
      assert(err instanceof Error);
      assert(result === undefined || result === null);
      done();
    });
  });

  it('callback Error if cwd doesn\'t exist', (done) => {
    gitBranchIs(BRANCH_CURRENT, { cwd: 'invalid' }, (err, result) => {
      assert(err instanceof Error);
      assert(result === undefined || result === null);
      done();
    });
  });

  it('callback Error if git is not executable', (done) => {
    const badGitPath = path.join(__dirname, '..', 'package.json');
    gitBranchIs(BRANCH_CURRENT, { gitPath: badGitPath }, (err, result) => {
      assert(err instanceof Error);
      assert(result === undefined || result === null);
      done();
    });
  });

  it('callback Error if gitDir is not a git repo', (done) => {
    gitBranchIs(BRANCH_CURRENT, { gitDir: SUBDIR_NAME }, (err, result) => {
      assert(err instanceof Error);
      assert(result === undefined || result === null);
      done();
    });
  });

  // Just like git -C and --git-dir
  it('gitDir is relative to cwd', (done) => {
    const options = {
      cwd: SUBDIR_NAME,
      gitDir: path.join('..', '.git'),
    };
    gitBranchIs(BRANCH_CURRENT, options, (err, result) => {
      assert.ifError(err);
      assert.strictEqual(result, true);
      done();
    });
  });

  it('gitPath is relative to cwd', (done) => {
    const options = {
      cwd: SUBDIR_NAME,
      gitArgs: [path.join('..', '..', 'test-bin', 'echo-surprise.js')],
      gitPath: path.relative(SUBDIR_NAME, process.execPath),
    };
    gitBranchIs('surprise', options, (err, result) => {
      assert.ifError(err);
      assert.strictEqual(result, true);
      done();
    });
  });

  describe('.getBranch()', () => {
    it('gets the branch name', (done) => {
      gitBranchIs.getBranch((err, result) => {
        assert.ifError(err);
        assert.strictEqual(result, BRANCH_CURRENT);
        done();
      });
    });
  });

  it('Promise resolves true for same branch name', () => {
    const promise = gitBranchIs(BRANCH_CURRENT);
    assert(promise instanceof global.Promise);
    return promise.then((result) => {
      assert.strictEqual(result, true);
    });
  });

  it('Promise resolves false for different branch name', () => {
    const promise = gitBranchIs('invalid');
    assert(promise instanceof global.Promise);
    return promise.then((result) => {
      assert.strictEqual(result, false);
    });
  });

  it('Promise rejects on Error', () => {
    const promise = gitBranchIs(BRANCH_CURRENT, 'opts');
    assert(promise instanceof global.Promise);
    return promise.then(
      (result) => { throw new Error('expecting Error'); },
      (err) => {
        assert(err instanceof TypeError);
        assertMatch(err.message, /\boptions\b/);
      },
    );
  });

  it('Promise flattens for function returning Promise', () => {
    function checkBranchName(branchName) {
      return global.Promise.resolve(branchName === BRANCH_CURRENT);
    }
    const promise = gitBranchIs(checkBranchName);
    assert(promise instanceof global.Promise);
    return promise.then((result) => {
      assert.strictEqual(result, true);
    });
  });

  it('Promise rejects for function returning Promise', () => {
    // Note: reject with non-Error to ensure no special handling
    function checkBranchName(branchName) {
      return global.Promise.reject(branchName === BRANCH_CURRENT);
    }
    const promise = gitBranchIs(checkBranchName);
    assert(promise instanceof global.Promise);
    return promise.then(
      (result) => { throw new Error('expecting rejection'); },
      (err) => {
        assert.strictEqual(err, true);
      },
    );
  });

  it('Promise rejects for function throwing Error', () => {
    const errTest = new Error('test');
    function checkBranchName(branchName) { throw errTest; }
    const promise = gitBranchIs(checkBranchName);
    assert(promise instanceof global.Promise);
    return promise.then(
      (result) => { throw new Error('expecting rejection'); },
      (err) => { assert.strictEqual(err, errTest); },
    );
  });

  describe('.getBranch()', () => {
    it('resolves to the branch name', () => {
      const promise = gitBranchIs.getBranch();
      assert(promise instanceof global.Promise);
      return promise.then((result) => {
        assert.strictEqual(result, BRANCH_CURRENT);
      });
    });

    it('rejects on Error', () => {
      const promise = gitBranchIs.getBranch(BRANCH_CURRENT);
      assert(promise instanceof global.Promise);
      return promise.then(
        (result) => { throw new Error('expecting Error'); },
        (err) => {
          assert(err instanceof TypeError);
          assertMatch(err.message, /\boptions\b/);
        },
      );
    });
  });
});
<|endoftext|>


<commit_before>describe('Haunting', function() {
  var fixture = '<input class="ghostwriter">'
    , strokes = stroke.builder();

  beforeEach(function() {
    var $fixtures;

    setFixtures(fixture);
    $fixtures = $('#jasmine-fixtures');

    this.$input = $fixtures.find('.ghostwriter');

    this.haunting = new Haunting({
      input: this.$input
    , manuscript: [strokes.noop.repeat(3)]
    });
  });

  describe('#start', function() {
    it('should trigger ghostwriter:start if stopped', function() {
      var startSpy = spyOnEvent(this.$input, 'ghostwriter:start')
        , resumeSpy = spyOnEvent(this.$input, 'ghostwriter:resume');

      this.haunting.start();
      expect(startSpy).toHaveBeenTriggered();
      expect(resumeSpy).not.toHaveBeenTriggered();
    });

    it('should trigger ghostwriter:pause if paused', function() {
      var startSpy, resumeSpy;
      this.haunting.start().pause();

      startSpy = spyOnEvent(this.$input, 'ghostwriter:start');
      resumeSpy = spyOnEvent(this.$input, 'ghostwriter:resume');

      this.haunting.start();
      expect(resumeSpy).toHaveBeenTriggered();
      expect(startSpy).not.toHaveBeenTriggered();
    });

    it('should not trigger ghostwriter:start or ghostwriter:resume if started'
    , function() {
      var startSpy, resumeSpy;
      this.haunting.start();

      startSpy = spyOnEvent(this.$input, 'ghostwriter:start');
      resumeSpy = spyOnEvent(this.$input, 'ghostwriter:resume');

      this.haunting.start();
      expect(resumeSpy).not.toHaveBeenTriggered();
      expect(startSpy).not.toHaveBeenTriggered();
    });
  });

  describe('#pause', function() {
    it('should trigger ghostwriter:pause if started', function() {
      var pauseSpy = spyOnEvent(this.$input, 'ghostwriter:pause');

      this.haunting.start().pause();
      expect(pauseSpy).toHaveBeenTriggered();
    });

    it('should not trigger ghostwriter:pause if paused', function() {
      var pauseSpy;
      this.haunting.start().pause();

      pauseSpy = spyOnEvent(this.$input, 'ghostwriter:pause');

      this.haunting.pause();
      expect(pauseSpy).not.toHaveBeenTriggered();
    });

    it('should not trigger ghostwriter:pause if stopped', function() {
      var pauseSpy;
      this.haunting.start().stop();

      pauseSpy = spyOnEvent(this.$input, 'ghostwriter:pause');

      this.haunting.pause();
      expect(pauseSpy).not.toHaveBeenTriggered();
    });
  });

  describe('#stop', function() {
    it('should trigger ghostwriter:stop if started', function() {
      var stopSpy;
      this.haunting.start();

      stopSpy = spyOnEvent(this.$input, 'ghostwriter:stop');

      this.haunting.stop();
      expect(stopSpy).toHaveBeenTriggered();
    });

    it('should trigger ghostwriter:stop if paused', function() {
      var stopSpy;
      this.haunting.start().pause();

      stopSpy = spyOnEvent(this.$input, 'ghostwriter:stop');

      this.haunting.stop();
      expect(stopSpy).toHaveBeenTriggered();
    });

    it('should not trigger ghostwriter:stop if stopped', function() {
      var stopSpy;
      this.haunting.start().stop();

      stopSpy = spyOnEvent(this.$input, 'ghostwriter:stop');

      this.haunting.stop();
      expect(stopSpy).not.toHaveBeenTriggered();
    });

    it('should reset the value of the input', function() {
      spyOn(this.haunting, 'reset');
      this.haunting.start().stop();
      expect(this.haunting.reset).toHaveBeenCalled();
    });

    it('should blur input', function() {
      this.$input.focus();
      this.haunting.start().stop();
      expect(this.$input).not.toBeFocused();
    });
  });

  describe('#restart', function() {
    it('should be alias for stop().start()', function() {
      spyOn(this.haunting, 'stop');
      spyOn(this.haunting, 'start');

      this.haunting.restart();
      expect(this.haunting.stop).toHaveBeenCalled();
      expect(this.haunting.start).toHaveBeenCalled();
    });
  });

  describe('#reset', function() {
    it('should restore the original value of the input', function() {
      this.haunting = new Haunting({
        input: this.$input.val('original value')
      , manuscript: [strokes.noop.repeat(3)]
      });

      this.$input.val('not original value');
      this.haunting.reset();
      expect(this.$input).toHaveValue('original value');
    });
  });
});
<commit_msg>Add tests for stroke execution.<commit_after>describe('Haunting', function() {
  var fixture = '<input class="ghostwriter">'
    , strokes = stroke.builder();

  beforeEach(function() {
    var $fixtures;

    setFixtures(fixture);
    $fixtures = $('#jasmine-fixtures');

    this.$input = $fixtures.find('.ghostwriter');

    this.haunting = new Haunting({
      input: this.$input
    , manuscript: [strokes.noop.repeat(3)]
    });
  });

  describe('#start', function() {
    it('should trigger ghostwriter:start if stopped', function() {
      var startSpy = spyOnEvent(this.$input, 'ghostwriter:start')
        , resumeSpy = spyOnEvent(this.$input, 'ghostwriter:resume');

      this.haunting.start();
      expect(startSpy).toHaveBeenTriggered();
      expect(resumeSpy).not.toHaveBeenTriggered();
    });

    it('should trigger ghostwriter:pause if paused', function() {
      var startSpy, resumeSpy;
      this.haunting.start().pause();

      startSpy = spyOnEvent(this.$input, 'ghostwriter:start');
      resumeSpy = spyOnEvent(this.$input, 'ghostwriter:resume');

      this.haunting.start();
      expect(resumeSpy).toHaveBeenTriggered();
      expect(startSpy).not.toHaveBeenTriggered();
    });

    it('should not trigger ghostwriter:start or ghostwriter:resume if started'
    , function() {
      var startSpy, resumeSpy;
      this.haunting.start();

      startSpy = spyOnEvent(this.$input, 'ghostwriter:start');
      resumeSpy = spyOnEvent(this.$input, 'ghostwriter:resume');

      this.haunting.start();
      expect(resumeSpy).not.toHaveBeenTriggered();
      expect(startSpy).not.toHaveBeenTriggered();
    });

    describe('stroke execution', function() {
      beforeEach(function() {
        this.strokeSpy = jasmine.createSpy();

        this.haunting = new Haunting({
          input: this.$input.val('original value')
        , interval: 50
        , manuscript: [stroke.factory(this.strokeSpy).repeat(3)]
        });

      });

      it('should execute each stroke once', function() {
        this.haunting.start();
        waits(300);
        runs(function() { expect(this.strokeSpy.callCount).toBe(3); });
      });

      it('should trigger ghostwriter:finish when the haunting finishes'
      , function() {
        var finishSpy = spyOnEvent(this.$input, 'ghostwriter:finish');

        this.haunting.start();
        waits(300);
        runs(function() { expect(finishSpy).toHaveBeenTriggered(); });
      });

      it('should not trigger ghostwriter:stop when the haunting finishes'
      , function() {
        var stopSpy = spyOnEvent(this.$input, 'ghostwriter:stop');

        this.haunting.start();
        waits(300);
        runs(function() { expect(stopSpy).not.toHaveBeenTriggered(); });
      });
    });
  });

  describe('#pause', function() {
    it('should trigger ghostwriter:pause if started', function() {
      var pauseSpy = spyOnEvent(this.$input, 'ghostwriter:pause');

      this.haunting.start().pause();
      expect(pauseSpy).toHaveBeenTriggered();
    });

    it('should not trigger ghostwriter:pause if paused', function() {
      var pauseSpy;
      this.haunting.start().pause();

      pauseSpy = spyOnEvent(this.$input, 'ghostwriter:pause');

      this.haunting.pause();
      expect(pauseSpy).not.toHaveBeenTriggered();
    });

    it('should not trigger ghostwriter:pause if stopped', function() {
      var pauseSpy;
      this.haunting.start().stop();

      pauseSpy = spyOnEvent(this.$input, 'ghostwriter:pause');

      this.haunting.pause();
      expect(pauseSpy).not.toHaveBeenTriggered();
    });
  });

  describe('#stop', function() {
    it('should trigger ghostwriter:stop if started', function() {
      var stopSpy;
      this.haunting.start();

      stopSpy = spyOnEvent(this.$input, 'ghostwriter:stop');

      this.haunting.stop();
      expect(stopSpy).toHaveBeenTriggered();
    });

    it('should trigger ghostwriter:stop if paused', function() {
      var stopSpy;
      this.haunting.start().pause();

      stopSpy = spyOnEvent(this.$input, 'ghostwriter:stop');

      this.haunting.stop();
      expect(stopSpy).toHaveBeenTriggered();
    });

    it('should not trigger ghostwriter:stop if stopped', function() {
      var stopSpy;
      this.haunting.start().stop();

      stopSpy = spyOnEvent(this.$input, 'ghostwriter:stop');

      this.haunting.stop();
      expect(stopSpy).not.toHaveBeenTriggered();
    });

    it('should reset the value of the input', function() {
      spyOn(this.haunting, 'reset');
      this.haunting.start().stop();
      expect(this.haunting.reset).toHaveBeenCalled();
    });

    it('should blur input', function() {
      this.$input.focus();
      this.haunting.start().stop();
      expect(this.$input).not.toBeFocused();
    });
  });

  describe('#restart', function() {
    it('should be alias for stop().start()', function() {
      spyOn(this.haunting, 'stop');
      spyOn(this.haunting, 'start');

      this.haunting.restart();
      expect(this.haunting.stop).toHaveBeenCalled();
      expect(this.haunting.start).toHaveBeenCalled();
    });
  });

  describe('#reset', function() {
    it('should restore the original value of the input', function() {
      this.haunting = new Haunting({
        input: this.$input.val('original value')
      , manuscript: [strokes.noop.repeat(3)]
      });

      this.$input.val('not original value');
      this.haunting.reset();
      expect(this.$input).toHaveValue('original value');
    });
  });
});
<|endoftext|>


<commit_before>/*
 * Copyright 2013 The Polymer Authors. All rights reserved.
 * Use of this source code is governed by a BSD-style
 * license that can be found in the LICENSE file.
 */

htmlSuite('MDV syntax', function() {
  htmlTest('html/mdv-syntax.html');
  htmlTest('html/mdv-syntax.html?shadow');
});
<commit_msg>Temporarily remove failing mdv syntax test, blocked on https://github.com/Polymer/ShadowDOM/issues/189<commit_after>/*
 * Copyright 2013 The Polymer Authors. All rights reserved.
 * Use of this source code is governed by a BSD-style
 * license that can be found in the LICENSE file.
 */

htmlSuite('MDV syntax', function() {
  // TODO(sorvell): only test under native until the following
  // ShadowDOMPolyfill issue is addressed:
  // https://github.com/Polymer/ShadowDOM/issues/189
  if (!window.ShadowDOMPolyfill) {
    htmlTest('html/mdv-syntax.html');
  }
  //htmlTest('html/mdv-syntax.html?shadow');
});
<|endoftext|>


<commit_before>const assert = require("assert");
const nock = require("nock");

const Client = require("swagger-test");

const mockAddress = "http://localhost:8000";
const alternateMockAddress = "http://localhost:8001";

describe("operations", function() {
  it("correctly fill out path, header and query params", function(done) {
    const c = new Client({address: mockAddress});
    const params = {
      authorization: "Bearer YOGI",
      bookID: "the-mediocre-gatsby",
      randomBytes: "4" // Very random
    };
    const mockResponse = {hello: "world"};
    const scope = nock(mockAddress, {reqheaders: {'authorization': params.authorization}})
      .get(`/v1/books/${params.bookID}`)
      .query({randomBytes: params.randomBytes})
      .reply(200, mockResponse);
    c.getBookByID(params, function(err, resp) {
      assert(scope.isDone());
      assert.ifError(err);
      assert.deepEqual(resp, mockResponse)
      done();
    });
  });

  it("works with multiple clients as long as a different serviceName is used", function(done) {
    let doneCount = 0;

    const c = new Client({address: mockAddress});
    const params = {
      authorization: "Bearer YOGI",
      bookID: "the-mediocre-gatsby",
      randomBytes: "4" // Very random
    };
    const mockResponse = {hello: "world"};
    const scope = nock(mockAddress, {reqheaders: {'authorization': params.authorization}})
      .get(`/v1/books/${params.bookID}`)
      .query({randomBytes: params.randomBytes})
      .reply(200, mockResponse);
    c.getBookByID(params, function(err, resp) {
      assert(scope.isDone());
      assert.ifError(err);
      assert.deepEqual(resp, mockResponse)
      doneCount++;
      if (doneCount == 2) {
        done();
      }
    });

    const alternateClient = new Client({address: alternateMockAddress, serviceName: "alternate-swagger-test"});
    const alternateScope = nock(alternateMockAddress, {reqheaders: {'authorization': params.authorization}})
      .get(`/v1/books/${params.bookID}`)
      .query({randomBytes: params.randomBytes})
      .reply(200, mockResponse);
    alternateClient.getBookByID(params, function(err, resp) {
      assert(alternateScope.isDone());
      assert.ifError(err);
      assert.deepEqual(resp, mockResponse)
      doneCount++;
      if (doneCount == 2) {
        done();
      }
    });
  });

  it("error on empty path param", function(done) {
    const c = new Client({address: mockAddress});
    const params = {
      bookID: "",
    };
    c.getBookByID(params, function(err, resp) {
      assert.equal(err.toString(), "Error: bookID must be non-empty because it's a path parameter")
      done()
    });
  });

  it("return a error in failure cases", function(done) {
    const c = new Client({address: mockAddress});
    const scope = nock(mockAddress)
      .get(`/v1/books`)
      .reply(400, {problems: 99, message: "hit me"});
    c.getBooks({}, {}, function(err, resp) {
      assert.equal(resp, undefined);
      assert.equal(err.message, "hit me");
      assert.equal(err.problems, 99);
      done();
    });
  });

  it("return a promise", function(done) {
    const c = new Client({address: mockAddress});
    const scope = nock(mockAddress)
      .get(`/v1/books`)
      .reply(200);
    c.getBooks({}, {}).then(function() {
      assert(scope.isDone());
      done();
    });
  });

  it("return a error to the promise", function(done) {
    const c = new Client({address: mockAddress});
    const scope = nock(mockAddress)
      .get(`/v1/books`)
      .reply(400, {problems: 99, message: "hit me"});
    c.getBooks({}, {}).then(function() {
      assert(false, "then callback should not have been called");
    }).catch(function(err) {
      assert.equal(err.message, "hit me");
      assert.equal(err.problems, 99);
      done();
    });
  });

  it("sends a version header", function(done) {
    const c = new Client({address: mockAddress});
    const scope = nock(mockAddress)
          .get(`/v1/books`)
      .reply(function(uri, requestBody) {
        assert.equal(Client.Version, this.req.headers[Client.VersionHeader.toLowerCase()]);
      }, 200);
    c.getBooks({}, {}).then(function() {
      assert(scope.isDone());
      done();
    });
  });
});
<commit_msg>test cases for OpenTracing span handling<commit_after>const assert = require("assert");
const nock = require("nock");
const opentracing = require("opentracing");

const Client = require("swagger-test");

const mockAddress = "http://localhost:8000";
const alternateMockAddress = "http://localhost:8001";

describe("operations", function() {
  it("correctly fill out path, header and query params", function(done) {
    const c = new Client({address: mockAddress});
    const params = {
      authorization: "Bearer YOGI",
      bookID: "the-mediocre-gatsby",
      randomBytes: "4" // Very random
    };
    const mockResponse = {hello: "world"};
    const scope = nock(mockAddress, {reqheaders: {'authorization': params.authorization}})
      .get(`/v1/books/${params.bookID}`)
      .query({randomBytes: params.randomBytes})
      .reply(200, mockResponse);
    c.getBookByID(params, function(err, resp) {
      assert(scope.isDone());
      assert.ifError(err);
      assert.deepEqual(resp, mockResponse)
      done();
    });
  });

  it("works with multiple clients as long as a different serviceName is used", function(done) {
    let doneCount = 0;

    const c = new Client({address: mockAddress});
    const params = {
      authorization: "Bearer YOGI",
      bookID: "the-mediocre-gatsby",
      randomBytes: "4" // Very random
    };
    const mockResponse = {hello: "world"};
    const scope = nock(mockAddress, {reqheaders: {'authorization': params.authorization}})
      .get(`/v1/books/${params.bookID}`)
      .query({randomBytes: params.randomBytes})
      .reply(200, mockResponse);
    c.getBookByID(params, function(err, resp) {
      assert(scope.isDone());
      assert.ifError(err);
      assert.deepEqual(resp, mockResponse)
      doneCount++;
      if (doneCount == 2) {
        done();
      }
    });

    const alternateClient = new Client({address: alternateMockAddress, serviceName: "alternate-swagger-test"});
    const alternateScope = nock(alternateMockAddress, {reqheaders: {'authorization': params.authorization}})
      .get(`/v1/books/${params.bookID}`)
      .query({randomBytes: params.randomBytes})
      .reply(200, mockResponse);
    alternateClient.getBookByID(params, function(err, resp) {
      assert(alternateScope.isDone());
      assert.ifError(err);
      assert.deepEqual(resp, mockResponse)
      doneCount++;
      if (doneCount == 2) {
        done();
      }
    });
  });

  it("error on empty path param", function(done) {
    const c = new Client({address: mockAddress});
    const params = {
      bookID: "",
    };
    c.getBookByID(params, function(err, resp) {
      assert.equal(err.toString(), "Error: bookID must be non-empty because it's a path parameter")
      done()
    });
  });

  it("return a error in failure cases", function(done) {
    const c = new Client({address: mockAddress});
    const scope = nock(mockAddress)
      .get(`/v1/books`)
      .reply(400, {problems: 99, message: "hit me"});
    c.getBooks({}, {}, function(err, resp) {
      assert.equal(resp, undefined);
      assert.equal(err.message, "hit me");
      assert.equal(err.problems, 99);
      done();
    });
  });

  it("return a promise", function(done) {
    const c = new Client({address: mockAddress});
    const scope = nock(mockAddress)
      .get(`/v1/books`)
      .reply(200);
    c.getBooks({}, {}).then(function() {
      assert(scope.isDone());
      done();
    });
  });

  it("return a error to the promise", function(done) {
    const c = new Client({address: mockAddress});
    const scope = nock(mockAddress)
      .get(`/v1/books`)
      .reply(400, {problems: 99, message: "hit me"});
    c.getBooks({}, {}).then(function() {
      assert(false, "then callback should not have been called");
    }).catch(function(err) {
      assert.equal(err.message, "hit me");
      assert.equal(err.problems, 99);
      done();
    });
  });

  it("sends a version header", function(done) {
    const c = new Client({address: mockAddress});
    const scope = nock(mockAddress)
          .get(`/v1/books`)
      .reply(function(uri, requestBody) {
        assert.equal(Client.Version, this.req.headers[Client.VersionHeader.toLowerCase()]);
      }, 200);
    c.getBooks({}, {}).then(function() {
      assert(scope.isDone());
      done();
    });
  });

  it("works with an OpenTracing span, and adds tag to it", function(done) {
    const tracer = new opentracing.MockTracer();
    const c = new Client({address: mockAddress, tracer});
    const span = tracer.startSpan("foo_span")
    const scope = nock(mockAddress)
      .get(`/v1/books`)
      .reply(200);
    c.getBooks({}, {span}).then(function() {
      assert(scope.isDone());
      const spans = tracer.report().spans;
      assert.equal(spans.length, 1);
      assert.deepEqual(spans[0].tags(), {"span.kind": "client"})
      done();
    });
  });

  it("doesn't error when passed a bad span", function(done) {
    const tracer = new opentracing.MockTracer();
    const c = new Client({address: mockAddress, tracer});
    const span = {
      foo: function() {}
    }
    const scope = nock(mockAddress)
      .get(`/v1/books`)
      .reply(200);
    c.getBooks({}, {span}).then(function() {
      assert(scope.isDone());
      assert.equal(tracer.report().spans.length, 0);
      done();
    });
  });
});
<|endoftext|>