<commit_before>// External dependencies
var assert = require('assert'),
    should = require('should'),
    fs     = require('fs'),
    zlib = require('zlib');

// Test to see if dynamically created CSS is well-formed
describe('The dynamically concatenated and minified CSS...', function() {

    var handle = 'build/css/all.min.css';
    var file = zlib.gunzipSync(fs.readFileSync(handle));

    it('Should exist', function(done) {
        fs.stat(handle, function(err) {
            if (err) throw err;
            done();
        });
    });

    it('Should contain Bootstrap styles', function() {
        if (file.indexOf('Bootstrap') < 0) {
            throw Error('/css/all.min.css does not contain Bootstrap styles');
        }
    });

    it('Should contain Custom styles', function() {
        if (file.indexOf('Custom Styles') < 0) {
            throw Error('/css/all.min.css does not contain custom styles');
        }
    });

    it('Should contain Font Awesome styles', function() {
        if (file.indexOf('Font Awesome') < 0) {
            throw Error('/css/all.min.css does not contain Font Awesome styles');
        }
    });

});<commit_msg>Async CSS tests<commit_after>// External dependencies
var fs   = require('fs'),
    zlib = require('zlib');

// Test to see if dynamically created CSS is well-formed
describe('The dynamically concatenated and minified CSS...', function() {

    var handle = 'build/css/all.min.css';
    var buf = null;
    var str = '';

    it('Should exist', function(done) {
        fs.readFile(handle, function(err, data) {
            if (err) throw err;
            buf = data;
            done();
        });
    });

    it('Should be gzipped', function(done) {
        zlib.gunzip(buf, function(err, data) {
            if (err) throw err;
            str = data;
            done();
        });
    });

    it('Should contain Bootstrap styles', function() {
        str.indexOf('Bootstrap').should.not.equal(-1);
    });

    it('Should contain Custom styles', function() {
        str.indexOf('Custom Styles').should.not.equal(-1);
    });

    it('Should contain Font Awesome styles', function() {
        str.indexOf('Font Awesome').should.not.equal(-1);
    });

});<|endoftext|>


<commit_before>var tape = require('tape');
var mjAPI = require("../lib/main.js");

tape('CSS output', function(t) {
    t.plan(2);
    mjAPI.start();
    var tex = 'x';
    mjAPI.typeset({
        math: tex,
        format: "TeX",
        css: true
    }, function(data) {
        t.ok(data.css, 'css output while no other output');
    });
    mjAPI.typeset({
        math: tex,
        format: "TeX",
        css: true,
        svg: true
    }, function(data) {
        t.ok(data.css, 'css output with SVG output');
    });
});
<commit_msg>[test] css.js: check SVG output<commit_after>var tape = require('tape');
var mjAPI = require("../lib/main.js");

tape('CSS output', function(t) {
    t.plan(3);
    mjAPI.start();
    var tex = 'x';
    mjAPI.typeset({
        math: tex,
        format: "TeX",
        css: true
    }, function(data) {
        t.ok(data.css, 'css output while no other output');
    });
    mjAPI.typeset({
        math: tex,
        format: "TeX",
        css: true,
        svg: true
    }, function(data) {
        t.ok(data.css, 'css output created alongside SVG output');
        t.ok(data.svg, 'svg output is created');
    });
});
<|endoftext|>


<commit_before>'use strict';

const KBase = require('../bot/KBase');
const Utils = require('../../lib/utils/Utils');
const AppConfig = require('../../config/AppConfig');
const InputWrap = require('../bot/InputWrap');
const _ = require('lodash');

const newline = '\n';

const BotCommands = {
  isCommand: function(input) {
    let res;

    const cmds = BotCommands.cmdList.filter(c => {
      return (c === input.keyword);
    });

    const one = cmds[0];
    if (one) {
      res = true;
    } else {
      res = false;
      // Todo : raisedadead : commenting out the below for clean up later
      /*
      Utils.warn('isCommand', 'not command', input);
      Utils.warn('isCommand',
        '[ isCommand: ' + input.keyword + ' one: ' + one + ' res: ' + res );
      */
    }
    return res;
  },

  cbot: function(input, bot) {
    switch (input.params) {
      case 'version':
        return this.botversion(input, bot);
      case 'status':
        Utils.log('input', input);
        const status = this.botstatus(input, bot);
        Utils.clog('status', status);
        return status;
      default:
        return 'you called?';
    }
  },

  // very simple example function showing how to parse a message and respond
  // 'echo' is already a botCommand
  echo: function(input) {
    const username = input.message.model.fromUser.username;
    return '@' + username + ' said: ' + input.message.model.text.slice(4);
  },

  botversion: function() {
    return 'botVersion: ' + AppConfig.botVersion;
  },

  botstatus: function() {
    return 'All bot systems are go!  \n' + this.botversion() + newline +
      this.botenv() + newline + 'botname: ' + AppConfig.getBotName() + newline;
  },

  botenv: function() {
    return 'env: ' + AppConfig.serverEnv;
  },

  archive: function(input) {
    const roomName = input.message.room.name;
    const shortName = InputWrap.roomShortName(input);
    const roomUri = AppConfig.gitterHost + roomName + '/archives/';
    const timeStamp = Utils.timeStamp('yesterday');

    return 'Archives for **' + shortName + '**' + newline +
      '\n- [All Time](' + roomUri + 'all)' +
      '\n- [Yesterday](' + roomUri + timeStamp + ')';
  },

  init: function(bot) {
    // TODO - FIXME this is sketchy storing references like a global
    // called from the bot where we don't always have an instance
    BotCommands.bot = bot;
  },

  tooNoisy: function() {
    // if this.room.name
    return false;
  },

  // TODO - sort alphabetically
  rooms: function() {
    return '#### freeCodeCamp rooms:' +
    '\n:point_right: Here is a [list of our official chat rooms]' +
    '(https://forum.freecodecamp.com/t/' +
    'free-code-camp-official-chat-rooms/19390)';
  },

  find: function(input, bot) {
    const shortList = KBase.getTopicsAsList(input.params);

    bot.context = {
        state: 'finding',
        commands: shortList.commands
    };

    const str = 'find **' + input.params + '**\n' + shortList;
    bot.makeListOptions(str);
    return str;
  },

  commands: function() {
    return '## commands:\n- ' + BotCommands.cmdList.join('\n- ');
  },

  // TODO - FIXME this isn't working it seems
  // rejoin: function (input, bot) {
  //     clog('GBot', GBot);
  //     BotCommands.bot.scanRooms();
  //     return 'rejoined';
  // },

  music: function() {
    return '## Music!\n http://musare.com/';
  },

  announce: function(input) {
    const parts = input.params.split(' ');
    const roomName = parts[0];
    const text = parts.join(' ');
    this.bot.sayToRoom(text, roomName);
  },

  rollem: function(input) {
    const fromUser = '@' + input.message.model.fromUser.username;
    return fromUser + ' says enjoy!' +
      'https://www.youtube.com/watch?v=dQw4w9WgXcQ';
  },

  eightball: function(input) {
    const fromUser = '@' + input.message.model.fromUser.username;
    const replies = [
      'it is certain', 'it is decidedly so', 'without a doubt',
      'yes. Definitely', 'you may rely on it', 'as I see it, yes',
      'most likely', 'outlook good', 'yes', 'signs point to yes',
      'reply hazy try again', 'ask again later', 'better not tell you now',
      'cannot predict now', 'concentrate and ask again', 'don\'t count on it',
      'my reply is no', 'my sources say no', 'outlook not so good',
      'very doubtful'
    ];

    var reply = replies[Math.floor(Math.random() * replies.length)];
    return fromUser + ' :8ball: ' + reply + ' :sparkles:';
  },

  wiki: function() {
    return '#### freeCodeCamp Wiki:' +
    '\n:point_right: The freeCodeCamp wiki can be found on ' +
    '[our forum](https://forum.freecodecamp.com). ' +
    '\nPlease follow the link and search there.'
    ;
  }
};

// TODO - iterate and read all files in /cmds
const thanks = require('./cmds/thanks');

_.merge(BotCommands, thanks);

// aliases
BotCommands.explain = BotCommands.wiki;
BotCommands.bot = BotCommands.wiki;
BotCommands.hi = BotCommands.welcome;
BotCommands.index = BotCommands.topics;
BotCommands.thank = BotCommands.thanks;
BotCommands.log = BotCommands.archive;
BotCommands.archives = BotCommands.archive;

// TODO - some of these should be filtered/as private
BotCommands.cmdList = Object.keys(BotCommands);

module.exports = BotCommands;
<commit_msg>remove echo command<commit_after>'use strict';

const KBase = require('../bot/KBase');
const Utils = require('../../lib/utils/Utils');
const AppConfig = require('../../config/AppConfig');
const InputWrap = require('../bot/InputWrap');
const _ = require('lodash');

const newline = '\n';

const BotCommands = {
  isCommand: function(input) {
    let res;

    const cmds = BotCommands.cmdList.filter(c => {
      return (c === input.keyword);
    });

    const one = cmds[0];
    if (one) {
      res = true;
    } else {
      res = false;
      // Todo : raisedadead : commenting out the below for clean up later
      /*
      Utils.warn('isCommand', 'not command', input);
      Utils.warn('isCommand',
        '[ isCommand: ' + input.keyword + ' one: ' + one + ' res: ' + res );
      */
    }
    return res;
  },

  cbot: function(input, bot) {
    switch (input.params) {
      case 'version':
        return this.botversion(input, bot);
      case 'status':
        Utils.log('input', input);
        const status = this.botstatus(input, bot);
        Utils.clog('status', status);
        return status;
      default:
        return 'you called?';
    }
  },

  botversion: function() {
    return 'botVersion: ' + AppConfig.botVersion;
  },

  botstatus: function() {
    return 'All bot systems are go!  \n' + this.botversion() + newline +
      this.botenv() + newline + 'botname: ' + AppConfig.getBotName() + newline;
  },

  botenv: function() {
    return 'env: ' + AppConfig.serverEnv;
  },

  archive: function(input) {
    const roomName = input.message.room.name;
    const shortName = InputWrap.roomShortName(input);
    const roomUri = AppConfig.gitterHost + roomName + '/archives/';
    const timeStamp = Utils.timeStamp('yesterday');

    return 'Archives for **' + shortName + '**' + newline +
      '\n- [All Time](' + roomUri + 'all)' +
      '\n- [Yesterday](' + roomUri + timeStamp + ')';
  },

  init: function(bot) {
    // TODO - FIXME this is sketchy storing references like a global
    // called from the bot where we don't always have an instance
    BotCommands.bot = bot;
  },

  tooNoisy: function() {
    // if this.room.name
    return false;
  },

  // TODO - sort alphabetically
  rooms: function() {
    return '#### freeCodeCamp rooms:' +
    '\n:point_right: Here is a [list of our official chat rooms]' +
    '(https://forum.freecodecamp.com/t/' +
    'free-code-camp-official-chat-rooms/19390)';
  },

  find: function(input, bot) {
    const shortList = KBase.getTopicsAsList(input.params);

    bot.context = {
        state: 'finding',
        commands: shortList.commands
    };

    const str = 'find **' + input.params + '**\n' + shortList;
    bot.makeListOptions(str);
    return str;
  },

  commands: function() {
    return '## commands:\n- ' + BotCommands.cmdList.join('\n- ');
  },

  // TODO - FIXME this isn't working it seems
  // rejoin: function (input, bot) {
  //     clog('GBot', GBot);
  //     BotCommands.bot.scanRooms();
  //     return 'rejoined';
  // },

  music: function() {
    return '## Music!\n http://musare.com/';
  },

  announce: function(input) {
    const parts = input.params.split(' ');
    const roomName = parts[0];
    const text = parts.join(' ');
    this.bot.sayToRoom(text, roomName);
  },

  rollem: function(input) {
    const fromUser = '@' + input.message.model.fromUser.username;
    return fromUser + ' says enjoy!' +
      'https://www.youtube.com/watch?v=dQw4w9WgXcQ';
  },

  eightball: function(input) {
    const fromUser = '@' + input.message.model.fromUser.username;
    const replies = [
      'it is certain', 'it is decidedly so', 'without a doubt',
      'yes. Definitely', 'you may rely on it', 'as I see it, yes',
      'most likely', 'outlook good', 'yes', 'signs point to yes',
      'reply hazy try again', 'ask again later', 'better not tell you now',
      'cannot predict now', 'concentrate and ask again', 'don\'t count on it',
      'my reply is no', 'my sources say no', 'outlook not so good',
      'very doubtful'
    ];

    var reply = replies[Math.floor(Math.random() * replies.length)];
    return fromUser + ' :8ball: ' + reply + ' :sparkles:';
  },

  wiki: function() {
    return '#### freeCodeCamp Wiki:' +
    '\n:point_right: The freeCodeCamp wiki can be found on ' +
    '[our forum](https://forum.freecodecamp.com). ' +
    '\nPlease follow the link and search there.'
    ;
  }
};

