<commit_before>var assert      = require("assert"),
    melted      = require('../api/Melted'),
    helpers     = require('./media_helpers'),
    Mosto       = require('../models/Mosto'),
    _           = require('underscore'),
    moment      = require('moment'),
    exec        = require('child_process').exec,
    heartbeats  = require('../heartbeats');

describe.only('Mosto Heartbeats Test', function(done) {
    before(function(done) {
        melted.take(function() {
            melted.stop(function(){
                melted.start(function(pid) {
                    melted.setup(undefined, undefined, function(has_err) {
                        done();
                    });
                });
            });
        });
    });

    describe('#Heartbeats: Init with custom config and without medias', function() {
        var self = this;
        self.hb = undefined;
        before(function(done) {
            var config = {
                gc_interval: 5000,
                sync_interval: 50,
                min_scheduled: 1000,
                mvcp_server: "melted"
            };
            self.hb = new heartbeats(config);
            done();
        });

        describe('- Suscribe and wait 1.1 second', function() {
            self.checkouts = 0;
            self.clipStatus = 0;
            self.frameStatus = 0;
            self.startPlaying = 0;
            self.outOfSync = 0;
            self.hbErrors = 0;
            self.noClips = 0;
            before(function(done) {
                self.hb.on('forceCheckout', function() {
                    self.ckeckouts++;
                });
                self.hb.on('clipStatus', function() {
                    self.clipStatus++;
                });
                self.hb.on('frameStatus', function() {
                    self.frameStatus++;
                });
                self.hb.on('startPlaying', function() {
                    self.startPlaying++;
                });
                self.hb.on('outOfSync', function() {
                    self.outOfSync++;
                });
                self.hb.on('hbErrors', function() {
                    self.hbErrors++;
                });
                self.hb.on('noClips', function() {
                    self.noClips++;
                });
                self.hb.init();
                setTimeout(function() {
                    done();
                }, 1100);
            });
            it('-- Should have received 0 forceCheckout events', function() {
                assert.equal(self.checkouts, 0);
            });
            it('-- Should have received 0 clipStatus events', function() {
                assert.equal(self.clipStatus, 0);
            });
            it('-- Should have received 0 frameStatus events', function() {
                assert.equal(self.frameStatus, 0);
            });
            it('-- Should have received 0 startPlaying events', function() {
                assert.equal(self.startPlaying, 0);
            });
            it('-- Should have received 0 outOfSync events', function() {
                assert.equal(self.outOfSync, 0);
            });
            it('-- Should have received 0 hbError events', function() {
                assert.equal(self.hbErrors, 0);
            });
            it('-- Should have received > 10 noClips events', function() {
                assert.ok(self.noClips > 10);
            });
        });

        after(function(done) {
            self.hb.stop();
            done();
        });
    });

    describe('#Heartbeats: Init with custom config and with medias', function() {
        var self = this;
        self.hb = undefined;

        var playlists = Mosto.Playlists;
        var medias = helpers.getMedia();

        createPlaylist = function(medias, start) {
            var duration = _.reduce(medias, function(acc, m) { return acc + m.get('length') * m.get('fps'); }, 0);
            start = start || moment();
            var pl = new Mosto.Playlist({
                id: start.valueOf(),
                name: 'test',
                start: moment(start),
                end: start.add(duration)
            });
            pl.get('medias').add(medias);
            return pl;
        };

        self.checkouts = 0;
        self.clipStatus = 0;
        self.frameStatus = 0;
        self.startPlaying = 0;
        self.outOfSync = 0;
        self.hbErrors = 0;
        self.noClips = 0;

        before(function(done) {
            var config = {
                gc_interval: 5000,
                sync_interval: 50,
                min_scheduled: 1000 * 60 * 60 * 4,
                checkout_interval: 900,
                mvcp_server: "melted"
            };
            self.hb = new heartbeats(config);

            self.hb.on('forceCheckout', function() {
                self.checkouts++;
            });
            self.hb.on('clipStatus', function() {
                self.clipStatus++;
            });
            self.hb.on('frameStatus', function() {
                self.frameStatus++;
            });
            self.hb.on('startPlaying', function() {
                self.startPlaying++;
            });
            self.hb.on('outOfSync', function() {
                self.outOfSync++;
            });
            self.hb.on('hbErrors', function() {
                self.hbErrors++;
            });
            self.hb.on('noClips', function() {
                self.noClips++;
            });
            self.hb.init();

            var mediamodels = _.map(medias, function(media, ix) { return new Mosto.Media(_.extend(media, { playlist_order: ix })); });

            var pl = createPlaylist(mediamodels);

            playlists().addPlaylist(pl);
            playlists().save();

            done();
        });

        describe('-- Starting playback and wait 2 seconds', function() {
            before(function(done) {
                setTimeout(function() {
                    done();
                }, 2050);
            });
            it('--- Should have received 2 forceCheckout events', function() {
                assert.equal(self.checkouts, 2);
            });
            it('--- Should have received 1 clipStatus events', function() {
                assert.equal(self.clipStatus, 1);
            });
            it('--- Should have received > 10 frameStatus events', function() {
                assert.ok(self.frameStatus > 10);
            });
            it('--- Should have received 1 startPlaying events', function() {
                assert.equal(self.startPlaying, 1);
            });
            it('--- Should have received 1 outOfSync events', function() {
                assert.equal(self.outOfSync, 1);
            });
            it('--- Should have received 0 hbError events', function() {
                assert.equal(self.hbErrors, 0);
            });
            it('--- Should have received 0 noClips events', function(done) {
                assert.equal(self.noClips, 0);
                done();
            });
        });
        describe('-- Make a goto in melted and wait 1 second', function() {
            before(function(done) {
                self.checkouts = 0;
                self.clipStatus = 0;
                self.frameStatus = 0;
                self.startPlaying = 0;
                self.outOfSync = 0;
                self.hbErrors = 0;
                self.noClips = 0;
                exec("echo 'goto u0 500' | nc localhost 5250", function (error, stdout, stderr) {
                    setTimeout(function() {
                        done();
                    }, 1000);
                });
            });
            it('--- Should have received 1 forceCheckout events', function() {
                assert.equal(self.checkouts, 1);
            });
            it('--- Should have received 0 clipStatus events', function() {
                assert.equal(self.clipStatus, 0);
            });
            it('--- Should have received > 5 frameStatus events', function() {
                assert.ok(self.frameStatus > 5);
            });
            it('--- Should have received 0 startPlaying events', function() {
                assert.equal(self.startPlaying, 0);
            });
            it('--- Should have received 1 outOfSync events', function() {
                assert.equal(self.outOfSync, 1);
            });
            it('--- Should have received 0 hbError events', function() {
                assert.equal(self.hbErrors, 0);
            });
            it('--- Should have received 0 noClips events', function(done) {
                assert.equal(self.noClips, 0);
                done();
            });
        });
        describe('-- Pause in melted and wait 1.7 second', function() {
            before(function(done) {
                self.checkouts = 0;
                self.clipStatus = 0;
                self.frameStatus = 0;
                self.startPlaying = 0;
                self.outOfSync = 0;
                self.hbErrors = 0;
                self.noClips = 0;
                exec("echo 'pause u0' | nc localhost 5250", function (error, stdout, stderr) {
                    setTimeout(function() {
                        done();
                    }, 1700);
                });
            });
            it('--- Should have received 2 forceCheckout events', function() {
                assert.equal(self.checkouts, 2);
            });
            it('--- Should have received 0 clipStatus events', function() {
                assert.equal(self.clipStatus, 0);
            });
            it('--- Should have received > 5 frameStatus events', function() {
                assert.ok(self.frameStatus > 5);
            });
            it('--- Should have received 1 startPlaying events', function() {
                assert.equal(self.startPlaying, 1);
            });
            it('--- Should have received 1 outOfSync events', function() {
                assert.equal(self.outOfSync, 1);
            });
            it('--- Should have received 0 hbError events', function() {
                assert.equal(self.hbErrors, 0);
            });
            it('--- Should have received 0 noClips events', function(done) {
                assert.equal(self.noClips, 0);
                done();
            });
        });

        after(function(done) {
            self.hb.stop();
            melted.stop(function(){
                melted.start(function(pid) {
                    melted.setup(undefined, undefined, function(has_err) {
                        done();
                    });
                });
            });
        });
    });

    describe('#leave melted', function() {
        it('-- leave melted', function(done) {
            melted.stop(function(pid) {
                melted.leave();
                done();
            });
        });
    });

});<commit_msg>Incremented timeout time<commit_after>var assert      = require("assert"),
    melted      = require('../api/Melted'),
    helpers     = require('./media_helpers'),
    Mosto       = require('../models/Mosto'),
    _           = require('underscore'),
    moment      = require('moment'),
    exec        = require('child_process').exec,
    heartbeats  = require('../heartbeats');

