<commit_before>var assert = require('assert');
var should = require('should');
var fs = require('fs');
var mosto = require('../mosto');
var melted = require('melted-node');
var _ = require('underscore');
var seed = require('seed-random');
var mbc = require('mbc-common');
var Media = require('mbc-common/models/Media');
var Q = require('q');

_.mixin({
    shuffleSeed: function(list, s) {
        seed(s, true);
        var ret = _.shuffle(list);
        seed(undefined, true);
    },
    randint: function(x, y, s) {
        var from = 0;
        var to = 0;
        if( y === undefined )
            to = x;
        else {
            from = x;
            to = y;
        }
        var width = to - from;
        return (parseInt(seed(s)() * width) + from)
    },
    randelem: function(list) {
        return list[_.randint(list.length)];
    },
    draw: function(list, n) {
        var ret = [];
        for(var i = 0 ; i < n ; i++) {
            ret.push(_.randelem(list));
        }
        return ret;
    },
});

describe.only("Mosto functional test", function() {
    /*
     * arrancar sin playlists
     ** ver negro
     */
    this.timeout(5000);
    var self = this;
    // use a random seed
    self.start_seed = seed()();
    self.rand = seed(self.start_seed);

    self.create_playlist = function(medias) {
        var mediamodels = [];
        medias.forEach(function(media) {
            mediamodels.push( Media.Piece(media) );
        });
        return Media.List({
            collection: mediamodels,
        });
    };

    self.setup_playlists = function(start_time) {
        /*
         * sets up playlists to be consecutive starting from start_time
         * and annotates the medias to keep track of start and end times
         *
         * returns a promise
         */
        var timewalk = moment(start_time);
        self.occurrences = [];
        var defer = Q.defer();
        var done = _.after(self.playlists.length, defer.resolve);
        var occcol = self.db.collection('scheds');
        var listcol = self.db.collection('lists');
        for( var i = 0 ; i < self.playlists.length ; i++ ) {
            var playlist = self.playlists[i];
            var occurrence = {
                start: timewalk.unix(),
            };
            for( var j = 0 ; j < playlist.medias.length ; j++ ) {
                var media = playlist.medias[j];
                media.start_time = timewalk.valueOf();
                timewalk.add(playlist.medias[j].length);
                media.end_time = timewalk.valueOf();
            }
            occurrence.end = timewalk.unix();
            listcol.insert(playlist, function(err, obj) {
                obj = obj[0];
                occurrence = Media.Ocurrence({
                    list: obj._id,
                    start: occurrence.start,
                    end: occurrence.end
                });
                occcol.insert(occurrence, function(err, obj) {
                    self.occurrences.push(obj[0]);
                    done();
                });
            });
        }
        return defer.promise;
    };

    self.get_playlist = function(time) {
        return _.find(self.playlists, function(pl) {
            return pl.start <= time.unix() && pl.end >= time.unix();
        });
    };

    self.get_media = function(time) {
        var playlist = self.get_playlist(time);

        return _.find(playlist.medias, function(me) {
            return me.start_time <= time && me.end_time >= time;
        });
    };

    self.publisher = mbc.pubsub();
    self.listener = mbc.pubsub();
    self.db = mbc.db();

    before(function() {
        self.melted = melted();
    });
    after(function() {
        delete self.melted;
    });
    describe('start without playlists', function() {
        before(function(done) {
            self.mosto = new mosto();
            self.mosto.once('playing', function() {
                done()});
            self.mosto.init();
        });
        after(function(done) {
            self.mosto.finish(function() {
                delete self.mosto;
                done();
            });
        });
        it('should show black', function(done) {
            var promise = self.melted.sendPromisedCommand('USTA U0', '202 OK');
            promise.then(function(result) {
                console.log(result);
                result = result.split('\r\n')[1].split(' ');
                var file = result[2];
                file.should.include('black_id');
            }).then(done, done);
        });
    });
    /*
     * arrancar con playlists
     ** ver que haya el play correspondiente
     ** ver que este en el frame correcto
     */
    describe('start with playlists', function() {
        self.playlist_count = _.randint(5, 10, self.rand());
        before(function() {
            // I assume all non-hidden files are videos
            self.medias = _.reject(fs.readdirSync('./test/videos'), function(el){ return el[0] == '.' });
            // self.medias = parseXMLs(self.medias);
            self.medias = [];
            self.playlists = [];
            for(var i = 0 ; i < self.playlist_count ; i++) {
                var playlist_length = _.randint(1, 10, self.rand());
                self.playlists.push(self.create_playlist(
                    _.draw(self.medias, playlist_length)));
            }
        });
        describe('starting now', function() {
            before(function(done) {
                self.db.dropDatabase(function(err, success) {
                    // let playlists start somewhere between now and 30
                    //  seconds ago
                    var setup = self.setup_playlists(moment(
                        moment() + _.randint(0, -30000)));
                    setup.then(function() {
                        self.mosto = new mosto();
                        self.mosto.once('playing', function() {
                            // send pubsub messages with new playlists
                            done();
                        });
                        self.mosto.init();
                    });
                });
            });
            after(function(done) {
                self.mosto.finish(function() {
                    delete self.mosto;
                    done();
                });
            });
            it('should start the right clip');
            it('should start on the right frame');
            /*
            ** borrar la playlist
            *** ver que no se rompa nada
            *** ver que se este pasando negro
            */
            describe('delete currently playing playlist', function() {
                it('should not break');
                it('should be playing blank clip');
            });
        });
        /*
         * arrancar un playlist empezado hace 5m
         */
        describe('starting 5m ago', function() {
            /*
            ** ver que el frame se mantenga sincronizado durante 10 segundos
            */
            it("should keep sync'ed for at least 10 secs");
            /*
            ** mover la playlist hacia atras 1m
            *** ver que el frame se sincronice correctamente
            */
            describe('move playlist back', function() {
                it("should stay sync'ed");
            });
            /*
            ** mover la playlist hacia adelante 2m
            *** ver que el frame se sincronice correctamente
            */
            describe('move playlist forward', function() {
                it("should stay sync'ed");
            });
        });
    });
    /*
     * pruebas de timespan
     */
    describe('timespan tests', function() {
        /*
        ** levantar mosto con una ventana de 1m de ancho
        ** que haya una playlist de 2m empezando now
        ** que haya otra playlist de 30s empezando t+2m
        ** que haya otra playlist de 30s empezando en t+2m30s
        ** al start chequear que solo este la 1er playlist
        ** al 1m05 chequear que la 2da playlist este cargada
        */
        describe("start mosto with a 2m timeSpan", function() {
            it('should have a 2m timeSpan');
            describe('playlists longer than timespan', function() {
                describe('start with these [playlists:[clips]]: [3m:[1m, 1m, 1m], 1m:[30s, 30s], 1m:[1m]]', function() {
                    it('should start with a 3m playlist starting now');
                    it('should start with a playlist 1m long starting in t+3m');
                    it('should start with a playlist 1m long starting in t+4m');
                    describe('at startup', function() {
                        it('should load only the first playlist at start');
                    });
                    describe('after 1m05s', function() {
                        it('should have loaded the 2nd playlist');
                    });
                });
            });
            describe('clips longer than timespan', function() {
                describe('start with these [playlists:[clips]]: [3m:[3m], 1m[30s, 30s], 1m:[1m]]', function() {
                    it('should preload at least one clip');
                });
            });
        });
    });
    /*
     * idem anterior con una playlist de un solo clip
     ** si tengo un clip (playlist?) mas largo que la ventana, deberia haber n+1 cargados
     */
    describe("modify melted test", function() {
        it("should rectify things");
    });
});
<commit_msg>remove playlists from database after we're done<commit_after>var assert = require('assert');
var should = require('should');
var fs = require('fs');
var mosto = require('../mosto');
var melted = require('melted-node');
var _ = require('underscore');
var seed = require('seed-random');
var mbc = require('mbc-common');
var Media = require('mbc-common/models/Media');
var Q = require('q');

_.mixin({
    shuffleSeed: function(list, s) {
        seed(s, true);
        var ret = _.shuffle(list);
        seed(undefined, true);
    },
    randint: function(x, y, s) {
        var from = 0;
        var to = 0;
        if( y === undefined )
            to = x;
        else {
            from = x;
            to = y;
        }
        var width = to - from;
        return (parseInt(seed(s)() * width) + from)
    },
    randelem: function(list) {
        return list[_.randint(list.length)];
    },
    draw: function(list, n) {
        var ret = [];
        for(var i = 0 ; i < n ; i++) {
            ret.push(_.randelem(list));
        }
        return ret;
    },
});

describe.only("Mosto functional test", function() {
    /*
     * arrancar sin playlists
     ** ver negro
     */
    this.timeout(5000);
    var self = this;
    // use a random seed
    self.start_seed = seed()();
    self.rand = seed(self.start_seed);

    self.create_playlist = function(medias) {
        var mediamodels = [];
        medias.forEach(function(media) {
            mediamodels.push( Media.Piece(media) );
        });
        return Media.List({
            collection: mediamodels,
        });
    };

    self.setup_playlists = function(start_time) {
        /*
         * sets up playlists to be consecutive starting from start_time
         * and annotates the medias to keep track of start and end times
         *
         * returns a promise
         */
        var timewalk = moment(start_time);
        self.occurrences = [];
        var defer = Q.defer();
        var done = _.after(self.playlists.length, defer.resolve);
        var occcol = self.db.collection('scheds');
        var listcol = self.db.collection('lists');
        for( var i = 0 ; i < self.playlists.length ; i++ ) {
            var playlist = self.playlists[i];
            var occurrence = {
                start: timewalk.unix(),
            };
            for( var j = 0 ; j < playlist.medias.length ; j++ ) {
                var media = playlist.medias[j];
                media.start_time = timewalk.valueOf();
                timewalk.add(playlist.medias[j].length);
                media.end_time = timewalk.valueOf();
            }
            occurrence.end = timewalk.unix();
            listcol.insert(playlist, function(err, obj) {
                obj = obj[0];
                occurrence = Media.Ocurrence({
                    list: obj._id,
                    start: occurrence.start,
                    end: occurrence.end
                });
                occcol.insert(occurrence, function(err, obj) {
                    self.occurrences.push(obj[0]);
                    done();
                });
            });
        }
        return defer.promise;
    };
    self.clean_playlists = function(done) {
        // Cleans the playlists and occurrences from the database
        var ready = _.after(2, function(){ done(); });
        self.db.collection('scheds').drop(ready);
        self.db.collection('lists').drop(ready);
    }

    self.get_playlist = function(time) {
        return _.find(self.playlists, function(pl) {
            return pl.start <= time.unix() && pl.end >= time.unix();
        });
    };

    self.get_media = function(time) {
        var playlist = self.get_playlist(time);

        return _.find(playlist.medias, function(me) {
            return me.start_time <= time && me.end_time >= time;
        });
    };

    self.publisher = mbc.pubsub();
    self.listener = mbc.pubsub();
    self.db = mbc.db();

    before(function() {
        self.melted = melted();
    });
    after(function() {
        delete self.melted;
    });
    describe('start without playlists', function() {
        before(function(done) {
            self.mosto = new mosto();
            self.mosto.once('playing', function() {
                done()});
            self.mosto.init();
        });
        after(function(done) {
            self.mosto.finish(function() {
                delete self.mosto;
                done();
            });
        });
        it('should show black', function(done) {
            var promise = self.melted.sendPromisedCommand('USTA U0', '202 OK');
            promise.then(function(result) {
                console.log(result);
                result = result.split('\r\n')[1].split(' ');
                var file = result[2];
                file.should.include('black_id');
            }).then(done, done);
        });
    });
    /*
     * arrancar con playlists
     ** ver que haya el play correspondiente
     ** ver que este en el frame correcto
     */
    describe('start with playlists', function() {
        self.playlist_count = _.randint(5, 10, self.rand());
        before(function() {
            // I assume all non-hidden files are videos
            self.medias = _.reject(fs.readdirSync('./test/videos'), function(el){ return el[0] == '.' });
            // self.medias = parseXMLs(self.medias);
            self.medias = [];
            self.playlists = [];
            for(var i = 0 ; i < self.playlist_count ; i++) {
                var playlist_length = _.randint(1, 10, self.rand());
                self.playlists.push(self.create_playlist(
                    _.draw(self.medias, playlist_length)));
            }
        });
        describe('starting now', function() {
            before(function(done) {
                self.db.dropDatabase(function(err, success) {
                    // let playlists start somewhere between now and 30
                    //  seconds ago
                    var setup = self.setup_playlists(moment(
                        moment() + _.randint(0, -30000)));
                    setup.then(function() {
                        self.mosto = new mosto();
                        self.mosto.once('playing', function() {
                            // send pubsub messages with new playlists
                            done();
                        });
                        self.mosto.init();
                    });
                });
            });
            after(function(done) {
                self.mosto.finish(function() {
                    delete self.mosto;
                    self.clean_playlists(done);
                });
            });
            it('should start the right clip');
            it('should start on the right frame');
            /*
            ** borrar la playlist
            *** ver que no se rompa nada
            *** ver que se este pasando negro
            */
            describe('delete currently playing playlist', function() {
                it('should not break');
                it('should be playing blank clip');
            });
        });
        /*
         * arrancar un playlist empezado hace 5m
         */
        describe('starting 5m ago', function() {
            /*
            ** ver que el frame se mantenga sincronizado durante 10 segundos
            */
            it("should keep sync'ed for at least 10 secs");
            /*
            ** mover la playlist hacia atras 1m
            *** ver que el frame se sincronice correctamente
            */
            describe('move playlist back', function() {
                it("should stay sync'ed");
            });
            /*
            ** mover la playlist hacia adelante 2m
            *** ver que el frame se sincronice correctamente
            */
            describe('move playlist forward', function() {
                it("should stay sync'ed");
            });
        });
    });
    /*
     * pruebas de timespan
     */
    describe('timespan tests', function() {
        /*
        ** levantar mosto con una ventana de 1m de ancho
        ** que haya una playlist de 2m empezando now
        ** que haya otra playlist de 30s empezando t+2m
        ** que haya otra playlist de 30s empezando en t+2m30s
        ** al start chequear que solo este la 1er playlist
        ** al 1m05 chequear que la 2da playlist este cargada
        */
        describe("start mosto with a 2m timeSpan", function() {
            it('should have a 2m timeSpan');
            describe('playlists longer than timespan', function() {
                describe('start with these [playlists:[clips]]: [3m:[1m, 1m, 1m], 1m:[30s, 30s], 1m:[1m]]', function() {
                    it('should start with a 3m playlist starting now');
                    it('should start with a playlist 1m long starting in t+3m');
                    it('should start with a playlist 1m long starting in t+4m');
                    describe('at startup', function() {
                        it('should load only the first playlist at start');
                    });
                    describe('after 1m05s', function() {
                        it('should have loaded the 2nd playlist');
                    });
                });
            });
            describe('clips longer than timespan', function() {
                describe('start with these [playlists:[clips]]: [3m:[3m], 1m[30s, 30s], 1m:[1m]]', function() {
                    it('should preload at least one clip');
                });
            });
        });
    });
    /*
     * idem anterior con una playlist de un solo clip
     ** si tengo un clip (playlist?) mas largo que la ventana, deberia haber n+1 cargados
     */
    describe("modify melted test", function() {
        it("should rectify things");
    });
});
<|endoftext|>