// TODO - iterate and read all files in /cmds
const thanks = require('./cmds/thanks');

_.merge(BotCommands, thanks);

// aliases
BotCommands.explain = BotCommands.wiki;
BotCommands.bot = BotCommands.wiki;
BotCommands.hi = BotCommands.welcome;
BotCommands.index = BotCommands.topics;
BotCommands.thank = BotCommands.thanks;
BotCommands.log = BotCommands.archive;
BotCommands.archives = BotCommands.archive;

// TODO - some of these should be filtered/as private
BotCommands.cmdList = Object.keys(BotCommands);

module.exports = BotCommands;
<|endoftext|>


<commit_before>/* global describe, it */
"use strict";
var should = require('should');
var path = require('path');
var fs = require('fs');
var CSV = require('../lib/csv.js');

describe('CSV', function () {
    describe('stringify()', function () {
        it('should #1', function() {
            var str = CSV.stringify([0, 1, 2, 3]);
            str.should.equal('0,1,2,3\r\n');
        });
        it('should #2', function() {
            var str = CSV.stringify(['1', '2', '3']);
            str.should.equal('1,2,3\r\n');
        });
        it('should #3', function() {
            var str = CSV.stringify(['"1"', '2', '3']);
            str.should.equal('"""1""",2,3\r\n');
        });
        it('should #4', function() {
            var str = CSV.stringify(['1', '2', '3,4']);
            str.should.equal('1,2,"3,4"\r\n');
        });
        it('should #5', function() {
            var str = CSV.stringify();
            str.should.equal('\r\n');
        });
        it('should #5bis', function() {
            var str = CSV.stringify([]);
            str.should.equal('\r\n');
        });
        it('should #6', function() {
            var str = CSV.stringify('1234');
            str.should.equal('1234\r\n');
        });
        it('should #7', function() {
            var str = CSV.stringify(1234);
            str.should.equal('1234\r\n');
        });
        it('should #8', function() {
            var str = CSV.stringify("12,34");
            str.should.equal('"12,34"\r\n');
        });
        it('should #9', function() {
            var str = CSV.stringify({
                a: 1
                , b: 2
                , c: 3
                , d: 4
            });
            str.should.equal('1,2,3,4\r\n');
        });
        it('should #10', function() {
            var str = CSV.stringify(['a', 'b\nb', 'c']);
            str.should.equal('a,"b\nb",c\r\n');
        });
        it('should #11', function() {
            var str = CSV.stringify({
                a: 1
                , b: null
            });
            str.should.equal('1,\r\n');
        });
        it('should #12', function() {
            var str = CSV.stringify([[1, 2], [3, 4], [5, 6]]);
            str.should.equal('1,2\r\n3,4\r\n5,6\r\n');
        });
        it('should #13', function() {
            var header = ['one', 'two', 'three'];
            var line1 =  ['', 'l-two', 'l-three'];
            var headerCols = CSV.stringify(header).split(',').length;
            var line1Cols = CSV.stringify(line1).split(',').length;
            headerCols.should.equal(line1Cols);
        });
        it('should #14', function() {
            var str = CSV.stringify({
                a: null
                , b: ''
                , c: 1
            });
            str.should.equal(',,1\r\n');
        });
    });

    describe('fetch()', function () {
        it('should #1', function() {
            var obj = CSV.fetch("a,b,c");
            obj.should.eql(['a', 'b', 'c']);
        });
        it('should #2', function() {
            var obj = CSV.fetch('a ,\tb , c\n');
            obj.should.eql(['a ', '\tb ', ' c']);
        });
        it('should #3', function() {
            var obj = CSV.fetch('"a ","\tb "," c\n"');
            obj.should.eql(['a ', '\tb ', ' c\n']);
        });
        it('should #3', function() {
            var obj = CSV.fetch('"a" , "b"\t, "c" \n');
            obj.should.eql(['a', 'b', 'c']);
        });
        it('should #4', function() {
            var obj = CSV.fetch("a,b,c\nd,e");
            obj.should.eql(['a', 'b', 'c']);
        });
        it('should', function() {
            var obj = CSV.fetch('a,b,"c\nd",e');
            obj.should.eql(['a', 'b', 'c\nd', 'e']);
        });
        it('should #5', function() {
            var obj = CSV.fetch('a,b,"c\n');
            obj.should.eql(['a', 'b']);
        });
        it('should #6', function() {
            var obj = CSV.fetch('"a,a","b,b","c"');
            obj.should.eql(['a,a', 'b,b', 'c']);
        });
        it('should #7', function() {
            var obj = CSV.fetch('"a,a" ,  "b,b","c"');
            obj.should.eql(['a,a', 'b,b', 'c']);
        });
        it('should #8', function() {
            var obj = CSV.fetch('"a,a",,"c"');
            obj.should.eql(['a,a', '', 'c']);
        });
        it('should #9', function() {
            var obj = CSV.fetch("a'a;b;;c\nd,e,f,g", ';');
            obj.should.eql(["a'a", 'b', '', 'c']);
        });
        it('should #10', function() {
            var obj = CSV.fetch('a,b,c\r\n"d","e","f"');
            obj.should.eql(['a', 'b', 'c']);
        });
        it('should #11', function() {
            var obj = CSV.fetch('a,"b,b""b,b""b",c\r\nd,e,f');
            obj.should.eql(['a', 'b,b"b,b"b', 'c']);
        });
        it('should #12', function () {
            var obj = CSV.fetch('a,"b1,""b2""b3,b4""""",c\r\nd,e,f');
            obj.should.eql(['a', 'b1,"b2"b3,b4""', 'c']);
        });
        it('should #13', function () {
            var obj = CSV.fetch("a,\"b1,\"\"b2\"\"b3,b4\"\"\"\"b5\r\nb6\"\r\nc,d");
            obj.should.eql(['a', "b1,\"b2\"b3,b4\"\"b5\r\nb6"]);
        });
        it('should #14', function () {
            var obj = CSV.fetch("a,\"b1,\"\"b2\"\"b3,b4\"\"\"\"b5\nb6\" \t\r\nc,d");
            obj.should.eql(['a', "b1,\"b2\"b3,b4\"\"b5\nb6"]);
        });
        it('should #15', function () {
            var obj = CSV.fetch("a,\"b1,\"\"b2\"\"b3,b4\"\"\"\"b5\nb6\" ,c\r\n,d");
            obj.should.eql(['a', "b1,\"b2\"b3,b4\"\"b5\nb6", 'c']);
        });
        it('should #15', function () {
            var obj = CSV.fetch("a,\",b\",c\r\n,d");
            obj.should.eql(['a', ',b', 'c']);
        });
        it('should #16', function () {
            var obj = CSV.fetch('a,"b",c\r\na,"b""b",c');
            obj.should.eql(['a', 'b', 'c']);
        });
        it('should #17', function () {
            var obj = CSV.fetch('a,this "should" work,b');
            obj.should.eql(['a', 'this "should" work', 'b']);
        });
    });

    describe('forEach()', function () {
        it('should #1', function() {
            var i = 0;
            CSV.forEach('a,b,c\nd,e,f\ng,h,i', function(row, index) {
                index.should.equal(i++);
                if (index === 0) {
                    row.should.eql(['a', 'b', 'c']);
                }
                else if (index == 1) {
                    row.should.eql(['d', 'e', 'f']);
                }
                else if (index == 2) {
                    row.should.eql(['g', 'h', 'i']);
                }
            });
        });
        it('should #2', function() {
            var i = 0;
            CSV.forEach('a,b,c\nd,e,f\ng,h,i', ',', function(row, index) {
                index.should.equal(i++);
                if (index == 0) {
                    row.should.eql(['a', 'b', 'c']);
                }
                else if (index == 1) {
                    row.should.eql(['d', 'e', 'f']);
                }
                else if (index == 2) {
                    row.should.eql(['g', 'h', 'i']);
                }
            });
        });
        it('should #3', function() {
            var i = 0;
            CSV.forEach('a,b,c\nd,e,f\ng,h', ',', function(row, index) {
                index.should.equal(i++);
                if (index == 0) {
                    row.should.eql(['a', 'b', 'c']);
                }
                else if (index == 1) {
                    row.should.eql(['d', 'e', 'f']);
                }
                else if (index == 2) {
                    row.should.eql(['g', 'h']);
                }
            });
        });
    });

    describe('parse()', function () {
        it('should #1', function() {
            var obj = CSV.parse('a,b,c\nd,e,f\ng,h,i');
            obj[0].should.eql(['a', 'b', 'c']);
            obj[1].should.eql(['d', 'e', 'f']);
            obj[2].should.eql(['g', 'h', 'i']);
        });
        it('should #2', function () {
            var data = 'a,b,c,1,"hello ""world""",12,14'
            var cols = CSV.parse(data)[0]
            cols.length.should.equal(7)
            var expected = ['a', 'b', 'c', '1', 'hello "world"', '12', '14']
            JSON.stringify(cols).should.equal(JSON.stringify(expected))
        })
        it('should #3', function () {
            var data = 'a,b,c,1,"hello, ""world""",12,14'
            var cols = CSV.parse(data)[0]
            cols.length.should.equal(7)
            var expected = ['a', 'b', 'c', '1', 'hello, "world"', '12', '14']
            JSON.stringify(cols).should.equal(JSON.stringify(expected))
        });
        it('should #4', function() {
            var obj = CSV.parse('a;b;c\nd;e;f\ng;h;i');
            obj[0].should.eql(['a', 'b', 'c']);
            obj[1].should.eql(['d', 'e', 'f']);
        });
        it('should #5', function() {
            var obj = CSV.parse('a,b,c\nd,e,f\ng,h,i', ',,,,,,');
            obj[0].should.eql(['a', 'b', 'c']);
            obj[1].should.eql(['d', 'e', 'f']);
            obj[2].should.eql(['g', 'h', 'i']);
        });
        it('should #6', function() {
            var obj = CSV.parse('a,b,c\nd,e,f\ng,h,i', ',');
            obj[0].should.eql(['a', 'b', 'c']);
            obj[1].should.eql(['d', 'e', 'f']);
            obj[2].should.eql(['g', 'h', 'i']);
        });
    });

    describe('detect()', function () {
        it('should #1', function() {
            CSV.detect('a,b,c\nd,e,f\ng,h,i').should.equal(',');
            CSV.detect('a;b;c\nd;e;f\ng;h;i').should.equal(';');
            CSV.detect('a|b|c\nd|e|f\ng|h|i').should.equal('|');
            CSV.detect('a\tb\tc\nd\te\tf\ng\th\ti').should.equal('\t');
        });
    });

    describe('readAll()', function () {
        it('should #0', function() {
            CSV.readAll("A,B,C\nD,E,F", function(rows) {
                rows.should.includeEql(['A', 'B', 'C'])
                rows.should.includeEql(['D', 'E', 'F'])
            });
        });
        it('should #1', function() {
            CSV.readAll("A,B,C\nD,E,F\n", function(rows) {
                rows.should.includeEql(['A', 'B', 'C'])
                rows.should.includeEql(['D', 'E', 'F'])
            });
        });
        it('should #2', function() {
            CSV.readAll("A,B,C\nD,E,\"F\n", function(rows) {
                rows.should.includeEql(['A', 'B', 'C'])
                rows.should.not.includeEql(['D', 'E', 'F'])
            });
        });
        it('should #3', function() {
            CSV.readAll("A,B,C\nD,E", function(rows) {
                rows.should.includeEql(['A', 'B', 'C'])
                rows.should.includeEql(['D', 'E'])
            });
        });
    });

    describe('readChunk()', function () {
        it('should #1', function() {
            CSV.readChunk("A,B,C\nD,E,F", function(rows) {
                rows.should.includeEql(['A', 'B', 'C'])
                rows.should.not.includeEql(['D', 'E', 'F'])
            });
        });
        it('should #2', function() {
            CSV.readChunk("A,B,C\nD,E,\"F\n", function(rows) {
                rows.should.includeEql(['A', 'B', 'C'])
                rows.should.not.includeEql(['D', 'E', 'F'])
            });
        });
        it('should #3', function() {
            CSV.readChunk("A,B,C\nD,E", function(rows) {
                rows.should.includeEql(['A', 'B', 'C'])
                rows.should.not.includeEql(['D', 'E'])
            });
        });
    });

    describe('readStream()', function () {
        it('should #1', function() {
            var reader = fs.createReadStream(path.resolve(__dirname, './sample.csv'));
            var parser = CSV.createStream({ separator: ',' });
            var rows = [];
            parser.on('data', function(row) {
                rows.push(row);
            });
            parser.on('end', function() {
                should.deepEqual(rows, CSV.parse('1,2,"3,3",4\n1,2,3,4'))
            });
            reader.pipe(parser);
        });
        it('should #2', function() {
            var reader = fs.createReadStream(path.resolve(__dirname, './sample.csv'), {highWaterMark: 5});
            var parser = CSV.createStream({ separator: ',' });
            var rows = [];
            parser.on('data', function(row) {
                rows.push(row);
            });
            parser.on('end', function() {
                should.deepEqual(rows, CSV.parse('1,2,"3,3",4\n1,2,3,4'))
            });
            reader.pipe(parser);
        });
    });
});
<commit_msg>fix unit test<commit_after>/* global describe, it */
"use strict";
var should = require('should');
var path = require('path');
var fs = require('fs');
var CSV = require('../lib/csv.js');