describe.only('Mosto Heartbeats Test', function(done) {
    before(function(done) {
        melted.take(function() {
            melted.stop(function(){
                melted.start(function(pid) {
                    melted.setup(undefined, undefined, function(has_err) {
                        done();
                    });
                });
            });
        });
    });

    describe('#Heartbeats: Init with custom config and without medias', function() {
        var self = this;
        self.hb = undefined;
        before(function(done) {
            var config = {
                gc_interval: 5000,
                sync_interval: 50,
                min_scheduled: 1000,
                mvcp_server: "melted"
            };
            self.hb = new heartbeats(config);
            done();
        });

        describe('- Suscribe and wait 1.1 second', function() {
            self.checkouts = 0;
            self.clipStatus = 0;
            self.frameStatus = 0;
            self.startPlaying = 0;
            self.outOfSync = 0;
            self.hbErrors = 0;
            self.noClips = 0;
            before(function(done) {
                self.hb.on('forceCheckout', function() {
                    self.ckeckouts++;
                });
                self.hb.on('clipStatus', function() {
                    self.clipStatus++;
                });
                self.hb.on('frameStatus', function() {
                    self.frameStatus++;
                });
                self.hb.on('startPlaying', function() {
                    self.startPlaying++;
                });
                self.hb.on('outOfSync', function() {
                    self.outOfSync++;
                });
                self.hb.on('hbErrors', function() {
                    self.hbErrors++;
                });
                self.hb.on('noClips', function() {
                    self.noClips++;
                });
                self.hb.init();
                setTimeout(function() {
                    done();
                }, 1100);
            });
            it('-- Should have received 0 forceCheckout events', function() {
                assert.equal(self.checkouts, 0);
            });
            it('-- Should have received 0 clipStatus events', function() {
                assert.equal(self.clipStatus, 0);
            });
            it('-- Should have received 0 frameStatus events', function() {
                assert.equal(self.frameStatus, 0);
            });
            it('-- Should have received 0 startPlaying events', function() {
                assert.equal(self.startPlaying, 0);
            });
            it('-- Should have received 0 outOfSync events', function() {
                assert.equal(self.outOfSync, 0);
            });
            it('-- Should have received 0 hbError events', function() {
                assert.equal(self.hbErrors, 0);
            });
            it('-- Should have received > 10 noClips events', function() {
                assert.ok(self.noClips > 10);
            });
        });

        after(function(done) {
            self.hb.stop();
            done();
        });
    });

    describe('#Heartbeats: Init with custom config and with medias', function() {
        var self = this;
        self.hb = undefined;

        var playlists = Mosto.Playlists;
        var medias = helpers.getMedia();

        createPlaylist = function(medias, start) {
            var duration = _.reduce(medias, function(acc, m) { return acc + m.get('length') * m.get('fps'); }, 0);
            start = start || moment();
            var pl = new Mosto.Playlist({
                id: start.valueOf(),
                name: 'test',
                start: moment(start),
                end: start.add(duration)
            });
            pl.get('medias').add(medias);
            return pl;
        };

        self.checkouts = 0;
        self.clipStatus = 0;
        self.frameStatus = 0;
        self.startPlaying = 0;
        self.outOfSync = 0;
        self.hbErrors = 0;
        self.noClips = 0;

        before(function(done) {
            var config = {
                gc_interval: 5000,
                sync_interval: 50,
                min_scheduled: 1000 * 60 * 60 * 4,
                checkout_interval: 900,
                mvcp_server: "melted"
            };
            self.hb = new heartbeats(config);

            self.hb.on('forceCheckout', function() {
                self.checkouts++;
            });
            self.hb.on('clipStatus', function() {
                self.clipStatus++;
            });
            self.hb.on('frameStatus', function() {
                self.frameStatus++;
            });
            self.hb.on('startPlaying', function() {
                self.startPlaying++;
            });
            self.hb.on('outOfSync', function() {
                self.outOfSync++;
            });
            self.hb.on('hbErrors', function() {
                self.hbErrors++;
            });
            self.hb.on('noClips', function() {
                self.noClips++;
            });
            self.hb.init();

            var mediamodels = _.map(medias, function(media, ix) { return new Mosto.Media(_.extend(media, { playlist_order: ix })); });

            var pl = createPlaylist(mediamodels);

            playlists().addPlaylist(pl);
            playlists().save();

            done();
        });

        describe('-- Starting playback and wait 2 seconds', function() {
            before(function(done) {
                setTimeout(function() {
                    done();
                }, 2150);
            });
            it('--- Should have received 2 forceCheckout events', function() {
                assert.equal(self.checkouts, 2);
            });
            it('--- Should have received 1 clipStatus events', function() {
                assert.equal(self.clipStatus, 1);
            });
            it('--- Should have received > 10 frameStatus events', function() {
                assert.ok(self.frameStatus > 10);
            });
            it('--- Should have received 1 startPlaying events', function() {
                assert.equal(self.startPlaying, 1);
            });
            it('--- Should have received 1 outOfSync events', function() {
                assert.equal(self.outOfSync, 1);
            });
            it('--- Should have received 0 hbError events', function() {
                assert.equal(self.hbErrors, 0);
            });
            it('--- Should have received 0 noClips events', function(done) {
                assert.equal(self.noClips, 0);
                done();
            });
        });
        describe('-- Make a goto in melted and wait 1 second', function() {
            before(function(done) {
                self.checkouts = 0;
                self.clipStatus = 0;
                self.frameStatus = 0;
                self.startPlaying = 0;
                self.outOfSync = 0;
                self.hbErrors = 0;
                self.noClips = 0;
                exec("echo 'goto u0 500' | nc localhost 5250", function (error, stdout, stderr) {
                    setTimeout(function() {
                        done();
                    }, 1000);
                });
            });
            it('--- Should have received 1 forceCheckout events', function() {
                assert.equal(self.checkouts, 1);
            });
            it('--- Should have received 0 clipStatus events', function() {
                assert.equal(self.clipStatus, 0);
            });
            it('--- Should have received > 5 frameStatus events', function() {
                assert.ok(self.frameStatus > 5);
            });
            it('--- Should have received 0 startPlaying events', function() {
                assert.equal(self.startPlaying, 0);
            });
            it('--- Should have received 1 outOfSync events', function() {
                assert.equal(self.outOfSync, 1);
            });
            it('--- Should have received 0 hbError events', function() {
                assert.equal(self.hbErrors, 0);
            });
            it('--- Should have received 0 noClips events', function(done) {
                assert.equal(self.noClips, 0);
                done();
            });
        });
        describe('-- Pause in melted and wait 1.7 second', function() {
            before(function(done) {
                self.checkouts = 0;
                self.clipStatus = 0;
                self.frameStatus = 0;
                self.startPlaying = 0;
                self.outOfSync = 0;
                self.hbErrors = 0;
                self.noClips = 0;
                exec("echo 'pause u0' | nc localhost 5250", function (error, stdout, stderr) {
                    setTimeout(function() {
                        done();
                    }, 1700);
                });
            });
            it('--- Should have received 2 forceCheckout events', function() {
                assert.equal(self.checkouts, 2);
            });
            it('--- Should have received 0 clipStatus events', function() {
                assert.equal(self.clipStatus, 0);
            });
            it('--- Should have received > 5 frameStatus events', function() {
                assert.ok(self.frameStatus > 5);
            });
            it('--- Should have received 1 startPlaying events', function() {
                assert.equal(self.startPlaying, 1);
            });
            it('--- Should have received 1 outOfSync events', function() {
                assert.equal(self.outOfSync, 1);
            });
            it('--- Should have received 0 hbError events', function() {
                assert.equal(self.hbErrors, 0);
            });
            it('--- Should have received 0 noClips events', function(done) {
                assert.equal(self.noClips, 0);
                done();
            });
        });

        after(function(done) {
            self.hb.stop();
            melted.stop(function(){
                melted.start(function(pid) {
                    melted.setup(undefined, undefined, function(has_err) {
                        done();
                    });
                });
            });
        });
    });

    describe('#leave melted', function() {
        it('-- leave melted', function(done) {
            melted.stop(function(pid) {
                melted.leave();
                done();
            });
        });
    });

});<|endoftext|>