<commit_before>// Load in modules
var fs = require('fs'),
    path = require('path'),
    exec = require('child_process').exec,
    assert = require('assert'),
    async = require('async'),
    stylus = require('stylus'),
    TempFile = require('temporary/lib/file');

// Clean up actual_files/
var actualDir = __dirname + '/actual_files/',
    expectedDir = __dirname + '/expected_files/';
try { fs.unlinkSync(actualDir); } catch (e) {}

// DEV: Warn myself if we are loading from offline
var gruntFontsmithSrc = fs.readFileSync(__dirname + '/../tasks/grunt-fontsmith.js', 'utf8');
if (!gruntFontsmithSrc.match(/\s+\/\/[^\n]*=[^\n]*tmp.json/)) {
  console.error('WARNING!!!');
  console.error('YOU ARE WORKING ON AN OFFLINE VERSION!!!');
}

// Load in common expected CSS
var expectedCssObj = {
      eot: fs.readFileSync(__dirname + '/test_files/font.eot.css', 'utf8'),
      svg: fs.readFileSync(__dirname + '/test_files/font.svg.css', 'utf8'),
      ttf: fs.readFileSync(__dirname + '/test_files/font.ttf.css', 'utf8'),
      woff: fs.readFileSync(__dirname + '/test_files/font.woff.css', 'utf8')
    };

// Prepare common stylus for font testing
var charStyl = [
  '.icon-eye',
  '  icon($eye)',
  '.icon-building_block',
  '  icon($building_block)',
  '.icon-moon',
  '  icon($moon)'
].join('\n');

// Expose our test commands
module.exports = {
  // Fixture setups
  'A set of SVGs': function () {},
  'processed into a single font and stylesheet': [function () {
    this.task = 'single';
    this.cssFiles = ['single/font.styl'];
    this.fontFiles = [{
      path: 'single/font.svg',
      format: 'svg'
    }];
  }, 'processed via grunt-fontsmith'],

  'processed into multiple fonts and stylesheets': [function () {
    this.task = 'multiple';
    this.cssFiles = ['multiple/font.styl', 'multiple/font.json'];
    this.fontFiles = [{
      path: 'multiple/font.svg',
      format: 'svg'
    }, {
      path: 'multiple/font.ttf',
      format: 'ttf'
    }, {
      path: 'multiple/font.eot',
      format: 'eot'
    }, {
      path: 'multiple/font.woff',
      format: 'woff'
    }];
  }, 'processed via grunt-fontsmith'],

  'processed into overridden fonts and stylesheets': [function () {
    this.task = 'overrides';
    this.cssFiles = ['overrides/jason.less', 'overrides/styleee.json'];
    this.fontFiles = [{
      path: 'overrides/waffles.ttf',
      format: 'woff'
    }, {
      path: 'overrides/eof.svg',
      format: 'eot'
    }];
  }, 'processed via grunt-fontsmith'],

  'processed via grunt-fontsmith': function (done) {
    // Bump the timeout for fontsmith
    this.timeout(60000);

    // Relocate to test directory
    process.chdir(__dirname);

    // Execute the cmd and task combination
    var that = this;
    console.log('wat');
    exec('grunt font:' + this.task, function (err, stdout, stderr) {
      // If there was an error, show me the output
      if (err) {
        console.log(stdout, stderr);
      }

      // Fallback error
      if (stderr) {
        err = new Error(stderr);
      }

      // Save results for later
      that.stdout = stdout;
      console.log('hai');

      // Callback
      done(err);
    });

  },

  // CSS assertions
  'produces a stylesheet': 'produces stylesheets',
  'produces multiple stylesheets': 'produces stylesheets',
  'produces stylesheets with proper formats': 'produces stylesheets',
  'produces stylesheets': function () {
    // Assert each of the CSS files exist
    this.cssFiles.forEach(function (filename) {
      // Grab the expected and actual content
      var expectedContent = fs.readFileSync(expectedDir + filename, 'utf8'),
          actualContent = fs.readFileSync(actualDir + filename, 'utf8');

      // Break down the content into separate lines
      var expectedLines = expectedContent.split('\n'),
          actualLines = actualContent.split('\n');

      // Determine how many lines are different
      var differentLines = expectedLines.filter(function (line) {
            return actualLines.indexOf(line) === -1;
          });

      // Assert that only the character lines are different
      // TODO: If we ever have more than 3 sprites, update
      // the tests to be explicit about how many characters are being used
      assert(differentLines.length <= 3);
    });
  },

  // Font assertions
  'produces a font': 'produces fonts',
  'produces multiple fonts': 'produces fonts',
  'produces fonts with proper formats': 'produces fonts',
  'produces fonts': function (done) {
    // DEV: This is an ugly monstrosity which renders and compares every generated font
    // Load in Stylus
    var styl = fs.readFileSync(expectedDir + '/multiple/font.styl', 'utf8');

    // Iterate over the fontFiles
    var fontFiles = this.fontFiles;
    async.forEach(fontFiles, function compareFontFile (fontFile, cb) {
      // Remove unused font formats
      var fontFormat = fontFile.format,
          actualStyl = styl;
      if (fontFormat !== 'eot') {
        actualStyl = actualStyl.replace(/\s+src:url\("font.eot"\);/, '');
        actualStyl = actualStyl.replace(/\s*url\("font.eot\?#iefix"\) format\("embedded-opentype"\),\s*/, '');
      }
      if (fontFormat !== 'woff') {
        actualStyl = actualStyl.replace(/\s*url\("font.woff"\) format\("woff"\),\s*/, '');
      }
      if (fontFormat !== 'ttf') {
        actualStyl = actualStyl.replace(/\s*url\("font.ttf"\) format\("truetype"\),\s*/, '');
      }
      if (fontFormat !== 'svg') {
        // Guarantee no-commas for font formats
        actualStyl = actualStyl.replace(',', ';');
        actualStyl = actualStyl.replace(/\s*url\("font.svg#icomoon"\) format\("svg"\);\s*/, '');
      }

      // If the fontFormat is `eot`, skip this assertion as it can only be done by IE
      if (fontFormat === 'eot') {
        return cb();
      }

      // Replace font path with our font path
      var filepath = fontFile.path,
          fontname = 'font.' + fontFormat,
          expectedCss = expectedCssObj[fontFormat];
      actualStyl = actualStyl.replace(fontname, actualDir + filepath);
      expectedCss = expectedCss.replace(fontname, expectedDir + filepath);

      // Assert our replacements were successful
      assert.notEqual(actualStyl.indexOf(actualDir), -1, 'Actual stylus has not replaced "' + fontname + '" with "' + actualDir + filepath + '" successfully');
      assert.notEqual(expectedCss.indexOf(expectedDir), -1, 'Expected css has not replaced "' + fontname + '" with "' + expectedDir + filepath + '" successfully');

      function saveToFile(content, cb) {
        // DEV: PhantomJS may require a .css extension for proper mime-types and whatnot
        // Save css to a temporary file
        var tmpFile = new TempFile();
        tmpFile.writeFileSync(content, 'utf8');

        // Save a reference to the file path
        cb(null, tmpFile.path);
      }

      function screenshotFont(options, cssPath, cb) {
        // Screenshot the font in use
        console.log(cssPath);
        exec('phantomjs test_scripts/screenshot_font.js ' + cssPath, function (err, stdout, stderr) {
          // Fallback error with stderr
          if (!err && stderr) {
            err = new Error(stderr);
          }

          // If there was stdout, log it
          if (stdout) {
            console.log('SCREENSHOT FONT STDOUT: ', stdout);
          }

          // Always create screenshots for debugging
          fs.writeFileSync('tmp.' + options.context + '.' + fontFormat + '.png', stdout, 'base64');

          // Callback with our error and font
          cb(err, stdout);
        });
      }

      // In parallel, screenshot the expected and actual font
      async.parallel([
        function renderActualFont (cb) {
          async.waterfall([
            stylus.render.bind(this, actualStyl + '\n' + charStyl),
            saveToFile,
            screenshotFont.bind(this, {context: 'actual'})
          ], cb);
        },
        function renderExpectedFont (cb) {
          async.waterfall([
            saveToFile.bind(this, expectedCss),
            screenshotFont.bind(this, {context: 'expected'})
          ], cb);
        }
      ], function compareFonts (err, fonts) {
        // If there is an error, callback with it
        if (err) { return cb(err); }

        // Otherwise, assert the fonts are equal and callback
        assert.strictEqual(fonts[0], fonts[1]);
        cb();
      });
    }, done);

  }
};
<commit_msg>Moving back the comma shows why the tests were previously passing -_-;;<commit_after>// Load in modules
var fs = require('fs'),
    path = require('path'),
    exec = require('child_process').exec,
    assert = require('assert'),
    async = require('async'),
    stylus = require('stylus'),
    TempFile = require('temporary/lib/file');