describe('CSV', function () {
    describe('stringify()', function () {
        it('should #1', function() {
            var str = CSV.stringify([0, 1, 2, 3]);
            str.should.equal('0,1,2,3\r\n');
        });
        it('should #2', function() {
            var str = CSV.stringify(['1', '2', '3']);
            str.should.equal('1,2,3\r\n');
        });
        it('should #3', function() {
            var str = CSV.stringify(['"1"', '2', '3']);
            str.should.equal('"""1""",2,3\r\n');
        });
        it('should #4', function() {
            var str = CSV.stringify(['1', '2', '3,4']);
            str.should.equal('1,2,"3,4"\r\n');
        });
        it('should #5', function() {
            var str = CSV.stringify();
            str.should.equal('\r\n');
        });
        it('should #5bis', function() {
            var str = CSV.stringify([]);
            str.should.equal('\r\n');
        });
        it('should #6', function() {
            var str = CSV.stringify('1234');
            str.should.equal('1234\r\n');
        });
        it('should #7', function() {
            var str = CSV.stringify(1234);
            str.should.equal('1234\r\n');
        });
        it('should #8', function() {
            var str = CSV.stringify("12,34");
            str.should.equal('"12,34"\r\n');
        });
        it('should #9', function() {
            var str = CSV.stringify({
                a: 1
                , b: 2
                , c: 3
                , d: 4
            });
            str.should.equal('1,2,3,4\r\n');
        });
        it('should #10', function() {
            var str = CSV.stringify(['a', 'b\nb', 'c']);
            str.should.equal('a,"b\nb",c\r\n');
        });
        it('should #11', function() {
            var str = CSV.stringify({
                a: 1
                , b: null
            });
            str.should.equal('1,\r\n');
        });
        it('should #12', function() {
            var str = CSV.stringify([[1, 2], [3, 4], [5, 6]]);
            str.should.equal('1,2\r\n3,4\r\n5,6\r\n');
        });
        it('should #13', function() {
            var header = ['one', 'two', 'three'];
            var line1 =  ['', 'l-two', 'l-three'];
            var headerCols = CSV.stringify(header).split(',').length;
            var line1Cols = CSV.stringify(line1).split(',').length;
            headerCols.should.equal(line1Cols);
        });
        it('should #14', function() {
            var str = CSV.stringify({
                a: null
                , b: ''
                , c: 1
            });
            str.should.equal(',,1\r\n');
        });
    });

    describe('fetch()', function () {
        it('should #1', function() {
            var obj = CSV.fetch("a,b,c");
            obj.should.eql(['a', 'b', 'c']);
        });
        it('should #2', function() {
            var obj = CSV.fetch('a ,\tb , c\n');
            obj.should.eql(['a ', '\tb ', ' c']);
        });
        it('should #3', function() {
            var obj = CSV.fetch('"a ","\tb "," c\n"');
            obj.should.eql(['a ', '\tb ', ' c\n']);
        });
        it('should #3', function() {
            var obj = CSV.fetch('"a" , "b"\t, "c" \n');
            obj.should.eql(['a', 'b', 'c']);
        });
        it('should #4', function() {
            var obj = CSV.fetch("a,b,c\nd,e");
            obj.should.eql(['a', 'b', 'c']);
        });
        it('should', function() {
            var obj = CSV.fetch('a,b,"c\nd",e');
            obj.should.eql(['a', 'b', 'c\nd', 'e']);
        });
        it('should #5', function() {
            var obj = CSV.fetch('a,b,"c\n');
            obj.should.eql(['a', 'b']);
        });
        it('should #6', function() {
            var obj = CSV.fetch('"a,a","b,b","c"');
            obj.should.eql(['a,a', 'b,b', 'c']);
        });
        it('should #7', function() {
            var obj = CSV.fetch('"a,a" ,  "b,b","c"');
            obj.should.eql(['a,a', 'b,b', 'c']);
        });
        it('should #8', function() {
            var obj = CSV.fetch('"a,a",,"c"');
            obj.should.eql(['a,a', '', 'c']);
        });
        it('should #9', function() {
            var obj = CSV.fetch("a'a;b;;c\nd,e,f,g", ';');
            obj.should.eql(["a'a", 'b', '', 'c']);
        });
        it('should #10', function() {
            var obj = CSV.fetch('a,b,c\r\n"d","e","f"');
            obj.should.eql(['a', 'b', 'c']);
        });
        it('should #11', function() {
            var obj = CSV.fetch('a,"b,b""b,b""b",c\r\nd,e,f');
            obj.should.eql(['a', 'b,b"b,b"b', 'c']);
        });
        it('should #12', function () {
            var obj = CSV.fetch('a,"b1,""b2""b3,b4""""",c\r\nd,e,f');
            obj.should.eql(['a', 'b1,"b2"b3,b4""', 'c']);
        });
        it('should #13', function () {
            var obj = CSV.fetch("a,\"b1,\"\"b2\"\"b3,b4\"\"\"\"b5\r\nb6\"\r\nc,d");
            obj.should.eql(['a', "b1,\"b2\"b3,b4\"\"b5\r\nb6"]);
        });
        it('should #14', function () {
            var obj = CSV.fetch("a,\"b1,\"\"b2\"\"b3,b4\"\"\"\"b5\nb6\" \t\r\nc,d");
            obj.should.eql(['a', "b1,\"b2\"b3,b4\"\"b5\nb6"]);
        });
        it('should #15', function () {
            var obj = CSV.fetch("a,\"b1,\"\"b2\"\"b3,b4\"\"\"\"b5\nb6\" ,c\r\n,d");
            obj.should.eql(['a', "b1,\"b2\"b3,b4\"\"b5\nb6", 'c']);
        });
        it('should #15', function () {
            var obj = CSV.fetch("a,\",b\",c\r\n,d");
            obj.should.eql(['a', ',b', 'c']);
        });
        it('should #16', function () {
            var obj = CSV.fetch('a,"b",c\r\na,"b""b",c');
            obj.should.eql(['a', 'b', 'c']);
        });
        it('should #17', function () {
            var obj = CSV.fetch('a,this "should" work,b');
            obj.should.eql(['a', 'this "should" work', 'b']);
        });
    });

    describe('forEach()', function () {
        it('should #1', function() {
            var i = 0;
            CSV.forEach('a,b,c\nd,e,f\ng,h,i', function(row, index) {
                index.should.equal(i++);
                if (index === 0) {
                    row.should.eql(['a', 'b', 'c']);
                }
                else if (index == 1) {
                    row.should.eql(['d', 'e', 'f']);
                }
                else if (index == 2) {
                    row.should.eql(['g', 'h', 'i']);
                }
            });
        });
        it('should #2', function() {
            var i = 0;
            CSV.forEach('a,b,c\nd,e,f\ng,h,i', ',', function(row, index) {
                index.should.equal(i++);
                if (index == 0) {
                    row.should.eql(['a', 'b', 'c']);
                }
                else if (index == 1) {
                    row.should.eql(['d', 'e', 'f']);
                }
                else if (index == 2) {
                    row.should.eql(['g', 'h', 'i']);
                }
            });
        });
        it('should #3', function() {
            var i = 0;
            CSV.forEach('a,b,c\nd,e,f\ng,h', ',', function(row, index) {
                index.should.equal(i++);
                if (index == 0) {
                    row.should.eql(['a', 'b', 'c']);
                }
                else if (index == 1) {
                    row.should.eql(['d', 'e', 'f']);
                }
                else if (index == 2) {
                    row.should.eql(['g', 'h']);
                }
            });
        });
    });

    describe('parse()', function () {
        it('should #1', function() {
            var obj = CSV.parse('a,b,c\nd,e,f\ng,h,i');
            obj[0].should.eql(['a', 'b', 'c']);
            obj[1].should.eql(['d', 'e', 'f']);
            obj[2].should.eql(['g', 'h', 'i']);
        });
        it('should #2', function () {
            var data = 'a,b,c,1,"hello ""world""",12,14'
            var cols = CSV.parse(data)[0]
            cols.length.should.equal(7)
            var expected = ['a', 'b', 'c', '1', 'hello "world"', '12', '14']
            JSON.stringify(cols).should.equal(JSON.stringify(expected))
        })
        it('should #3', function () {
            var data = 'a,b,c,1,"hello, ""world""",12,14'
            var cols = CSV.parse(data)[0]
            cols.length.should.equal(7)
            var expected = ['a', 'b', 'c', '1', 'hello, "world"', '12', '14']
            JSON.stringify(cols).should.equal(JSON.stringify(expected))
        });
        it('should #4', function() {
            var obj = CSV.parse('a;b;c\nd;e;f\ng;h;i');
            obj[0].should.eql(['a', 'b', 'c']);
            obj[1].should.eql(['d', 'e', 'f']);
        });
        it('should #5', function() {
            var obj = CSV.parse('a,b,c\nd,e,f\ng,h,i', ',,,,,,');
            obj[0].should.eql(['a', 'b', 'c']);
            obj[1].should.eql(['d', 'e', 'f']);
            obj[2].should.eql(['g', 'h', 'i']);
        });
        it('should #6', function() {
            var obj = CSV.parse('a,b,c\nd,e,f\ng,h,i', ',');
            obj[0].should.eql(['a', 'b', 'c']);
            obj[1].should.eql(['d', 'e', 'f']);
            obj[2].should.eql(['g', 'h', 'i']);
        });
    });

    describe('detect()', function () {
        it('should #1', function() {
            CSV.detect('a,b,c\nd,e,f\ng,h,i').should.equal(',');
            CSV.detect('a;b;c\nd;e;f\ng;h;i').should.equal(';');
            CSV.detect('a|b|c\nd|e|f\ng|h|i').should.equal('|');
            CSV.detect('a\tb\tc\nd\te\tf\ng\th\ti').should.equal('\t');
        });
    });

    describe('readAll()', function () {
        it('should #0', function() {
            CSV.readAll("A,B,C\nD,E,F", function(rows) {
                rows.should.containEql(['A', 'B', 'C'])
                rows.should.containEql(['D', 'E', 'F'])
            });
        });
        it('should #1', function() {
            CSV.readAll("A,B,C\nD,E,F\n", function(rows) {
                rows.should.containEql(['A', 'B', 'C'])
                rows.should.containEql(['D', 'E', 'F'])
            });
        });
        it('should #2', function() {
            CSV.readAll("A,B,C\nD,E,\"F\n", function(rows) {
                rows.should.containEql(['A', 'B', 'C'])
                rows.should.not.containEql(['D', 'E', 'F'])
            });
        });
        it('should #3', function() {
            CSV.readAll("A,B,C\nD,E", function(rows) {
                rows.should.containEql(['A', 'B', 'C'])
                rows.should.containEql(['D', 'E'])
            });
        });
    });

    describe('readChunk()', function () {
        it('should #1', function() {
            CSV.readChunk("A,B,C\nD,E,F", function(rows) {
                rows.should.containEql(['A', 'B', 'C'])
                rows.should.not.containEql(['D', 'E', 'F'])
            });
        });
        it('should #2', function() {
            CSV.readChunk("A,B,C\nD,E,\"F\n", function(rows) {
                rows.should.containEql(['A', 'B', 'C'])
                rows.should.not.containEql(['D', 'E', 'F'])
            });
        });
        it('should #3', function() {
            CSV.readChunk("A,B,C\nD,E", function(rows) {
                rows.should.containEql(['A', 'B', 'C'])
                rows.should.not.containEql(['D', 'E'])
            });
        });
    });

    describe('readStream()', function () {
        it('should #1', function() {
            var reader = fs.createReadStream(path.resolve(__dirname, './sample.csv'));
            var parser = CSV.createStream({ separator: ',' });
            var rows = [];
            parser.on('data', function(row) {
                rows.push(row);
            });
            parser.on('end', function() {
                should.deepEqual(rows, CSV.parse('1,2,"3,3",4\n1,2,3,4'))
            });
            reader.pipe(parser);
        });
        it('should #2', function() {
            var reader = fs.createReadStream(path.resolve(__dirname, './sample.csv'), {highWaterMark: 5});
            var parser = CSV.createStream({ separator: ',' });
            var rows = [];
            parser.on('data', function(row) {
                rows.push(row);
            });
            parser.on('end', function() {
                should.deepEqual(rows, CSV.parse('1,2,"3,3",4\n1,2,3,4'))
            });
            reader.pipe(parser);
        });
    });
});
<|endoftext|>