<commit_before>/*eslint strict: [2, "function"]*/ // IIFE form
/*global xhr*/
(function () {
    "use strict";
    /*jshint browser: true*/
    /*eslint-env browser*/
    /*global __coverage__*/ // Coverage data

    function log (msg) {
        if (console.expects) {
            console.expects("log", msg, true);
        }
        console.log(msg);
    }

    function error (msg) {
        if (console.expects) {
            console.expects("error", msg, true);
        }
        console.error(msg);
    }

    var MAX_WAIT = 50;

    function _waitForTestCases (testFiles, callback) {
        function _testCaseLoaded (testCaseSource) {
            /*jshint -W061*/
            eval(testCaseSource); //eslint-disable-line no-eval
            /*jshint +W061*/
            _waitForTestCases(testFiles, callback);
        }
        if (testFiles.length) {
            xhr(testFiles.shift()).get()
                .then(_testCaseLoaded, error);
            return;
        }
        // Everything is loaded
        callback();
    }

    function _detectLegacy () {
        var legacyVersion = (/version=([0-9\.]+)/).exec(window.location.search);
        if (legacyVersion) {
            return legacyVersion[1];
        }
    }

    function _patchLegacy (version) {
        // gpf is loaded
        return xhr("/test/legacy/legacy.json").get().asJson()
            .then(function (legacy) {
                return legacy.filter(function (item) {
                    return item.before > version;
                });
            })
            .then(function (legacy) {
                var
                    _describes = [],
                    _describe = window.describe,
                    _it = window.it;
                window.describe = function (label) {
                    var issue;
                    legacy.every(function (item) {
                        if (item.ignore.some(function (ignore) {
                            return ignore.describe === label && !ignore.it;

                        })) {
                            issue = item.issue;
                            return false;
                        }
                        return true;
                    });
                    if (issue) {
                        log("describe(\"" + label + "\", ...) ignored, see issue #" + issue);
                    } else {
                        _describes.unshift(label);
                        _describe.apply(this, arguments);
                        _describes.shift();
                    }
                };
                window.it = function (label) {
                    var issue;
                    legacy.every(function (item) {
                        if (item.ignore.some(function (ignore) {
                            return ignore.describe === _describes[0] && ignore.it === label;

                        })) {
                            issue = item.issue;
                            return false;
                        }
                        return true;
                    });
                    if (issue) {
                        log("it(\"" + label + "\", ...) ignored, see issue #" + issue);
                    } else {
                        _it.apply(this, arguments);
                    }
                };
            });
    }

    // Actively wait for GPF to be loaded
    function _waitForLoad (callback) {
        // Check if the GPF library is loaded
        if ("undefined" === typeof gpf) {
            if (--MAX_WAIT) {
                setTimeout(function () {
                    _waitForLoad(callback);
                }, 100);
            } else {
                error("Unable to load GPF");
            }
            return;
        }
        // Legacy test case?
        var legacy = _detectLegacy();
        if (legacy) {
            delete gpf.internals;
            _patchLegacy(legacy)
                .then(function () {
                    _waitForTestCases([window.gpfTestsPath + "legacy/" + legacy + ".js"], callback);
                });
            return;
        }
        // Test files from sources.json
        var xhr = new XMLHttpRequest();
        xhr.open("GET", gpfSourcesPath + "sources.json");
        xhr.onreadystatechange = function () {
            if (4 === xhr.readyState) {
                _waitForTestCases(JSON.parse(xhr.responseText)
                    .filter(function (source) {
                        return source.load !== false && source.test !== false;
                    })
                    .map(function (source) {
                        return window.gpfTestsPath + source.name + ".js";
                    }), callback);
            }
        };
        xhr.send();
    }

    function _detectVersion () {
        var locationSearch = window.location.search,
            release = -1 < locationSearch.indexOf("release"),
            debug = -1 < locationSearch.indexOf("debug"),
            coverage = -1 < locationSearch.indexOf("coverage"),
            version,
            path;
        if (release) {
            version = "release";
            path = "../build/gpf.js";
        } else if (debug) {
            version = "debug";
            path = "../build/gpf-debug.js";
        } else if (coverage) {
            version = "instrumented sources";
            window.global = window;
            gpfSourcesPath += "../tmp/coverage/instrument/src/";
            path = "boot.js";
        } else {
            version = "sources";
            path = "boot.js";
        }
        log("Using " + version + " version");
        return path;
    }

    function _loadVersion (callback) {
        var head = document.getElementsByTagName("head")[0],
            script = document.createElement("script"),
            version = _detectVersion();
        script.src = gpfSourcesPath + version;
        script.language = "javascript";
        head.insertBefore(script, head.firstChild);
        _waitForLoad(callback);
    }

    function _setupConfig () {
        window.config = {};
        config.httpPort = parseInt(location.port, 10);
        var msie = (/(msie|trident)/i).test(navigator.userAgent);
        if (msie) {
            config.timerResolution = 5; // Found out that this is the only way to safely run tests
        }
    }

    /*
     * Load the GPF framework and test cases.
     * When done, execute the callback.
     */
    window.load = function (callback) {
        _setupConfig();
        _loadVersion(callback);
    };

    // Call it after tests to handle cached results & coverage storage
    window.afterRun = function (data) {
        // Check if result must be cached
        var match = (/cache=([0-9]+)/).exec(location.search);
        if (match) {
            xhr("/cache/" + match[1]).post(JSON.stringify(data));
        }
        // Store coverage data
        if ("undefined" !== typeof __coverage__) {
            xhr("/fs/tmp/coverage/reports/coverage.browser.json").post(JSON.stringify(__coverage__));
        }
    };

}());
<commit_msg>Removes useless escapes (#231)<commit_after>/*eslint strict: [2, "function"]*/ // IIFE form
/*global xhr*/
(function () {
    "use strict";
    /*jshint browser: true*/
    /*eslint-env browser*/
    /*global __coverage__*/ // Coverage data

    function log (msg) {
        if (console.expects) {
            console.expects("log", msg, true);
        }
        console.log(msg);
    }

    function error (msg) {
        if (console.expects) {
            console.expects("error", msg, true);
        }
        console.error(msg);
    }

    var MAX_WAIT = 50;

    function _waitForTestCases (testFiles, callback) {
        function _testCaseLoaded (testCaseSource) {
            /*jshint -W061*/
            eval(testCaseSource); //eslint-disable-line no-eval
            /*jshint +W061*/
            _waitForTestCases(testFiles, callback);
        }
        if (testFiles.length) {
            xhr(testFiles.shift()).get()
                .then(_testCaseLoaded, error);
            return;
        }
        // Everything is loaded
        callback();
    }

    function _detectLegacy () {
        var legacyVersion = (/version=([0-9.]+)/).exec(window.location.search);
        if (legacyVersion) {
            return legacyVersion[1];
        }
    }

    function _patchLegacy (version) {
        // gpf is loaded
        return xhr("/test/legacy/legacy.json").get().asJson()
            .then(function (legacy) {
                return legacy.filter(function (item) {
                    return item.before > version;
                });
            })
            .then(function (legacy) {
                var
                    _describes = [],
                    _describe = window.describe,
                    _it = window.it;
                window.describe = function (label) {
                    var issue;
                    legacy.every(function (item) {
                        if (item.ignore.some(function (ignore) {
                            return ignore.describe === label && !ignore.it;

                        })) {
                            issue = item.issue;
                            return false;
                        }
                        return true;
                    });
                    if (issue) {
                        log("describe(\"" + label + "\", ...) ignored, see issue #" + issue);
                    } else {
                        _describes.unshift(label);
                        _describe.apply(this, arguments);
                        _describes.shift();
                    }
                };
                window.it = function (label) {
                    var issue;
                    legacy.every(function (item) {
                        if (item.ignore.some(function (ignore) {
                            return ignore.describe === _describes[0] && ignore.it === label;

                        })) {
                            issue = item.issue;
                            return false;
                        }
                        return true;
                    });
                    if (issue) {
                        log("it(\"" + label + "\", ...) ignored, see issue #" + issue);
                    } else {
                        _it.apply(this, arguments);
                    }
                };
            });
    }

    // Actively wait for GPF to be loaded
    function _waitForLoad (callback) {
        // Check if the GPF library is loaded
        if ("undefined" === typeof gpf) {
            if (--MAX_WAIT) {
                setTimeout(function () {
                    _waitForLoad(callback);
                }, 100);
            } else {
                error("Unable to load GPF");
            }
            return;
        }
        // Legacy test case?
        var legacy = _detectLegacy();
        if (legacy) {
            delete gpf.internals;
            _patchLegacy(legacy)
                .then(function () {
                    _waitForTestCases([window.gpfTestsPath + "legacy/" + legacy + ".js"], callback);
                });
            return;
        }
        // Test files from sources.json
        var xhr = new XMLHttpRequest();
        xhr.open("GET", gpfSourcesPath + "sources.json");
        xhr.onreadystatechange = function () {
            if (4 === xhr.readyState) {
                _waitForTestCases(JSON.parse(xhr.responseText)
                    .filter(function (source) {
                        return source.load !== false && source.test !== false;
                    })
                    .map(function (source) {
                        return window.gpfTestsPath + source.name + ".js";
                    }), callback);
            }
        };
        xhr.send();
    }

    function _detectVersion () {
        var locationSearch = window.location.search,
            release = -1 < locationSearch.indexOf("release"),
            debug = -1 < locationSearch.indexOf("debug"),
            coverage = -1 < locationSearch.indexOf("coverage"),
            version,
            path;
        if (release) {
            version = "release";
            path = "../build/gpf.js";
        } else if (debug) {
            version = "debug";
            path = "../build/gpf-debug.js";
        } else if (coverage) {
            version = "instrumented sources";
            window.global = window;
            gpfSourcesPath += "../tmp/coverage/instrument/src/";
            path = "boot.js";
        } else {
            version = "sources";
            path = "boot.js";
        }
        log("Using " + version + " version");
        return path;
    }

    function _loadVersion (callback) {
        var head = document.getElementsByTagName("head")[0],
            script = document.createElement("script"),
            version = _detectVersion();
        script.src = gpfSourcesPath + version;
        script.language = "javascript";
        head.insertBefore(script, head.firstChild);
        _waitForLoad(callback);
    }

    function _setupConfig () {
        window.config = {};
        config.httpPort = parseInt(location.port, 10);
        var msie = (/(msie|trident)/i).test(navigator.userAgent);
        if (msie) {
            config.timerResolution = 5; // Found out that this is the only way to safely run tests
        }
    }

    /*
     * Load the GPF framework and test cases.
     * When done, execute the callback.
     */
    window.load = function (callback) {
        _setupConfig();
        _loadVersion(callback);
    };

    // Call it after tests to handle cached results & coverage storage
    window.afterRun = function (data) {
        // Check if result must be cached
        var match = (/cache=([0-9]+)/).exec(location.search);
        if (match) {
            xhr("/cache/" + match[1]).post(JSON.stringify(data));
        }
        // Store coverage data
        if ("undefined" !== typeof __coverage__) {
            xhr("/fs/tmp/coverage/reports/coverage.browser.json").post(JSON.stringify(__coverage__));
        }
    };

}());
<|endoftext|>


<commit_before>describe('IDBWrapper', function(){

  describe('basic CRUD, in-line keys', function(){

    var store;

    before(function(done){
      store = new IDBStore({
        storeName: 'spec-store-simple'
      }, done);
    });

    it('should store a well-formed object', function(done){
      var data = {
        id: 1,
        name: 'John'
      };
      store.put(data, function(insertId){
        expect(insertId).to.equal(data.id);
        done();
      }, done);
    });

    it('should fetch a stored object', function(done){
      store.get(1, function(data){
        expect(data.name).to.equal('John');
        done();
      }, done);
    });

    it('should overwrite a given object', function(done){
      var data = {
        id: 1,
        name: 'James'
      };
      store.put(data, function(insertId){
        store.get(1, function(data){
          expect(data.name).to.equal('James');
          done();
        }, done);
      }, done);
    });

    it('should store an object w/o an id', function(done){
      var data = {
        name: 'Joe'
      };
      store.put(data, function(insertId){
        expect(insertId).to.exist;
        store.get(insertId, function(result){
          expect(result.name).to.equal(data.name);
          done();
        }, done);
        done();
      }, done);
    });

    it('should get all stored objects', function(done){
      store.getAll(function(data){
        expect(data.length).to.equal(2);
        done();
      }, done);
    });

    it('should delete a given object', function(done){
      store.remove(1, function(result){
        store.get(1, function(data){
          expect(data).to.not.exist;
          done();
        }, done);
      }, done);
    });

    it('should clear all objects', function(done){
      store.clear(function(){
        store.getAll(function(data){
          expect(data.length).to.equal(0);
        }, done);
        done();
      }, done);
    });

    after(function(done){
      store.clear(function(){
        done();
      });
    });

  });

  describe('basic CRUD, out-of-line keys', function(){

    var store;

    before(function(done){
      store = new IDBStore({
        storeName: 'spec-store--simple-out-of-line',
        keyPath: null
      }, done);
    });

    it('should store a well-formed object', function(done){
      var data = {
        name: 'John'
      };
      var id = 1;
      store.put(id, data, function(insertId){
        expect(insertId).to.equal(id);
        done();
      }, done);
    });

    it('should fetch a stored object', function(done){
      store.get(1, function(data){
        expect(data.name).to.equal('John');
        done();
      }, done);
    });

    it('should overwrite a given object', function(done){
      var data = {
        name: 'James'
      };
      var id = 1;
      store.put(id, data, function(insertId){
        store.get(id, function(data){
          expect(data.name).to.equal('James');
          done();
        }, done);
      }, done);
    });

    it('should delete a given object', function(done){
      store.remove(1, function(result){
        store.get(1, function(data){
          expect(data).to.not.exist;
          done();
        }, done);
      }, done);
    });

    after(function(done){
      store.clear(function(){
        done();
      });
    });

  });

  describe('batch ops', function(){

    var store;
    var dataArray = [
      {
        id: 1,
        name: 'John'
      },
      {
        id: 2,
        name: 'Joe'
      },
      {
        id: 3,
        name: 'James'
      }
    ];

    before(function(done){
      store = new IDBStore({
        storeName: 'spec-store-simple'
      }, done);
    });

    it('should store multiple objects', function(done){
      store.putBatch(dataArray, function(result){
        expect(result).to.be.ok;
        done();
      }, done);
    });

    it('should fetch multiple objects', function(done){
      store.getBatch([1,2,3], function(data){
        expect(data[0].name).to.equal('John');
        expect(data[1].name).to.equal('Joe');
        expect(data[2].name).to.equal('James');
        done();
      }, done);
    });

    it('should delete multiple objects', function(done){
      store.removeBatch([1,2], function(result){
        expect(result).to.be.ok;
        store.getAll(function(data){
          expect(data.length).to.equal(1);
          expect(data[0].name).to.equal('James');
        }, done);
        done();
      }, done);
    });

    after(function(done){
      store.clear(function(){
        done();
      });
    });

  });

  describe('getBatch() dataArray return type', function(){

    var store;
    var dataArray = [
      {
        id: 1,
        name: 'John'
      },
      {
        id: 2,
        name: 'Joe'
      },
      {
        id: 3,
        name: 'James'
      }
    ];

    before(function(done){
      store = new IDBStore({
        storeName: 'spec-store-simple'
      }, function(){
        store.putBatch(dataArray, function(){
          done();
        }, done);
      });
    });

    it('should return a sparse array for arrayType="sparse"', function(done){
      store.getBatch([1,10,3], function(data){
        expect(data.length).to.equal(3);

        expect(data[0].name).to.equal('John');
        expect(data[1]).to.not.exist;
        expect(data[2].name).to.equal('James');

        var forEachCount = 0;
        data.forEach(function(){
          forEachCount++;
        });
        expect(forEachCount).to.equal(2);

        done();
      }, done, 'sparse');
    });

    it('should return a dense array for arrayType="dense"', function(done){
      store.getBatch([1,10,3], function(data){
        expect(data.length).to.equal(3);

        expect(data[0].name).to.equal('John');
        expect(data[1]).to.not.exist;
        expect(data[2].name).to.equal('James');

        var forEachCount = 0;
        data.forEach(function(){
          forEachCount++;
        });
        expect(forEachCount).to.equal(3);

        done();
      }, done, 'dense');
    });

    it('should return a reduced array for arrayType="skip"', function(done){
      store.getBatch([1,10,3], function(data){
        expect(data.length).to.equal(2);

        expect(data[0].name).to.equal('John');
        expect(data[1].name).to.equal('James');

        done();
      }, done, 'skip');
    });

    after(function(done){
      store.clear(function(){
        done();
      });
    });

  });

});
<commit_msg>wrong store name<commit_after>describe('IDBWrapper', function(){

  describe('basic CRUD, in-line keys', function(){

    var store;

    before(function(done){
      store = new IDBStore({
        storeName: 'spec-store-simple'
      }, done);
    });

    it('should store a well-formed object', function(done){
      var data = {
        id: 1,
        name: 'John'
      };
      store.put(data, function(insertId){
        expect(insertId).to.equal(data.id);
        done();
      }, done);
    });

    it('should fetch a stored object', function(done){
      store.get(1, function(data){
        expect(data.name).to.equal('John');
        done();
      }, done);
    });

    it('should overwrite a given object', function(done){
      var data = {
        id: 1,
        name: 'James'
      };
      store.put(data, function(insertId){
        store.get(1, function(data){
          expect(data.name).to.equal('James');
          done();
        }, done);
      }, done);
    });

    it('should store an object w/o an id', function(done){
      var data = {
        name: 'Joe'
      };
      store.put(data, function(insertId){
        expect(insertId).to.exist;
        store.get(insertId, function(result){
          expect(result.name).to.equal(data.name);
          done();
        }, done);
        done();
      }, done);
    });

    it('should get all stored objects', function(done){
      store.getAll(function(data){
        expect(data.length).to.equal(2);
        done();
      }, done);
    });

    it('should delete a given object', function(done){
      store.remove(1, function(result){
        store.get(1, function(data){
          expect(data).to.not.exist;
          done();
        }, done);
      }, done);
    });

    it('should clear all objects', function(done){
      store.clear(function(){
        store.getAll(function(data){
          expect(data.length).to.equal(0);
        }, done);
        done();
      }, done);
    });

    after(function(done){
      store.clear(function(){
        done();
      });
    });

  });

  describe('basic CRUD, out-of-line keys', function(){

    var store;

    before(function(done){
      store = new IDBStore({
        storeName: 'spec-store-simple-out-of-line',
        keyPath: null
      }, done);
    });

    it('should store a well-formed object', function(done){
      var data = {
        name: 'John'
      };
      var id = 1;
      store.put(id, data, function(insertId){
        expect(insertId).to.equal(id);
        done();
      }, done);
    });

    it('should fetch a stored object', function(done){
      store.get(1, function(data){
        expect(data.name).to.equal('John');
        done();
      }, done);
    });

    it('should overwrite a given object', function(done){
      var data = {
        name: 'James'
      };
      var id = 1;
      store.put(id, data, function(insertId){
        store.get(id, function(data){
          expect(data.name).to.equal('James');
          done();
        }, done);
      }, done);
    });

    it('should delete a given object', function(done){
      store.remove(1, function(result){
        store.get(1, function(data){
          expect(data).to.not.exist;
          done();
        }, done);
      }, done);
    });

    after(function(done){
      store.clear(function(){
        done();
      });
    });

  });

  describe('batch ops', function(){

    var store;
    var dataArray = [
      {
        id: 1,
        name: 'John'
      },
      {
        id: 2,
        name: 'Joe'
      },
      {
        id: 3,
        name: 'James'
      }
    ];

    before(function(done){
      store = new IDBStore({
        storeName: 'spec-store-simple'
      }, done);
    });

    it('should store multiple objects', function(done){
      store.putBatch(dataArray, function(result){
        expect(result).to.be.ok;
        done();
      }, done);
    });

    it('should fetch multiple objects', function(done){
      store.getBatch([1,2,3], function(data){
        expect(data[0].name).to.equal('John');
        expect(data[1].name).to.equal('Joe');
        expect(data[2].name).to.equal('James');
        done();
      }, done);
    });

    it('should delete multiple objects', function(done){
      store.removeBatch([1,2], function(result){
        expect(result).to.be.ok;
        store.getAll(function(data){
          expect(data.length).to.equal(1);
          expect(data[0].name).to.equal('James');
        }, done);
        done();
      }, done);
    });

    after(function(done){
      store.clear(function(){
        done();
      });
    });

  });

  describe('getBatch() dataArray return type', function(){

    var store;
    var dataArray = [
      {
        id: 1,
        name: 'John'
      },
      {
        id: 2,
        name: 'Joe'
      },
      {
        id: 3,
        name: 'James'
      }
    ];

    before(function(done){
      store = new IDBStore({
        storeName: 'spec-store-simple'
      }, function(){
        store.putBatch(dataArray, function(){
          done();
        }, done);
      });
    });

    it('should return a sparse array for arrayType="sparse"', function(done){
      store.getBatch([1,10,3], function(data){
        expect(data.length).to.equal(3);

        expect(data[0].name).to.equal('John');
        expect(data[1]).to.not.exist;
        expect(data[2].name).to.equal('James');

        var forEachCount = 0;
        data.forEach(function(){
          forEachCount++;
        });
        expect(forEachCount).to.equal(2);

        done();
      }, done, 'sparse');
    });

    it('should return a dense array for arrayType="dense"', function(done){
      store.getBatch([1,10,3], function(data){
        expect(data.length).to.equal(3);

        expect(data[0].name).to.equal('John');
        expect(data[1]).to.not.exist;
        expect(data[2].name).to.equal('James');

        var forEachCount = 0;
        data.forEach(function(){
          forEachCount++;
        });
        expect(forEachCount).to.equal(3);

        done();
      }, done, 'dense');
    });

    it('should return a reduced array for arrayType="skip"', function(done){
      store.getBatch([1,10,3], function(data){
        expect(data.length).to.equal(2);

        expect(data[0].name).to.equal('John');
        expect(data[1].name).to.equal('James');

        done();
      }, done, 'skip');
    });

    after(function(done){
      store.clear(function(){
        done();
      });
    });

  });

});
<|endoftext|>


<commit_before>npm i -g curl
npm i -g jstestdriver
<commit_msg>Testing travis.yml<commit_after>npm -g curl
npm -g jstestdriver
<|endoftext|>


<commit_before>const {observable} = require('../src/middleware')
const requester = require('../src/index')
const {expect, baseUrl} = require('./helpers')

describe('observable middleware', () => {
  it('should turn the return value into an observable', done => {
    const request = requester([baseUrl, observable])
    request({url: '/plain-text'})
      .filter(ev => ev.type === 'response')
      .map(ev => ev.response)
      .subscribe(res => {
        expect(res).to.containSubset({
          body: 'Just some plain text for you to consume',
          method: 'GET',
          statusCode: 200
        })

        done()
      })
  })

  it('should trigger error handler on failures', done => {
    const request = requester([baseUrl, observable])
    request({url: '/permafail'}).subscribe({
      next: () => done(new Error('next() called when error() should have been')),
      error: err => {
        expect(err.message).to.match(/(socket|network)/i)
        done()
      }
    })
  })

  // @todo test timeout errors
  // @todo cancelation
})
<commit_msg>Ensure unsubscribing from observable cancels request<commit_after>const once = require('lodash.once')
const {observable} = require('../src/middleware')
const requester = require('../src/index')
const {expect, baseUrl} = require('./helpers')

describe('observable middleware', () => {
  it('should turn the return value into an observable', done => {
    const request = requester([baseUrl, observable])
    request({url: '/plain-text'})
      .filter(ev => ev.type === 'response')
      .map(ev => ev.response)
      .subscribe(res => {
        expect(res).to.containSubset({
          body: 'Just some plain text for you to consume',
          method: 'GET',
          statusCode: 200
        })

        done()
      })
  })

  it('should trigger error handler on failures', done => {
    const request = requester([baseUrl, observable])
    request({url: '/permafail'}).subscribe({
      next: () => done(new Error('next() called when error() should have been')),
      error: err => {
        expect(err.message).to.match(/(socket|network)/i)
        done()
      }
    })
  })

  it('should not trigger request unless subscribe is called', done => {
    const onRequest = () => done(new Error('Request triggered without subscribe()'))
    const request = requester([baseUrl, observable, {onRequest}])
    request({url: '/plain-text'})
    setTimeout(() => done(), 100)
  })

  it('should cancel the request when unsubscribing from observable', cb => {
    const done = once(cb)
    const request = requester([baseUrl, observable])
    const subscriber = request({url: '/delay'}).subscribe({
      next: res => done(new Error('response channel should not be called when aborting')),
      error: err => done(new Error(`error channel should not be called when aborting, got:\n\n${err.message}`))
    })

    setTimeout(() => subscriber.unsubscribe(), 15)
    setTimeout(() => done(), 250)
  })

  // @todo test timeout errors
})
<|endoftext|>


<commit_before>function Minimax(heuristic, childhood) {

    function maximize(start, depth) {

        // return negamax implementation of a maximized move
        return negamax(start, depth, Number.NEGATIVE_INFINITY, Number.POSITIVE_INFINITY, 1, true);
    }

    function minimize(start, depth) {

        // return negamax implementation of a minimized move
        return negamax(start, depth, Number.NEGATIVE_INFINITY, Number.POSITIVE_INFINITY, -1, true);
    }

    function negamax(move, distance, alpha, beta, color, caller) {

        // return current move as leaf when it doesn't have any depth left
        if (distance === 0) {

            return move;
        }

        // retrieve child moves of current move
        const moves = childhood(move);

        // return current move as leaf when it doesn't have any child moves
        if (moves.length === 0) {

            return move;
        }

        let bestScore = Number.NEGATIVE_INFINITY;
        let bestLeaf = null;
        let bestMove = null;

        // iterate through child moves
        for (let iterator = 0, length = moves.length; iterator < length; iterator++) {

            const currentMove = moves[iterator];
            const currentLeaf = negamax(currentMove, distance - 1, -beta, -alpha, -color, false);
            const currentScore = color * heuristic(currentLeaf);

            // save the best move
            if (currentScore > bestScore)  {

                bestScore = currentScore;
                bestLeaf = currentLeaf;
                bestMove = currentMove;
            }

            alpha = Math.max(alpha, currentScore);

            // alpha-beta pruning
            if (alpha >= beta)  {

                break;
            }
        }

        // return best leaf of tree when iterate and best move for the caller
        return caller !== true ? bestLeaf : bestMove;
    }

    this.maximize = maximize;
    this.minimize = minimize;
}

export {

    Minimax
};
<commit_msg>update export type<commit_after>function Minimax(heuristic, childhood) {

    function maximize(start, depth) {

        // return negamax implementation of a maximized move
        return negamax(start, depth, Number.NEGATIVE_INFINITY, Number.POSITIVE_INFINITY, 1, true);
    }

    function minimize(start, depth) {

        // return negamax implementation of a minimized move
        return negamax(start, depth, Number.NEGATIVE_INFINITY, Number.POSITIVE_INFINITY, -1, true);
    }

    function negamax(move, distance, alpha, beta, color, caller) {

        // return current move as leaf when it doesn't have any depth left
        if (distance === 0) {

            return move;
        }

        // retrieve child moves of current move
        const moves = childhood(move);

        // return current move as leaf when it doesn't have any child moves
        if (moves.length === 0) {

            return move;
        }

        let bestScore = Number.NEGATIVE_INFINITY;
        let bestLeaf = null;
        let bestMove = null;

        // iterate through child moves
        for (let iterator = 0, length = moves.length; iterator < length; iterator++) {

            const currentMove = moves[iterator];
            const currentLeaf = negamax(currentMove, distance - 1, -beta, -alpha, -color, false);
            const currentScore = color * heuristic(currentLeaf);

            // save the best move
            if (currentScore > bestScore)  {

                bestScore = currentScore;
                bestLeaf = currentLeaf;
                bestMove = currentMove;
            }

            alpha = Math.max(alpha, currentScore);

            // alpha-beta pruning
            if (alpha >= beta)  {

                break;
            }
        }

        // return best leaf of tree when iterate and best move for the caller
        return caller !== true ? bestLeaf : bestMove;
    }

    this.maximize = maximize;
    this.minimize = minimize;
}

// exports current module as an object
export {Minimax};
<|endoftext|>


<commit_before>describe("Stack", function() {

	var stack;

	beforeEach(function() {
		stack = new Stack();
		stack.push('a');
		stack.push('b');
		stack.push('c')
	});

	// Test push
	it('pushes an element onto the stack', function() {
		stack.push('d');
		expect(stack.getLength()).toBeGreaterThan(0);
	});

	// Test pop
	it('pops an element off the stack', function() {
		stack.pop();
		expect(stack.pop()).toEqual('b');
	});

	// Test peek
	it('peeks at the top element of the stack', function() {
		expect(stack.peek()).toEqual('c');
	});

	// Test clear
	it('clears the stack', function() {
		stack.clear();
		expect(stack.getLength()).toEqual(0);
	});

	// Test getLength
	it('gets the length of the stack', function() {
		expect(stack.getLength()).toEqual(jasmine.any(Number));
	});

	// Test toString
	it('gets a string representation of the stack', function() {
		expect(stack.toString()).toEqual(jasmine.any(String));
	});

});<commit_msg>Fix Typo in Stack.spec.js<commit_after>describe("Stack", function() {

	var stack;

	beforeEach(function() {
		stack = new Stack();
		stack.push('a');
		stack.push('b');
		stack.push('c');
	});

	// Test push
	it('pushes an element onto the stack', function() {
		stack.push('d');
		expect(stack.getLength()).toBeGreaterThan(0);
	});

	// Test pop
	it('pops an element off the stack', function() {
		stack.pop();
		expect(stack.pop()).toEqual('b');
	});

	// Test peek
	it('peeks at the top element of the stack', function() {
		expect(stack.peek()).toEqual('c');
	});

	// Test clear
	it('clears the stack', function() {
		stack.clear();
		expect(stack.getLength()).toEqual(0);
	});

	// Test getLength
	it('gets the length of the stack', function() {
		expect(stack.getLength()).toEqual(jasmine.any(Number));
	});

	// Test toString
	it('gets a string representation of the stack', function() {
		expect(stack.toString()).toEqual(jasmine.any(String));
	});

});<|endoftext|>


<commit_before>var robotIds = require('../lib/robotIds');

function getRobot(req, res) {
  'use strict';

  res.send(robotIds.robotIds);
}

module.exports = getRobot;
<commit_msg>Updates getRobotIds for new ESLint config.<commit_after>'use strict';

const robotIds = require('../lib/robotIds');

function getRobot(req, res) {
  res.send(robotIds.robotIds);
}

module.exports = getRobot;
<|endoftext|>


<commit_before>var AssertError;
if (Error.captureStackTrace) {
  AssertError = function AssertError(message, caller) {
    Error.prototype.constructor.call(this, message);
    this.message = message;

    if (Error.captureStackTrace) {
      Error.captureStackTrace(this, caller || AssertError);
    }
  };

  AssertError.prototype = new Error();
} else {
  AssertError = Error;
}

global.shouldCompileTo = function(string, hashOrArray, expected, message) {
  shouldCompileToWithPartials(string, hashOrArray, false, expected, message);
};

global.shouldCompileToWithPartials = function shouldCompileToWithPartials(string, hashOrArray, partials, expected, message) {
  var result = compileWithPartials(string, hashOrArray, partials);
  if (result !== expected) {
    throw new AssertError("'" + result + "' should === '" + expected + "': " + message, shouldCompileToWithPartials);
  }
};

global.compileWithPartials = function(string, hashOrArray, partials) {
  var template,
      ary,
      options;
  if (Object.prototype.toString.call(hashOrArray) === '[object Array]') {
    ary = [];
    ary.push(hashOrArray[0]);
    ary.push({ helpers: hashOrArray[1], partials: hashOrArray[2] });
    options = typeof hashOrArray[3] === 'object' ? hashOrArray[3] : {compat: hashOrArray[3]};
    if (hashOrArray[4] != null) {
      options.data = !!hashOrArray[4];
      ary[1].data = hashOrArray[4];
    }
  } else {
    ary = [hashOrArray];
  }

  template = CompilerContext[partials ? 'compileWithPartial' : 'compile'](string, options);
  return template.apply(this, ary);
};

global.equals = global.equal = function equals(a, b, msg) {
  if (a !== b) {
    throw new AssertError("'" + a + "' should === '" + b + "'" + (msg ? ': ' + msg : ''), equals);
  }
};

global.shouldThrow = function(callback, type, msg) {
  var failed;
  try {
    callback();
    failed = true;
  } catch (err) {
    if (type && !(err instanceof type)) {
      throw new AssertError('Type failure: ' + err);
    }
    if (msg && !(msg.test ? msg.test(err.message) : msg === err.message)) {
      equal(msg, err.message);
    }
  }
  if (failed) {
    throw new AssertError('It failed to throw', shouldThrow);
  }
};
<commit_msg>Add object option to test runner<commit_after>var AssertError;
if (Error.captureStackTrace) {
  AssertError = function AssertError(message, caller) {
    Error.prototype.constructor.call(this, message);
    this.message = message;

    if (Error.captureStackTrace) {
      Error.captureStackTrace(this, caller || AssertError);
    }
  };

  AssertError.prototype = new Error();
} else {
  AssertError = Error;
}

global.shouldCompileTo = function(string, hashOrArray, expected, message) {
  shouldCompileToWithPartials(string, hashOrArray, false, expected, message);
};

global.shouldCompileToWithPartials = function shouldCompileToWithPartials(string, hashOrArray, partials, expected, message) {
  var result = compileWithPartials(string, hashOrArray, partials);
  if (result !== expected) {
    throw new AssertError("'" + result + "' should === '" + expected + "': " + message, shouldCompileToWithPartials);
  }
};

global.compileWithPartials = function(string, hashOrArray, partials) {
  var template,
      ary,
      options;
  if (hashOrArray && hashOrArray.hash) {
    ary = [hashOrArray.hash, hashOrArray];
    delete hashOrArray.hash;
  } else if (Object.prototype.toString.call(hashOrArray) === '[object Array]') {
    ary = [];
    ary.push(hashOrArray[0]);
    ary.push({ helpers: hashOrArray[1], partials: hashOrArray[2] });
    options = typeof hashOrArray[3] === 'object' ? hashOrArray[3] : {compat: hashOrArray[3]};
    if (hashOrArray[4] != null) {
      options.data = !!hashOrArray[4];
      ary[1].data = hashOrArray[4];
    }
  } else {
    ary = [hashOrArray];
  }

  template = CompilerContext[partials ? 'compileWithPartial' : 'compile'](string, options);
  return template.apply(this, ary);
};

global.equals = global.equal = function equals(a, b, msg) {
  if (a !== b) {
    throw new AssertError("'" + a + "' should === '" + b + "'" + (msg ? ': ' + msg : ''), equals);
  }
};

global.shouldThrow = function(callback, type, msg) {
  var failed;
  try {
    callback();
    failed = true;
  } catch (err) {
    if (type && !(err instanceof type)) {
      throw new AssertError('Type failure: ' + err);
    }
    if (msg && !(msg.test ? msg.test(err.message) : msg === err.message)) {
      equal(msg, err.message);
    }
  }
  if (failed) {
    throw new AssertError('It failed to throw', shouldThrow);
  }
};
<|endoftext|>


<commit_before>const linz = require('../');
const moment = require('moment');
const { deprecate } = require('util');

const { isDate } = require('../lib/util');
const {
    boolean,
    date,
    referenceName,
} = require('../lib/formtools/renderers-cell');
const { getTransposeFn } = require('../lib/util');

const promisify = (fn, callWith = []) => () => new Promise((resolve, reject) => {

    fn.apply(null, callWith.concat((err, form) => {

        if (err) {
            return reject(err);
        }

        return resolve(form);

    }));

});

const prettifyData = (req, fieldName, val) => new Promise((resolve, reject) => {

    if (typeof val === 'boolean') {

        return boolean(val, null, null, null, (err, result) => {

            if (err) {
                return reject(err);
            }

            return resolve(result);

        });

    }

    if (isDate(val)) {

        return date(val, null, null, null, (err, result) => {

            if (err) {
                return reject(err);
            }

            return resolve(result);

        });

    }

    if (val && req.linz.model.schema.tree[fieldName].ref) {

        return referenceName(val, null, fieldName, req.linz.model, (err, result) => {

            if (err) {
                return reject(err);
            }

            return resolve(result);

        });

    }

    return resolve(val);

});

// this will retrieve the export object, using Linz's default export handler amongst custom export handlers
// this is based on the knowledge that only Linz's default export handler can have an `action` of `export`
// `exports` should be model.list.export
var getExport = function (exports) {

    var exp = undefined;

    // retrieve the export object
    exports.forEach(function (_export) {

        // Linz's default export function is called export
        if (_export.action && _export.action === 'export') {
            exp = _export;
        }

    });

    // if the export object could not be found, throw an error
    if (!exp) {
        throw new Error('The export was using Linz default export method, yet the model\'s list.export object could not be found.');
    }

    return exp;

}

// When deprecating this, also remove the following lines:
// plugin-helps.js#L361: exclusions: exp.exclusions || '_id,dateCreated,dateModified,createdBy,modifiedBy',
const getInclusionsFromExclusions = deprecate(function (exportObj, model) {

    const exclusions = (exportObj.exclusions || '').split(',');
    const inclusions = [];

    model.schema.eachPath(function (pathname) {

        const exclude = ['__v'].concat(exclusions);

        if (exclude.includes(pathname)) {
            return;
        }

        inclusions.push(pathname);

    });

    return inclusions;

}, 'Export exclusions have been deprecated, use inclusions instead.');

module.exports = {

    get: function (req, res, next) {

        const getLabels = promisify(req.linz.model.getLabels);
        const getList = promisify(req.linz.model.getList, [req]);

        Promise.all([
            getLabels(),
            getList(),
        ])
            .then(([labels, list]) => {

                // attach our list object to the model
                req.linz.model.list = list;

                // retrieve the export object
                req.linz.export = getExport(list.export);
                req.linz.export.fields = {};

                const includedFields = req.linz.export.inclusions.length > 0 ? req.linz.export.inclusions.split(',') : getInclusionsFromExclusions(req.linz.export, req.linz.model);

                const fieldLabels = {};
                const includedPaths = Object
                    .keys(req.linz.model.schema.paths)
                    .filter((key) => includedFields.includes(key));

                includedPaths.forEach(function (field) {

                    if (!labels[field]) {
                        throw new Error(`Could not find ${field} field in the labels object.`);
                    }

                    // get a list of fields by the label ready for sorting
                    fieldLabels[labels[field]] = field;

                });

                // sort fields by label
                var sortedFieldsByLabel = Object.keys(fieldLabels).sort();

                // iterate through sorted label and re-constructs in the order of labels
                sortedFieldsByLabel.forEach(function (label) {
                    req.linz.export.fields[fieldLabels[label]] = label;
                });

                return next(null);

            })
            .catch(next);

    },

    post: function (req, res, next) {

        var Model = req.linz.model;
        const getForm = promisify(req.linz.model.getForm, [req]);
        const getLabels = promisify(req.linz.model.getLabels);
        const getList = promisify(req.linz.model.getList, [req]);

        return Promise.all([
            getForm(),
            getLabels(),
            getList(),
            linz.api.formtools.list.getFilters(req),
        ])
            .then(([form, labels, list, filters]) => {

                const exportObj = getExport(list.export);
                const includedFields = exportObj.inclusions.length > 0 ? exportObj.inclusions.split(',') : getInclusionsFromExclusions(exportObj, Model);
                const bodyFields = req.body.selectedFields.split(',');
                const refFieldNames = [];
                const fields = includedFields.filter((field) => bodyFields.includes(field))

                let filterFieldNames = [];

                fields.forEach(function (fieldName, index, arr) {

                    // check if there any ref fields selected to be exported
                    if(!Model.schema.tree[fieldName] || !Model.schema.tree[fieldName].ref) {
                        return;
                    }

                    return refFieldNames.push(fieldName);

                });

                // If _id is not included, exclude it from the export;
                if (!fields.includes('_id')) {
                    filterFieldNames.push('-_id');
                }

                filterFieldNames = filterFieldNames.concat(fields);

                // pipe data to response stream
                req.linz.model.getQuery(req, filters, function getQuery (err, query) {

                    if (err) {
                        return next(err);
                    }

                    req.linz.model.listQuery(req, query, (listQueryErr, listQuery) => {

                        if (listQueryErr) {
                            return next(listQueryErr);
                        }

                        const exclusions = exportObj.exclusions.split(',');
                        const exportQuery = listQuery.select(filterFieldNames.join(' '));
                        const columnsFn = exportObj.columns || ((columns) => columns);
                        const formattedFields = fields
                            .map(fieldName => ({
                                header: labels[fieldName],
                                key: fieldName,
                            }));
                        const columns = columnsFn(formattedFields);

                        linz.api.util.generateExport({
                            columns,
                            contentType: 'text/csv',
                            name: `${Model.linz.formtools.model.plural}-${moment(Date.now()).format('l').replace(/\//g, '.', 'g')}`,
                            req,
                            res,
                            stream: exportQuery.lean().cursor(),
                            transform: (doc, callback) => {

                                const fields = Object.keys(doc);
                                const promises = [];

                                fields.forEach((fieldName) => {

                                    if (getTransposeFn(form, fieldName, 'export')) {

                                        return promises.push(getTransposeFn(form, fieldName, 'export')(doc[fieldName], doc)
                                            .then((result) => {

                                                const updatedDoc = doc;
                                                let val = result;
                                                let merge = false;

                                                if (Array.isArray(val)) {
                                                    [val, merge = false] = val;
                                                }

                                                if (!merge) {
                                                    return (doc[fieldName] = val);
                                                }

                                                return (doc = Object.assign({}, updatedDoc, val));

                                            }));

                                    }

                                    return promises.push(prettifyData(req, fieldName, doc[fieldName])
                                        .then((val) => (doc[fieldName] = val)));

                                });

                                Promise.all(promises)
                                    .then(() => callback(null, doc))
                                    .catch(callback);

                            },
                        });

                    });

                });

            })
            .catch(next);

    }
};
<commit_msg>Removed a variable no longer being used.<commit_after>const linz = require('../');
const moment = require('moment');
const { deprecate } = require('util');

const { isDate } = require('../lib/util');
const {
    boolean,
    date,
    referenceName,
} = require('../lib/formtools/renderers-cell');
const { getTransposeFn } = require('../lib/util');

const promisify = (fn, callWith = []) => () => new Promise((resolve, reject) => {

    fn.apply(null, callWith.concat((err, form) => {

        if (err) {
            return reject(err);
        }

        return resolve(form);

    }));

});

const prettifyData = (req, fieldName, val) => new Promise((resolve, reject) => {

    if (typeof val === 'boolean') {

        return boolean(val, null, null, null, (err, result) => {

            if (err) {
                return reject(err);
            }

            return resolve(result);

        });

    }

    if (isDate(val)) {

        return date(val, null, null, null, (err, result) => {

            if (err) {
                return reject(err);
            }

            return resolve(result);

        });

    }

    if (val && req.linz.model.schema.tree[fieldName].ref) {

        return referenceName(val, null, fieldName, req.linz.model, (err, result) => {

            if (err) {
                return reject(err);
            }

            return resolve(result);

        });

    }

    return resolve(val);

});

// this will retrieve the export object, using Linz's default export handler amongst custom export handlers
// this is based on the knowledge that only Linz's default export handler can have an `action` of `export`
// `exports` should be model.list.export
var getExport = function (exports) {

    var exp = undefined;

    // retrieve the export object
    exports.forEach(function (_export) {

        // Linz's default export function is called export
        if (_export.action && _export.action === 'export') {
            exp = _export;
        }

    });

    // if the export object could not be found, throw an error
    if (!exp) {
        throw new Error('The export was using Linz default export method, yet the model\'s list.export object could not be found.');
    }

    return exp;

}

// When deprecating this, also remove the following lines:
// plugin-helps.js#L361: exclusions: exp.exclusions || '_id,dateCreated,dateModified,createdBy,modifiedBy',
const getInclusionsFromExclusions = deprecate(function (exportObj, model) {

    const exclusions = (exportObj.exclusions || '').split(',');
    const inclusions = [];

    model.schema.eachPath(function (pathname) {

        const exclude = ['__v'].concat(exclusions);

        if (exclude.includes(pathname)) {
            return;
        }

        inclusions.push(pathname);

    });

    return inclusions;

}, 'Export exclusions have been deprecated, use inclusions instead.');

module.exports = {

    get: function (req, res, next) {

        const getLabels = promisify(req.linz.model.getLabels);
        const getList = promisify(req.linz.model.getList, [req]);

        Promise.all([
            getLabels(),
            getList(),
        ])
            .then(([labels, list]) => {

                // attach our list object to the model
                req.linz.model.list = list;

                // retrieve the export object
                req.linz.export = getExport(list.export);
                req.linz.export.fields = {};

                const includedFields = req.linz.export.inclusions.length > 0 ? req.linz.export.inclusions.split(',') : getInclusionsFromExclusions(req.linz.export, req.linz.model);

                const fieldLabels = {};
                const includedPaths = Object
                    .keys(req.linz.model.schema.paths)
                    .filter((key) => includedFields.includes(key));

                includedPaths.forEach(function (field) {

                    if (!labels[field]) {
                        throw new Error(`Could not find ${field} field in the labels object.`);
                    }

                    // get a list of fields by the label ready for sorting
                    fieldLabels[labels[field]] = field;

                });

                // sort fields by label
                var sortedFieldsByLabel = Object.keys(fieldLabels).sort();

                // iterate through sorted label and re-constructs in the order of labels
                sortedFieldsByLabel.forEach(function (label) {
                    req.linz.export.fields[fieldLabels[label]] = label;
                });

                return next(null);

            })
            .catch(next);

    },

    post: function (req, res, next) {

        var Model = req.linz.model;
        const getForm = promisify(req.linz.model.getForm, [req]);
        const getLabels = promisify(req.linz.model.getLabels);
        const getList = promisify(req.linz.model.getList, [req]);

        return Promise.all([
            getForm(),
            getLabels(),
            getList(),
            linz.api.formtools.list.getFilters(req),
        ])
            .then(([form, labels, list, filters]) => {

                const exportObj = getExport(list.export);
                const includedFields = exportObj.inclusions.length > 0 ? exportObj.inclusions.split(',') : getInclusionsFromExclusions(exportObj, Model);
                const bodyFields = req.body.selectedFields.split(',');
                const refFieldNames = [];
                const fields = includedFields.filter((field) => bodyFields.includes(field))

                let filterFieldNames = [];

                fields.forEach(function (fieldName, index, arr) {

                    // check if there any ref fields selected to be exported
                    if(!Model.schema.tree[fieldName] || !Model.schema.tree[fieldName].ref) {
                        return;
                    }

                    return refFieldNames.push(fieldName);

                });

                // If _id is not included, exclude it from the export;
                if (!fields.includes('_id')) {
                    filterFieldNames.push('-_id');
                }

                filterFieldNames = filterFieldNames.concat(fields);

                // pipe data to response stream
                req.linz.model.getQuery(req, filters, function getQuery (err, query) {

                    if (err) {
                        return next(err);
                    }

                    req.linz.model.listQuery(req, query, (listQueryErr, listQuery) => {

                        if (listQueryErr) {
                            return next(listQueryErr);
                        }

                        const exportQuery = listQuery.select(filterFieldNames.join(' '));
                        const columnsFn = exportObj.columns || ((columns) => columns);
                        const formattedFields = fields
                            .map(fieldName => ({
                                header: labels[fieldName],
                                key: fieldName,
                            }));
                        const columns = columnsFn(formattedFields);

                        linz.api.util.generateExport({
                            columns,
                            contentType: 'text/csv',
                            name: `${Model.linz.formtools.model.plural}-${moment(Date.now()).format('l').replace(/\//g, '.', 'g')}`,
                            req,
                            res,
                            stream: exportQuery.lean().cursor(),
                            transform: (doc, callback) => {

                                const fields = Object.keys(doc);
                                const promises = [];

                                fields.forEach((fieldName) => {

                                    if (getTransposeFn(form, fieldName, 'export')) {

                                        return promises.push(getTransposeFn(form, fieldName, 'export')(doc[fieldName], doc)
                                            .then((result) => {

                                                const updatedDoc = doc;
                                                let val = result;
                                                let merge = false;

                                                if (Array.isArray(val)) {
                                                    [val, merge = false] = val;
                                                }

                                                if (!merge) {
                                                    return (doc[fieldName] = val);
                                                }

                                                return (doc = Object.assign({}, updatedDoc, val));

                                            }));

                                    }

                                    return promises.push(prettifyData(req, fieldName, doc[fieldName])
                                        .then((val) => (doc[fieldName] = val)));

                                });

                                Promise.all(promises)
                                    .then(() => callback(null, doc))
                                    .catch(callback);

                            },
                        });

                    });

                });

            })
            .catch(next);

    }
};
<|endoftext|>


<commit_before>import {describeWithWebdriver, describeWithoutTravisCI, visit} from './spec_helper';
import fs from 'fs';
import path from 'path';
import childProcess from 'child_process';

describe('gulp-jasmine-browser', function() {
  const gulpTimeout = 15000;

  let processes;

  beforeEach(function() {
    processes = [];
  });

  function gulp(task) {
    let resolveCompleted;
    const completed = new Promise(resolve => resolveCompleted = resolve);

    const gulpPath = path.resolve('node_modules', '.bin', 'gulp');
    const gulpFile = path.resolve(__dirname, 'fixtures', 'gulpfile.js');
    const process = childProcess.exec([gulpPath, '--gulpfile', gulpFile, task].join(' '),
      {timeout: gulpTimeout}, (error, stdout, stderr) => resolveCompleted({error, stdout, stderr}));

    const closed = new Promise(resolve => process.on('close', resolve));

    processes.push({process, closed});

    return {
      completed,
      process
    };
  }

  afterEach.async(async function() {
    (await Promise.all(processes)).filter(p => p.process).map(p => (p.process.kill(), p.closed));
  });

  it.async('can run tests via PhantomJS', async function() {
    const {error, stdout, stderr} = await gulp('phantomjs').completed;
    expect(error).toBeTruthy();
    expect(stderr).toBe('');
    expect(stdout).toContain('.F');
  });

  it.async('can run tests via SlimerJS', async function() {
    const {error, stdout, stderr} = await gulp('slimerjs').completed;
    expect(error).toBeTruthy();
    expect(stderr).toBe('');
    expect(stdout).toContain('.F');
  });

  it.async('can run tests via headless chrome', async () => {
    const {error, stdout, stderr} = await gulp('chrome').completed;
    expect(error).toBeTruthy();
    expect(stderr).toBe('');
    expect(stdout).toContain('.F');
  });

  describeWithoutTravisCI('when running in a browser', function() {
    describeWithWebdriver('when running with webdriver', () => {
      let page;
      it.async('allows running tests in a browser', async function() {
        gulp('server');
        page = (await visit('http://localhost:8888')).page;
        const text = await page.getText('.jasmine-bar.jasmine-failed');
        expect(text).toMatch('2 specs, 1 failure');
      });

      it.async('allows re-running tests in a browser', async function() {
        gulp('server');
        page = (await visit('http://localhost:8888')).page;
        const text = await page.url('http://localhost:8888').refresh().getText('.jasmine-bar.jasmine-failed');
        expect(text).toMatch('2 specs, 1 failure');
      });

      describe('when the file is mutated', function() {
        const oldSpec = 'it(\'makes a basic failing assertion\', function() { expect(true).toBe(false); });';
        const newSpec = 'it(\'makes a basic passing assertion\', function() { expect(true).toBe(true); });';
        let pathToMutableSpec;

        beforeEach(function() {
          pathToMutableSpec = path.resolve(__dirname, 'fixtures', 'mutable_spec.js');
        });

        afterEach(function(done) {
          fs.writeFile(pathToMutableSpec, oldSpec, done);
        });

        it.async('supports webpack with watch: true', async function() {
          const {process: gulpProcess} = gulp('webpack-server');
          page = (await visit('http://localhost:8888')).page;
          let text = await page.getText('.jasmine-bar.jasmine-failed');
          expect(text).toMatch('1 spec, 1 failure');
          function waitForWebpack() {
            return new Promise(resolve => {
              gulpProcess.stdout.on('data', chunk => chunk.match(/webpack is watching for changes/i) && resolve());
            });
          }
          fs.writeFileSync(pathToMutableSpec, newSpec);

          await waitForWebpack();
          text = await page.refresh().getText('.jasmine-bar.jasmine-passed');
          expect(text).toMatch('1 spec, 0 failures');
        });
      });
    });
  });
});
<commit_msg>Revert "re-enable headless specs in travis"<commit_after>import {describeWithWebdriver, describeWithoutTravisCI, visit} from './spec_helper';
import fs from 'fs';
import path from 'path';
import childProcess from 'child_process';

describe('gulp-jasmine-browser', function() {
  const gulpTimeout = 15000;

  let processes;

  beforeEach(function() {
    processes = [];
  });

  function gulp(task) {
    let resolveCompleted;
    const completed = new Promise(resolve => resolveCompleted = resolve);

    const gulpPath = path.resolve('node_modules', '.bin', 'gulp');
    const gulpFile = path.resolve(__dirname, 'fixtures', 'gulpfile.js');
    const process = childProcess.exec([gulpPath, '--gulpfile', gulpFile, task].join(' '),
      {timeout: gulpTimeout}, (error, stdout, stderr) => resolveCompleted({error, stdout, stderr}));

    const closed = new Promise(resolve => process.on('close', resolve));

    processes.push({process, closed});

    return {
      completed,
      process
    };
  }

  afterEach.async(async function() {
    (await Promise.all(processes)).filter(p => p.process).map(p => (p.process.kill(), p.closed));
  });

  describeWithoutTravisCI('when running a headless browser', () => {
    it.async('can run tests via PhantomJS', async function() {
      const {error, stdout, stderr} = await gulp('phantomjs').completed;
      expect(error).toBeTruthy();
      expect(stderr).toBe('');
      expect(stdout).toContain('.F');
    });

    it.async('can run tests via SlimerJS', async function() {
      const {error, stdout, stderr} = await gulp('slimerjs').completed;
      expect(error).toBeTruthy();
      expect(stderr).toBe('');
      expect(stdout).toContain('.F');
    });

    it.async('can run tests via headless chrome', async () => {
      const {error, stdout, stderr} = await gulp('chrome').completed;
      expect(error).toBeTruthy();
      expect(stderr).toBe('');
      expect(stdout).toContain('.F');
    });
  });

  describeWithoutTravisCI('when running in a browser', function() {
    describeWithWebdriver('when running with webdriver', () => {
      let page;
      it.async('allows running tests in a browser', async function() {
        gulp('server');
        page = (await visit('http://localhost:8888')).page;
        const text = await page.getText('.jasmine-bar.jasmine-failed');
        expect(text).toMatch('2 specs, 1 failure');
      });

      it.async('allows re-running tests in a browser', async function() {
        gulp('server');
        page = (await visit('http://localhost:8888')).page;
        const text = await page.url('http://localhost:8888').refresh().getText('.jasmine-bar.jasmine-failed');
        expect(text).toMatch('2 specs, 1 failure');
      });

      describe('when the file is mutated', function() {
        const oldSpec = 'it(\'makes a basic failing assertion\', function() { expect(true).toBe(false); });';
        const newSpec = 'it(\'makes a basic passing assertion\', function() { expect(true).toBe(true); });';
        let pathToMutableSpec;

        beforeEach(function() {
          pathToMutableSpec = path.resolve(__dirname, 'fixtures', 'mutable_spec.js');
        });

        afterEach(function(done) {
          fs.writeFile(pathToMutableSpec, oldSpec, done);
        });

        it.async('supports webpack with watch: true', async function() {
          const {process: gulpProcess} = gulp('webpack-server');
          page = (await visit('http://localhost:8888')).page;
          let text = await page.getText('.jasmine-bar.jasmine-failed');
          expect(text).toMatch('1 spec, 1 failure');
          function waitForWebpack() {
            return new Promise(resolve => {
              gulpProcess.stdout.on('data', chunk => chunk.match(/webpack is watching for changes/i) && resolve());
            });
          }
          fs.writeFileSync(pathToMutableSpec, newSpec);

          await waitForWebpack();
          text = await page.refresh().getText('.jasmine-bar.jasmine-passed');
          expect(text).toMatch('1 spec, 0 failures');
        });
      });
    });
  });
});
<|endoftext|>


<commit_before>/*
Copyright (c) 2011, Rob Ellis, Chris Umbel

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
*/

var TfIdf = require('../lib/natural/tfidf/tfidf');
var tfidf;

describe('tfidf', function() {
    describe('stateless operations', function() {
        it('should tf', function() {
            expect(TfIdf.tf('document', { document : 2, one : 1 })).toBe(2);
            expect(TfIdf.tf('document', { greetings : 1, program : 1 })).toBe(0);
            expect(TfIdf.tf('program', { greetings : 1, program : 1 })).toBe(1);
        });
    });

    describe('keys', function() {
        it('should store and recall keys', function() {
            tfidf = new TfIdf();
            tfidf.addDocument('document one', 'un');
	        tfidf.addDocument('document Two', 'deux');

            tfidf.tfidfs('two', function(i, tfidf, key) {
                if(i == 0)
                    expect(key).toBe('un');
                else
                    expect(key).toBe('deux');
            });
        });
    });

    describe('stateful operations', function() {
        beforeEach(function() {
            tfidf = new TfIdf();
            tfidf.addDocument('document one');
            tfidf.addDocument('document Two');
        });

	it('should list important terms', function() {
        var terms = tfidf.listTerms(0);
        expect(terms[0].tfidf).toBeGreaterThan(terms[1].tfidf);
	});
    });

    describe("correct calculations", function(){

        it("should compute idf correctly", function(){

            tfidf = new TfIdf();
            tfidf.addDocument('this document is about node.');
            tfidf.addDocument('this document is about ruby.');
            tfidf.addDocument('this document is about ruby and node.');
            tfidf.addDocument('this document is about node. it has node examples');

            expect(tfidf.idf("node")).toBe(Math.log( 4.0 / 3.0 ));
        });

        it("should compute tf correctly", function(){
            expect(TfIdf.tf("node", {this:1, document:1, is:1, about:1, node:1})).toBe(1);
            expect(TfIdf.tf("node", {this:1, document:1, is:1, about:1, ruby:1})).toBe(0);
            expect(TfIdf.tf("node", {this:1, document:1, is:1, about:1, ruby:1, and:1, node:1})).toBe(1);
            expect(TfIdf.tf("node", {this:1, document:1, is:1, about:1, node:2, it:1, has:1, examples:1})).toBe(2);
        });

        // This is a test of the use case outlined in the readme.
        it("should compute tf-idf correctly", function(){

            var correctCalculations = [
                1 * Math.log( 4.0 / 3.0 ),
                0,
                2 * Math.log( 4.0 / 3.0 ),
                1 * Math.log( 4.0 / 2.0 )
            ];

            tfidf = new TfIdf();
            tfidf.addDocument('this document is about node.', {node: 0, ruby:1});
            tfidf.addDocument('this document is about ruby.', {node:1, ruby:3});
            tfidf.addDocument('this document is about ruby and node.', {node:0, ruby:3});
            tfidf.addDocument('this document is about node. it has node examples', {node:2, ruby:1});

            tfidf.tfidfs('node', function(i, measure, k) {
                expect(measure).toBe(correctCalculations[k.node])
            });

            tfidf.tfidfs('ruby', function(i, measure, k) {
                expect(measure).toBe(correctCalculations[k.ruby])
            });

        });

    });
});
<commit_msg>working on fixing unit test<commit_after>/*
Copyright (c) 2011, Rob Ellis, Chris Umbel

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
*/

var TfIdf = require('../lib/natural/tfidf/tfidf');
var tfidf;

describe('tfidf', function() {
    describe('stateless operations', function() {
        it('should tf', function() {
            expect(TfIdf.tf('document', { document : 2, one : 1 })).toBe(2);
            expect(TfIdf.tf('document', { greetings : 1, program : 1 })).toBe(0);
            expect(TfIdf.tf('program', { greetings : 1, program : 1 })).toBe(1);
        });
    });

    describe('keys', function() {
        it('should store and recall keys', function() {
            tfidf = new TfIdf();
            tfidf.addDocument('document one', 'un');
	        tfidf.addDocument('document Two', 'deux');

            tfidf.tfidfs('two', function(i, tfidf, key) {
                if(i == 0)
                    expect(key).toBe('un');
                else
                    expect(key).toBe('deux');
            });
        });
    });

    describe('stateful operations', function() {
        beforeEach(function() {
            tfidf = new TfIdf();
            tfidf.addDocument('document one');
            tfidf.addDocument('document Two');
        });

	it('should list important terms', function() {
        var terms = tfidf.listTerms(0);
        expect(terms[0].tfidf).toBeGreaterThan(terms[1].tfidf);
	});
    });

    describe("correct calculations", function(){

        it("should compute idf correctly", function(){

            tfidf = new TfIdf();
            tfidf.addDocument('this document is about node.');
            tfidf.addDocument('this document is about ruby.');
            tfidf.addDocument('this document is about ruby and node.');
            tfidf.addDocument('this document is about node. it has node examples');

            expect(tfidf.idf("node")).toBe(Math.log( 4.0 / 3.0 ));
        });

        it("should compute tf correctly", function(){
            expect(TfIdf.tf("node", {this:1, document:1, is:1, about:1, node:1})).toBe(1);
            expect(TfIdf.tf("node", {this:1, document:1, is:1, about:1, ruby:1})).toBe(0);
            expect(TfIdf.tf("node", {this:1, document:1, is:1, about:1, ruby:1, and:1, node:1})).toBe(1);
            expect(TfIdf.tf("node", {this:1, document:1, is:1, about:1, node:2, it:1, has:1, examples:1})).toBe(2);
        });

        // This is a test of the use case outlined in the readme.
        it("should compute tf-idf correctly", function(){

            var correctCalculations = [
                1 * Math.log( 4.0 / 3.0 ),
                0,
                2 * Math.log( 4.0 / 3.0 ),
                1 * Math.log( 4.0 / 2.0 )
            ];

            tfidf = new TfIdf();
            tfidf.addDocument('this document is about node.', {node: 0, ruby:1});
            tfidf.addDocument('this document is about ruby.', {node:1, ruby:3});
            tfidf.addDocument('this document is about ruby and node.', {node:0, ruby:3});
            tfidf.addDocument('this document is about node. it has node examples', {node:2, ruby:1});

            tfidf.tfidfs('node', function(i, measure, k) {
                expect(measure).toBe(correctCalculations[k.node])
            });

            tfidf.tfidfs('ruby', function(i, measure, k) {
                expect(measure).toBe(correctCalculations[k.ruby])
            });

        });

        // This test assures that tf-idf is computed correctly before and after a document is added
        // Computes and tests a few tf-idfs, then adds a document and ensures that those terms tf-idf value
        // is updated accordingly.
        it("should update a terms tf-idf score after adding documents", function(){

            tfidf = new TfIdf();

            // Add 2 documents
            tfidf.addDocument('this document is about node.');
            tfidf.addDocument('this document is about ruby.');

            // check the tf-idf for 'node'
            expect(tfidf.tfidf(
                'node',
                {this:1, document:1, is:1, about:1, node:1})
            ).toBe( 1 * Math.log( 2.0 / 1.0 ) );

            // Add 2 more documents
            tfidf.addDocument('this document is about ruby and node.');
            tfidf.addDocument('this document is about node. it has node examples');

            // check that the tf-idf for 'node' has changed for the same document, and is correct.
            expect(tfidf.tfidf(
                'node',
                {this:1, document:1, is:1, about:1, node:1})
            ).toBe( 1 * Math.log( 4.0 / 3.0 ) );
        });

    });
});
<|endoftext|>