// Clean up actual_files/
var actualDir = __dirname + '/actual_files/',
    expectedDir = __dirname + '/expected_files/';
try { fs.unlinkSync(actualDir); } catch (e) {}

// DEV: Warn myself if we are loading from offline
var gruntFontsmithSrc = fs.readFileSync(__dirname + '/../tasks/grunt-fontsmith.js', 'utf8');
if (!gruntFontsmithSrc.match(/\s+\/\/[^\n]*=[^\n]*tmp.json/)) {
  console.error('WARNING!!!');
  console.error('YOU ARE WORKING ON AN OFFLINE VERSION!!!');
}

// Load in common expected CSS
var expectedCssObj = {
      eot: fs.readFileSync(__dirname + '/test_files/font.eot.css', 'utf8'),
      svg: fs.readFileSync(__dirname + '/test_files/font.svg.css', 'utf8'),
      ttf: fs.readFileSync(__dirname + '/test_files/font.ttf.css', 'utf8'),
      woff: fs.readFileSync(__dirname + '/test_files/font.woff.css', 'utf8')
    };

// Prepare common stylus for font testing
var charStyl = [
  '.icon-eye',
  '  icon($eye)',
  '.icon-building_block',
  '  icon($building_block)',
  '.icon-moon',
  '  icon($moon)'
].join('\n');

// Expose our test commands
module.exports = {
  // Fixture setups
  'A set of SVGs': function () {},
  'processed into a single font and stylesheet': [function () {
    this.task = 'single';
    this.cssFiles = ['single/font.styl'];
    this.fontFiles = [{
      path: 'single/font.svg',
      format: 'svg'
    }];
  }, 'processed via grunt-fontsmith'],

  'processed into multiple fonts and stylesheets': [function () {
    this.task = 'multiple';
    this.cssFiles = ['multiple/font.styl', 'multiple/font.json'];
    this.fontFiles = [{
      path: 'multiple/font.svg',
      format: 'svg'
    }, {
      path: 'multiple/font.ttf',
      format: 'ttf'
    }, {
      path: 'multiple/font.eot',
      format: 'eot'
    }, {
      path: 'multiple/font.woff',
      format: 'woff'
    }];
  }, 'processed via grunt-fontsmith'],

  'processed into overridden fonts and stylesheets': [function () {
    this.task = 'overrides';
    this.cssFiles = ['overrides/jason.less', 'overrides/styleee.json'];
    this.fontFiles = [{
      path: 'overrides/waffles.ttf',
      format: 'woff'
    }, {
      path: 'overrides/eof.svg',
      format: 'eot'
    }];
  }, 'processed via grunt-fontsmith'],

  'processed via grunt-fontsmith': function (done) {
    // Bump the timeout for fontsmith
    this.timeout(60000);

    // Relocate to test directory
    process.chdir(__dirname);

    // Execute the cmd and task combination
    var that = this;
    console.log('wat');
    exec('grunt font:' + this.task, function (err, stdout, stderr) {
      // If there was an error, show me the output
      if (err) {
        console.log(stdout, stderr);
      }

      // Fallback error
      if (stderr) {
        err = new Error(stderr);
      }

      // Save results for later
      that.stdout = stdout;
      console.log('hai');

      // Callback
      done(err);
    });

  },

  // CSS assertions
  'produces a stylesheet': 'produces stylesheets',
  'produces multiple stylesheets': 'produces stylesheets',
  'produces stylesheets with proper formats': 'produces stylesheets',
  'produces stylesheets': function () {
    // Assert each of the CSS files exist
    this.cssFiles.forEach(function (filename) {
      // Grab the expected and actual content
      var expectedContent = fs.readFileSync(expectedDir + filename, 'utf8'),
          actualContent = fs.readFileSync(actualDir + filename, 'utf8');

      // Break down the content into separate lines
      var expectedLines = expectedContent.split('\n'),
          actualLines = actualContent.split('\n');

      // Determine how many lines are different
      var differentLines = expectedLines.filter(function (line) {
            return actualLines.indexOf(line) === -1;
          });

      // Assert that only the character lines are different
      // TODO: If we ever have more than 3 sprites, update
      // the tests to be explicit about how many characters are being used
      assert(differentLines.length <= 3);
    });
  },

  // Font assertions
  'produces a font': 'produces fonts',
  'produces multiple fonts': 'produces fonts',
  'produces fonts with proper formats': 'produces fonts',
  'produces fonts': function (done) {
    // DEV: This is an ugly monstrosity which renders and compares every generated font
    // Load in Stylus
    var styl = fs.readFileSync(expectedDir + '/multiple/font.styl', 'utf8');

    // Iterate over the fontFiles
    var fontFiles = this.fontFiles;
    async.forEach(fontFiles, function compareFontFile (fontFile, cb) {
      // Remove unused font formats
      var fontFormat = fontFile.format,
          actualStyl = styl;
      if (fontFormat !== 'eot') {
        actualStyl = actualStyl.replace(/\s+src:url\("font.eot"\);/, '');
        actualStyl = actualStyl.replace(/\s*url\("font.eot\?#iefix"\) format\("embedded-opentype"\),\s*/, '');
      }
      if (fontFormat !== 'woff') {
        actualStyl = actualStyl.replace(/\s*url\("font.woff"\) format\("woff"\),\s*/, '');
      }
      if (fontFormat !== 'ttf') {
        actualStyl = actualStyl.replace(/\s*url\("font.ttf"\) format\("truetype"\),\s*/, '');
      }
      if (fontFormat !== 'svg') {
        // Guarantee no-commas for font formats
        actualStyl = actualStyl.replace(',', ';');
        actualStyl = actualStyl.replace(/\s*url\("font.svg#icomoon"\) format\("svg"\);\s*/, '');
      }

      // If the fontFormat is `eot`, skip this assertion as it can only be done by IE
      if (fontFormat === 'eot') {
        return cb();
      }

      // Replace font path with our font path
      var filepath = fontFile.path,
          fontname = 'font.' + fontFormat,
          expectedCss = expectedCssObj[fontFormat];
      actualStyl = actualStyl.replace(fontname, actualDir + filepath),
      expectedCss = expectedCss.replace(fontname, expectedDir + filepath);

      // Assert our replacements were successful
      assert.notEqual(actualStyl.indexOf(actualDir), -1, 'Actual stylus has not replaced "' + fontname + '" with "' + actualDir + filepath + '" successfully');
      assert.notEqual(expectedCss.indexOf(expectedDir), -1, 'Expected css has not replaced "' + fontname + '" with "' + expectedDir + filepath + '" successfully');

      function saveToFile(content, cb) {
        // DEV: PhantomJS may require a .css extension for proper mime-types and whatnot
        // Save css to a temporary file
        var tmpFile = new TempFile();
        tmpFile.writeFileSync(content, 'utf8');

        // Save a reference to the file path
        cb(null, tmpFile.path);
      }

      function screenshotFont(options, cssPath, cb) {
        // Screenshot the font in use
        console.log(cssPath);
        exec('phantomjs test_scripts/screenshot_font.js ' + cssPath, function (err, stdout, stderr) {
          // Fallback error with stderr
          if (!err && stderr) {
            err = new Error(stderr);
          }

          // If there was stdout, log it
          if (stdout) {
            console.log('SCREENSHOT FONT STDOUT: ', stdout);
          }

          // Always create screenshots for debugging
          fs.writeFileSync('tmp.' + options.context + '.' + fontFormat + '.png', stdout, 'base64');

          // Callback with our error and font
          cb(err, stdout);
        });
      }

      // In parallel, screenshot the expected and actual font
      async.parallel([
        function renderActualFont (cb) {
          async.waterfall([
            stylus.render.bind(this, actualStyl + '\n' + charStyl),
            saveToFile,
            screenshotFont.bind(this, {context: 'actual'})
          ], cb);
        },
        function renderExpectedFont (cb) {
          async.waterfall([
            saveToFile.bind(this, expectedCss),
            screenshotFont.bind(this, {context: 'expected'})
          ], cb);
        }
      ], function compareFonts (err, fonts) {
        // If there is an error, callback with it
        if (err) { return cb(err); }

        // Otherwise, assert the fonts are equal and callback
        assert.strictEqual(fonts[0], fonts[1]);
        cb();
      });
    }, done);

  }
};
<|endoftext|>


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

describe( 'DKIM', function() {

  describe( '.processHeader()', function() {

    context( '"relaxed" method', function() {

      it( 'normalizes RFC 6376 Example 1', function() {
        var headers = [ 'A: X', 'B : Y\t\r\n\tZ  ', '' ]
        var result = DKIM.processHeader( headers, 'relaxed' )
        assert.equal( result, 'a:X\r\nb:Y Z\r\n' )
      })

      /**
       * The DKIM-Signature header field being created or verified is always included in the signature calculation
       * source: https://tools.ietf.org/html/rfc6376#section-3.5
       */
      it( 'normalizes RFC 6376 Example 2 - Including DKIM-Signature header', function() {
        var headers = [
          'From: X',
          'To : Y  ',
          'Subject : Y\t\r\n\tZ  ',
          'Date : Sun, 22 Oct 2017 10:43:49 +0000  ',
          `DKIM-Signature: v=1; a=rsa-sha256; d=example.net; s=brisbane; c=simple; q=dns/txt; i=@eng.example.net; t=1117574938; x=1118006938; h=from:to:subject:date; z=From:foo@eng.example.net|To:joe@example.com|Subject:demo=20run|Date:July=205,=202005=203:44:08=20PM=20-0700; bh=MTIzNDU2Nzg5MDEyMzQ1Njc4OTAxMjM0NTY3ODkwMTI=; b=dzdVyOfAKCdLXdJOc9G2q8LoXSlEniSbav+yuU4zGeeruD00lszZVoG4ZHRNiYzR`
        ]
        var sigHeaders = [
          'from',
          'to',
          'subject',
          'date',
        ]
        var result = DKIM.processHeader( headers, sigHeaders, 'relaxed' )
        assert.equal( result, 'from:X\r\nto:Y\r\nsubject:Y Z\r\ndate:Sun, 22 Oct 2017 10:43:49 +0000\r\ndkim-signature:v=1; a=rsa-sha256; d=example.net; s=brisbane; c=simple; q=dns/txt; i=@eng.example.net; t=1117574938; x=1118006938; h=from:to:subject:date; z=From:foo@eng.example.net|To:joe@example.com|Subject:demo=20run|Date:July=205,=202005=203:44:08=20PM=20-0700; bh=MTIzNDU2Nzg5MDEyMzQ1Njc4OTAxMjM0NTY3ODkwMTI=; b=' )
      })

      it('Preserves the order of signing headers')

    })

    context( '"simple" method', function() {

      it( 'normalizes RFC 6376 Example 2', function() {
        var headers = [ 'A: X', 'B : Y\t\r\n\tZ  ', '' ]
        var result = DKIM.processHeader( headers, 'simple' )
        assert.equal( result, headers.join( '\r\n' ) )
      })

    })

  })

})
<commit_msg>add a test case for unordered headers<commit_after>var assert = require( 'assert' )
var DKIM = require( '..' )