<commit_before>var assert = require('assert');
var ift = require('../library/ift');
var Transport = require('../library/base/transport');
var util = require('./util');

describe('ift', function() {
  var createIframe = sinon.stub(), _createIframe;

  // Hook into ParentTransport#_createIframe to attach a `code` query param
  // containing a raw function to execute on the child page for a given test.
  _createIframe = ift.ParentTransport.prototype._createIframe;
  function stubChild(code) {
    createIframe = sinon.stub(ift.ParentTransport.prototype, '_createIframe', function(uri) {
      return _createIframe.call(this, uri + '?code=' + encodeURIComponent(code));
    });
  }

  function dispatchMessageEvent(data, origin) {
    util.dispatchEvent(window, 'message', {
      data: data,
      origin: origin
    }, 'MessageEvent', ['data', 'origin']);
  }

  describe('Transport', function() {
    it("ignores 'message' events from non-targeted origins", function() {
      var incoming = sinon.stub();
      var transport = new Transport(['http://origin1']);
      transport.on('incoming', incoming);
      dispatchMessageEvent('data', 'http://origin1');
      sinon.assert.calledOnce(incoming);
      dispatchMessageEvent('data', 'http://origin2');
      sinon.assert.calledOnce(incoming);
    });

    describe('#destroy', function() {
      it("stops listening for 'message'", function() {
        var transport = new Transport(['http://origin']);
        var incoming = sinon.stub();
        transport.on('incoming', incoming);
        dispatchMessageEvent('data', 'http://origin');
        sinon.assert.calledOnce(incoming);
        transport.destroy();
        dispatchMessageEvent('data', 'http://origin');
        sinon.assert.calledOnce(incoming);
      });

      it("clears out event listeners", function() {
        var transport = new Transport(['http://origin']);
        var incoming = sinon.stub();
        transport.on('incoming', incoming);
        transport.trigger('incoming');
        sinon.assert.calledOnce(incoming);
        transport.destroy();
        transport.trigger('incoming');
        sinon.assert.calledOnce(incoming);
      });
    });
  });

  describe('ParentTransport', function() {
    it("creates an iframe from childOrigin and childPath", function() {
      var appendChild = sinon.stub(document.body, 'appendChild');
      var transport = new ift.ParentTransport('http://origin', '/path');
      assert.strictEqual(transport.iframe.src, 'http://origin/path');
      appendChild.restore();
    });

    it("creates an iframe not visible on the page", function() {
      var transport = new ift.ParentTransport(CHILD_ORIGIN, CHILD_PATH);
      assert(transport.iframe.offsetTop < 100);
      assert.strictEqual(transport.iframe.border, 0);
      assert.strictEqual(transport.iframe.frameBorder, '0');
    });

    describe('#ready', function() {
      var appendChild, transport, onReady;

      beforeEach(function() {
        appendChild = sinon.stub(document.body, 'appendChild');
        transport = new ift.ParentTransport('http://origin', '/path');
        onReady = sinon.stub();
      });

      afterEach(function() {
        appendChild.restore();
      });

      it("invokes onReady once child sends 'ready' postMessage", function() {
        transport.ready(onReady);
        sinon.assert.notCalled(onReady);
        dispatchMessageEvent('ready', 'http://origin');
        sinon.assert.calledOnce(onReady);
        sinon.assert.calledWith(onReady, transport);
      });

      it("only invokes onReady once", function() {
        transport.ready(onReady);
        sinon.assert.notCalled(onReady);
        dispatchMessageEvent('ready', 'http://origin');
        sinon.assert.calledOnce(onReady);
        dispatchMessageEvent('ready', 'http://origin');
        sinon.assert.calledOnce(onReady);
        transport.trigger('ready');
        sinon.assert.calledOnce(onReady);
      });

      it("fires immediately if transport is already ready", function() {
        dispatchMessageEvent('ready', 'http://origin');
        transport.ready(onReady);
        sinon.assert.calledOnce(onReady);
      });
    });

    describe('#send', function() {
      it("calls postMessage on the iframe with message and childOrigin", function() {
        var transport = new ift.ParentTransport(CHILD_ORIGIN, CHILD_PATH);
        var postMessage = sinon.stub(transport.iframe.contentWindow, 'postMessage');
        transport.send('test');
        sinon.assert.calledOnce(postMessage);
        sinon.assert.calledWith(postMessage, 'test', CHILD_ORIGIN);
      });
    });

    describe('#destroy', function() {
      it("removes iframe from the dom", function() {
        var transport = new ift.ParentTransport(CHILD_ORIGIN, CHILD_PATH);
        assert(transport.iframe.parentNode);
        transport.destroy();
        assert.strictEqual(transport.iframe.parentNode, null);
      });
    });
  });
});
<commit_msg>Test for ChildTransport<commit_after>var assert = require('assert');
var ift = require('../library/ift');
var Transport = require('../library/base/transport');
var util = require('./util');

describe('ift', function() {
  var createIframe = sinon.stub(), _createIframe;

  // Hook into ParentTransport#_createIframe to attach a `code` query param
  // containing a raw function to execute on the child page for a given test.
  _createIframe = ift.ParentTransport.prototype._createIframe;
  function stubChild(code) {
    createIframe = sinon.stub(ift.ParentTransport.prototype, '_createIframe', function(uri) {
      return _createIframe.call(this, uri + '?code=' + encodeURIComponent(code));
    });
  }

  function dispatchMessageEvent(data, origin) {
    util.dispatchEvent(window, 'message', {
      data: data,
      origin: origin
    }, 'MessageEvent', ['data', 'origin']);
  }

  describe('Transport', function() {
    it("ignores 'message' events from non-targeted origins", function() {
      var incoming = sinon.stub();
      var transport = new Transport(['http://origin1']);
      transport.on('incoming', incoming);
      dispatchMessageEvent('data', 'http://origin1');
      sinon.assert.calledOnce(incoming);
      dispatchMessageEvent('data', 'http://origin2');
      sinon.assert.calledOnce(incoming);
    });

    describe('#destroy', function() {
      it("stops listening for 'message'", function() {
        var transport = new Transport(['http://origin']);
        var incoming = sinon.stub();
        transport.on('incoming', incoming);
        dispatchMessageEvent('data', 'http://origin');
        sinon.assert.calledOnce(incoming);
        transport.destroy();
        dispatchMessageEvent('data', 'http://origin');
        sinon.assert.calledOnce(incoming);
      });

      it("clears out event listeners", function() {
        var transport = new Transport(['http://origin']);
        var incoming = sinon.stub();
        transport.on('incoming', incoming);
        transport.trigger('incoming');
        sinon.assert.calledOnce(incoming);
        transport.destroy();
        transport.trigger('incoming');
        sinon.assert.calledOnce(incoming);
      });
    });
  });

  describe('ParentTransport', function() {
    it("creates an iframe from childOrigin and childPath", function() {
      var appendChild = sinon.stub(document.body, 'appendChild');
      var transport = new ift.ParentTransport('http://origin', '/path');
      assert.strictEqual(transport.iframe.src, 'http://origin/path');
      appendChild.restore();
    });

    it("creates an iframe not visible on the page", function() {
      var transport = new ift.ParentTransport(CHILD_ORIGIN, CHILD_PATH);
      assert(transport.iframe.offsetTop < 100);
      assert.strictEqual(transport.iframe.border, 0);
      assert.strictEqual(transport.iframe.frameBorder, '0');
    });

    describe('#ready', function() {
      var appendChild, transport, onReady;

      beforeEach(function() {
        appendChild = sinon.stub(document.body, 'appendChild');
        transport = new ift.ParentTransport('http://origin', '/path');
        onReady = sinon.stub();
      });

      afterEach(function() {
        appendChild.restore();
      });

      it("invokes onReady once child sends 'ready' postMessage", function() {
        transport.ready(onReady);
        sinon.assert.notCalled(onReady);
        dispatchMessageEvent('ready', 'http://origin');
        sinon.assert.calledOnce(onReady);
        sinon.assert.calledWith(onReady, transport);
      });

      it("only invokes onReady once", function() {
        transport.ready(onReady);
        sinon.assert.notCalled(onReady);
        dispatchMessageEvent('ready', 'http://origin');
        sinon.assert.calledOnce(onReady);
        dispatchMessageEvent('ready', 'http://origin');
        sinon.assert.calledOnce(onReady);
        transport.trigger('ready');
        sinon.assert.calledOnce(onReady);
      });

      it("fires immediately if transport is already ready", function() {
        dispatchMessageEvent('ready', 'http://origin');
        transport.ready(onReady);
        sinon.assert.calledOnce(onReady);
      });
    });

    describe('#send', function() {
      it("calls postMessage on the iframe with message and childOrigin", function() {
        var transport = new ift.ParentTransport(CHILD_ORIGIN, CHILD_PATH);
        var postMessage = sinon.stub(transport.iframe.contentWindow, 'postMessage');
        transport.send('test');
        sinon.assert.calledOnce(postMessage);
        sinon.assert.calledWith(postMessage, 'test', CHILD_ORIGIN);
        postMessage.restore();
      });
    });

    describe('#destroy', function() {
      it("removes iframe from the dom", function() {
        var transport = new ift.ParentTransport(CHILD_ORIGIN, CHILD_PATH);
        assert(transport.iframe.parentNode);
        transport.destroy();
        assert.strictEqual(transport.iframe.parentNode, null);
      });
    });
  });

  describe('ChildTransport', function() {
    it("sends 'ready' message on instantiation", function() {
      var parent = window.parent;
      window.parent = {
        postMessage: sinon.stub()
      };
      var transport = new ift.ChildTransport(['http://origin']);
      sinon.assert.calledOnce(window.parent.postMessage);
      sinon.assert.calledWith(window.parent.postMessage, 'ready', '*');
      window.parent = parent;
    });
  });
});
<|endoftext|>