describe( 'DKIM', function() {

  describe( '.processHeader()', function() {

    context( '"relaxed" method', function() {

      it( 'normalizes RFC 6376 Example 1', function() {
        var headers = [ 'A: X', 'B : Y\t\r\n\tZ  ', '' ]
        var result = DKIM.processHeader( headers, 'relaxed' )
        assert.equal( result, 'a:X\r\nb:Y Z\r\n' )
      })

      /**
       * The DKIM-Signature header field being created or verified is always included in the signature calculation
       * source: https://tools.ietf.org/html/rfc6376#section-3.5
       */
      it( 'normalizes RFC 6376 Example 2 - Including DKIM-Signature header', function() {
        var headers = [
          'From: X',
          'To : Y  ',
          'Subject : Y\t\r\n\tZ  ',
          'Date : Sun, 22 Oct 2017 10:43:49 +0000  ',
          `DKIM-Signature: v=1; a=rsa-sha256; d=example.net; s=brisbane; c=simple; q=dns/txt; i=@eng.example.net; t=1117574938; x=1118006938; h=from:to:subject:date; z=From:foo@eng.example.net|To:joe@example.com|Subject:demo=20run|Date:July=205,=202005=203:44:08=20PM=20-0700; bh=MTIzNDU2Nzg5MDEyMzQ1Njc4OTAxMjM0NTY3ODkwMTI=; b=dzdVyOfAKCdLXdJOc9G2q8LoXSlEniSbav+yuU4zGeeruD00lszZVoG4ZHRNiYzR`
        ]
        var sigHeaders = [
          'from',
          'to',
          'subject',
          'date',
        ]
        var result = DKIM.processHeader( headers, sigHeaders, 'relaxed' )
        assert.equal( result, 'from:X\r\nto:Y\r\nsubject:Y Z\r\ndate:Sun, 22 Oct 2017 10:43:49 +0000\r\ndkim-signature:v=1; a=rsa-sha256; d=example.net; s=brisbane; c=simple; q=dns/txt; i=@eng.example.net; t=1117574938; x=1118006938; h=from:to:subject:date; z=From:foo@eng.example.net|To:joe@example.com|Subject:demo=20run|Date:July=205,=202005=203:44:08=20PM=20-0700; bh=MTIzNDU2Nzg5MDEyMzQ1Njc4OTAxMjM0NTY3ODkwMTI=; b=' )
      })

      it('Preserves the order of signing headers', function() {
        var headers = [
          'From: X',
          'To : Y  ',
          'Date : Sun, 22 Oct 2017 10:43:49 +0000  ',
          'Subject : Y\t\r\n\tZ  ',
          `DKIM-Signature: v=1; a=rsa-sha256; d=example.net; s=brisbane; c=simple; q=dns/txt; i=@eng.example.net; t=1117574938; x=1118006938; h=from:to:subject:date; z=From:foo@eng.example.net|To:joe@example.com|Subject:demo=20run|Date:July=205,=202005=203:44:08=20PM=20-0700; bh=MTIzNDU2Nzg5MDEyMzQ1Njc4OTAxMjM0NTY3ODkwMTI=; b=dzdVyOfAKCdLXdJOc9G2q8LoXSlEniSbav+yuU4zGeeruD00lszZVoG4ZHRNiYzR`
        ]
        var sigHeaders = [
          'from',
          'to',
          'subject',
          'date',
        ]
        var result = DKIM.processHeader( headers, sigHeaders, 'relaxed' )
        assert.equal( result, 'from:X\r\nto:Y\r\nsubject:Y Z\r\ndate:Sun, 22 Oct 2017 10:43:49 +0000\r\ndkim-signature:v=1; a=rsa-sha256; d=example.net; s=brisbane; c=simple; q=dns/txt; i=@eng.example.net; t=1117574938; x=1118006938; h=from:to:subject:date; z=From:foo@eng.example.net|To:joe@example.com|Subject:demo=20run|Date:July=205,=202005=203:44:08=20PM=20-0700; bh=MTIzNDU2Nzg5MDEyMzQ1Njc4OTAxMjM0NTY3ODkwMTI=; b=' )
      })

    })

    context( '"simple" method', function() {

      it( 'normalizes RFC 6376 Example 2', function() {
        var headers = [ 'A: X', 'B : Y\t\r\n\tZ  ', '' ]
        var result = DKIM.processHeader( headers, 'simple' )
        assert.equal( result, headers.join( '\r\n' ) )
      })

    })

  })

})
<|endoftext|>


<commit_before>// Load in modules
var fs = require('fs');
global.fs = fs;
global.assert = require('assert');
global.request = require('request');

// Load in DOM specific modules
global.jsdom = require('jsdom');
var jqueryPath =  __dirname + '/test_files/jquery.js';
global.jqueryPath = jqueryPath;
global.jquerySrc = fs.readFileSync(jqueryPath, 'utf8');

// Set up config
var config = {
  host: 'http://localhost:8080',
  url: function getUrl (path) {
    return this.host + path;
  },
  navigateToRaw: function (options, cb) {
    // Collect arguments
    var args = [].slice.call(arguments);

    // If the options are a string
    if (typeof options === 'string') {
      options = config.url(options);
    } else {
      options.url = config.url(options.url);
    }

    // Call request
    var that = this;
    request(options, function getPage (err, res, body) {
      // Save response
      that.err = err;
      that.res = res;
      that.body = body;

      // Callback
      cb(err);
    });
  },
  navigateTo: function (options) {
    return function navFn (cb) {
      return config.navigateToRaw.call(this, options, cb);
    };
  }
};
global.config = config;<commit_msg>Revert "Moving to localhost for testing"<commit_after>// Load in modules
var fs = require('fs');
global.fs = fs;
global.assert = require('assert');
global.request = require('request');

// Load in DOM specific modules
global.jsdom = require('jsdom');
var jqueryPath =  __dirname + '/test_files/jquery.js';
global.jqueryPath = jqueryPath;
global.jquerySrc = fs.readFileSync(jqueryPath, 'utf8');

// Set up config
var config = {
  host: 'http://twolfson.com',
  url: function getUrl (path) {
    return this.host + path;
  },
  navigateToRaw: function (options, cb) {
    // Collect arguments
    var args = [].slice.call(arguments);

    // If the options are a string
    if (typeof options === 'string') {
      options = config.url(options);
    } else {
      options.url = config.url(options.url);
    }

    // Call request
    var that = this;
    request(options, function getPage (err, res, body) {
      // Save response
      that.err = err;
      that.res = res;
      that.body = body;

      // Callback
      cb(err);
    });
  },
  navigateTo: function (options) {
    return function navFn (cb) {
      return config.navigateToRaw.call(this, options, cb);
    };
  }
};
global.config = config;<|endoftext|>


<commit_before>var dynode = require("../../lib/dynode"),
    DynamoDB = require('../test-helper'),
    util = require('utile'),
    should = require('chai').should();

describe('Dynode Integration Tests', function() {

  beforeEach(function() {
    dynode.auth({accessKeyId : process.env.AWS_ACCEESS_KEY_ID, secretAccessKey: process.env.AWS_SECRET_ACCESS_KEY});
  });

  describe("Tables", function() {

    it('should list all tables', function(done) {

      dynode.listTables({}, function(err, tables) {
        tables.should.have.property("TableNames");
        done();
      });

    });

    it('should describe table', function(done) {

      dynode.describeTable("TestTable", function(err, table) {
        table.TableName.should.equal("TestTable");
        done();
      });

    });

  });

  describe("Put Item", function() {

    it('should create new item', function(done) {
      dynode.putItem("TestTable", {id : "Blah", foo: "Bar", num: 123, baz : ["a", "b", "c"]}, function(err, resp) {
        done(err);
      });

    });
  });

  describe("Get Item", function() {

    before(function(done) {
      DynamoDB.createProduct({id : "TestItem", foo: "Bar"}, done);
    });

    it('should get item', function(done) {
      dynode.getItem("TestTable", "TestItem", function(err, item, meta) {
        item.should.eql({id : "TestItem", foo: "Bar"});
        meta.ConsumedCapacityUnits.should.equal(0.5);
        done(err);
      });
    });

    it('should return null for not found item', function(done) {
      dynode.getItem("TestTable", "ThisKeyDoesntExist", function(err, item, meta) {
        should.not.exist(err);
        should.not.exist(item);
        meta.ConsumedCapacityUnits.should.equal(0.5);
        done(err);
      });
    });
  });

  describe("Update Item", function() {

    before(function(done) {
      DynamoDB.createProducts([
        {id: "updateTest", foo: "baz"},
        {id: "update2", nums: [1,2,3], age: 22},
        {id: "update3", foo: "bar", age: 22},
        {id: "update4", foo: "blah", age: 99, nums : [4,5,6], lname : 'tester'}
      ], done);
    });

    it('should update existing item and return its new values', function(done) {
      dynode.updateItem(DynamoDB.TestTable, "updateTest", {foo: "Bar"}, {ReturnValues: "UPDATED_NEW"}, function(err, resp) {
        resp.Attributes.should.eql({ foo: 'Bar' });
        done(err);
      });
    });

    it('should update existing Item by adding a number to a set of numbers', function(done) {
      dynode.updateItem(DynamoDB.TestTable, "update2", {nums: {add : [5]}, age: {add: 2}}, {ReturnValues: "UPDATED_NEW"}, function(err, resp) {
        var nums = resp.Attributes.nums.sort();
        nums.should.eql([1, 2, 3, 5]);
        resp.Attributes.age.should.eql(24);
        done(err);
      });
    });

    it('should delete age attribute', function(done) {
      dynode.updateItem(DynamoDB.TestTable, "update3", {age: {'Action' : "DELETE"}}, {ReturnValues: "ALL_NEW"}, function(err, resp) {
        resp.Attributes.should.eql({ id: 'update3', foo: 'bar' });
        should.not.exist(resp.Attributes.age);
        done(err);
      });
    });

    it('should delete attributes', function(done) {
      dynode.updateItem(DynamoDB.TestTable, "update4", {age: null, nums : [], lname : ''}, {ReturnValues: "ALL_NEW"}, function(err, resp) {
        resp.Attributes.should.eql({ id: 'update4', foo: 'blah' });
        should.not.exist(resp.Attributes.age);
        should.not.exist(resp.Attributes.nums);
        should.not.exist(resp.Attributes.lname);
        done(err);
      });
    });

  });

  describe("Delete Item", function() {

    beforeEach(function(done) {
      DynamoDB.createProduct({id : "DeleteMe", foo: "Bar"}, done);
    });

    it('should delete an item', function(done) {
      dynode.deleteItem(DynamoDB.TestTable, "DeleteMe", function(err, resp) {
        should.exist(resp.ConsumedCapacityUnits);
        done(err);
      });

    });

    it('should delete an item and return its old values', function(done) {
      dynode.deleteItem(DynamoDB.TestTable, "DeleteMe", {ReturnValues: "ALL_OLD"}, function(err, resp) {
        resp.Attributes.should.eql({ foo: 'Bar', id: 'DeleteMe' });
        done(err);
      });
    });

  });

  describe("Scan", function() {

    before(function(done) {
      DynamoDB.createProducts(DynamoDB.products, done);
    });

    it('should get all items', function(done) {
      dynode.scan(DynamoDB.TestTable, function(err, items, meta) {
        items.should.have.length(meta.Count);
        done(err);
      });

    });

    it('should accept limit filter', function(done) {
      dynode.scan(DynamoDB.TestTable,{Limit: 2}, function(err, items, meta) {
        items.should.have.length(2);
        meta.Count.should.equal(2);
        done(err);
      });

    });

  });

  describe("Truncate", function(){
    before(function(done) {
      this.timeout(0);
      var products = [];

      for(var i = 0; i <= 10; i++) {
        products.push({id: "prod-"+i, foo: "bar-" +i});
      }

      DynamoDB.createProducts(products, done);
    });

    it("should remove all items from table", function(done){
      this.timeout(0);

      dynode.truncate(DynamoDB.TestTable, function(err){

        dynode.getItem(DynamoDB.TestTable, 'prod-1', function(err, item){
          should.not.exist(err);
          should.not.exist(item);
          done();
        });

      });
    });
  });

  describe("Error Handling", function(){

    it("should return error for non existant table", function(done) {

      dynode.describeTable("NonExistTable", function(err) {
        err.type.should.equal("ResourceNotFoundException");

        done();
      });

    });
  });

  describe('HTTPS', function(){

    before(function(done){
      dynode.auth({
        https : true,
        accessKeyId: process.env.AWS_ACCEESS_KEY_ID,
        secretAccessKey: process.env.AWS_SECRET_ACCESS_KEY
      });

      DynamoDB.createProducts(DynamoDB.products, done);
    });

    it("should use https when passing setting https to true in config", function(done){
      dynode.scan(DynamoDB.TestTable, function(err, items, meta) {
        items.should.have.length(meta.Count);
        done(err);
      });
    });
  });

});<commit_msg>integration testing batch write item<commit_after>var dynode = require("../../lib/dynode"),
    DynamoDB = require('../test-helper'),
    util = require('utile'),
    should = require('chai').should();