<commit_before>/* Tests for reactor.js */

var expect = require('chai').expect;
var rnr = require('../dist/rnr.cjs.js');

describe('Reactor', function() {

	describe('cr()', function() {

		var a = rnr.cr();

		it('should return a Reactor instance', function() {

			expect(a).to.be.an.instanceof(rnr.Reactor);
		});

		it('should have a value of undefined when no initial value given', function() {

			expect(a.value).to.be.undefined;
		});

		it('should have the given initial value after creation', function() {

			a = rnr.cr(1);

			expect(a.value).to.equal(1);
		});

		it('should only take a function as param thenfn', function() {

			var goodfn = function() {
				rnr.cr(undefined, function(){});
			};

			var badfn = function() {
				rnr.cr(undefined, 1);
			};

			expect(goodfn).to.not.throw(Error);

			expect(badfn).to.throw(Error);
		});

		it('should only take a function as param finalfn', function() {

			var goodfn = function() {
				rnr.cr(undefined, function(){}, function(){});
			};

			var badfn = function() {
				rnr.cr(undefined, function(){}, 1);
			};

			expect(goodfn).to.not.throw(Error);

			expect(badfn).to.throw(Error);
		});

	});

	describe('set()', function() {

		it('should update the value when set');

		it('should update if value is different from previous');

		it('should not update if value is the same as previous');

		it('should update the value with the output of thenfn');

		it('should not run thenfn when the value is undefined');

	});

	describe('then()', function() {

		it('should return a new Reactor instance');

		it('should update children when parent set');

		it('should run thenfn when parent updated');

		it('should not run thenfn when parent passes undefined');

	});

	describe.skip('finally()', function(){});

	describe.skip('cancel()', function(){});

	describe.skip('persist()', function(){});

	describe.skip('attach()', function(){});

	describe.skip('detach()', function(){});

	describe.skip('clear()', function(){});

	describe.skip('crAny()', function(){});

	describe.skip('crAll()', function(){});
});
<commit_msg>First batch of tests complete and passing<commit_after>/* Tests for reactor.js */

var expect = require('chai').expect;
var rnr = require('../dist/rnr.cjs.js');

describe('Reactor', function() {

	describe('cr()', function() {

		var a = rnr.cr();

		it('should return a Reactor instance', function() {

			expect(a).to.be.an.instanceof(rnr.Reactor);
		});

		it('should have a value of undefined when no initial value given', function() {

			expect(a.value).to.be.undefined;
		});

		it('should have the given initial value after creation', function() {

			a = rnr.cr(1);

			expect(a.value).to.equal(1);
		});

		it('should be active after creation', function() {

			expect(a.done).to.be.false;
		});

		it('should only take a function as param thenfn', function() {

			var goodfn = function() {
				rnr.cr(undefined, function(){});
			};

			var badfn = function() {
				rnr.cr(undefined, 1);
			};

			expect(goodfn).to.not.throw(Error);

			expect(badfn).to.throw(Error);
		});

		it('should only take a function as param finalfn', function() {

			var goodfn = function() {
				rnr.cr(undefined, function(){}, function(){});
			};

			var badfn = function() {
				rnr.cr(undefined, function(){}, 1);
			};

			expect(goodfn).to.not.throw(Error);

			expect(badfn).to.throw(Error);
		});

	});

	describe('set()', function() {

		var a, b, c;
		var counter = 0;

		it('should update the value when set', function() {

			a = rnr.cr();

			expect(a.value).to.be.undefined;

			a.set(1);

			expect(a.value).to.equal(1);
		});

		it('should update the value each time it is set', function() {

			a.set(2);

			expect(a.value).to.equal(2);

			a.set('a');

			expect(a.value).to.equal('a');
		});

		it('should not run thenfn when initial value is undefined', function() {

			b = rnr.cr(undefined, function(x) {
				counter++;
				return x + 1;
			});

			expect(counter).to.equal(0);
		});

		it('should run thenfn when updated', function() {

			b.set(0);

			expect(counter).to.equal(1);
		});

		it('should update the value with the output of thenfn', function() {

			b.set(1);

			expect(b.value).to.equal(2);
		});

		it('should not run thenfn when the passed value is undefined', function() {

			var tmpcount = counter;

			b.set(undefined);

			expect(counter).to.equal(tmpcount);

		});

		it('should update with passed value if thenfn returns undefined', function() {

			c = rnr.cr(0, function() {
				counter++;
			});

			c.set(1);

			expect(c.value).to.equal(1);
		});

	});

	describe('then()', function() {

		var counter = 0;
		var a = rnr.cr(1);
		var b = a.then();
		var c = a.then(function(x) {
			counter++;
			return x + 1;
		});

		it('should return a new Reactor instance', function() {

			expect(b).to.be.an.instanceof(rnr.Reactor);

			expect(c).to.be.an.instanceof(rnr.Reactor);
		});

		it('should be in its parent\'s child set', function() {

			var children = a.children;

			expect(children).to.include(b);

			expect(children).to.include(c);
		});

		it('should have its parent\'s current value if no thenfn given', function() {

			expect(b.value).to.equal(a.value);
		});

		it('should have the result of thenfn called with its parent\'s current value', function () {

			expect(c.value).to.equal(a.value + 1);
		});

		it('should be updated when its parent is set to a new value', function() {

			var tmpvalue = c.value;

			a.set(2);

			expect(c.value).to.not.equal(tmpvalue);

			expect(c.value).to.equal(a.value + 1);
		});

		it('should be updated only if its parent\'s new value differs from previous', function() {

			var tmpcount = counter;
			var tmpvalue = a.value;

			a.set(tmpvalue);

			expect(counter).to.equal(tmpcount);
		});

	});

	describe.skip('cancel()', function(){});

	describe.skip('finally()', function(){});

	describe.skip('persist()', function(){});

	describe.skip('attach()', function(){});

	describe.skip('detach()', function(){});

	describe.skip('clear()', function(){});

	describe.skip('crAny()', function(){});

	describe.skip('crAll()', function(){});
});
<|endoftext|>


<commit_before>'use strict';

var logFormat = require('../');
var path = require('path');
var map = ['createdAt', 'origin', 'xForwardFor', 'referrer', 'country', 'city',
           'latitude|number', 'longitude|number', 'query|url', 'userAgent', 'arr|array', transform];
var separator = '•-•';
var src = path.join(__dirname, './log');
var dist = path.join(__dirname, './log.json');
var removeSrc = false;
var configure = {map, separator, src, dist, removeSrc};

var the1stobj = {
  "createdAt": "2015-11-14T23:59:14+08:00",
  "origin": "223.104.14.184",
  "xForwardFor": "-",
  "referrer": "http://opensite.ele.me/place/ww24pej69znn",
  "country": "CN",
  "city": "-",
  "latitude": 35,
  "longitude": 105,
  "query": { "test": "1st" },
  "userAgent": "Mozilla/5.0 (Linux; Android 4.4.4; m1 note Build/KTU84P) AppleWebKit/537.36 (KHTML, like Gecko) Version/4.0 Chrome/33.0.0.0 Mobile Safari/537.36 Proxy/cootekservice Proxy/cootekservice",
  "arr": [ "a", "b", "c", "d" ],
  "transformed": "fortestonly"
};

logFormat(configure, ret => {
  if(!ret) console.log('✓ it\'s an empty file');
  if(ret) console.log(`✓  JSON is generated: ${ret}`);

  // run test
  test(ret);
});

function transform(text) {
  var value= '';
  var name = 'transformed';
  if(text) value = text.toLowerCase();
  return {name, value};
}

function test(path) {
  var json = require(path);
  var obj = json[0];
  var keys = Object.keys(obj);
  var arr = [];
  var fail = 0;

  // parse keys
  keys = map.map((item, i) => {
    var name = kv(item, obj[item], i);
    if(name.directive) arr[i] = name.directive;
    return name.name || name;
  });

  // test map
  keys.forEach((item, i) => {
    if(keys.indexOf(item) !== -1) {
      if(
        the1stobj[item] === obj[item] ||
        (obj[item] && typeof obj[item] === 'object' && JSON.stringify(the1stobj[item]) === JSON.stringify(obj[item]))
      ) return console.log('✓  mapped as `%s` with right value', item);
      fail++;
      return console.log(`✖  mapped, but the expected value of \`${item}\` is ${the1stobj[item]}`);
    }
    fail++;
    console.log('✖  item is not mapped %s', item);
  });

  if(obj.notMappedField12 === 'key is missing') {
    console.log('✓  when key is missing, will mapping as `notMappedFieldN`, like `%s`', 'notMappedField12');
  } else {
    fail++;
    console.log('✖  notMappedField12 is not mapped');
  }

  console.log();
  console.log('=  SUCCESS: %d, FAIL: %d', Object.keys(the1stobj).length - fail, fail);
  console.log('=  done!\n' );
}

function kv(name, value, i) {
  if(typeof name === 'function') return name(value).name;
  if(!name) return `notMappedField${i}`;;

  var candidateKey = name.split('|');
  if(candidateKey[1]) return {name: candidateKey[0], directive: candidateKey[1]};

  return name;
}
<commit_msg>update testcase<commit_after>'use strict';

var logFormat = require('../');
var path = require('path');
var map = ['createdAt', 'origin', 'xForwardFor', 'referrer', 'country', 'city',
           'latitude|number', 'longitude|number', 'query|url', 'userAgent', 'arr|array', transform];
var separator = '•-•';
var src = path.join(__dirname, './log');
var dist = path.join(__dirname, './log.json');
var removeSrc = false;
var configure = {map, separator, src, dist, removeSrc};

var the1stobj = {
  "createdAt": "2015-11-14T23:59:14+08:00",
  "origin": "223.104.14.184",
  "xForwardFor": "-",
  "referrer": "http://opensite.ele.me/place/ww24pej69znn",
  "country": "CN",
  "city": "-",
  "latitude": 35,
  "longitude": 105,
  "query": { "test": "1st" },
  "userAgent": "Mozilla/5.0 (Linux; Android 4.4.4; m1 note Build/KTU84P) AppleWebKit/537.36 (KHTML, like Gecko) Version/4.0 Chrome/33.0.0.0 Mobile Safari/537.36 Proxy/cootekservice Proxy/cootekservice",
  "arr": [ "a", "b", "c", "d" ],
  "transformed": "fortestonly",
  "notMappedField12": "key is missing"
};

logFormat(configure, ret => {
  if(!ret) console.log('✓ it\'s an empty file');
  if(ret) console.log(`✓  JSON is generated: ${ret}`);

  // run test
  test(ret);
});

function transform(text) {
  var value= '';
  var name = 'transformed';
  if(text) value = text.toLowerCase();
  return {name, value};
}

function test(path) {
  var json = require(path);
  var obj = json[0];
  var keys = Object.keys(obj);
  var arr = [];
  var fail = 0;

  // parse keys
  keys = map.map((item, i) => {
    var name = kv(item, obj[item], i);
    if(name.directive) arr[i] = name.directive;
    return name.name || name;
  });

  // test map
  keys.forEach((item, i) => {
    if(keys.indexOf(item) !== -1) {
      if(
        the1stobj[item] === obj[item] ||
        (obj[item] && typeof obj[item] === 'object' && JSON.stringify(the1stobj[item]) === JSON.stringify(obj[item]))
      ) return console.log('✓  mapped as `%s` with right value', item);
      fail++;
      return console.log(`✖  mapped, but the expected value of \`${item}\` is ${the1stobj[item]}`);
    }
    fail++;
    console.log('✖  item is not mapped %s', item);
  });

  if(obj.notMappedField12 === the1stobj.notMappedField12) {
    console.log('✓  when key is missing, will mapping as `notMappedFieldN`, like `%s`', 'notMappedField12');
  } else {
    fail++;
    console.log('✖  notMappedField12 is not mapped');
  }

  console.log();
  console.log('=  SUCCESS: %d, FAIL: %d', Object.keys(the1stobj).length - fail, fail);
  console.log('=  done!\n' );
}

function kv(name, value, i) {
  if(typeof name === 'function') return name(value).name;
  if(!name) return `notMappedField${i}`;;

  var candidateKey = name.split('|');
  if(candidateKey[1]) return {name: candidateKey[0], directive: candidateKey[1]};

  return name;
}
<|endoftext|>


<commit_before>var roleHarvester = {

    run: function(creep, source) {

    	setHarvestFlagForCreep(creep)

    	console.log("Harvester "+creep.name+" is harvesting "+creep.memory.harvesting +" energy "+creep.carry.energy+" max "+creep.carryCapacity);

    	if (creep.memory.harvesting) {
    		if(creep.harvest(source) == ERR_NOT_IN_RANGE) {
    			creep.moveTo(source);
    			return;
    		}
    	}

    	var targets = getTargetsForEnergyTransfer(creep);

        if(targets.length > 0) {

            if(creep.transfer(targets[0], RESOURCE_ENERGY) == ERR_NOT_IN_RANGE) {
                creep.moveTo(targets[0]);
            }
        }
    }
}

function getTargetsForEnergyTransfer(creep){
	return creep.room.find(FIND_STRUCTURES, {
        filter: (structure) => {
            return (structure.structureType == STRUCTURE_EXTENSION ||
                    structure.structureType == STRUCTURE_SPAWN ||
                    structure.structureType == STRUCTURE_TOWER) && structure.energy < structure.energyCapacity;
        }
	});
}

function setHarvestFlagForCreep(creep){
	if (creep.carry.energy == 0){
		 creep.memory.harvesting = true;
		 return;
	}

	if (creep.carry.energy == creep.carryCapacity){
		 creep.memory.harvesting = false;
		 return;
	}
}

module.exports = roleHarvester;<commit_msg>Bugfix<commit_after>var roleHarvester = {

    run: function(creep, source) {

    	setHarvestFlagForCreep(creep)

    	console.log("Harvester "+creep.name+" is harvesting "+creep.memory.harvesting +" energy "+creep.carry.energy+" max "+creep.carryCapacity);

    	if (creep.memory.harvesting) {
    		if(creep.harvest(source) == ERR_NOT_IN_RANGE) {
    			creep.moveTo(source);
    		}
    	}else{
	    	var targets = getTargetsForEnergyTransfer(creep);

	        if(targets.length > 0) {

	            if(creep.transfer(targets[0], RESOURCE_ENERGY) == ERR_NOT_IN_RANGE) {
	                creep.moveTo(targets[0]);
	            }
	        }
        }
    }
}

function getTargetsForEnergyTransfer(creep){
	return creep.room.find(FIND_STRUCTURES, {
        filter: (structure) => {
            return (structure.structureType == STRUCTURE_EXTENSION ||
                    structure.structureType == STRUCTURE_SPAWN ||
                    structure.structureType == STRUCTURE_TOWER) && structure.energy < structure.energyCapacity;
        }
	});
}

function setHarvestFlagForCreep(creep){
	if (creep.carry.energy == 0){
		 creep.memory.harvesting = true;
		 return;
	}

	if (creep.carry.energy == creep.carryCapacity){
		 creep.memory.harvesting = false;
		 return;
	}
}

module.exports = roleHarvester;<|endoftext|>


<commit_before>'use strict';
exports.info = {
  desc: 'Posts the top 5 games being played by Discord Members.',
  usage: '',
  aliases: [],
  permissions: ['SEND_MESSAGES'],
};

exports.run = (client, msg, [num]) => new Promise((resolve, reject) => {
  if (msg.channel.type === 'dm') {
    client.utils.dmDenied(msg).then(resolve).catch(reject);
    return;
  }
  const games = {};
  msg.guild.members.forEach(m => {
    if (m.user.presence.game) {
      const name = m.user.presence.game.name;
      if (games[name]) {
        games[name]++;
      } else {
        games[name] = 1;
      }
    }
  });
  const sortable = [];
  for (const game in games) {
    sortable.push([game, games[game]]);
  }
  sortable.sort((a, b) => b[1] - a[1]);
  const none = sortable.length === 0 ? ' NONE' : '';
  let str = `\`\`\`Top games currently being played:${none}\`\`\``;
  sortable.slice(0, num || 5).forEach(g => {
    str += `\n${g[1]} playing: **${g[0]}**`;
  });
  msg.channel.send(str).then(resolve).catch(reject);
});
<commit_msg>topplaying v12 changes<commit_after>'use strict';
exports.info = {
  desc: 'Posts the top 5 games being played by Discord Members.',
  usage: '',
  aliases: [],
  permissions: ['SEND_MESSAGES'],
};

exports.run = (client, msg, [num]) => new Promise((resolve, reject) => {
  if (msg.channel.type === 'dm') {
    client.utils.dmDenied(msg).then(resolve).catch(reject);
    return;
  }
  const games = {};
  msg.guild.members.forEach(m => {
    if (m.user.presence.activity && m.user.presence.activity.type === 'PLAYING') {
      const name = m.user.presence.activity.name;
      if (games[name]) {
        games[name]++;
      } else {
        games[name] = 1;
      }
    }
  });
  const sortable = [];
  for (const game in games) {
    sortable.push([game, games[game]]);
  }
  sortable.sort((a, b) => b[1] - a[1]);
  const none = sortable.length === 0 ? ' NONE' : '';
  let str = `\`\`\`Top games currently being played:${none}\`\`\``;
  sortable.slice(0, num || 5).forEach(g => {
    str += `\n${g[1]} playing: **${g[0]}**`;
  });
  msg.channel.send(str).then(resolve).catch(reject);
});
<|endoftext|>


<commit_before>
var fs = require('fs')
  , files = process.argv.slice(2)
  , exec = require('child_process').exec
  , Batch = require('batch')
  , batch = new Batch
  , start = new Date;

console.log();

files.forEach(function(file){
  batch.push(function(done){
    exec('node ' + file, function(err){
      if (err) return done(err);
      console.log('  \033[32m✓\033[0m \033[90m%s\033[0m', file);
      done();
    });
  });
});

batch.end(function(err){
  if (err) throw err;
  var duration = new Date - start;
  console.log('  \033[32m✓\033[0m \033[90m%s\033[0m', 'completed in ' + duration + 'ms\n');
});<commit_msg>bump completion msg down a line<commit_after>
var fs = require('fs')
  , files = process.argv.slice(2)
  , exec = require('child_process').exec
  , Batch = require('batch')
  , batch = new Batch
  , start = new Date;

console.log();

files.forEach(function(file){
  batch.push(function(done){
    exec('node ' + file, function(err){
      if (err) return done(err);
      console.log('  \033[32m✓\033[0m \033[90m%s\033[0m', file);
      done();
    });
  });
});

batch.end(function(err){
  if (err) throw err;
  var duration = new Date - start;
  console.log('\n  \033[32m✓\033[0m \033[90m%s\033[0m', 'completed in ' + duration + 'ms\n');
});<|endoftext|>


<commit_before>var _ = require('lodash');
var callbacks = require('../internal/callbacks');
var fs = require('fs');
var path = require('path');
var paths = require('../internal/paths');
var Request = require('../api/request');
var Response = require('../api/response');
var rjson = require('relaxed-json');
var url = require('url');
var utils = require('../internal/utils');

var DEFAULT_HEADERS = {
  'Accept': '*/*',
  'Content-Type': 'application/json',
  'User-Agent': 'Lambdafai invoker',
  'Host': 'localhost',
};

function loadRequest(pathOrLiteral) {
  var opts;
  if (fs.existsSync(pathOrLiteral)) {
    opts = rjson.parse(fs.readFileSync(pathOrLiteral, 'utf8'));
  } else {
    opts = rjson.parse(pathOrLiteral);  // Try to parse as a literal.
  }

  if (!_.isObject(opts) || _.isArray(opts) || _.isString(opts)) {
    console.error('Request must be a JSON object.');
    return null;
  }
  if (!opts.path) {
    console.error('"path" field is missing in request.');
    return null;
  }

  // Add any caller-supplied headers to the defaults.
  var headers = _.clone(DEFAULT_HEADERS);
  if (opts.headers) {
    _.assign(headers, opts.headers);
  }

  // Parse the path and query out of the path.
  var parsedURL = url.parse('http://localhost' + opts.path, true);

  return {
    method: opts.method || 'GET',
    path: parsedURL.pathname,
    headers: headers,
    query: parsedURL.query,
    body: opts.body,
  };
}

function findRoute(app, method, path) {
  var routes = _.flatten(app.lambdas.map(function(lambda) { return lambda.routes; }));
  for (var i = 0; i < routes.length; i++) {
    if (routes[i].method == method && paths.matchPath(routes[i].path, path)) {
      return routes[i];
    }
  }
}

module.exports = {
  description: 'Invokes a Lambda locally.',

  configureParser: function(parser) {
    parser.addArgument([ 'environment' ], {
      help: 'Name of the environment to simulate running in, e.g. "dev".'
    });
    parser.addArgument([ 'request' ], {
      help: 'A request object to send to the lambda, either inline or a JSON file to load.'
    });
  },

  execute: function(app, args, callback) {
    var request = loadRequest(args.request);
    request.app = app;
    request.environment = args.environment;

    var route = findRoute(app, request.method, request.path);
    if (!route) {
      callback(new Error('No route matches: ' + request.method + ' ' + request.path));
      return;
    }

    // Extract path parameters:
    request.params = paths.matchPath(route.path, request.path);
    request.path = route.path;

    if (args.verbose) {
      utils.logBanner('Request:\n' + JSON.stringify(request, null, 2));
    }

    app._handleRequest(new Request(request), callbacks.logData(callback));
  },
};
<commit_msg>Include lamdba arn in the request<commit_after>var _ = require('lodash');
var callbacks = require('../internal/callbacks');
var fs = require('fs');
var path = require('path');
var paths = require('../internal/paths');
var Request = require('../api/request');
var Response = require('../api/response');
var rjson = require('relaxed-json');
var url = require('url');
var utils = require('../internal/utils');

var DEFAULT_HEADERS = {
  'Accept': '*/*',
  'Content-Type': 'application/json',
  'User-Agent': 'Lambdafai invoker',
  'Host': 'localhost',
};

function loadRequest(pathOrLiteral) {
  var opts;
  if (fs.existsSync(pathOrLiteral)) {
    opts = rjson.parse(fs.readFileSync(pathOrLiteral, 'utf8'));
  } else {
    opts = rjson.parse(pathOrLiteral);  // Try to parse as a literal.
  }

  if (!_.isObject(opts) || _.isArray(opts) || _.isString(opts)) {
    console.error('Request must be a JSON object.');
    return null;
  }
  if (!opts.path) {
    console.error('"path" field is missing in request.');
    return null;
  }

  // Add any caller-supplied headers to the defaults.
  var headers = _.clone(DEFAULT_HEADERS);
  if (opts.headers) {
    _.assign(headers, opts.headers);
  }

  // Parse the path and query out of the path.
  var parsedURL = url.parse('http://localhost' + opts.path, true);

  return {
    environment: opts.environment,
    lambdaArn: opts.lambdaArn,
    method: opts.method || 'GET',
    path: parsedURL.pathname,
    headers: headers,
    query: parsedURL.query,
    body: opts.body,
  };
}

function findRoute(app, method, path) {
  var routes = _.flatten(app.lambdas.map(function(lambda) { return lambda.routes; }));
  for (var i = 0; i < routes.length; i++) {
    if (routes[i].method == method && paths.matchPath(routes[i].path, path)) {
      return routes[i];
    }
  }
}

module.exports = {
  description: 'Invokes a Lambda locally.',

  configureParser: function(parser) {
    parser.addArgument([ 'environment' ], {
      help: 'Name of the environment to simulate running in, e.g. "dev".'
    });
    parser.addArgument([ 'request' ], {
      help: 'A request object to send to the lambda, either inline or a JSON file to load.'
    });
  },

  execute: function(app, args, callback) {
    var request = loadRequest(args.request);
    request.app = app;
    request.environment = args.environment;

    var route = findRoute(app, request.method, request.path);
    if (!route) {
      callback(new Error('No route matches: ' + request.method + ' ' + request.path));
      return;
    }

    // Extract path parameters:
    request.params = paths.matchPath(route.path, request.path);
    request.path = route.path;

    if (args.verbose) {
      utils.logBanner('Request:\n' + JSON.stringify(request, null, 2));
    }

    app._handleRequest(new Request(request), callbacks.logData(callback));
  },
};
<|endoftext|>