describe('Dynode Integration Tests', function() {

  beforeEach(function() {
    dynode.auth({accessKeyId : process.env.AWS_ACCEESS_KEY_ID, secretAccessKey: process.env.AWS_SECRET_ACCESS_KEY});
  });

  describe("Tables", function() {

    it('should list all tables', function(done) {

      dynode.listTables({}, function(err, tables) {
        tables.should.have.property("TableNames");
        done();
      });

    });

    it('should describe table', function(done) {

      dynode.describeTable("TestTable", function(err, table) {
        table.TableName.should.equal("TestTable");
        done();
      });

    });

  });

  describe("Put Item", function() {

    it('should create new item', function(done) {
      dynode.putItem("TestTable", {id : "Blah", foo: "Bar", num: 123, baz : ["a", "b", "c"]}, function(err, resp) {
        done(err);
      });

    });
  });

  describe("Get Item", function() {

    before(function(done) {
      DynamoDB.createProduct({id : "TestItem", foo: "Bar"}, done);
    });

    it('should get item', function(done) {
      dynode.getItem("TestTable", "TestItem", function(err, item, meta) {
        item.should.eql({id : "TestItem", foo: "Bar"});
        meta.ConsumedCapacityUnits.should.equal(0.5);
        done(err);
      });
    });

    it('should return null for not found item', function(done) {
      dynode.getItem("TestTable", "ThisKeyDoesntExist", function(err, item, meta) {
        should.not.exist(err);
        should.not.exist(item);
        meta.ConsumedCapacityUnits.should.equal(0.5);
        done(err);
      });
    });
  });

  describe("Update Item", function() {

    before(function(done) {
      DynamoDB.createProducts([
        {id: "updateTest", foo: "baz"},
        {id: "update2", nums: [1,2,3], age: 22},
        {id: "update3", foo: "bar", age: 22},
        {id: "update4", foo: "blah", age: 99, nums : [4,5,6], lname : 'tester'}
      ], done);
    });

    it('should update existing item and return its new values', function(done) {
      dynode.updateItem(DynamoDB.TestTable, "updateTest", {foo: "Bar"}, {ReturnValues: "UPDATED_NEW"}, function(err, resp) {
        resp.Attributes.should.eql({ foo: 'Bar' });
        done(err);
      });
    });

    it('should update existing Item by adding a number to a set of numbers', function(done) {
      dynode.updateItem(DynamoDB.TestTable, "update2", {nums: {add : [5]}, age: {add: 2}}, {ReturnValues: "UPDATED_NEW"}, function(err, resp) {
        var nums = resp.Attributes.nums.sort();
        nums.should.eql([1, 2, 3, 5]);
        resp.Attributes.age.should.eql(24);
        done(err);
      });
    });

    it('should delete age attribute', function(done) {
      dynode.updateItem(DynamoDB.TestTable, "update3", {age: {'Action' : "DELETE"}}, {ReturnValues: "ALL_NEW"}, function(err, resp) {
        resp.Attributes.should.eql({ id: 'update3', foo: 'bar' });
        should.not.exist(resp.Attributes.age);
        done(err);
      });
    });

    it('should delete attributes', function(done) {
      dynode.updateItem(DynamoDB.TestTable, "update4", {age: null, nums : [], lname : ''}, {ReturnValues: "ALL_NEW"}, function(err, resp) {
        resp.Attributes.should.eql({ id: 'update4', foo: 'blah' });
        should.not.exist(resp.Attributes.age);
        should.not.exist(resp.Attributes.nums);
        should.not.exist(resp.Attributes.lname);
        done(err);
      });
    });

  });

  describe("Delete Item", function() {

    beforeEach(function(done) {
      DynamoDB.createProduct({id : "DeleteMe", foo: "Bar"}, done);
    });

    it('should delete an item', function(done) {
      dynode.deleteItem(DynamoDB.TestTable, "DeleteMe", function(err, resp) {
        should.exist(resp.ConsumedCapacityUnits);
        done(err);
      });

    });

    it('should delete an item and return its old values', function(done) {
      dynode.deleteItem(DynamoDB.TestTable, "DeleteMe", {ReturnValues: "ALL_OLD"}, function(err, resp) {
        resp.Attributes.should.eql({ foo: 'Bar', id: 'DeleteMe' });
        done(err);
      });
    });

  });

  describe("Scan", function() {

    before(function(done) {
      DynamoDB.createProducts(DynamoDB.products, done);
    });

    it('should get all items', function(done) {
      dynode.scan(DynamoDB.TestTable, function(err, items, meta) {
        items.should.have.length(meta.Count);
        done(err);
      });

    });

    it('should accept limit filter', function(done) {
      dynode.scan(DynamoDB.TestTable,{Limit: 2}, function(err, items, meta) {
        items.should.have.length(2);
        meta.Count.should.equal(2);
        done(err);
      });

    });

  });

  describe("Batch Write Item", function(){
    before(function(done) {
      DynamoDB.createProducts([
        {id: "batch1", foo: "baz"},
        {id: "batch2", nums: [1,2,3], age: 22},
        {id: "batch3", foo: "bar", age: 22},
        {id: "batch4", foo: "blah", age: 99, nums : [4,5,6], lname : 'tester'}
      ], done);
    });

    it("should update all items", function(done){
      var writes = {};
      writes[DynamoDB.TestTable] = [
        {put : {id : "batch1", foo: "new foo"}},
        {del : "batch2"},
        {del : "batch3"}
      ];

      dynode.batchWriteItem(writes, function(err, resp){
        should.not.exist(err);
        done();
      });

    });
  });
  describe("Truncate", function(){
    before(function(done) {
      this.timeout(0);
      var products = [];

      for(var i = 0; i <= 10; i++) {
        products.push({id: "prod-"+i, foo: "bar-" +i});
      }

      DynamoDB.createProducts(products, done);
    });

    it("should remove all items from table", function(done){
      this.timeout(0);

      dynode.truncate(DynamoDB.TestTable, function(err){

        dynode.getItem(DynamoDB.TestTable, 'prod-1', function(err, item){
          should.not.exist(err);
          should.not.exist(item);
          done();
        });

      });
    });
  });

  describe("Error Handling", function(){

    it("should return error for non existant table", function(done) {

      dynode.describeTable("NonExistTable", function(err) {
        err.type.should.equal("ResourceNotFoundException");

        done();
      });

    });
  });

  describe('HTTPS', function(){

    before(function(done){
      dynode.auth({
        https : true,
        accessKeyId: process.env.AWS_ACCEESS_KEY_ID,
        secretAccessKey: process.env.AWS_SECRET_ACCESS_KEY
      });

      DynamoDB.createProducts(DynamoDB.products, done);
    });

    it("should use https when passing setting https to true in config", function(done){
      dynode.scan(DynamoDB.TestTable, function(err, items, meta) {
        items.should.have.length(meta.Count);
        done(err);
      });
    });
  });

});<|endoftext|>


<commit_before>let timeout = 120;
let tickInterval = 500;

let steps = {
	"openMenu" : {
		stepName : "openMenu",
		className: "a",
		predicate: isArrow,
		nextStep : "clickDeletePost"
	},
	"clickDeletePost" : {
		stepName : "clickDeletePost",
		className: "div",
		predicate: isDeletePostOption,
		nextStep : "clickDelete"
	},
	"clickDelete" : {
		stepName : "clickDelete",
		className: "button",
		predicate: isDeleteButton,
		nextStep : null
	}
};

let currentStep = steps["openMenu"];
let prevStep = undefined;
let isFinished = false;

timeoutMonitor();
deletedMonitor();
doStep(0);

function timeoutMonitor() {
	if (currentStep === prevStep) {
		cleanup();
		return;
	}

	prevStep = currentStep;
	window.setTimeout(timeoutMonitor, timeout * tickInterval);
}

function deletedMonitor() {
	let deleteMessage = getElement("div", isDeleteMessage);
	if (deleteMessage) {
		cleanup();
		return;
	}

	window.setTimeout(deletedMonitor, tickInterval);
}

function doStep(tick) {
	if (currentStep === null) {
		cleanup();
		return;
	}

	if (tick % 25 === 0 && tick > 0) {
		console.log(`${currentStep.stepName} has used ${tick} ticks`);
	}

	let element = getElement(currentStep.className, currentStep.predicate)
	if (element) {
		element.click();
		currentStep = steps[currentStep.nextStep];
		tick = 0;
	}

	window.setTimeout(doStep, tickInterval, tick + 1);
}

function cleanup() {
	// this may get called multiple times since the
	// timer is still going
	if (isFinished) {
		return;
	}

	isFinished = true;
	browser.runtime.sendMessage({
		to: "deleter",
		body: window.location.href
	});
}

function getElement(tagName, predicate) {
	let elems = document.getElementsByTagName(tagName);
	for (let elem of elems) {
		if (predicate(elem)) {
			return elem;
		}
	}

	return null;
}

function caseInsensitiveEqual(a, b) {
	if (a === b) {
		return true;
	}

	if (!a || !b) {
		return false;
	}

	return (a.toUpperCase() === b.toUpperCase());
}

function isDeleteMessage(elem) {
	let content = "This post has been removed or could not be loaded.";
	return (caseInsensitiveEqual(elem.innerHTML, content));
}

function isArrow(elem) {
	let attribute = "Story options";
	return (caseInsensitiveEqual(elem.getAttribute("aria-label"), attribute);
}

function isDeletePostOption(elem) {
	let nodeValue = "Delete Post";
	return (
		elem.childNodes.length === 3 &&
		elem.childNodes[2].nodeValue &&
		caseInsensitiveEqual(elem.childNodes[2].nodeValue, nodeValue)
	);
}

function isDeleteButton(elem) {
	let deleteMessage = "Delete";
	let noSoldMessage = "Haven't Sold";

	return (
		caseInsensitiveEqual(elem.innerHTML, deleteMessage) ||
		caseInsensitiveEqual(elem.innerHTML, noSoldMessage)
	);
}
<commit_msg>Fixed syntax error<commit_after>let timeout = 120;
let tickInterval = 500;

let steps = {
	"openMenu" : {
		stepName : "openMenu",
		className: "a",
		predicate: isArrow,
		nextStep : "clickDeletePost"
	},
	"clickDeletePost" : {
		stepName : "clickDeletePost",
		className: "div",
		predicate: isDeletePostOption,
		nextStep : "clickDelete"
	},
	"clickDelete" : {
		stepName : "clickDelete",
		className: "button",
		predicate: isDeleteButton,
		nextStep : "done"
	},
	"done" : null
};

let currentStep = steps["openMenu"];
let prevStep = undefined;
let isFinished = false;

timeoutMonitor();
deletedMonitor();
doStep(0);

function timeoutMonitor() {
	if (currentStep === prevStep) {
		cleanup();
		return;
	}

	prevStep = currentStep;
	window.setTimeout(timeoutMonitor, timeout * tickInterval);
}

function deletedMonitor() {
	let deleteMessage = getElement("div", isDeleteMessage);
	if (deleteMessage) {
		cleanup();
		return;
	}

	window.setTimeout(deletedMonitor, tickInterval);
}

function doStep(tick) {
	if (currentStep === null) {
		cleanup();
		return;
	}

	if (tick % 25 === 0 && tick > 0) {
		console.log(`${currentStep.stepName} has used ${tick} ticks`);
	}

	let element = getElement(currentStep.className, currentStep.predicate)
	if (element) {
		element.click();
		currentStep = steps[currentStep.nextStep];
		tick = 0;
	}

	window.setTimeout(doStep, tickInterval, tick + 1);
}

function cleanup() {
	// this may get called multiple times since the
	// timer is still going
	if (isFinished) {
		return;
	}

	isFinished = true;
	browser.runtime.sendMessage({
		to: "deleter",
		body: window.location.href
	});
}

function getElement(tagName, predicate) {
	let elems = document.getElementsByTagName(tagName);
	for (let elem of elems) {
		if (predicate(elem)) {
			return elem;
		}
	}

	return null;
}

function caseInsensitiveEqual(a, b) {
	if (a === b) {
		return true;
	}

	if (!a || !b) {
		return false;
	}

	return (a.toUpperCase() === b.toUpperCase());
}

function isDeleteMessage(elem) {
	let content = "This post has been removed or could not be loaded.";
	return (caseInsensitiveEqual(elem.innerHTML, content));
}

function isArrow(elem) {
	let attribute = "Story options";
	return (caseInsensitiveEqual(elem.getAttribute("aria-label"), attribute));
}

function isDeletePostOption(elem) {
	let nodeValue = "Delete Post";
	return (
		elem.childNodes.length === 3 &&
		elem.childNodes[2].nodeValue &&
		caseInsensitiveEqual(elem.childNodes[2].nodeValue, nodeValue)
	);
}

function isDeleteButton(elem) {
	let deleteMessage = "Delete";
	let noSoldMessage = "Haven't Sold";

	return (
		caseInsensitiveEqual(elem.innerHTML, deleteMessage) ||
		caseInsensitiveEqual(elem.innerHTML, noSoldMessage)
	);
}
<|endoftext|>


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

var promptModuleOptionsModule = require('../bin/promptModuleOptions');

chai.should();

describe('As a user of the prompt module options module', function() {

	var moduleOptionsData;

	before(function() {
		promptModuleOptionsModule.setup({
			silent: true
		});
	})

	describe('When getting prompt options data', function() {

		beforeEach(function(done) {

			promptModuleOptionsModule
				.getOptions()
				.then(function(moduleData) {
					moduleOptionsData = moduleData;
					done();
				})
		})

		it('should return an array', function() {
			expect(moduleOptionsData).to.be.a('array');
		})

	})

})<commit_msg>test: check that module data is a collection<commit_after>var chai = require('chai');
var expect = chai.expect;

var promptModuleOptionsModule = require('../bin/promptModuleOptions');

chai.should();

describe('As a user of the prompt module options module', function() {

	var moduleOptionsData;

	this.timeout(5000);

	before(function() {
		promptModuleOptionsModule.setup({
			silent: true
		});
	})

	describe('When getting module data', function() {

		beforeEach(function(done) {

			promptModuleOptionsModule
				.getOptions()
				.then(function(moduleData) {
					moduleOptionsData = moduleData;
					done();
				})
		})

		it('should return an array', function() {
			expect(moduleOptionsData).to.be.a('array');
		})

		it('should return a collection (array of objects)', function() {
			moduleOptionsData.forEach(function(singleModule) {
				expect(singleModule).to.be.a('object');
			})
		})

	})

})<|endoftext|>


<commit_before>/* eslint-env mocha */

const Chargehound = require('../../lib')
const nock = require('nock')

const chargehound = new Chargehound('API_KEY')

const getHeaders = {
  'accept': 'application/json',
  'authorization': 'Basic QVBJX0tFWTo=',
  'host': 'api.chargehound.com',
  'user-agent': 'Chargehound/v1 NodeBindings/1.0.0'
}

const postHeaders = {
  'accept': 'application/json',
  'authorization': 'Basic QVBJX0tFWTo=',
  'content-type': 'application/json',
  'host': 'api.chargehound.com',
  'user-agent': 'Chargehound/v1 NodeBindings/1.0.0'
}

describe('dispute', function () {
  afterEach(function () {
    nock.restore()
  })

  describe('retrieve', function () {
    it('Sends the correct request', function (done) {
      const scope = nock('https://api.chargehound.com', { reqheaders: getHeaders })
        .get('/v1/disputes/dp_123')
        .reply(200, {'id': 'dp_123'})
      chargehound.Disputes.retrieve('dp_123').then(function (body) {
        scope.done()
        done()
      })
    })
  })

  describe('list', function (done) {
    it('Sends the correct request', function () {
      const scope = nock('https://api.chargehound.com', { reqheaders: getHeaders })
        .get('/v1/disputes')
        .reply(200, {'data': [{'id': 'dp_123'}]})
      chargehound.Disputes.list().then(function (body) {
        scope.done()
        done()
      })
    })
  })

  describe('submit', function (done) {
    it('Sends the correct request', function () {
      const scope = nock('https://api.chargehound.com', { reqheaders: postHeaders })
        .post('/v1/disputes/dp_123/submit', {fields: {customer_name: 'Susie'}})
        .reply(201, {'id': 'dp_123'})
      chargehound.Disputes.submit('dp_123', {fields: {customer_name: 'Susie'}})
        .then(function (body) {
          scope.done()
          done()
        })
    })
  })

  describe('update', function (done) {
    it('Sends the correct request', function () {
      const scope = nock('https://api.chargehound.com', { reqheaders: postHeaders })
        .post('/v1/disputes/dp_123', {fields: {customer_name: 'Susie'}})
        .reply(200, {'id': 'dp_123'})
      chargehound.Disputes.update('dp_123', {fields: {customer_name: 'Susie'}})
        .then(function (body) {
          scope.done()
          done()
        })
    })
  })
})
<commit_msg>Fix tests against user agent header<commit_after>/* eslint-env mocha */

const Chargehound = require('../../lib')
const clientVersion = require('../../package.json').version
const nock = require('nock')

const chargehound = new Chargehound('API_KEY')
const CHARGEHOUND_USERAGENT = 'Chargehound/v1 NodeBindings/' + clientVersion

const getHeaders = {
  'accept': 'application/json',
  'authorization': 'Basic QVBJX0tFWTo=',
  'host': 'api.chargehound.com',
  'user-agent': CHARGEHOUND_USERAGENT
}

const postHeaders = {
  'accept': 'application/json',
  'authorization': 'Basic QVBJX0tFWTo=',
  'content-type': 'application/json',
  'host': 'api.chargehound.com',
  'user-agent': CHARGEHOUND_USERAGENT
}

describe('dispute', function () {
  afterEach(function () {
    nock.restore()
  })

  describe('retrieve', function () {
    it('Sends the correct request', function (done) {
      const scope = nock('https://api.chargehound.com', { reqheaders: getHeaders })
        .get('/v1/disputes/dp_123')
        .reply(200, {'id': 'dp_123'})
      chargehound.Disputes.retrieve('dp_123').then(function (body) {
        scope.done()
        done()
      })
    })
  })

  describe('list', function (done) {
    it('Sends the correct request', function () {
      const scope = nock('https://api.chargehound.com', { reqheaders: getHeaders })
        .get('/v1/disputes')
        .reply(200, {'data': [{'id': 'dp_123'}]})
      chargehound.Disputes.list().then(function (body) {
        scope.done()
        done()
      })
    })
  })

  describe('submit', function (done) {
    it('Sends the correct request', function () {
      const scope = nock('https://api.chargehound.com', { reqheaders: postHeaders })
        .post('/v1/disputes/dp_123/submit', {fields: {customer_name: 'Susie'}})
        .reply(201, {'id': 'dp_123'})
      chargehound.Disputes.submit('dp_123', {fields: {customer_name: 'Susie'}})
        .then(function (body) {
          scope.done()
          done()
        })
    })
  })

  describe('update', function (done) {
    it('Sends the correct request', function () {
      const scope = nock('https://api.chargehound.com', { reqheaders: postHeaders })
        .post('/v1/disputes/dp_123', {fields: {customer_name: 'Susie'}})
        .reply(200, {'id': 'dp_123'})
      chargehound.Disputes.update('dp_123', {fields: {customer_name: 'Susie'}})
        .then(function (body) {
          scope.done()
          done()
        })
    })
  })
})
<|endoftext|>


<commit_before>const hash = require('../../../../server/auth/hash')

exports.seed = (knex, Promise) => {
  return knex('users').insert([
    {id: 1, ghid: '1A', username: 'stina', hash: hash.generate('stina')},
    {id: 2, ghid: '2B', username: 'kimmi', hash: hash.generate('kimmi')},
    {id: 3, ghid: '3C', username: 'julia', hash: hash.generate('julia')},
    {id: 4, ghid: '4D', username: 'steve', hash: hash.generate('steve')},
    {id: 5, ghid: '5E', username: 'jules', hash: hash.generate('jules')}
  ])
}
<commit_msg>edited user migration<commit_after>const hash = require('../../../../server/auth/hash')

exports.seed = (knex, Promise) => {
  return knex('users').insert([
    {id: 1, ghid: '1A', username: 'jules', hash: hash.generate('jules')},
    {id: 2, ghid: '2B', username: 'kimmi', hash: hash.generate('kimmi')},
    {id: 3, ghid: '3C', username: 'julia', hash: hash.generate('julia')},
    {id: 4, ghid: '4D', username: 'steve', hash: hash.generate('steve')},
    {id: 5, ghid: '5E', username: 'stina', hash: hash.generate('stina')}
  ])
}
<|endoftext|>


<commit_before>/**
 * Created by ndyumin on 05.06.2015.
 */
define(function (require) {

    var Wreqr = require('backbone.wreqr');

    var gameBus = Wreqr.radio.channel('game');

    var Model = require('game/GameModel');
    var Block = require('game/geom/Block');
    var Shape = require('game/geom/shapes/Shape');

    describe("Model", function () {
        it("should create a field of a given size", function () {
            var model = new Model(21,11);
            expect(model.fieldMap.length).toBe(21);
        });
        it("should return a copy of a field", function () {
            var model = new Model(21,11);
            model.fieldMap[5][5] = 1;
            model.fieldMap[3][2] = 1;
            var copy = model.getCells();
            model.fieldMap[5][5] = 2;
            model.fieldMap[3][2] = 2;
            expect(copy[5][5]).toBe(1);
            expect(copy[3][2]).toBe(1);
        });
        it("should set an active block of {Block}", function () {
            var model = new Model(21,11);
            var block = new Block(new Shape(2), null);
            model.setActiveBlock(block);
            expect(model.getActiveBlock()).toBe(block);
            try {
                model.setActiveBlock(123);
            } catch(e) {

            }
            expect(model.getActiveBlock()).toBe(block);
        });
        it("should remove full rows filling the field with empty ones", function () {
            var model = new Model(5,5);
            model.fieldMap[0] = [1,1,1,1,1];
            model.fieldMap[4] = [1,1,1,1,1];
            model.removeFullRows();
            expect(model.fieldMap.length).toBe(5);
            expect(model.fieldMap[0]).toEqual([]);
            expect(model.fieldMap[4]).toEqual([]);
        });
        it("should trigger 'collapse' on gameBus", function (clb) {
            var model = new Model(5,5);
            model.fieldMap[0] = [1,1,1,1,1];
            model.fieldMap[4] = [1,1,1,1,1];
            var count = 0;
            function handler() {
                count += 1;
                if (count === 2) {
                    gameBus.vent.off('collapse', handler);
                    clb();
                }
            }
            gameBus.vent.on('collapse', handler);
            model.removeFullRows();
        });
        it("should call removeFullRows method on adding a block", function () {
            var model = new Model(21,11);
            var block = new Block(new Shape(2), null);
            spyOn(model, 'removeFullRows');
            model.addBlock(block);
            expect(model.removeFullRows).toHaveBeenCalled();
        });
    });

});<commit_msg>increased game model coverage<commit_after>/**
 * Created by ndyumin on 05.06.2015.
 */
define(function (require) {

    var Wreqr = require('backbone.wreqr');

    var gameBus = Wreqr.radio.channel('game');

    var Model = require('game/GameModel');
    var Block = require('game/geom/Block');
    var Shape = require('game/geom/shapes/Shape');

    describe("Model", function () {
        it("should create a field of a given size", function () {
            var model = new Model(21,11);
            expect(model.fieldMap.length).toBe(21);
            model.dispose();
        });
        it("should return a copy of a field", function () {
            var model = new Model(21,11);
            model.fieldMap[5][5] = 1;
            model.fieldMap[3][2] = 1;
            var copy = model.getCells();
            model.fieldMap[5][5] = 2;
            model.fieldMap[3][2] = 2;
            expect(copy[5][5]).toBe(1);
            expect(copy[3][2]).toBe(1);
        });
        it("should set an active block of {Block}", function () {
            var model = new Model(21,11);
            var block = new Block(new Shape(2), null);
            model.setActiveBlock(block);
            expect(model.getActiveBlock()).toBe(block);
            var failure = jasmine.createSpy('failure');
            try {
                model.setActiveBlock(123);
            } catch(e) {
                failure();
            }
            expect(failure).toHaveBeenCalled();
            expect(model.getActiveBlock()).toBe(block);
        });
        it("should remove full rows filling the field with empty ones", function () {
            var model = new Model(5,5);
            model.fieldMap[0] = [1,1,1,1,1];
            model.fieldMap[4] = [1,1,1,1,1];
            model.removeFullRows();
            expect(model.fieldMap.length).toBe(5);
            expect(model.fieldMap[0]).toEqual([]);
            expect(model.fieldMap[4]).toEqual([]);
        });
        it("should trigger 'collapse' on gameBus", function (clb) {
            var model = new Model(5,5);
            model.fieldMap[0] = [1,1,1,1,1];
            model.fieldMap[4] = [1,1,1,1,1];
            var count = 0;
            function handler() {
                count += 1;
                if (count === 2) {
                    gameBus.vent.off('collapse', handler);
                    clb();
                }
            }
            gameBus.vent.on('collapse', handler);
            model.removeFullRows();
        });
        it("should call removeFullRows method on adding a block", function () {
            var model = new Model(21,11);
            var block = new Block(new Shape(2), null);
            spyOn(model, 'removeFullRows');
            model.addBlock(block);
            expect(model.removeFullRows).toHaveBeenCalled();
        });
        it("should be able to check if an external set of cells collides with a field at a given coordinates", function () {
            /**
             * @type {GameModel}
             */
            var model = new Model(5, 5);
            model.fieldMap[2][2] = 1;
            var block = new Block(new Shape(2), 5);
            block.shape.setCells([[2, 2],[2, 2]]);
            expect(model.checkCollision(block.shape.getCells(), 1, 1)).toBeTruthy();
            expect(model.checkCollision(block.shape.getCells(), 2, 2)).toBeTruthy();
            expect(model.checkCollision(block.shape.getCells(), 0, 0)).toBeFalsy();
            expect(model.checkCollision(block.shape.getCells(), 3, 3)).toBeFalsy();
        });
        it("should be able to add a block to a field permanently using a block color and throw exception if it is not successful", function () {
            /**
             * @type {GameModel}
             */
            var model = new Model(5, 5);
            model.fieldMap[2][2] = 1;
            var COLOR = 5;
            var block = new Block(new Shape(2), COLOR);
            block.shape.setCells([[2, 2],[2, 2]]);
            block.positionX = 0;
            block.positionY = 0;
            model.addBlock(block);
            expect(model.fieldMap[0][0]).toBe(COLOR);
            expect(model.fieldMap[1][1]).toBe(COLOR);
            expect(model.fieldMap[2][2]).toBe(1);
            var failure = jasmine.createSpy('failure');
            try {
                model.addBlock(block);
            } catch(e) {
                failure();
            }
            expect(failure).toHaveBeenCalled();
        });
    });

});<|endoftext|>


<commit_before>'use strict';

describe('scheduler', function() {
  beforeEach(function() {
    var pollSchedule = 25;
    module('deckApp', function($provide) {
      return $provide.constant('settings', {
        pollSchedule: pollSchedule,
      });
    });
    this.pollSchedule = pollSchedule;

    inject(function(scheduler) {
      this.scheduler = scheduler;
    });

    this.test = {
      call: angular.noop,
    };
  });

  describe('#get', function() {
    it('returns the underlying RxSubject', function() {
      spyOn(this.test, 'call');

      this.scheduler.subscribe(this.test.call);

      expect(this.test.call.calls.count()).toEqual(0);

      this.scheduler.get().onNext();

      expect(this.test.call.calls.count()).toEqual(1);
    });
  });

  describe('subscription methods', function() {
    beforeEach(function() {
      this.numIterations = 10;
      this.cycles = 2;
    });

    xdescribe('#subscribe', function() {
      it('it takes a callback that is invoked at each iteration of the scheduler', function(done) {

        spyOn(this.test, 'call');
        this.pre = this.test.call.calls.count();
        this.scheduler.subscribe(this.test.call);
        setTimeout(function() {
          var post = this.test.call.calls.count();
          // error bounds of +/- 1
          expect(post - this.pre).toBeGreaterThan(this.numIterations - 2);
          expect(post - this.pre).toBeLessThan(this.numIterations + 2);
          done();
        }.bind(this), this.pollSchedule * this.numIterations);

      });
    });

    xdescribe('#subscribeEveryN', function() {
      it('it takes an int N, a callback that is invoked every N scheduler iterations', function(done) {
        spyOn(this.test, 'call');
        this.pre = this.test.call.calls.count();
        this.scheduler.subscribeEveryN(this.cycles, this.test.call);
        setTimeout(function() {
          var post = this.test.call.calls.count();
          // error bounds of +/- 1
          expect(post - this.pre).toBeGreaterThan(this.numIterations/this.cycles - 2);
          expect(post - this.pre).toBeLessThan(this.numIterations/this.cycles + 2);
          done();
        }.bind(this), this.pollSchedule * this.numIterations);
      });
    });
  });

  describe('#scheduleImmediate', function() {
    it('invokes all subscribed callbacks immediately', function() {
      var numSubscribers = 20;

      spyOn(this.test, 'call');
      for(var i = 0; i < numSubscribers; i++) {
        this.scheduler.subscribe(this.test.call);
      }
      var pre = this.test.call.calls.count();
      this.scheduler.scheduleImmediate();
      expect(this.test.call.calls.count() - pre).toBe(numSubscribers);
    });
  });
});
<commit_msg>Removing ignore form some tests<commit_after>'use strict';

describe('scheduler', function() {
  beforeEach(function() {
    var pollSchedule = 25;
    module('deckApp', function($provide) {
      return $provide.constant('settings', {
        pollSchedule: pollSchedule,
      });
    });
    this.pollSchedule = pollSchedule;

    inject(function(scheduler) {
      this.scheduler = scheduler;
    });

    this.test = {
      call: angular.noop,
    };
  });

  describe('#get', function() {
    it('returns the underlying RxSubject', function() {
      spyOn(this.test, 'call');

      this.scheduler.subscribe(this.test.call);

      expect(this.test.call.calls.count()).toEqual(0);

      this.scheduler.get().onNext();

      expect(this.test.call.calls.count()).toEqual(1);
    });
  });

  describe('subscription methods', function() {
    beforeEach(function() {
      this.numIterations = 10;
      this.cycles = 2;
    });

    describe('#subscribe', function() {
      it('it takes a callback that is invoked at each iteration of the scheduler', function(done) {

        spyOn(this.test, 'call');
        this.pre = this.test.call.calls.count();
        this.scheduler.subscribe(this.test.call);
        setTimeout(function() {
          var post = this.test.call.calls.count();
          // error bounds of +/- 1
          expect(post - this.pre).toBeGreaterThan(this.numIterations - 2);
          expect(post - this.pre).toBeLessThan(this.numIterations + 2);
          done();
        }.bind(this), this.pollSchedule * this.numIterations);

      });
    });

    describe('#subscribeEveryN', function() {
      it('it takes an int N, a callback that is invoked every N scheduler iterations', function(done) {
        spyOn(this.test, 'call');
        this.pre = this.test.call.calls.count();
        this.scheduler.subscribeEveryN(this.cycles, this.test.call);
        setTimeout(function() {
          var post = this.test.call.calls.count();
          // error bounds of +/- 1
          expect(post - this.pre).toBeGreaterThan(this.numIterations/this.cycles - 2);
          expect(post - this.pre).toBeLessThan(this.numIterations/this.cycles + 2);
          done();
        }.bind(this), this.pollSchedule * this.numIterations);
      });
    });
  });

  describe('#scheduleImmediate', function() {
    it('invokes all subscribed callbacks immediately', function() {
      var numSubscribers = 20;

      spyOn(this.test, 'call');
      for(var i = 0; i < numSubscribers; i++) {
        this.scheduler.subscribe(this.test.call);
      }
      var pre = this.test.call.calls.count();
      this.scheduler.scheduleImmediate();
      expect(this.test.call.calls.count() - pre).toBe(numSubscribers);
    });
  });
});
<|endoftext|>


<commit_before>'use strict';

/* global describe, it, require */
'use strict';

var isArray = require('../../../src/utils/is_array.js');

describe('is_array.js public API', function() {
  it('should positively identify arrays', function() {
    expect(isArray([])).to.be.true;
    expect(isArray([
      []
    ])).to.be.true;
    expect(isArray([1, 2, 3])).to.be.true;
  });
  it('should negatively identify non-arrays', function() {
    expect(isArray({})).to.be.false;
    expect(isArray(true)).to.be.false;
    expect(isArray(5)).to.be.false;
  });
});
<commit_msg>Add <ES5 test for isArray<commit_after>'use strict';

/* global describe, it, require */
'use strict';

var isArray = require('../../../src/utils/is_array.js');

describe('is_array.js public API', function() {
  it('should positively identify arrays', function() {
    expect(isArray([])).to.be.true;
    expect(isArray([
      []
    ])).to.be.true;
    expect(isArray([1, 2, 3])).to.be.true;
  });
  it('should negatively identify non-arrays', function() {
    expect(isArray({})).to.be.false;
    expect(isArray(true)).to.be.false;
    expect(isArray(5)).to.be.false;
  });
  it('should positively identify arrays (< ES5)', function() {
    var _isArray = Array.isArray.bind({});
    Array.isArray = undefined;
    expect(isArray([])).to.be.true;
    expect(isArray([
      []
    ])).to.be.true;
    expect(isArray([1, 2, 3])).to.be.true;
    Array.isArray = _isArray;
  });
  it('should negatively identify non-arrays (< ES5)', function() {
    var _isArray = Array.isArray.bind({});
    Array.isArray = undefined;
    expect(isArray({})).to.be.false;
    expect(isArray(true)).to.be.false;
    expect(isArray(5)).to.be.false;
    Array.isArray = _isArray;
  });
});
<|endoftext|>


<commit_before>'use strict';
/**
 * Unit tests for SNS events.
 */

const getInstalledPath = require('get-installed-path');
const BbPromise = require('bluebird');
const chai = require('chai');
const sinon = require('sinon');
const AWSAlias = require('../../index');

const serverlessPath = getInstalledPath.sync('serverless', { local: true });
const AwsProvider = require(`${serverlessPath}/lib/plugins/aws/provider/awsProvider`);
const Serverless = require(`${serverlessPath}/lib/Serverless`);

chai.use(require('chai-as-promised'));
chai.use(require('sinon-chai'));
const expect = chai.expect;

describe('SNS Events', () => {
	let serverless;
	let options;
	let awsAlias;
	// Sinon and stubs for SLS CF access
	let sandbox;
	let logStub;

	before(() => {
		sandbox = sinon.sandbox.create();
	});

	beforeEach(() => {
		options = {
			alias: 'myAlias',
			stage: 'myStage',
			region: 'us-east-1',
		};
		serverless = new Serverless(options);
		serverless.setProvider('aws', new AwsProvider(serverless));
		serverless.cli = new serverless.classes.CLI(serverless);
		serverless.service.service = 'testService';
		serverless.service.provider.compiledCloudFormationAliasTemplate = {};
		awsAlias = new AWSAlias(serverless, options);

		// Disable logging
		logStub = sandbox.stub(serverless.cli, 'log');
		logStub.returns();
	});

	afterEach(() => {
		sandbox.restore();
	});

	describe('#aliasHandleSNSEvents()', () => {
		it('should succeed with standard template', () => {
			serverless.service.provider.compiledCloudFormationTemplate = require('../data/sls-stack-1.json');
			serverless.service.provider.compiledCloudFormationAliasTemplate = require('../data/alias-stack-1.json');
			return expect(awsAlias.aliasHandleSNSEvents({}, [], {})).to.be.fulfilled;
		});

		it('should move resources to alias stack', () => {
			const snsStack = serverless.service.provider.compiledCloudFormationTemplate = require('../data/sns-stack.json');
			const aliasStack = serverless.service.provider.compiledCloudFormationAliasTemplate = require('../data/alias-stack-1.json');
			return expect(awsAlias.aliasHandleSNSEvents({}, [], {})).to.be.fulfilled
			.then(() => BbPromise.all([
				expect(snsStack).to.not.have.property('SNSTopicSlstestprojecttopic'),
				expect(snsStack).to.not.have.property('Testfct1LambdaPermissionSlstestprojecttopicSNS'),
				expect(aliasStack).to.not.have.property('SNSTopicSlstestprojecttopic'),
				expect(aliasStack).to.not.have.property('Testfct1LambdaPermissionSlstestprojecttopicSNS'),
			]));
		});

		it('should replace function with alias reference', () => {
			const aliasStack = serverless.service.provider.compiledCloudFormationAliasTemplate = require('../data/alias-stack-1.json');
			return expect(awsAlias.aliasHandleSNSEvents({}, [], {})).to.be.fulfilled
			.then(() => BbPromise.all([
				expect(aliasStack).to.not.have.property('SNSTopicSlstestprojecttopic')
				.that.has.deep.property('Properties.Subscription[0].Endpoint')
				.that.deep.equals({ Ref: 'Testfct1Alias' }),
			]));
		});
	});
});
<commit_msg>Fixed unit tests<commit_after>'use strict';
/**
 * Unit tests for SNS events.
 */

const getInstalledPath = require('get-installed-path');
const BbPromise = require('bluebird');
const chai = require('chai');
const sinon = require('sinon');
const AWSAlias = require('../../index');

const serverlessPath = getInstalledPath.sync('serverless', { local: true });
const AwsProvider = require(`${serverlessPath}/lib/plugins/aws/provider/awsProvider`);
const Serverless = require(`${serverlessPath}/lib/Serverless`);

chai.use(require('chai-as-promised'));
chai.use(require('sinon-chai'));
const expect = chai.expect;

describe('SNS Events', () => {
	let serverless;
	let options;
	let awsAlias;
	// Sinon and stubs for SLS CF access
	let sandbox;
	let logStub;

	before(() => {
		sandbox = sinon.sandbox.create();
	});

	beforeEach(() => {
		options = {
			alias: 'myAlias',
			stage: 'myStage',
			region: 'us-east-1',
		};
		serverless = new Serverless(options);
		serverless.setProvider('aws', new AwsProvider(serverless));
		serverless.cli = new serverless.classes.CLI(serverless);
		serverless.service.service = 'testService';
		serverless.service.provider.compiledCloudFormationAliasTemplate = {};
		awsAlias = new AWSAlias(serverless, options);

		// Disable logging
		logStub = sandbox.stub(serverless.cli, 'log');
		logStub.returns();
	});

	afterEach(() => {
		sandbox.restore();
	});

	describe('#aliasHandleSNSEvents()', () => {
		it('should succeed with standard template', () => {
			serverless.service.provider.compiledCloudFormationTemplate = require('../data/sls-stack-1.json');
			serverless.service.provider.compiledCloudFormationAliasTemplate = require('../data/alias-stack-1.json');
			return expect(awsAlias.aliasHandleSNSEvents({}, [], {})).to.be.fulfilled;
		});

		it('should move resources to alias stack', () => {
			const snsStack = serverless.service.provider.compiledCloudFormationTemplate = require('../data/sns-stack.json');
			const aliasStack = serverless.service.provider.compiledCloudFormationAliasTemplate = require('../data/alias-stack-1.json');
			return expect(awsAlias.aliasHandleSNSEvents({}, [], {})).to.be.fulfilled
			.then(() => BbPromise.all([
				expect(snsStack).to.not.have.property('SNSTopicSlstestprojecttopic'),
				expect(snsStack).to.not.have.property('Testfct1LambdaPermissionSlstestprojecttopicSNS'),
				expect(aliasStack).to.not.have.property('SNSTopicSlstestprojecttopic'),
				expect(aliasStack).to.not.have.property('Testfct1LambdaPermissionSlstestprojecttopicSNS'),
			]));
		});

		it('should replace function with alias reference', () => {
			serverless.service.provider.compiledCloudFormationTemplate = require('../data/sns-stack.json');
			const aliasStack = serverless.service.provider.compiledCloudFormationAliasTemplate = require('../data/alias-stack-1.json');
			return expect(awsAlias.aliasHandleSNSEvents({}, [], {})).to.be.fulfilled
			.then(() => BbPromise.all([
				expect(aliasStack).to.not.have.property('SNSTopicSlstestprojecttopic')
				.that.has.deep.property('Properties.Subscription[0].Endpoint')
				.that.deep.equals({ Ref: 'Testfct1Alias' }),
			]));
		});
	});
});
<|endoftext|>


<commit_before>/* Copyright (c) 2018 e-soa Jacques Desodt, MIT License */
'use strict'

/* Prerequisites */
const processThen = require('../../process/then')
const testFunctions = require('../functions')

/* Test prerequisites */
const Code = require('code')
const Lab = require('lab', {timeout: testFunctions.timeout})
const lab = (exports.lab = Lab.script())
const after = lab.after
const describe = lab.describe
const it = lab.it
const expect = Code.expect

/* Backups functions before mock */
const backups = new Map()
backups.set(processThen, [
  ['replaceValuesForProperty', processThen.replaceValuesForProperty.bind({})]
])

describe('then replaceValues', function () {
  after((done) => {
    /* Restores the origin functions */
    for (var [key, values] of backups) {
      values.forEach(function (item) { key[item[0]] = item[1] })
    }
    done()
  })
  /* Bad arguments */
  it('no args', function (fin) {
    /* Fires the test */
    var newObject = processThen.replaceValues(null, null)
    /* Checks the result */
    expect(newObject).to.equal({})
    fin()
  })
  /* Object without properties */
  it('not an object', function (fin) {
    /* Fires the test */
    var newObject = processThen.replaceValues(null, 12345)
    /* Checks the result */
    expect(newObject).to.equal({})
    fin()
  })
  it('empty object', function (fin) {
    /* Fires the test */
    var newObject = processThen.replaceValues(null, {})
    /* Checks the result */
    expect(newObject).to.equal({})
    fin()
  })
  /* Object with properties */
  it('simple object', function (fin) {
    /* Mocks the process */
    var newValue = 'abc'
    mockReplaceValuesForProperty(newValue)
    /* Fires the test */
    var newObject = processThen.replaceValues(null, getObject())
    /* Checks the result */
    expect(newObject.role).to.equal(newValue)
    expect(newObject.name).to.equal(newValue)
    expect(newObject.data).to.equal(newValue)
    expect(Object.keys(newObject).length).to.equal(3)
    fin()
  })
})

/* ---------- MOCKS ---------- */

function mockReplaceValuesForProperty (newValue) {
  processThen.replaceValuesForProperty = function (entity, value) {
    return newValue
  }
  return false
}

/* ---------- FUNCTIONS ---------- */

function getObject () {
  return {
    role: 'my_%role%',
    name: '%name%',
    data: {
      id: '123',
      type: '%type%',
      entity: '%_entity%'
    }
  }
}
<commit_msg>This project has been moved to GitLab<commit_after><|endoftext|>


<commit_before>import AbstractApp from '../../src/abstract-app';

describe('App-Lifecycle', function () {
  beforeEach(function () {
    this.myApp = new AbstractApp();
  });

  describe('when starting the application', function () {
    beforeEach(function () {
      this.myApp.start();
    });

    it('should be successfully started', function () {
      expect(this.myApp._isRunning).to.equal(true);
    });

    describe('when the application has already been started', function () {
      it('should not start the app again', function () {
        this.myApp.start();
        // TODO:  Check needed here?
      });
    });

    describe('and stopping the application', function () {
      it('should stop the application', function () {
        this.myApp.stop();
        expect(this.myApp._isRunning).to.equal(false);
      });

      it('should NOT stop the application if the application has already been stopped', function () {
        this.myApp.stop();
        this.myApp.stop();
        // TODO:  Check needed here?
      });
    });
  });

  describe('when destroying an application', function () {
    beforeEach(function () {
      this.myApp.start();
    });

    it('should have isDestroyed() to return false PRIOR to destroying', function () {
      expect(this.myApp.isDestroyed()).to.equal(false);
    });

    it('should successfully be destroyed', function () {
      this.myApp.destroy();
      expect(this.myApp.isDestroyed()).to.equal(true);
    });

    describe('and restarting the destroyed application', function () {
      it('should throw an error', function () {
        this.myApp.destroy();
        expect(_.bind(function(){
          this.myApp.start();
        }, this)).to.throw('App has already been destroyed and cannot be used.');
      });
    });
  });

});
<commit_msg>Update app-lifecycle.spec<commit_after>import AbstractApp from '../../src/abstract-app';

describe('App-Lifecycle', function () {
  beforeEach(function () {
    this.beforeStartStub = this.sinon.stub();
    this.startStub = this.sinon.stub();
    this.beforeStopStub = this.sinon.stub();
    this.stopStub = this.sinon.stub();
    this.myApp = new AbstractApp();
    this.myApp.on('before:start', this.beforeStartStub);
    this.myApp.on('start', this.startStub);
    this.myApp.on('before:stop', this.beforeStopStub);
    this.myApp.on('stop', this.stopStub);
  });

  describe('when starting the application', function () {
    beforeEach(function () {
      this.myApp.start();
    });

    it('should trigger before:start event', function () {
      expect(this.beforeStartStub).to.have.been.calledOnce;
    });

    it('should trigger start event', function () {
      expect(this.startStub).to.have.been.calledOnce;
    });

    it('should be successfully started', function () {
      expect(this.myApp._isRunning).to.equal(true);
    });

    describe('when the application has already been started', function () {
      it('should not start the app again and not trigger before:start twice', function () {
        this.myApp.start();
        expect(this.beforeStartStub).to.have.not.been.calledTwice;
      });

      it('should not start the app again and not trigger start twice', function () {
        this.myApp.start();
        expect(this.startStub).to.have.not.been.calledTwice;
      });
    });

    describe('and stopping the application', function () {
      beforeEach(function() {
        this.myApp.stop();
      });

      it('should stop the application', function () {
        expect(this.myApp._isRunning).to.equal(false);
      });

      it('should call before:stop', function () {
        expect(this.beforeStopStub).to.have.been.calledOnce;
      });

      it('should call stop', function () {
        expect(this.stopStub).to.have.been.calledOnce;
      });

      it('should NOT stop the application if the application has already been stopped and not call before:stop twice', function () {
        this.myApp.stop();
        expect(this.beforeStopStub).to.have.not.been.calledTwice;
      });

      it('should NOT stop the application if the application has already been stopped and not call stop twice', function () {
        expect(this.stopStub).to.have.not.been.calledTwice;
      });
    });
  });

  describe('when destroying an application', function () {
    beforeEach(function () {
      this.myApp.start();
    });

    it('should have isDestroyed() to return false PRIOR to destroying', function () {
      expect(this.myApp.isDestroyed()).to.equal(false);
    });

    it('should successfully be destroyed', function () {
      this.myApp.destroy();
      expect(this.myApp.isDestroyed()).to.equal(true);
    });

    describe('and restarting the destroyed application', function () {
      it('should throw an error', function () {
        this.myApp.destroy();
        expect(_.bind(function(){
          this.myApp.start();
        }, this)).to.throw('App has already been destroyed and cannot be used.');
      });
    });
  });

});
<|endoftext|>