<commit_before>var jsdom = require("jsdom");
var fs = require('fs');
var path = require('path');
var assert = require('assert');

fs.readdirSync(__dirname).filter(function(file) {
	if (path.extname(file) != ".html") return;
	var str = fs.readFileSync(path.join(__dirname, file)).toString();
	var doc = jsdom.jsdom(str, null, {features: {
		FetchExternalResources   : false,
		ProcessExternalResources : false
	}});
	var win = doc.parentWindow;
	win.console = console;
	win.describe = describe;
	win.it = it;
	win.assert = assert;

	Array.prototype.forEach.call(doc.querySelectorAll('script'), function(script) {
		if (script.type == "text/template") return;
		try {
			if (script.textContent) {
				win.run(script.textContent);
			} else if (script.src) {
				win.run(fs.readFileSync(path.join(__dirname, script.src)).toString());
			}
		} catch(e) {
			console.error("Error while trying to execute script sourced by\n" + file);
			process.exit(1);
		}
	});
});
<commit_msg>Be independent of jsdom version<commit_after>var jsdom = require("jsdom");
var fs = require('fs');
var path = require('path');
var assert = require('assert');

fs.readdirSync(__dirname).filter(function(file) {
	if (path.extname(file) != ".html") return;
	var str = fs.readFileSync(path.join(__dirname, file)).toString();
	var doc = jsdom.jsdom(str, {
		virtualConsole: jsdom.createVirtualConsole && jsdom.createVirtualConsole().sendTo(console),
		features: {
			FetchExternalResources   : false,
			ProcessExternalResources : false
		}
	});
	var win = doc.parentWindow || doc.defaultView;
	if (!win.run) {
		win.run = runShim.bind(null, require('vm').createContext(win));
	}
	win.console = console;
	win.describe = describe;
	win.it = it;
	win.assert = assert;

	Array.prototype.forEach.call(doc.querySelectorAll('script'), function(script) {
		if (script.type == "text/template") return;
		try {
			if (script.textContent) {
				win.run(script.textContent);
			} else if (script.src) {
				win.run(fs.readFileSync(path.join(__dirname, script.src)).toString());
			}
		} catch(e) {
			console.error("Error while trying to execute script sourced by\n" + file);
			process.exit(1);
		}
	});
});

function runShim(context, script) {
	var vmscript = new (require('vm').Script)(script);
	return vmscript.runInContext(context);
}
<|endoftext|>


<commit_before>"use strict";

var childProcess = require("child_process");
var chai = require("chai");
var run = require("../lib/run");

var expect = chai.expect;

var reporter;
var execBackup;
var noOutdatedModules = {};
var outdatedModules = {
    unicons: {
        current: "0.1.4",
        wanted: "1.1.5",
        latest: "2.0.0",
        location: "unicons",
        type: "dependencies"
    }
};
var outdatedModulesWithGitDependencies = {
    unicons: outdatedModules.unicons,
    "xunit-file": {
        current: "0.0.7",
        wanted: "git",
        latest: "git",
        location: "xunit-file",
        type: "dependencies"
    },
    "servus.js": {
        current: "0.0.1",
        wanted: "git",
        latest: "git",
        location: "servus.js",
        type: "dependencies"
    }
};

var expectedOptions = {
    infos: [{
        current: "0.1.4",
        wanted: "1.1.5",
        latest: "2.0.0",
        location: "unicons",
        type: "dependencies",
        name: "unicons",
        saveCmd: "--save"
    }],
    total: 1
};

var expectedOptionsWithCurrentCount = {
    current: 1,
    total: 1,
    info: {
        current: "0.1.4",
        wanted: "1.1.5",
        latest: "2.0.0",
        location: "unicons",
        type: "dependencies",
        name: "unicons",
        saveCmd: "--save"
    }
};

function tearDown() {
    childProcess.exec = execBackup;
}

function execMock(object) {
    return function (cmd, obj, cb) {
        if (cmd === "npm outdated --json --long --depth=0") {
            setImmediate(cb, null, JSON.stringify(object), null);
        } else if (cmd === "npm test") {
            setImmediate(cb, new Error());
        } else {
            setImmediate(cb, null);
        }
    };
}

function setupOutdatedModules(obj) {
    return function () {
        execBackup = childProcess.exec;
        childProcess.exec = execMock(obj);
    };
}

describe("run()", function () {
    describe(".emit('init')", function () {
        before(setupOutdatedModules(outdatedModules));

        after(tearDown);

        it("should throw an error, if no options set", function () {
            expect(run).to.throw(Error);
        });

        it("should throw an error, if cwd is missing", function () {
            expect(
                function () {
                    run({ cwd: 1 });
                }
            ).to.throw(Error);
        });

        it("should be emitted, if cwd is set", function (done) {
            reporter = function (emitter) {
                emitter.on("init", function (options) {
                    expect(options).to.eql({ cwd: "/Users/peerigon/Workspace/peerigon/updtr" });
                });
            };

            run({ cwd: process.cwd(), reporter: reporter }, done);
        });
    });

    describe(".emit('noop')", function () {
        before(setupOutdatedModules(noOutdatedModules));

        afterEach(tearDown);

        it("should be emitted if no outdated modules were found", function (done) {
            reporter = function (emitter) {
                emitter.on("noop", function (options) {
                    expect(options).to.be.undefined; // eslint-disable-line
                });
            };

            run({ cwd: process.cwd(), reporter: reporter }, done);
        });
    });

    describe(".emit('outdated')", function () {
        describe("without git modules", function () {
            before(setupOutdatedModules(outdatedModules));

            afterEach(tearDown);

            it("should be emitted if outdated modules were found", function (done) {
                reporter = function (emitter) {
                    emitter.on("outdated", function (options) {
                        expect(options).to.eql(expectedOptions);
                    });
                };

                run({ cwd: process.cwd(), reporter: reporter }, done);
            });
        });

        describe("whit git modules", function () {
            before(setupOutdatedModules(outdatedModulesWithGitDependencies));

            afterEach(tearDown);

            it("should be emitted without git modules", function (done) {
                reporter = function (emitter) {
                    emitter.on("outdated", function (options) {
                        expect(options).to.eql(expectedOptions);
                    });
                };

                run({ cwd: process.cwd(), reporter: reporter }, done);
            });
        });
    });

    describe(".emit('updating')", function () {
        before(setupOutdatedModules(outdatedModules));
        afterEach(tearDown);

        it("should be emitted if outdated modules were found", function (done) {
            reporter = function (emitter) {
                emitter.on("updating", function (options) {
                    expect(options).to.eql(expectedOptionsWithCurrentCount);
                });
            };

            run({ cwd: process.cwd(), reporter: reporter }, done);
        });
    });

    describe(".emit('testing')", function () {
        before(setupOutdatedModules(outdatedModules));
        afterEach(tearDown);

        it("should be emitted if outdated modules were found", function (done) {
            reporter = function (emitter) {
                emitter.on("testing", function (options) {
                    expect(options).to.eql(expectedOptionsWithCurrentCount);
                });
            };

            run({ cwd: process.cwd(), reporter: reporter }, done);
        });
    });

    describe(".emit('rollback')", function () {
        before(setupOutdatedModules(outdatedModules));
        afterEach(tearDown);

        it("should be emitted if outdated modules were found", function (done) {
            reporter = function (emitter) {
                emitter.on("rollback", function (options) {
                    expect(options).to.eql(expectedOptionsWithCurrentCount);
                });
            };

            run({ cwd: process.cwd(), reporter: reporter }, done);
        });
    });

    describe(".emit('rollbackDone')", function () {
        before(setupOutdatedModules(outdatedModules));
        afterEach(tearDown);

        it("should be emitted if outdated modules were found", function (done) {
            reporter = function (emitter) {
                emitter.on("rollbackDone", function (options) {
                    expect(options).to.eql(expectedOptionsWithCurrentCount);
                });
            };

            run({ cwd: process.cwd(), reporter: reporter }, done);
        });
    });

    describe(".emit('updatingDone')", function () {
        before(setupOutdatedModules(outdatedModules));
        afterEach(tearDown);

        it("should be emitted if outdated modules were found", function (done) {
            reporter = function (emitter) {
                emitter.on("updatingDone", function (options) {
                    expect(options).to.eql(expectedOptionsWithCurrentCount);
                });
            };

            run({ cwd: process.cwd(), reporter: reporter }, done);
        });
    });

    describe(".emit('finished')", function () {
        before(setupOutdatedModules(outdatedModules));
        afterEach(tearDown);

        it("should be emitted if outdated modules were found", function (done) {
            reporter = function (emitter) {
                emitter.on("finished", function (options) {
                    expect(options).to.be.undefined; // eslint-disable-line
                });
            };

            run({ cwd: process.cwd(), reporter: reporter }, done);
        });
    });
});
<commit_msg>Improve tests for updating, rollback and updatingDone events<commit_after>"use strict";

var childProcess = require("child_process");
var chai = require("chai");
var run = require("../lib/run");

var expect = chai.expect;

var reporter;
var execBackup;
var noOutdatedModules = {};
var outdatedModules = {
    unicons: {
        current: "0.1.4",
        wanted: "1.1.5",
        latest: "2.0.0",
        location: "unicons",
        type: "dependencies"
    }
};
var outdatedModulesWithGitDependencies = {
    unicons: outdatedModules.unicons,
    "xunit-file": {
        current: "0.0.7",
        wanted: "git",
        latest: "git",
        location: "xunit-file",
        type: "dependencies"
    },
    "servus.js": {
        current: "0.0.1",
        wanted: "git",
        latest: "git",
        location: "servus.js",
        type: "dependencies"
    }
};

var expectedOptions = {
    infos: [{
        current: "0.1.4",
        wanted: "1.1.5",
        latest: "2.0.0",
        location: "unicons",
        type: "dependencies",
        name: "unicons",
        saveCmd: "--save"
    }],
    total: 1
};

var expectedOptionsWithCurrentCount = {
    current: 1,
    total: 1,
    info: {
        current: "0.1.4",
        wanted: "1.1.5",
        latest: "2.0.0",
        location: "unicons",
        type: "dependencies",
        name: "unicons",
        saveCmd: "--save"
    }
};

function tearDown() {
    childProcess.exec = execBackup;
}

function execMock(object, testsExpectToPass) {
    return function (cmd, obj, cb) {
        if (cmd === "npm outdated --json --long --depth=0") {
            setImmediate(cb, null, JSON.stringify(object), null);
        } else if (cmd === "npm test" && !testsExpectToPass) {
            setImmediate(cb, new Error());
        } else {
            setImmediate(cb, null);
        }
    };
}

function setupOutdatedModules(obj, testsExpectToPass) {
    return function () {
        execBackup = childProcess.exec;
        childProcess.exec = execMock(obj, testsExpectToPass);
    };
}

describe("run()", function () {
    describe(".emit('init')", function () {
        before(setupOutdatedModules(outdatedModules));

        after(tearDown);

        it("should throw an error, if no options set", function () {
            expect(run).to.throw(Error);
        });

        it("should throw an error, if cwd is missing", function () {
            expect(
                function () {
                    run({ cwd: 1 });
                }
            ).to.throw(Error);
        });

        it("should be emitted, if cwd is set", function (done) {
            reporter = function (emitter) {
                emitter.on("init", function (options) {
                    expect(options).to.eql({ cwd: "/Users/peerigon/Workspace/peerigon/updtr" });
                });
            };

            run({ cwd: process.cwd(), reporter: reporter }, done);
        });
    });

    describe(".emit('noop')", function () {
        before(setupOutdatedModules(noOutdatedModules));
        afterEach(tearDown);

        it("should be emitted if no outdated modules were found", function (done) {
            reporter = function (emitter) {
                emitter.on("noop", function (options) {
                    expect(options).to.be.undefined; // eslint-disable-line
                });
            };

            run({ cwd: process.cwd(), reporter: reporter }, done);
        });
    });

    describe(".emit('outdated')", function () {
        describe("without git modules", function () {
            before(setupOutdatedModules(outdatedModules));
            afterEach(tearDown);

            it("should be emitted if outdated modules were found", function (done) {
                reporter = function (emitter) {
                    emitter.on("outdated", function (options) {
                        expect(options).to.eql(expectedOptions);
                    });
                };

                run({ cwd: process.cwd(), reporter: reporter }, done);
            });
        });

        describe("whit git modules", function () {
            before(setupOutdatedModules(outdatedModulesWithGitDependencies));
            afterEach(tearDown);

            it("should be emitted without git modules", function (done) {
                reporter = function (emitter) {
                    emitter.on("outdated", function (options) {
                        expect(options).to.eql(expectedOptions);
                    });
                };

                run({ cwd: process.cwd(), reporter: reporter }, done);
            });
        });
    });

    describe(".emit('updating')", function () {
        describe("should be emitted", function () {
            before(setupOutdatedModules(outdatedModules));
            afterEach(tearDown);

            it("should be emitted if outdated modules were found", function (done) {
                reporter = function (emitter) {
                    emitter.on("updating", function (options) {
                        expect(options).to.eql(expectedOptionsWithCurrentCount);
                    });
                };

                run({ cwd: process.cwd(), reporter: reporter }, done);
            });
        });

        describe("should not be emitted", function () {
            before(setupOutdatedModules(noOutdatedModules));
            afterEach(tearDown);

            it("should be emitted if outdated modules were found", function (done) {
                reporter = function (emitter) {
                    emitter.on("updating", function () {
                        throw new Error();
                    });
                };

                run({ cwd: process.cwd(), reporter: reporter }, done);
            });
        });
    });

    describe(".emit('testing')", function () {
        before(setupOutdatedModules(outdatedModules));
        afterEach(tearDown);

        it("should be emitted if outdated modules were found", function (done) {
            reporter = function (emitter) {
                emitter.on("testing", function (options) {
                    expect(options).to.eql(expectedOptionsWithCurrentCount);
                });
            };

            run({ cwd: process.cwd(), reporter: reporter }, done);
        });
    });

    describe(".emit('rollback')", function () {
        describe("failing tests", function () {
            before(setupOutdatedModules(outdatedModules, false));
            afterEach(tearDown);

            it("should be emitted", function (done) {
                reporter = function (emitter) {
                    emitter.on("rollback", function (options) {
                        expect(options).to.eql(expectedOptionsWithCurrentCount);
                    });
                };

                run({ cwd: process.cwd(), reporter: reporter }, done);
            });
        });

        describe("passing tests", function () {
            before(setupOutdatedModules(outdatedModules, true));
            afterEach(tearDown);

            it("should not be emitted", function (done) {
                reporter = function (emitter) {
                    emitter.on("rollback", function (options) {
                        throw new Error();
                    });
                };

                run({ cwd: process.cwd(), reporter: reporter }, done);
            });
        });
    });

    describe(".emit('rollbackDone')", function () {
        before(setupOutdatedModules(outdatedModules, false));
        afterEach(tearDown);

        it("should be emitted if outdated modules were found", function (done) {
            reporter = function (emitter) {
                emitter.on("rollbackDone", function (options) {
                    expect(options).to.eql(expectedOptionsWithCurrentCount);
                });
            };

            run({ cwd: process.cwd(), reporter: reporter }, done);
        });
    });

    describe(".emit('updatingDone')", function () {
        describe("passing tests", function () {
            before(setupOutdatedModules(outdatedModules, true));
            afterEach(tearDown);

            it("should be emitted if outdated modules were found", function (done) {
                reporter = function (emitter) {
                    emitter.on("updatingDone", function (options) {
                        expect(options).to.eql(expectedOptionsWithCurrentCount);
                    });
                };

                run({ cwd: process.cwd(), reporter: reporter }, done);
            });
        });
        describe("failing tests", function () {
            before(setupOutdatedModules(outdatedModules, false));
            afterEach(tearDown);

            it("should not be emitted if outdated modules were found", function (done) {
                reporter = function (emitter) {
                    emitter.on("updatingDone", function (options) {
                        throw new Error();
                    });
                };

                run({ cwd: process.cwd(), reporter: reporter }, done);
            });
        });
    });

    describe(".emit('finished')", function () {
        before(setupOutdatedModules(outdatedModules));
        afterEach(tearDown);

        it("should be emitted if outdated modules were found", function (done) {
            reporter = function (emitter) {
                emitter.on("finished", function (options) {
                    expect(options).to.be.undefined; // eslint-disable-line
                });
            };

            run({ cwd: process.cwd(), reporter: reporter }, done);
        });
    });
});
<|endoftext|>


<commit_before>module.exports = function(grunt) {
  require('time-grunt')(grunt);
  grunt.initConfig({
    pkg: grunt.file.readJSON('package.json'),
    assets : grunt.file.readJSON('assets/assets.json'),

    jshint: {
      files: [
        'Gruntfile.js'
        ,'<%= uglify.app.src %>'
        ,'<%= uglify.admin.src %>'
      ],
      options: {
        reporter: require('jshint-stylish')
        ,globals: {
          jQuery   : true
          ,console : true
          ,module  : true
          ,document: true
        },
        laxcomma : true
        ,laxbreak: true
        ,sub     : true
      }
    },

    uglify: {
      options : {
        sourceMap: function( path ){ return path + 'map'; }
      }

      ,app: {
        src : '<%= assets.js.app %>',
        dest: 'assets/dist/javascripts/<%= pkg.name %>.min.js'
      }

      ,admin: {
        src : '<%= assets.js.admin %>',
        dest: 'assets/dist/javascripts/<%= pkg.name %>.admin.min.js'
      }

      ,vendor : {
        src : '<%= assets.js.vendor %>',
        dest: 'assets/dist/vendor/vendor.min.js'
      }
    },

    sass: {
      options: {
        style    : 'compressed',
        sourcemap: true,
        // compass  : true
      },

      screen: {
        src : '<%= assets.css.screen %>',
        dest: 'assets/dist/stylesheets/screen.css'
      },
      admin: {
        src : '<%= assets.css.admin %>',
        dest: 'assets/dist/stylesheets/admin.css'
      }
    },

    copy : {
      assets: {
        files: [
          {
            expand: true,
            cwd: 'assets/src',
            src: [
              'images/*'
              ,'images/**/*'
              ,'fonts/**/*'
            ],
            dest: 'assets/dist/'
          }
        ]
      }
    },

    sprite:{
      all: {
        src         : ['assets/src/images/sprites/*.png']
        ,destImg    : 'assets/dist/images/sprites.png'
        ,imgPath    : '../images/sprites.png'
        ,algorithm  : 'binary-tree'
        ,padding    : 10
        ,engine     : 'auto'
        ,destCSS    : 'assets/src/stylesheets/sprites/_sprites.scss'
        ,cssTemplate: 'assets/helpers/spritesmith.sass.template.mustache'
        ,engineOpts : {
          'imagemagick': true
        }
      }
    },

    clean: {
      build: ["assets/dist"]
    },

    csscss: {
      dist: {
        src: [ '<%= sass.admin.dest %>', '<%= sass.screen.dest %>' ]
      }
    },

    watch: {
      options: {
        nospawn       : true
        ,livereload   : true
      },

      css: {
        files: [ '<%= sass.app.src %>' ],
        tasks: [ "css" ]
      },

      admin : {
        files: [
          '<%= sass.admin.src %>'
          ,'<%= uglify.admin.src %>'
        ],
        tasks : [ "admin" ]
      },

      assets : {
        files: [
          'assets/src/images/*'
          ,'assets/src/images/**/*'
          ,'assets/src/fonts/**/*'
        ],
        tasks: [ 'copy' ]
      },

      js : {
        files: [ '<%= uglify.app.src %>' ],
        tasks: [ 'js' ]
      }
    },
  });

  require('load-grunt-tasks')(grunt);

  grunt.registerTask('js', [ 'jshint', 'uglify']);
  grunt.registerTask('css', [ 'sprite', 'sass' ]);
  grunt.registerTask('assets', [ 'copy' ]);
  grunt.registerTask('admin', [ 'sass:admin', 'uglify:admin' ]);

  grunt.registerTask('default', [ 'clean', 'js', 'css', 'assets' ]);
  grunt.registerTask('dev', [ 'default', 'watch' ]);
};<commit_msg> small fix<commit_after>module.exports = function(grunt) {
  require('time-grunt')(grunt);
  grunt.initConfig({
    pkg: grunt.file.readJSON('package.json'),
    assets : grunt.file.readJSON('assets/assets.json'),

    jshint: {
      files: [
        'Gruntfile.js'
        ,'<%= uglify.app.src %>'
        ,'<%= uglify.admin.src %>'
      ],
      options: {
        reporter: require('jshint-stylish')
        ,globals: {
          jQuery   : true
          ,console : true
          ,module  : true
          ,document: true
        },
        laxcomma : true
        ,laxbreak: true
        ,sub     : true
      }
    },

    uglify: {
      options : {
        sourceMap: function( path ){ return path + 'map'; }
      }

      ,app: {
        src : '<%= assets.js.app %>',
        dest: 'assets/dist/javascripts/<%= pkg.name %>.min.js'
      }

      ,admin: {
        src : '<%= assets.js.admin %>',
        dest: 'assets/dist/javascripts/<%= pkg.name %>.admin.min.js'
      }

      ,vendor : {
        src : '<%= assets.js.vendor %>',
        dest: 'assets/dist/vendor/vendor.min.js'
      }
    },

    sass: {
      options: {
        style    : 'compressed',
        sourcemap: true,
        // compass  : true
      },

      screen: {
        src : '<%= assets.css.screen %>',
        dest: 'assets/dist/stylesheets/screen.css'
      },
      admin: {
        src : '<%= assets.css.admin %>',
        dest: 'assets/dist/stylesheets/admin.css'
      }
    },

    copy : {
      assets: {
        files: [
          {
            expand: true,
            cwd: 'assets/src',
            src: [
              'images/*'
              ,'images/**/*'
              ,'fonts/**/*'
            ],
            dest: 'assets/dist/'
          }
        ]
      }
    },

    sprite:{
      all: {
        src         : ['assets/src/images/sprites/*.png']
        ,destImg    : 'assets/dist/images/sprites.png'
        ,imgPath    : '../images/sprites.png'
        ,algorithm  : 'binary-tree'
        ,padding    : 10
        ,engine     : 'auto'
        ,destCSS    : 'assets/src/stylesheets/sprites/_sprites.scss'
        ,cssTemplate: 'assets/helpers/spritesmith.sass.template.mustache'
        ,engineOpts : {
          'imagemagick': true
        }
      }
    },

    clean: {
      build: ["assets/dist"]
    },

    csscss: {
      dist: {
        src: [ '<%= sass.admin.dest %>', '<%= sass.screen.dest %>' ]
      }
    },

    watch: {
      options: {
        nospawn       : true
        ,livereload   : true
      },

      css: {
        files: [ '<%= sass.screen.src %>' ],
        tasks: [ "css" ]
      },

      admin : {
        files: [
          '<%= sass.admin.src %>'
          ,'<%= uglify.admin.src %>'
        ],
        tasks : [ "admin" ]
      },

      assets : {
        files: [
          'assets/src/images/*'
          ,'assets/src/images/**/*'
          ,'assets/src/fonts/**/*'
        ],
        tasks: [ 'copy' ]
      },

      js : {
        files: [ '<%= uglify.app.src %>' ],
        tasks: [ 'js' ]
      }
    },
  });

  require('load-grunt-tasks')(grunt);

  grunt.registerTask('js', [ 'jshint', 'uglify']);
  grunt.registerTask('css', [ 'sprite', 'sass' ]);
  grunt.registerTask('assets', [ 'copy' ]);
  grunt.registerTask('admin', [ 'sass:admin', 'uglify:admin' ]);

  grunt.registerTask('default', [ 'clean', 'js', 'css', 'assets' ]);
  grunt.registerTask('dev', [ 'default', 'watch' ]);
};<|endoftext|>