<commit_before>var Phantasma = require('../index');
var should = require('should');
var fs = require('fs');
var rimraf = require('rimraf');
var http = require('http');
var serveStatic = require('serve-static');
var finalhandler = require('finalhandler');

describe('Phantasma', function () {

  var server, ph;

  before(function (done) {

    var serve = serveStatic('./test/files');
    server = http.createServer(function(req, res){
      var d = finalhandler(req, res);
      serve(req, res, d);
    });
    server.listen(3000, function () {
      done();
    });
  });

  after(function (done) {
    ph.exit();
    server.close(function () {
      rimraf('test/temp', done);
    });
  });

  beforeEach(function () {
    ph = new Phantasma();
  });

  afterEach(function () {
    ph.exit();
  });

  it('should be constructable', function () {
    ph.should.be.ok;
  });

  describe('Methods', function () {

    it('should open page', function () {
      return ph.open('http://localhost:3000')
        .then(function (status) {
          status.should.equal('success');
        });
    });

    it('should get the page title', function () {
      return ph.open('http://localhost:3000')
        .title()
        .then(function (title) {
          title.should.equal('Test');
        });
    });

    it('should follow a link', function () {
      return ph.open('http://localhost:3000')
        .click('#link')
        .wait()
        .url()
        .then(function (url) {
          url.should.equal('http://localhost:3000/page1.html');
        });
    });

    it('should enter text', function () {
      return ph.open('http://localhost:3000')
        .type('#typehere', 'test value')
        .evaluate(function () {
          return document.querySelector('#typehere').value;
        })
        .then(function (val) {
          val.should.equal('test value');
        });
    });

    it('should set value', function () {
      return ph.open('http://localhost:3000')
        .value('#typehere', 'test value')
        .evaluate(function () {
          return document.querySelector('#typehere').value;
        })
        .then(function (val) {
          val.should.equal('test value');
        });
    });

    it('should select a value', function () {
      return ph.open('http://localhost:3000')
        .select('#selectthis', '2')
        .evaluate(function () {
          return document.querySelector('#selectthis').value;
        })
        .then(function (val) {
          val.should.equal('2');
        });
    });

    it('should take screenshots', function () {
      var path = 'test/temp/screenshot.png';
      return ph.open('http://localhost:3000')
        .screenshot(path)
        .then(function () {
          fs.existsSync(path).should.be.true;
        });
    });

     it('should extract h1 as image', function () {
      var path = 'test/temp/h1.png';
      return ph.open('http://localhost:3000')
        .screenshotDomElement('h1[id="heading"]',path)
        .then(function () {
          fs.existsSync(path).should.be.true;
        });
    });

    it('should navigate backwards and forwards', function () {
      return ph.open('http://localhost:3000')
        .open('http://localhost:3000/page1.html')
        .back()
        .url()
        .then(function (url) {
          url.should.equal('http://localhost:3000/');
        })
        .forward()
        .url(function (url) {
          url.should.equal('http://localhost:3000/page1.html');
        });
    });

    it('should refresh the page', function () {
      var count = 0;
      ph.on('onLoadFinished', function () {
        count++;
      });

      return ph.open('http://localhost:3000')
        .refresh()
        .then(function () {
          count.should.equal(2);
        });
    });

    it('should focus an element', function () {
      return ph.open('http://localhost:3000')
        .focus('#typehere')
        .evaluate(function () {
          return document.activeElement.id;
        })
        .then(function (active) {
          active.should.equal('typehere');
        });
    });

    it('should inject javascript', function () {
      return ph.open('http://localhost:3000')
        .injectJs('test/files/inject.js')
        .evaluate(function () {
          return test;
        })
        .then(function (result) {
          result.should.equal('testing!');
        });
    });

    it('should inject css', function () {
      return ph.open('http://localhost:3000')
        .injectCss('h1 { color: #ff0000; }')
        .evaluate(function () {
          var el = document.querySelector('#heading');
          var style = getComputedStyle(el);
          return style.color;
        })
        .then(function (result) {
          result.should.equal('rgb(255, 0, 0)');
        });
    });

    it('should get content', function () {
      return ph.open('http://localhost:3000/content.html')
        .content()
        .then(function (result) {
          result.should.equal('
Test
');
        });
    });

    it('should set content', function () {
      return ph.content('
Test
')
        .content()
        .then(function (result) {
          result.should.equal('
Test
');
        });
    });

  });

  describe('Events', function () {

    it('should emit on url change', function (done) {
      ph.open('http://localhost:3000')
        .once('onUrlChanged', function (url) {
          url.should.equal('http://localhost:3000/');
          done();
        });
    });

    it('should emit on resource requested', function (done) {
      ph.open('http://localhost:3000')
        .once('onResourceRequested', function (requestData, networkRequest) {
          requestData.url.should.equal('http://localhost:3000/');
          requestData.method.should.equal('GET');
          done();
        });
    });

    it('should emit on resource received', function (done) {
      ph.open('http://localhost:3000')
        .once('onResourceReceived', function (response) {
          response.url.should.equal('http://localhost:3000/');
          done();
        });
    });

    it('should emit on load started', function (done) {
      ph.open('http://localhost:3000')
        .once('onLoadStarted', function () {
          done();
        });
    });

    it('should emit on load finished', function (done) {
      ph.open('http://localhost:3000')
        .once('onLoadFinished', function (status) {
          status.should.equal('success');
          done();
        });
    });

    it('should emit on alert', function (done) {
      ph.open('http://localhost:3000/alert.html')
        .once('onAlert', function (msg) {
          msg.should.equal('test alert message');
          done();
        });
    });

    it('should emit on javascript error', function (done) {
      ph.open('http://localhost:3000/jserr.html')
        .once('onError', function (msg) {
          msg.should.not.be.empty;
          done();
        });
    });

    it('should emit on navigation requested', function (done) {
      ph.open('http://localhost:3000')
        .once('onNavigationRequested', function (url, type, willNavigate, main) {
          url.should.equal('http://localhost:3000/');
          willNavigate.should.be.true;
          done();
        });
    });

  });

});
<commit_msg>Updating Test description<commit_after>var Phantasma = require('../index');
var should = require('should');
var fs = require('fs');
var rimraf = require('rimraf');
var http = require('http');
var serveStatic = require('serve-static');
var finalhandler = require('finalhandler');

describe('Phantasma', function () {

  var server, ph;

  before(function (done) {

    var serve = serveStatic('./test/files');
    server = http.createServer(function(req, res){
      var d = finalhandler(req, res);
      serve(req, res, d);
    });
    server.listen(3000, function () {
      done();
    });
  });

  after(function (done) {
    ph.exit();
    server.close(function () {
      rimraf('test/temp', done);
    });
  });

  beforeEach(function () {
    ph = new Phantasma();
  });

  afterEach(function () {
    ph.exit();
  });

  it('should be constructable', function () {
    ph.should.be.ok;
  });

  describe('Methods', function () {

    it('should open page', function () {
      return ph.open('http://localhost:3000')
        .then(function (status) {
          status.should.equal('success');
        });
    });

    it('should get the page title', function () {
      return ph.open('http://localhost:3000')
        .title()
        .then(function (title) {
          title.should.equal('Test');
        });
    });

    it('should follow a link', function () {
      return ph.open('http://localhost:3000')
        .click('#link')
        .wait()
        .url()
        .then(function (url) {
          url.should.equal('http://localhost:3000/page1.html');
        });
    });

    it('should enter text', function () {
      return ph.open('http://localhost:3000')
        .type('#typehere', 'test value')
        .evaluate(function () {
          return document.querySelector('#typehere').value;
        })
        .then(function (val) {
          val.should.equal('test value');
        });
    });

    it('should set value', function () {
      return ph.open('http://localhost:3000')
        .value('#typehere', 'test value')
        .evaluate(function () {
          return document.querySelector('#typehere').value;
        })
        .then(function (val) {
          val.should.equal('test value');
        });
    });

    it('should select a value', function () {
      return ph.open('http://localhost:3000')
        .select('#selectthis', '2')
        .evaluate(function () {
          return document.querySelector('#selectthis').value;
        })
        .then(function (val) {
          val.should.equal('2');
        });
    });

    it('should take screenshots', function () {
      var path = 'test/temp/screenshot.png';
      return ph.open('http://localhost:3000')
        .screenshot(path)
        .then(function () {
          fs.existsSync(path).should.be.true;
        });
    });

     it('should screenshot h1 and save it as image', function () {
      var path = 'test/temp/h1.png';
      return ph.open('http://localhost:3000')
        .screenshotDomElement('h1[id="heading"]',path)
        .then(function () {
          fs.existsSync(path).should.be.true;
        });
    });

    it('should navigate backwards and forwards', function () {
      return ph.open('http://localhost:3000')
        .open('http://localhost:3000/page1.html')
        .back()
        .url()
        .then(function (url) {
          url.should.equal('http://localhost:3000/');
        })
        .forward()
        .url(function (url) {
          url.should.equal('http://localhost:3000/page1.html');
        });
    });

    it('should refresh the page', function () {
      var count = 0;
      ph.on('onLoadFinished', function () {
        count++;
      });

      return ph.open('http://localhost:3000')
        .refresh()
        .then(function () {
          count.should.equal(2);
        });
    });

    it('should focus an element', function () {
      return ph.open('http://localhost:3000')
        .focus('#typehere')
        .evaluate(function () {
          return document.activeElement.id;
        })
        .then(function (active) {
          active.should.equal('typehere');
        });
    });

    it('should inject javascript', function () {
      return ph.open('http://localhost:3000')
        .injectJs('test/files/inject.js')
        .evaluate(function () {
          return test;
        })
        .then(function (result) {
          result.should.equal('testing!');
        });
    });

    it('should inject css', function () {
      return ph.open('http://localhost:3000')
        .injectCss('h1 { color: #ff0000; }')
        .evaluate(function () {
          var el = document.querySelector('#heading');
          var style = getComputedStyle(el);
          return style.color;
        })
        .then(function (result) {
          result.should.equal('rgb(255, 0, 0)');
        });
    });

    it('should get content', function () {
      return ph.open('http://localhost:3000/content.html')
        .content()
        .then(function (result) {
          result.should.equal('
Test
');
        });
    });

    it('should set content', function () {
      return ph.content('
Test
')
        .content()
        .then(function (result) {
          result.should.equal('
Test
');
        });
    });

  });

  describe('Events', function () {

    it('should emit on url change', function (done) {
      ph.open('http://localhost:3000')
        .once('onUrlChanged', function (url) {
          url.should.equal('http://localhost:3000/');
          done();
        });
    });

    it('should emit on resource requested', function (done) {
      ph.open('http://localhost:3000')
        .once('onResourceRequested', function (requestData, networkRequest) {
          requestData.url.should.equal('http://localhost:3000/');
          requestData.method.should.equal('GET');
          done();
        });
    });

    it('should emit on resource received', function (done) {
      ph.open('http://localhost:3000')
        .once('onResourceReceived', function (response) {
          response.url.should.equal('http://localhost:3000/');
          done();
        });
    });

    it('should emit on load started', function (done) {
      ph.open('http://localhost:3000')
        .once('onLoadStarted', function () {
          done();
        });
    });

    it('should emit on load finished', function (done) {
      ph.open('http://localhost:3000')
        .once('onLoadFinished', function (status) {
          status.should.equal('success');
          done();
        });
    });

    it('should emit on alert', function (done) {
      ph.open('http://localhost:3000/alert.html')
        .once('onAlert', function (msg) {
          msg.should.equal('test alert message');
          done();
        });
    });

    it('should emit on javascript error', function (done) {
      ph.open('http://localhost:3000/jserr.html')
        .once('onError', function (msg) {
          msg.should.not.be.empty;
          done();
        });
    });

    it('should emit on navigation requested', function (done) {
      ph.open('http://localhost:3000')
        .once('onNavigationRequested', function (url, type, willNavigate, main) {
          url.should.equal('http://localhost:3000/');
          willNavigate.should.be.true;
          done();
        });
    });

  });

});
<|endoftext|>


<commit_before>// NO LOGGING IN THIS FILE

define(function(require) {
  'use strict';

  var config = {
    app: {
      logged_in_cookie_name: 'logged_in'
    },
    apps: {
      user: {
        // TODO: Is it worth config'ing local_username_field = local_email and local_password_field = local_password?
        local_password_min_length: 8,
        local_password_max_length: 256,
        facebook_auth_url: 'https://127.0.0.1:27974/api/user/access/facebook/auth',
        facebook_connect_url: 'https://127.0.0.1:27974/api/user/connect/facebook/auth',
        facebook_client_id: '',
        google_auth_url: 'https://127.0.0.1:27974/api/user/access/google/auth',
        google_connect_url: 'https://127.0.0.1:27974/api/user/connect/google/auth',
        google_client_id: '',
        twitter_auth_url: 'https://127.0.0.1:27974/api/user/access/twitter/auth',
        twitter_connect_url: 'https://127.0.0.1:27974/api/user/connect/twitter/auth',
        twitter_consumer_key: ''
      }
    },
    logger: {
      root: {
        js: {
          conf: {
            level: 'trace', // configure.py: js
            appenders: ['console']
          }
        },
        events_logger: {
          conf: {
            level: 'trace', // configure.py: events_logger
            appenders: ['console']
          }
        }
      }
    }
  };

  return config;
});
<commit_msg>server - config - twitter, google, facebook API URL's<commit_after>// NO LOGGING IN THIS FILE

define(function(require) {
  'use strict';

  var config = {
    app: {
      logged_in_cookie_name: 'logged_in'
    },
    apps: {
      user: {
        // TODO: Is it worth config'ing local_username_field = local_email and local_password_field = local_password?
        local_password_min_length: 8,
        local_password_max_length: 256,
        facebook_auth_url: 'https://127.0.0.1:27974/api/user/access/facebook/auth',
        facebook_connect_url: 'https://127.0.0.1:27974/api/user/connect/facebook/auth',
        facebook_disconnect_url: 'https://127.0.0.1:27974/api/user/connect/facebook/disconnect',
        facebook_client_id: '',
        google_auth_url: 'https://127.0.0.1:27974/api/user/access/google/auth',
        google_connect_url: 'https://127.0.0.1:27974/api/user/connect/google/auth',
        google_disconnect_url: 'https://127.0.0.1:27974/api/user/connect/google/disconnect',
        google_client_id: '',
        twitter_auth_url: 'https://127.0.0.1:27974/api/user/access/twitter/auth',
        twitter_connect_url: 'https://127.0.0.1:27974/api/user/connect/twitter/auth',
        twitter_disconnect_url: 'https://127.0.0.1:27974/api/user/connect/twitter/disconnect',
        twitter_consumer_key: ''
      }
    },
    logger: {
      root: {
        js: {
          conf: {
            level: 'trace', // configure.py: js
            appenders: ['console']
          }
        },
        events_logger: {
          conf: {
            level: 'trace', // configure.py: events_logger
            appenders: ['console']
          }
        }
      }
    }
  };

  return config;
});
<|endoftext|>


<commit_before>
var nodes = require('../lib/nodes');
var blocks = require('../lib/blocks');
var transactions = require('../lib/transactions');
var utils = require('../lib/utils');

exports['create node'] = function (test) {
	var node = nodes.node();

	test.ok(node);
	test.equal(typeof node, 'object');
};

exports['add genesis block'] = function (test) {
    var genesis = blocks.block();
	var node = nodes.node();

	node.addBlock(genesis);

	var best = node.bestBlock();

	test.ok(best);
	test.equal(best.number, genesis.number);
	test.equal(best.hash, genesis.hash);
};

exports['add transfer'] = function (test) {
    var from = utils.hash();
    var to = utils.hash();
    var value = 1000;

    var tx = transactions.transfer(from, to, value);

	var node = nodes.node();

	node.addTransaction(tx);

	var txs = node.transactions();

	test.ok(txs);
	test.ok(Array.isArray(txs));
	test.equal(txs.length, 1);

	var ntx = txs[0];

	test.equal(ntx.id, tx.id);
	test.equal(ntx.to, tx.to);
	test.equal(ntx.value, tx.value);
	test.equal(ntx.from, tx.from);
};

exports['mine with no transfers'] = function (test) {
    var genesis = blocks.block();
	var node = nodes.node();

	node.addBlock(genesis);

	var result = node.mine();

    test.ok(result);
    test.ok(result.hash);
    test.ok(result.transactions);
    test.ok(Array.isArray(result.transactions));
    test.equal(result.transactions.length, 0);
    test.ok(result.parentHash);
    test.equal(result.parentHash, genesis.hash);
};

<commit_msg>Node mine block with one transaction, WIP<commit_after>
var nodes = require('../lib/nodes');
var blocks = require('../lib/blocks');
var transactions = require('../lib/transactions');
var utils = require('../lib/utils');

exports['create node'] = function (test) {
	var node = nodes.node();

	test.ok(node);
	test.equal(typeof node, 'object');
};

exports['add genesis block'] = function (test) {
    var genesis = blocks.block();
	var node = nodes.node();

	node.addBlock(genesis);

	var best = node.bestBlock();

	test.ok(best);
	test.equal(best.number, genesis.number);
	test.equal(best.hash, genesis.hash);
};

exports['add transfer'] = function (test) {
    var from = utils.hash();
    var to = utils.hash();
    var value = 1000;

    var tx = transactions.transfer(from, to, value);

	var node = nodes.node();

	node.addTransaction(tx);

	var txs = node.transactions();

	test.ok(txs);
	test.ok(Array.isArray(txs));
	test.equal(txs.length, 1);

	var ntx = txs[0];

	test.equal(ntx.id, tx.id);
	test.equal(ntx.to, tx.to);
	test.equal(ntx.value, tx.value);
	test.equal(ntx.from, tx.from);
};

exports['mine with no transfers'] = function (test) {
    var genesis = blocks.block();
	var node = nodes.node();

	node.addBlock(genesis);

	var result = node.mine();

    test.ok(result);
    test.ok(result.hash);
    test.ok(result.transactions);
    test.ok(Array.isArray(result.transactions));
    test.equal(result.transactions.length, 0);
    test.ok(result.parentHash);
    test.equal(result.parentHash, genesis.hash);
};

exports['mine with one transfer'] = function (test) {
    var from = utils.hash();
    var to = utils.hash();
    var value = 1000;

    var tx = transactions.transfer(from, to, value);

    var genesis = blocks.block();
	var node = nodes.node();

	node.addBlock(genesis);
	node.addTransaction(tx);

	var result = node.mine();

    test.ok(result);
    test.ok(result.hash);
    test.ok(result.transactions);
    test.ok(Array.isArray(result.transactions));
    test.equal(result.transactions.length, 1);
    test.ok(result.parentHash);
    test.equal(result.parentHash, genesis.hash);
};
<|endoftext|>


<commit_before>
var after = require('after')
var Router = require('..')
var utils = require('./support/utils')

var assert = utils.assert
var createHitHandle = utils.createHitHandle
var shouldHitHandle = utils.shouldHitHandle
var shouldNotHitHandle = utils.shouldNotHitHandle
var createServer = utils.createServer
var request = utils.request

describe('Router', function () {
  describe('.param(name, fn)', function () {
    it('should reject missing name', function () {
      var router = new Router()
      assert.throws(router.param.bind(router), /argument name is required/)
    })

    it('should reject bad name', function () {
      var router = new Router()
      assert.throws(router.param.bind(router, 42), /argument name must be a string/)
    })

    it('should reject missing fn', function () {
      var router = new Router()
      assert.throws(router.param.bind(router, 'id'), /argument fn is required/)
    })

    it('should reject bad fn', function () {
      var router = new Router()
      assert.throws(router.param.bind(router, 'id', 42), /argument fn must be a function/)
    })

    it('should map logic for a path param', function (done) {
      var cb = after(2, done)
      var router = new Router()
      var server = createServer(router)

      router.param('id', function parseId(req, res, next, val) {
        req.params.id = Number(val)
        next()
      })

      router.get('/user/:id', function (req, res) {
        res.setHeader('Content-Type', 'text/plain')
        res.end('get user ' + req.params.id)
      })

      request(server)
      .get('/user/2')
      .expect(200, 'get user 2', cb)

      request(server)
      .get('/user/bob')
      .expect(200, 'get user NaN', cb)
    })

    it('should allow chaining', function (done) {
      var router = new Router()
      var server = createServer(router)

      router.param('id', function parseId(req, res, next, val) {
        req.params.id = Number(val)
        next()
      })

      router.param('id', function parseId(req, res, next, val) {
        req.itemId = Number(val)
        next()
      })

      router.get('/user/:id', function (req, res) {
        res.setHeader('Content-Type', 'text/plain')
        res.end('get user ' + req.params.id + ' (' + req.itemId + ')')
      })

      request(server)
      .get('/user/2')
      .expect(200, 'get user 2 (2)', done)
    })

    it('should automatically decode path value', function (done) {
      var router = new Router()
      var server = createServer(router)

      router.param('user', function parseUser(req, res, next, user) {
        req.user = user
        next()
      })

      router.get('/user/:id', function (req, res) {
        res.setHeader('Content-Type', 'text/plain')
        res.end('get user ' + req.params.id)
      })

      request(server)
      .get('/user/%22bob%2Frobert%22')
      .expect('get user "bob/robert"', done)
    })

    it('should 400 on invalid path value', function (done) {
      var router = new Router()
      var server = createServer(router)

      router.param('user', function parseUser(req, res, next, user) {
        req.user = user
        next()
      })

      router.get('/user/:id', function (req, res) {
        res.setHeader('Content-Type', 'text/plain')
        res.end('get user ' + req.params.id)
      })

      request(server)
      .get('/user/%bob')
      .expect(400, done)
    })

    it('should only invoke fn when necessary', function (done) {
      var cb = after(2, done)
      var router = new Router()
      var server = createServer(router)

      router.param('id', function parseId(req, res, next, val) {
        res.setHeader('x-id', val)
        next()
      })

      router.param('user', function parseUser(req, res, next, user) {
        throw new Error('boom')
      })

      router.get('/user/:user', saw)
      router.put('/user/:id', saw)

      request(server)
      .get('/user/bob')
      .expect(500, /Error: boom/, cb)

      request(server)
      .put('/user/bob')
      .expect('x-id', 'bob')
      .expect(200, 'saw PUT /user/bob', cb)
    })

    it('should only invoke fn once per request', function (done) {
      var router = new Router()
      var server = createServer(router)

      router.param('user', function parseUser(req, res, next, user) {
        req.count = (req.count || 0) + 1
        req.user = user
        next()
      })

      router.get('/user/:user', sethit(1))
      router.get('/user/:user', sethit(2))

      router.use(function (req, res) {
        res.end('get user ' + req.user + ' ' + req.count + ' times')
      })

      request(server)
      .get('/user/bob')
      .expect('get user bob 1 times', done)
    })

    it('should keep changes to req.params value', function (done) {
      var router = new Router()
      var server = createServer(router)

      router.param('id', function parseUser(req, res, next, val) {
        req.count = (req.count || 0) + 1
        req.params.id = Number(val)
        next()
      })

      router.get('/user/:id', function (req, res, next) {
        res.setHeader('x-user-id', req.params.id)
        next()
      })

      router.get('/user/:id', function (req, res) {
        res.end('get user ' + req.params.id + ' ' + req.count + ' times')
      })

      request(server)
      .get('/user/01')
      .expect('get user 1 1 times', done)
    })

    it('should invoke fn if path value differs', function (done) {
      var router = new Router()
      var server = createServer(router)

      router.param('user', function parseUser(req, res, next, user) {
        req.count = (req.count || 0) + 1
        req.user = user
        req.vals = (req.vals || []).concat(user)
        next()
      })

      router.get('/:user/bob', sethit(1))
      router.get('/user/:user', sethit(2))

      router.use(function (req, res) {
        res.end('get user ' + req.user + ' ' + req.count + ' times: ' + req.vals.join(', '))
      })

      request(server)
      .get('/user/bob')
      .expect('get user bob 2 times: user, bob', done)
    })

    it('should catch exception in fn', function (done) {
      var router = new Router()
      var server = createServer(router)

      router.param('user', function parseUser(req, res, next, user) {
        throw new Error('boom')
      })

      router.get('/user/:user', function (req, res) {
        res.setHeader('Content-Type', 'text/plain')
        res.end('get user ' + req.params.id)
      })

      request(server)
      .get('/user/bob')
      .expect(500, /Error: boom/, done)
    })

    it('should catch exception in chained fn', function (done) {
      var router = new Router()
      var server = createServer(router)

      router.param('user', function parseUser(req, res, next, user) {
        process.nextTick(next)
      })

      router.param('user', function parseUser(req, res, next, user) {
        throw new Error('boom')
      })

      router.get('/user/:user', function (req, res) {
        res.setHeader('Content-Type', 'text/plain')
        res.end('get user ' + req.params.id)
      })

      request(server)
      .get('/user/bob')
      .expect(500, /Error: boom/, done)
    })

    describe('next("route")', function () {
      it('should cause route with param to be skipped', function (done) {
        var cb = after(3, done)
        var router = new Router()
        var server = createServer(router)

        router.param('id', function parseId(req, res, next, val) {
          var id = Number(val)

          if (isNaN(id)) {
            return next('route')
          }

          req.params.id = id
          next()
        })

        router.get('/user/:id', function (req, res) {
          res.setHeader('Content-Type', 'text/plain')
          res.end('get user ' + req.params.id)
        })

        router.get('/user/new', function (req, res) {
          res.statusCode = 400
          res.setHeader('Content-Type', 'text/plain')
          res.end('cannot get a new user')
        })

        request(server)
        .get('/user/2')
        .expect(200, 'get user 2', cb)

        request(server)
        .get('/user/bob')
        .expect(404, cb)

        request(server)
        .get('/user/new')
        .expect(400, 'cannot get a new user', cb)
      })

      it('should invoke fn if path value differs', function (done) {
        var router = new Router()
        var server = createServer(router)

        router.param('user', function parseUser(req, res, next, user) {
          req.count = (req.count || 0) + 1
          req.user = user
          req.vals = (req.vals || []).concat(user)
          next(user === 'user' ? 'route' : null)
        })

        router.get('/:user/bob', createHitHandle(1))
        router.get('/user/:user', createHitHandle(2))

        router.use(function (req, res) {
          res.end('get user ' + req.user + ' ' + req.count + ' times: ' + req.vals.join(', '))
        })

        request(server)
        .get('/user/bob')
        .expect(shouldNotHitHandle(1))
        .expect(shouldHitHandle(2))
        .expect('get user bob 2 times: user, bob', done)
      })
    })
  })
})

function sethit(num) {
  var name = 'x-fn-' + String(num)
  return function hit(req, res, next) {
    res.setHeader(name, 'hit')
    next()
  }
}

function saw(req, res) {
  var msg = 'saw ' + req.method + ' ' + req.url
  res.statusCode = 200
  res.setHeader('Content-Type', 'text/plain')
  res.end(msg)
}
<commit_msg>test: check expected decode error message<commit_after>
var after = require('after')
var Router = require('..')
var utils = require('./support/utils')

var assert = utils.assert
var createHitHandle = utils.createHitHandle
var shouldHitHandle = utils.shouldHitHandle
var shouldNotHitHandle = utils.shouldNotHitHandle
var createServer = utils.createServer
var request = utils.request

describe('Router', function () {
  describe('.param(name, fn)', function () {
    it('should reject missing name', function () {
      var router = new Router()
      assert.throws(router.param.bind(router), /argument name is required/)
    })

    it('should reject bad name', function () {
      var router = new Router()
      assert.throws(router.param.bind(router, 42), /argument name must be a string/)
    })

    it('should reject missing fn', function () {
      var router = new Router()
      assert.throws(router.param.bind(router, 'id'), /argument fn is required/)
    })

    it('should reject bad fn', function () {
      var router = new Router()
      assert.throws(router.param.bind(router, 'id', 42), /argument fn must be a function/)
    })

    it('should map logic for a path param', function (done) {
      var cb = after(2, done)
      var router = new Router()
      var server = createServer(router)

      router.param('id', function parseId(req, res, next, val) {
        req.params.id = Number(val)
        next()
      })

      router.get('/user/:id', function (req, res) {
        res.setHeader('Content-Type', 'text/plain')
        res.end('get user ' + req.params.id)
      })

      request(server)
      .get('/user/2')
      .expect(200, 'get user 2', cb)

      request(server)
      .get('/user/bob')
      .expect(200, 'get user NaN', cb)
    })

    it('should allow chaining', function (done) {
      var router = new Router()
      var server = createServer(router)

      router.param('id', function parseId(req, res, next, val) {
        req.params.id = Number(val)
        next()
      })

      router.param('id', function parseId(req, res, next, val) {
        req.itemId = Number(val)
        next()
      })

      router.get('/user/:id', function (req, res) {
        res.setHeader('Content-Type', 'text/plain')
        res.end('get user ' + req.params.id + ' (' + req.itemId + ')')
      })

      request(server)
      .get('/user/2')
      .expect(200, 'get user 2 (2)', done)
    })

    it('should automatically decode path value', function (done) {
      var router = new Router()
      var server = createServer(router)

      router.param('user', function parseUser(req, res, next, user) {
        req.user = user
        next()
      })

      router.get('/user/:id', function (req, res) {
        res.setHeader('Content-Type', 'text/plain')
        res.end('get user ' + req.params.id)
      })

      request(server)
      .get('/user/%22bob%2Frobert%22')
      .expect('get user "bob/robert"', done)
    })

    it('should 400 on invalid path value', function (done) {
      var router = new Router()
      var server = createServer(router)

      router.param('user', function parseUser(req, res, next, user) {
        req.user = user
        next()
      })

      router.get('/user/:id', function (req, res) {
        res.setHeader('Content-Type', 'text/plain')
        res.end('get user ' + req.params.id)
      })

      request(server)
      .get('/user/%bob')
      .expect(400, /URIError: Failed to decode param/, done)
    })

    it('should only invoke fn when necessary', function (done) {
      var cb = after(2, done)
      var router = new Router()
      var server = createServer(router)

      router.param('id', function parseId(req, res, next, val) {
        res.setHeader('x-id', val)
        next()
      })

      router.param('user', function parseUser(req, res, next, user) {
        throw new Error('boom')
      })

      router.get('/user/:user', saw)
      router.put('/user/:id', saw)

      request(server)
      .get('/user/bob')
      .expect(500, /Error: boom/, cb)

      request(server)
      .put('/user/bob')
      .expect('x-id', 'bob')
      .expect(200, 'saw PUT /user/bob', cb)
    })

    it('should only invoke fn once per request', function (done) {
      var router = new Router()
      var server = createServer(router)

      router.param('user', function parseUser(req, res, next, user) {
        req.count = (req.count || 0) + 1
        req.user = user
        next()
      })

      router.get('/user/:user', sethit(1))
      router.get('/user/:user', sethit(2))

      router.use(function (req, res) {
        res.end('get user ' + req.user + ' ' + req.count + ' times')
      })

      request(server)
      .get('/user/bob')
      .expect('get user bob 1 times', done)
    })

    it('should keep changes to req.params value', function (done) {
      var router = new Router()
      var server = createServer(router)

      router.param('id', function parseUser(req, res, next, val) {
        req.count = (req.count || 0) + 1
        req.params.id = Number(val)
        next()
      })

      router.get('/user/:id', function (req, res, next) {
        res.setHeader('x-user-id', req.params.id)
        next()
      })

      router.get('/user/:id', function (req, res) {
        res.end('get user ' + req.params.id + ' ' + req.count + ' times')
      })

      request(server)
      .get('/user/01')
      .expect('get user 1 1 times', done)
    })

    it('should invoke fn if path value differs', function (done) {
      var router = new Router()
      var server = createServer(router)

      router.param('user', function parseUser(req, res, next, user) {
        req.count = (req.count || 0) + 1
        req.user = user
        req.vals = (req.vals || []).concat(user)
        next()
      })

      router.get('/:user/bob', sethit(1))
      router.get('/user/:user', sethit(2))

      router.use(function (req, res) {
        res.end('get user ' + req.user + ' ' + req.count + ' times: ' + req.vals.join(', '))
      })

      request(server)
      .get('/user/bob')
      .expect('get user bob 2 times: user, bob', done)
    })

    it('should catch exception in fn', function (done) {
      var router = new Router()
      var server = createServer(router)

      router.param('user', function parseUser(req, res, next, user) {
        throw new Error('boom')
      })

      router.get('/user/:user', function (req, res) {
        res.setHeader('Content-Type', 'text/plain')
        res.end('get user ' + req.params.id)
      })

      request(server)
      .get('/user/bob')
      .expect(500, /Error: boom/, done)
    })

    it('should catch exception in chained fn', function (done) {
      var router = new Router()
      var server = createServer(router)

      router.param('user', function parseUser(req, res, next, user) {
        process.nextTick(next)
      })

      router.param('user', function parseUser(req, res, next, user) {
        throw new Error('boom')
      })

      router.get('/user/:user', function (req, res) {
        res.setHeader('Content-Type', 'text/plain')
        res.end('get user ' + req.params.id)
      })

      request(server)
      .get('/user/bob')
      .expect(500, /Error: boom/, done)
    })

    describe('next("route")', function () {
      it('should cause route with param to be skipped', function (done) {
        var cb = after(3, done)
        var router = new Router()
        var server = createServer(router)

        router.param('id', function parseId(req, res, next, val) {
          var id = Number(val)

          if (isNaN(id)) {
            return next('route')
          }

          req.params.id = id
          next()
        })

        router.get('/user/:id', function (req, res) {
          res.setHeader('Content-Type', 'text/plain')
          res.end('get user ' + req.params.id)
        })

        router.get('/user/new', function (req, res) {
          res.statusCode = 400
          res.setHeader('Content-Type', 'text/plain')
          res.end('cannot get a new user')
        })

        request(server)
        .get('/user/2')
        .expect(200, 'get user 2', cb)

        request(server)
        .get('/user/bob')
        .expect(404, cb)

        request(server)
        .get('/user/new')
        .expect(400, 'cannot get a new user', cb)
      })

      it('should invoke fn if path value differs', function (done) {
        var router = new Router()
        var server = createServer(router)

        router.param('user', function parseUser(req, res, next, user) {
          req.count = (req.count || 0) + 1
          req.user = user
          req.vals = (req.vals || []).concat(user)
          next(user === 'user' ? 'route' : null)
        })

        router.get('/:user/bob', createHitHandle(1))
        router.get('/user/:user', createHitHandle(2))

        router.use(function (req, res) {
          res.end('get user ' + req.user + ' ' + req.count + ' times: ' + req.vals.join(', '))
        })

        request(server)
        .get('/user/bob')
        .expect(shouldNotHitHandle(1))
        .expect(shouldHitHandle(2))
        .expect('get user bob 2 times: user, bob', done)
      })
    })
  })
})

function sethit(num) {
  var name = 'x-fn-' + String(num)
  return function hit(req, res, next) {
    res.setHeader(name, 'hit')
    next()
  }
}

function saw(req, res) {
  var msg = 'saw ' + req.method + ' ' + req.url
  res.statusCode = 200
  res.setHeader('Content-Type', 'text/plain')
  res.end(msg)
}
<|endoftext|>


<commit_before>import React      from 'react'
import ReactDOM   from 'react-dom'
import { expect } from 'chai'
import A11y       from '../src/a11y'
import rules      from '../src/rules'

describe('rules', () => {
  Object.keys(rules).forEach(function (rule) {
    describe(rule, () => {
      const {
        'default': defn
      , pass = []
      , fail = []
      } = require('../src/rules/' + rule)

      // get all messages
      const msgs = defn.reduce((acc, def) => acc.concat(def.msg), [])

      pass.forEach(function (ok) {
        it(`doesn't warn when ${ok.when}`, done => {
          const a11y = new A11y(React, ReactDOM, {
            reporter (info) {
              const {
                msg
              } = info
              expect(msgs.indexOf(msg) >= 0).to.be.true
            }
          , rules: {
              [rule]: 'warn'
            }
          })

          // force a11y into sync mode for test
          a11y.__forceSync(true)

          // create the el
          ok.render(React)

          // restore and finish
          a11y.restoreAll()
          done()
        })
      })

      fail.forEach(function (bad) {
        it(`warns when ${bad.when}`, done => {
          let called = false
          const a11y = new A11y(React, ReactDOM, {
            reporter (info) {
              called = true
              const {
                msg
              } = info
              expect(msgs.indexOf(msg) >= 0).to.be.true
            }
          , rules: {
              [rule]: 'warn'
            }
          })

          // force a11y into sync mode for test
          a11y.__forceSync(true)

          // create the el
          bad.render(React)

          // make sure error was presented
          expect(called).to.be.true

          a11y.restoreAll()
          done()
        })
      })
    })
  })
})
<commit_msg>allow options in tests<commit_after>import React      from 'react'
import ReactDOM   from 'react-dom'
import { expect } from 'chai'
import A11y       from '../src/a11y'
import rules      from '../src/rules'

describe('rules', () => {
  Object.keys(rules).forEach(function (rule) {
    describe(rule, () => {
      const {
        'default': defn
      , pass = []
      , fail = []
      } = require('../src/rules/' + rule)

      // get all messages
      const msgs = defn.reduce((acc, def) => acc.concat(def.msg), [])

      pass.forEach(function (ok) {
        it(`doesn't warn when ${ok.when}`, done => {
          const a11y = new A11y(React, ReactDOM, {
            reporter (info) {
              const {
                msg
              } = info
              expect(msgs.indexOf(msg) >= 0).to.be.true
            }
          , rules: {
              [rule]: [
                'warn'
              , ...(ok.opts || [])
              ]
            }
          })

          // force a11y into sync mode for test
          a11y.__forceSync(true)

          // create the el
          ok.render(React)

          // restore and finish
          a11y.restoreAll()
          done()
        })
      })

      fail.forEach(function (bad) {
        it(`warns when ${bad.when}`, done => {
          let called = false
          const a11y = new A11y(React, ReactDOM, {
            reporter (info) {
              called = true
              const {
                msg
              } = info
              expect(msgs.indexOf(msg) >= 0).to.be.true
            }
          , rules: {
              [rule]: [
                'warn'
              , ...(bad.opts || [])
              ]
            }
          })

          // force a11y into sync mode for test
          a11y.__forceSync(true)

          // create the el
          bad.render(React)

          // make sure error was presented
          expect(called).to.be.true

          a11y.restoreAll()
          done()
        })
      })
    })
  })
})
<|endoftext|>


<commit_before>'use strict';

process.on('unhandledRejection', function (reason, p) {
    throw p;
});

process.env.REST_ON_COUCH_HOME_DIR = __dirname + '/homedir';

require('../lib/util/load')();
const server = require('../lib/server/server');
const supertest = require('supertest-as-promised')(Promise);

exports.getAgent = function () {
    return supertest.agent(server.app.callback());
};
<commit_msg>remove problematic call for travis tests<commit_after>'use strict';

process.on('unhandledRejection', function (reason, p) {
    throw p;
});

process.env.REST_ON_COUCH_HOME_DIR = __dirname + '/homedir';

// require('../lib/util/load')();
const server = require('../lib/server/server');
const supertest = require('supertest-as-promised')(Promise);

exports.getAgent = function () {
    return supertest.agent(server.app.callback());
};
<|endoftext|>


<commit_before>var mocha = require('../')
  , Suite = mocha.Suite;

describe('Suite', function() {
  describe('when initialized', function() {
    beforeEach(function() {
      this.suite = new Suite('A Suite');
    });

    it('is initialized with a title', function() {
      this.suite.title.should.equal('A Suite');
    });

    it('the suites array is empty', function() {
      this.suite.suites.should.be.empty;
    });

    it('the tests array is empty', function() {
      this.suite.tests.should.be.empty;
    });

    it('the _beforeEach array is empty', function() {
      this.suite._beforeEach.should.be.empty;
    });

    it('the _beforeAll array is empty', function() {
      this.suite._beforeEach.should.be.empty;
    });

    it('the _afterEach array is empty', function() {
      this.suite._afterEach.should.be.empty;
    });

    it('the _afterAll array is empty', function() {
      this.suite._afterAll.should.be.empty;
    });

    it('the root is false', function() {
      this.suite.root.should.be.false;
    });

    it('the _timeout is 2000', function() {
      this.suite._timeout.should.equal(2000);
    });

    it('the _bail is false', function() {
      this.suite._bail.should.be.false;
    });
  });

  describe('cloning', function() {
    beforeEach(function() {
      this.suite = new Suite('To be cloned');
      this.suite._timeout = 3043;
      this.suite._bail = true;
      this.suite.suites.push(1);
      this.suite.tests.push('hello');
      this.suite._beforeEach.push(2);
      this.suite._beforeAll.push(3);
      this.suite._afterEach.push(4);
      this.suite._afterAll.push(5);
    });

    describe('copies', function() {
      it('the title', function() {
        this.suite.clone().title.should.equal('To be cloned');
      });

      it('the timeout value', function() {
        this.suite.clone().timeout().should.equal(3043);
      });

      it('the bail value', function() {
        this.suite.clone().bail().should.be.true;
      });
    });

    describe('does NOT copy', function() {
      it('the values from the suites array', function() {
        this.suite.clone().suites.should.be.empty;
      });

      it('the values from the tests array', function() {
        this.suite.clone().tests.should.be.empty;
      });

      it('the values from the _beforeEach array', function() {
        this.suite.clone()._beforeEach.should.be.empty;
      });

      it('the values from the _beforeAll array', function() {
        this.suite.clone()._beforeAll.should.be.empty;
      });

      it('the values from the _afterEach array', function() {
        this.suite.clone()._afterEach.should.be.empty;
      });

      it('the values from the _afterAll array', function() {
        this.suite.clone()._afterAll.should.be.empty;
      });
    });

  });
});
<commit_msg>Completing the spec for suite.js<commit_after>var mocha = require('../')
  , Suite = mocha.Suite
  , Test = mocha.Test;

describe('Suite', function() {
  describe('when initialized', function() {
    beforeEach(function() {
      this.suite = new Suite('A Suite');
    });

    it('is initialized with a title', function() {
      this.suite.title.should.equal('A Suite');
    });

    it('the suites array is empty', function() {
      this.suite.suites.should.be.empty;
    });

    it('the tests array is empty', function() {
      this.suite.tests.should.be.empty;
    });

    it('the _beforeEach array is empty', function() {
      this.suite._beforeEach.should.be.empty;
    });

    it('the _beforeAll array is empty', function() {
      this.suite._beforeEach.should.be.empty;
    });

    it('the _afterEach array is empty', function() {
      this.suite._afterEach.should.be.empty;
    });

    it('the _afterAll array is empty', function() {
      this.suite._afterAll.should.be.empty;
    });

    it('the root is false', function() {
      this.suite.root.should.be.false;
    });

    it('the _timeout is 2000', function() {
      this.suite._timeout.should.equal(2000);
    });

    it('the _bail is false', function() {
      this.suite._bail.should.be.false;
    });
  });

  describe('cloning', function() {
    beforeEach(function() {
      this.suite = new Suite('To be cloned');
      this.suite._timeout = 3043;
      this.suite._bail = true;
      this.suite.suites.push(1);
      this.suite.tests.push('hello');
      this.suite._beforeEach.push(2);
      this.suite._beforeAll.push(3);
      this.suite._afterEach.push(4);
      this.suite._afterAll.push(5);
    });

    describe('copies', function() {
      it('the title', function() {
        this.suite.clone().title.should.equal('To be cloned');
      });

      it('the timeout value', function() {
        this.suite.clone().timeout().should.equal(3043);
      });

      it('the bail value', function() {
        this.suite.clone().bail().should.be.true;
      });
    });

    describe('does NOT copy', function() {
      it('the values from the suites array', function() {
        this.suite.clone().suites.should.be.empty;
      });

      it('the values from the tests array', function() {
        this.suite.clone().tests.should.be.empty;
      });

      it('the values from the _beforeEach array', function() {
        this.suite.clone()._beforeEach.should.be.empty;
      });

      it('the values from the _beforeAll array', function() {
        this.suite.clone()._beforeAll.should.be.empty;
      });

      it('the values from the _afterEach array', function() {
        this.suite.clone()._afterEach.should.be.empty;
      });

      it('the values from the _afterAll array', function() {
        this.suite.clone()._afterAll.should.be.empty;
      });
    });

  });

  describe('timeout', function() {
    beforeEach(function() {
      this.suite = new Suite('A Suite');
    });

    describe('when no argument is passed', function() {
      it('returns the _timeout value', function() {
        this.suite.timeout().should.equal(2000);
      });
    });

    describe('when argument is passed', function() {
      it('returns the Suite object', function() {
        var newSuite = this.suite.timeout(5000);
        newSuite.timeout().should.equal(5000);
      });
    });
  });

  describe('bail', function() {
    beforeEach(function() {
      this.suite = new Suite('A Suite');
      this.suite._bail = true
    });

    describe('when no argument is passed', function() {
      it('returns the _bail value', function() {
        this.suite.bail().should.be.true;
      });
    });

    describe('when argument is passed', function() {
      it('returns the Suite object', function() {
        var newSuite = this.suite.bail(false);
        newSuite.bail().should.be.false;
      });
    });
  });

  describe('beforeAll', function() {
    beforeEach(function() {
      this.suite = new Suite('A Suite');
    });

    describe('wraps the passed in function in a Hook', function() {
      it('adds it to _beforeAll', function() {
        var inputFn = function() {}
        this.suite.beforeAll(inputFn);

        this.suite._beforeAll.should.have.length(1);
        var beforeAllItem = this.suite._beforeAll[0];
        beforeAllItem.title.should.equal('"before all" hook');
        beforeAllItem.fn.should.equal(inputFn);
      });
    });
  });

  describe('afterAll', function() {
    beforeEach(function() {
      this.suite = new Suite('A Suite');
    });

    describe('wraps the passed in function in a Hook', function() {
      it('adds it to _afterAll', function() {
        var inputFn = function() {}
        this.suite.afterAll(inputFn);

        this.suite._afterAll.should.have.length(1);
        var afterAllItem = this.suite._afterAll[0];
        afterAllItem.title.should.equal('"after all" hook');
        afterAllItem.fn.should.equal(inputFn);
      });
    });
  });

  describe('beforeEach', function() {
    beforeEach(function() {
      this.suite = new Suite('A Suite');
    });

    describe('wraps the passed in function in a Hook', function() {
      it('adds it to _beforeEach', function() {
        var inputFn = function() {}
        this.suite.beforeEach(inputFn);

        this.suite._beforeEach.should.have.length(1);
        var beforeEachItem = this.suite._beforeEach[0];
        beforeEachItem.title.should.equal('"before each" hook');
        beforeEachItem.fn.should.equal(inputFn);
      });
    });
  });

  describe('afterEach', function() {
    beforeEach(function() {
      this.suite = new Suite('A Suite');
    });

    describe('wraps the passed in function in a Hook', function() {
      it('adds it to _afterEach', function() {
        var inputFn = function() {}
        this.suite.afterEach(inputFn);

        this.suite._afterEach.should.have.length(1);
        var afterEachItem = this.suite._afterEach[0];
        afterEachItem.title.should.equal('"after each" hook');
        afterEachItem.fn.should.equal(inputFn);
      });
    });
  });

  describe('addSuite', function() {
    beforeEach(function() {
      this.suite = new Suite('A Suite');
      this.suite.timeout(4002);
      this.suiteToAdd = new Suite('Suite to Add');
      this.suite.addSuite(this.suiteToAdd);
    });

    it('sets the parent on the added Suite', function() {
      this.suiteToAdd.parent.should.equal(this.suite);
    });

    it('copies the timeout value', function() {
      this.suiteToAdd.timeout().should.equal(4002);
    });

    it('adds the suite to the suites collection', function() {
      this.suite.suites.should.have.length(1);
      this.suite.suites[0].should.equal(this.suiteToAdd);
    });
  });

  describe('addTest', function() {
    beforeEach(function() {
      this.suite = new Suite('A Suite');
      this.suite.timeout(4002);
      this.testToAdd = new Test('Suite to Add');
      this.suite.addTest(this.testToAdd);
    });

    it('sets the parent on the added test', function() {
      this.testToAdd.parent.should.equal(this.suite);
    });

    it('copies the timeout value', function() {
      this.testToAdd.timeout().should.equal(4002);
    });

    it('adds the test to the tests collection', function() {
      this.suite.tests.should.have.length(1);
      this.suite.tests[0].should.equal(this.testToAdd);
    });
  });

  describe('fullTitle', function() {
    beforeEach(function() {
      this.suite = new Suite('A Suite');
    });

    describe('when there is no parent', function() {
      it('returns the suite title', function() {
        this.suite.fullTitle().should.equal('A Suite');
      });
    });

    describe('when there is a parent', function() {
      it('returns the combination of parent\'s and suite title', function() {
        var parentSuite = new Suite('I am a parent');
        parentSuite.addSuite(this.suite);
        this.suite.fullTitle().should.equal('I am a parent A Suite');
      });
    });
  });

  describe('total', function() {
    beforeEach(function() {
      this.suite = new Suite('A Suite');
    });

    describe('when there are no other suites or tests under the suite', function() {
      it('returns 0', function() {
        this.suite.total().should.equal(0);
      });
    });

    describe('when there are two tests under the suite', function() {
      it('returns 1', function() {
        this.suite.addTest(new Test('a child test'));
        this.suite.addTest(new Test('another child test'));
        this.suite.total().should.equal(2);
      });
    });
  });
});
<|endoftext|>


<commit_before>var mocha = require('../')
  , Suite = mocha.Suite;

describe('Suite', function() {
  describe('when initialized', function() {
    beforeEach(function() {
      this.suite = new Suite('A Suite');
    });

    it('is initialized with a title', function() {
      this.suite.title.should.equal('A Suite');
    });

    it('the suites array is empty', function() {
      this.suite.suites.length.should.equal(0);
    });

    it('the tests array is empty', function() {
      this.suite.tests.length.should.equal(0);
    });

    it('the _beforeEach array is empty', function() {
      this.suite._beforeEach.length.should.equal(0);
    });

    it('the _beforeAll array is empty', function() {
      this.suite._beforeEach.length.should.equal(0);
    });

    it('the _afterEach array is empty', function() {
      this.suite._afterEach.length.should.equal(0);
    });

    it('the _afterAll array is empty', function() {
      this.suite._afterAll.length.should.equal(0);
    });

    it('the root is false', function() {
      this.suite.root.should.equal(false);
    });

    it('the _timeout is 2000', function() {
      this.suite._timeout.should.equal(2000);
    });

    it('the _bail is false', function() {
      this.suite._bail.should.equal(false);
    });
  });

  describe('cloning', function() {
    beforeEach(function() {
      this.suite = new Suite('To be cloned');
      this.suite._timeout = 3043;
      this.suite._bail = true;
      this.suite.suites.push(1);
      this.suite.tests.push('hello');
      this.suite._beforeEach.push(2);
      this.suite._beforeAll.push(3);
      this.suite._afterEach.push(4);
      this.suite._afterAll.push(5);
    });

    describe('copies', function() {
      it('the title', function() {
        this.suite.clone().title.should.equal('To be cloned');
      });

      it('the timeout value', function() {
        this.suite.clone().timeout().should.equal(3043);
      });

      it('the bail value', function() {
        this.suite.clone().bail().should.equal(true);
      });
    });

    describe('does NOT copy', function() {
      it('the values from the suites array', function() {
        this.suite.clone().suites.length.should.equal(0);
      });

      it('the values from the tests array', function() {
        this.suite.clone().tests.length.should.equal(0);
      });

      it('the values from the _beforeEach array', function() {
        this.suite.clone()._beforeEach.length.should.equal(0);
      });

      it('the values from the _beforeAll array', function() {
        this.suite.clone()._beforeAll.length.should.equal(0);
      });

      it('the values from the _afterEach array', function() {
        this.suite.clone()._afterEach.length.should.equal(0);
      });

      it('the values from the _afterAll array', function() {
        this.suite.clone()._afterAll.length.should.equal(0);
      });
    });

  });
});
<commit_msg>Using the correct 'should' matchers<commit_after>var mocha = require('../')
  , Suite = mocha.Suite;

describe('Suite', function() {
  describe('when initialized', function() {
    beforeEach(function() {
      this.suite = new Suite('A Suite');
    });

    it('is initialized with a title', function() {
      this.suite.title.should.equal('A Suite');
    });

    it('the suites array is empty', function() {
      this.suite.suites.should.have.length(0);
    });

    it('the tests array is empty', function() {
      this.suite.tests.should.have.length(0);
    });

    it('the _beforeEach array is empty', function() {
      this.suite._beforeEach.should.have.length(0);
    });

    it('the _beforeAll array is empty', function() {
      this.suite._beforeEach.should.have.length(0);
    });

    it('the _afterEach array is empty', function() {
      this.suite._afterEach.should.have.length(0);
    });

    it('the _afterAll array is empty', function() {
      this.suite._afterAll.should.have.length(0);
    });

    it('the root is false', function() {
      this.suite.root.should.be.false;
    });

    it('the _timeout is 2000', function() {
      this.suite._timeout.should.equal(2000);
    });

    it('the _bail is false', function() {
      this.suite._bail.should.be.false;
    });
  });

  describe('cloning', function() {
    beforeEach(function() {
      this.suite = new Suite('To be cloned');
      this.suite._timeout = 3043;
      this.suite._bail = true;
      this.suite.suites.push(1);
      this.suite.tests.push('hello');
      this.suite._beforeEach.push(2);
      this.suite._beforeAll.push(3);
      this.suite._afterEach.push(4);
      this.suite._afterAll.push(5);
    });

    describe('copies', function() {
      it('the title', function() {
        this.suite.clone().title.should.equal('To be cloned');
      });

      it('the timeout value', function() {
        this.suite.clone().timeout().should.equal(3043);
      });

      it('the bail value', function() {
        this.suite.clone().bail().should.be.true;
      });
    });

    describe('does NOT copy', function() {
      it('the values from the suites array', function() {
        this.suite.clone().suites.should.have.length(0);
      });

      it('the values from the tests array', function() {
        this.suite.clone().tests.should.have.length(0);
      });

      it('the values from the _beforeEach array', function() {
        this.suite.clone()._beforeEach.should.have.length(0);
      });

      it('the values from the _beforeAll array', function() {
        this.suite.clone()._beforeAll.should.have.length(0);
      });

      it('the values from the _afterEach array', function() {
        this.suite.clone()._afterEach.should.have.length(0);
      });

      it('the values from the _afterAll array', function() {
        this.suite.clone()._afterAll.should.have.length(0);
      });
    });

  });
});
<|endoftext|>


<commit_before>(function($) {

    // empty text
    $.mockjax({
        url: '/api/no-content.json',
        responseText: {
            the_text: {
                html: '',
                text: ''
            }
        }
    });

    // one field
    $.mockjax({
        url: '/api/hello.json',
        responseText: {
            the_text: {
                html: '
Hello World!
',
                text: 'Hello *World*!'
            }
        }
    });

    var $baseDiv = $('
').attr('data-name', 'the_text'),
        body     = document.body;

    test( 'no URL', function() {

        var $theDiv = $baseDiv.clone().appendTo(body);

        throws( function() { $theDiv.ajaxedit();   }, Error);
        throws( function() { $theDiv.ajaxedit({}); }, Error);

        $theDiv.remove();
    });

    test( 'hover button', function() {

        var $theDiv = $baseDiv.clone().appendTo(body);

        ok(
            $theDiv.ajaxedit({
                url: '/api/no-content'
            })
        );

        ok( $('input[type="button"]', $theDiv).length === 0 );

        $theDiv.trigger('mouseenter');
        ok( $('input[type="button"]', $theDiv).length === 1 );

        $theDiv.trigger('mouseleave');
        ok( $('input[type="button"]', $theDiv).length === 0 );

        $theDiv.remove();

    });

    test( 'edit on 1 event', function() {

        var $theDiv = $baseDiv.clone().appendTo(body);

        ok(
            $theDiv.ajaxedit({
                url: '/api/no-content',
                editOn: 'mouseover'
            })
        );

        $theDiv.trigger('mouseover');

        $theDiv.remove();

    });

    test( 'edit on multiple events', function() {

        var $theDiv = $baseDiv.clone().appendTo(body);

        ok(
            $theDiv.ajaxedit({
                url: '/api/no-content',
                editOn: ['mouseover', 'hoverButton', 'click']
            })
        );

        $theDiv.trigger('mouseover');

        $theDiv.remove();

    });

})(jQuery);
<commit_msg>URLs fixed, one test added<commit_after>(function($) {

    // empty text
    $.mockjax({
        url: '/api/no-content.json',
        responseText: {
            the_text: {
                html: '',
                text: ''
            }
        }
    });

    // one field
    $.mockjax({
        url: '/api/hello.json',
        responseText: {
            the_text: {
                html: '
Hello World!
',
                text: 'Hello *World*!'
            }
        }
    });

    var $baseDiv = $('
').attr('data-name', 'the_text'),
        body     = document.body;

    test( 'no element', function() {

        ok( $('#no-elem').ajaxedit('foo') );

    });

    test( 'no URL', function() {

        var $theDiv = $baseDiv.clone().appendTo(body);

        throws( function() { $theDiv.ajaxedit();   }         , Error);
        throws( function() { $theDiv.ajaxedit(''); }         , Error);
        throws( function() { $theDiv.ajaxedit({}); }         , Error);
        throws( function() { $theDiv.ajaxedit({ url: '' }); }, Error);

        $theDiv.remove();
    });

    test( 'hover button', function() {

        var $theDiv = $baseDiv.clone().appendTo(body);

        ok(
            $theDiv.ajaxedit({
                url: '/api/no-content.json'
            })
        );

        ok( $('input[type="button"]', $theDiv).length === 0 );

        $theDiv.trigger('mouseenter');
        ok( $('input[type="button"]', $theDiv).length === 1 );

        $theDiv.trigger('mouseleave');
        ok( $('input[type="button"]', $theDiv).length === 0 );

        $theDiv.remove();

    });

    test( 'edit on 1 event', function() {

        var $theDiv = $baseDiv.clone().appendTo(body);

        ok(
            $theDiv.ajaxedit({
                url: '/api/no-content.json',
                editOn: 'mouseover'
            })
        );

        $theDiv.trigger('mouseover');

        $theDiv.remove();

    });

    test( 'edit on multiple events', function() {

        var $theDiv = $baseDiv.clone().appendTo(body);

        ok(
            $theDiv.ajaxedit({
                url: '/api/no-content.json',
                editOn: ['mouseover', 'hoverButton', 'click']
            })
        );

        $theDiv.trigger('mouseover');

        $theDiv.remove();

    });

    test( 'bad url', function() {

        var $theDiv = $baseDiv.clone().appendTo(body);

        ok(
            $theDiv.ajaxedit({
                url: '/api/bad-url'
            })
        );

        // there should be no exception
        $theDiv.trigger('mouseenter');

        $theDiv.remove();

    });

})(jQuery);
<|endoftext|>


<commit_before>function runAll() {
	asyncTest("does setImmediate call the handler", 1, function () {
		function pass() {
			if (timer) clearTimeout(timer);
			ok(true, 'it worked! the handler was called');
			start();
		}
		function fail() {
			ok(false, 'FAILED! the handler was never called');
			start();
		}

		var timer = setTimeout(fail, 1000);
		setImmediate(pass);
	});

	asyncTest("does setImmediate call the handler WITH one argument", 1, function () {
		var timer;
		function pass(abc) {
			if (timer) {clearTimeout(timer);}
			if (abc === "abc") {
				ok(true, 'it worked! the handler was called with the correct arguments');
			} else {
				ok(false, 'the handler was called but the arguments were incorrect');
			}
			start();
		}
		setImmediate(pass, "abc");
	});

	asyncTest("does setImmediate call the handler WITH two arguments", 1, function () {
		var timer;
		function pass(abc, num) {
			if (timer) {clearTimeout(timer);}
			if (abc === "abc" && num === 123) {
				ok(true, 'it worked! the handler was called with the correct arguments');
			} else {
				ok(false, 'the handler was called but the arguments were incorrect');
			}
			start();
		}
		setImmediate(pass, "abc", 123);
	});

	asyncTest("does clearImmediate clear a setImmediate that was just set", 1, function () {
		function pass() {
			if (timer) clearTimeout(timer);
			ok(false, 'FAILED! the handler was called');
			start();
		}
		function fail() {
			start();
			ok(true, 'it worked! the handler was correctly never called');
		}

		var timer = setTimeout(fail, 1000);
		var handle = setImmediate(pass);
		clearImmediate(handle);
	});

	asyncTest("does clearImmediate clear a non-sequential setImmediate", 2, function () {

		var y = 1;

		function pass(x) {
			switch (x) {
			case 1:
				strictEqual(y, 1, "setImmediate(pass, 1)");
				break;
			case 2:
				ok(false, 'oops! should not be here. x={0} y={1}'.format(x,y));
				break;
			case 3:
				strictEqual(y, 2, "setImmediate(pass, 3)");
				start();
				break;
			}
			y++;
		}

		setImmediate(pass, 1);
		var handle = setImmediate(pass, 2);
		clearImmediate(handle);
		setImmediate(pass, 3);
	});

	asyncTest("Does setImmediate yield to subsequent code before executing its callback", 2, function () {
    var callbackCalled = false;
    function callback() {
      callbackCalled = true;

      ok(true, "The callback was called eventually.");

      start();
    }

    setImmediate(callback);
    strictEqual(callbackCalled, false, "The callback wasn't called immediately.");
	});
}
<commit_msg>Test cleanup.<commit_after>function runAll() {
	asyncTest("Does setImmediate call the handler", 1, function () {
		function pass() {
			if (timer) {
				clearTimeout(timer);
			}
			ok(true, 'it worked! the handler was called');
			start();
		}
		function fail() {
			ok(false, 'FAILED! the handler was never called');
			start();
		}

		var timer = setTimeout(fail, 1000);
		setImmediate(pass);
	});

	asyncTest("Does setImmediate call the handler WITH one argument", 1, function () {
		function pass(abc) {
			if (abc === "abc") {
				ok(true, 'it worked! the handler was called with the correct arguments');
			} else {
				ok(false, 'the handler was called but the arguments were incorrect');
			}
			start();
		}
		setImmediate(pass, "abc");
	});

	asyncTest("Does setImmediate call the handler WITH two arguments", 1, function () {
		function pass(abc, num) {
			if (abc === "abc" && num === 123) {
				ok(true, 'it worked! the handler was called with the correct arguments');
			} else {
				ok(false, 'the handler was called but the arguments were incorrect');
			}
			start();
		}
		setImmediate(pass, "abc", 123);
	});

	asyncTest("Does clearImmediate clear a setImmediate that was just set", 1, function () {
		function pass() {
			clearTimeout(timer);
			ok(false, 'FAILED! the handler was called');
			start();
		}
		function fail() {
			start();
			ok(true, 'it worked! the handler was correctly never called');
		}

		var timer = setTimeout(fail, 1000);
		var handle = setImmediate(pass);
		clearImmediate(handle);
	});

	asyncTest("Does clearImmediate clear a non-sequential setImmediate", 2, function () {
		var y = 1;

		function pass(x) {
			switch (x) {
			case 1:
				strictEqual(y, 1, "setImmediate(pass, 1)");
				break;
			case 2:
				ok(false, 'oops! should not be here. x=' + x + ' y=' + y);
				break;
			case 3:
				strictEqual(y, 2, "setImmediate(pass, 3)");
				start();
				break;
			}
			y++;
		}

		setImmediate(pass, 1);
		var handle = setImmediate(pass, 2);
		clearImmediate(handle);
		setImmediate(pass, 3);
	});

	asyncTest("Does setImmediate yield to subsequent code before executing its callback", 2, function () {
		var callbackCalled = false;
		function callback() {
		  callbackCalled = true;

		  ok(true, "The callback was called eventually.");

		  start();
		}

		setImmediate(callback);
		strictEqual(callbackCalled, false, "The callback wasn't called immediately.");
	});
}
<|endoftext|>


<commit_before>const tap = require('tap');
const fastly = require('../lib/fastly.js');
const fastly_api_key =  process.env.FASTLY_API_KEY || ''

tap.test('utilities', function(t) {

	var flib = new fastly(fastly_api_key);

	t.type(flib, 'object', 'constructor');
	t.type(flib.content, 'function', 'method content');
	t.type(flib.datacenters, 'function', 'method datacenters');
	t.type(flib.docs, 'function', 'method docs');
	t.type(flib.public_ip_list, 'function', 'method public_ip_list');
	t.end();
});

tap.test('purge', function(t) {

	var flib = new fastly(fastly_api_key);

	t.type(flib, 'object', 'constructor');
	t.type(flib.purge, 'object', 'purge method');
	t.type(flib.purge_all, 'object', 'purge all method');
	t.type(flib.purge_by_key, 'object', 'purge by key method');
	t.type(flib.purge_multiple, 'object', 'purge multiple method');
	t.end();
});

<commit_msg>Updated<commit_after>const tap = require('tap');
const fastly = require('../lib/fastly.js');
const fastly_api_key =  process.env.FASTLY_API_KEY || ''

tap.test('utilities', function(t) {

	var flib = new fastly(fastly_api_key);

	t.type(flib, 'object', 'constructor');
	t.type(flib.content, 'function', 'method content');
	t.type(flib.datacenters, 'function', 'method datacenters');
	t.type(flib.docs, 'function', 'method docs');
	t.type(flib.public_ip_list, 'function', 'method public_ip_list');
	t.end();
});

tap.test('purge', function(t) {

	var flib = new fastly(fastly_api_key);

	t.type(flib, 'object', 'constructor');
	t.type(flib.purge, 'function', 'purge method');
	t.type(flib.purge_all, 'function', 'purge all method');
	t.type(flib.purge_by_key, 'function', 'purge by key method');
	t.type(flib.purge_multiple, 'function', 'purge multiple method');
	t.end();
});

<|endoftext|>


<commit_before>module.exports = function (robot) {
    'use strict'

    var slackmsg = require("./slackMsgs.js");
    var request = require('request');
    var rp = require('request-promise');
    var Trello = require('node-trello');

    // auth
    var key = process.env.HUBOT_TRELLO_KEY;
    var secret = process.env.HUBOT_TRELLO_OAUTH;
    var token = process.env.HUBOT_TRELLO_TOKEN;
    var trelloAuth = new Trello(key, token);

    var cb = `https://andreasbot.herokuapp.com/hubot/trello-token`;
    var t = new Trello.OAuth(key, secret, cb, 'App Name');
    // robot.logger.warning(t);
    t.getRequestToken(function (err, data) {
        robot.logger.warning(data)
    })

    robot.router.get('/hubot/trello-token', function (req, res) {
         robot.logger.warning('res'+res);
         if (res==req){
             robot.logger.warning('SAME!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!1')
         }
        // t.getAccessToken(res, function (err, data) {
        //     robot.logger.warning(data)
        // })
        res.send(`
Token succesfuly received. You can now close the window.
\n
					<button onclick=window.close()>close</button>`)
    });

    // convert node-trello callbacks to promises
    const Promise = require("bluebird");
    var trello = Promise.promisifyAll(trelloAuth);

    robot.hear(/trello hooks/, function (res) {
        let boardId = 'BE7seI7e';
        let cb_url = 'https://andreasbot.herokuapp.com/hubot/trello-webhooks';
        let args = { description: "my test webhook", callbackURL: cb_url, idModel: '59245663c76f54b975558854' };

        trello.postAsync('/1/webhooks', args).then(function (data) {
            res.send(data)
        }).catch(function (err) {
            res.send();
            robot.logger.error(err.Error)
        })
    })

    robot.on('trello-webhook-event', function (data, res) {

        var room = "random";
        let payload = data.body;
        let type = payload.action.type;
        robot.logger.info(type);
        switch (type) {
            case 'updateList':
                robot.messageRoom(room, `updateList`);
                break;
            default:
                robot.messageRoom(room, `trello-webhook-event`);
                break;
        }
    })

    /*******************************************************************/
    /*                   Slack Buttons Implementation                  */
    /*******************************************************************/

    function sendMessageToSlackResponseURL(responseURL, JSONmessage) {
        var postOptions = {
            uri: responseURL,
            method: 'POST',
            headers: {
                'Content-type': 'application/json'
            },
            json: JSONmessage
        };
        request(postOptions, (error, response, body) => {
            if (error) {
                // handle errors as you see fit
            };
        })
    }

    // trello board
    robot.hear(/trello board/i, function (res_r) {
        // TODO: fetch the board id from other source (env, redis or mongodb)
        let boardId = 'BE7seI7e';
        let args = { fields: "name,url,prefs" };

        trello.get("/1/board/" + boardId, args, function (err, data) {
            if (err) {
                res.send('Error: ' + err);
                robot.logger.error(err);
                return 0;
            }
            // else !err
            let msg = slackmsg.buttons();
            msg.attachments[0].title = `<${data.url}|${data.name}>`;
            msg.attachments[0].title_url = 'www.google.com'
            msg.attachments[0].author_name = 'Board'
            msg.attachments[0].callback_id = `trello_board`;
            msg.attachments[0].color = `${data.prefs.backgroundColor}`;

            // attach the board lists to buttons
            let joinBtn = { "name": "join", "text": "Join", "type": "button", "value": "join" };
            let subBtn = { "name": "sub", "text": "Subscribe", "type": "button", "value": "sub" };
            let starBtn = { "name": "star", "text": "Star", "type": "button", "value": "star" };
            let listsBtn = { "name": "lists", "text": "Lists", "type": "button", "value": "lists" };
            let doneBtn = { "name": "done", "text": "Done", "type": "button", "value": "done", "style": "danger" };
            msg.attachments[0].actions.push(joinBtn);
            msg.attachments[0].actions.push(subBtn);
            msg.attachments[0].actions.push(starBtn);
            msg.attachments[0].actions.push(listsBtn);
            msg.attachments[0].actions.push(doneBtn);

            res_r.send(msg);
        })
    })

    var slackCB = 'slack:msg_action:';

    // responding to 'trello_board' interactive message
    robot.on(slackCB + 'trello_board', function (data, res) {
        robot.logger.info(`robot.on: ${slackCB}trello_board`);
        let btnId = data.actions[0].value;
        let btnName = data.actions[0].name;
        let response_url = data.response_url;
        let msg;

        switch (btnId) {
            case 'join':
                break;
            case 'sub':
                break;
            case 'star':
                break;
            case 'lists':
                res.status(200).end(); // best practice to respond with 200 status
                // get board info to fetch lists
                let boardId = 'BE7seI7e';
                let args = { lists: "all" };
                trello.get("1/board/" + boardId, args, function (err, data) {
                    if (err) {
                        res.send(err);
                        robot.logger.error(err);
                        return;
                    }
                    // else if (!err)
                    // create buttons msg
                    let msg = slackmsg.buttons();
                    msg.text = `*${data.name}* board`;

                    msg.attachments[0].text = `Available lists`;
                    msg.attachments[0].callback_id = `trello_list`;
                    let listsNum = Object.keys(data.lists).length;
                    for (var i = 0; i < listsNum; i++) {
                        // TODO change value to some id or something similar
                        let name = data.lists[i].name;
                        let id = data.lists[i].id;
                        let list = { "name": name, "text": name, "type": "button", "value": id };
                        msg.attachments[0].actions.push(list);
                    }
                    sendMessageToSlackResponseURL(response_url, msg);
                })
                break;
            case 'done':
                //res.status(200).end() // best practice to respond with 200 status
                msg = slackmsg.plainText();
                res.send(msg);
                //sendMessageToSlackResponseURL(response_url, msg);
                // res.send(msg);
                break;
            default:
                //Statements executed when none of the values match the value of the expression
                break;
        }
    })

    // responding to 'trello_list' interactive message
    robot.on(slackCB + 'trello_list', function (data_board, res) {
        let response_url = data_board.response_url;

        res.status(200).end() // best practice to respond with 200 status
        robot.logger.info(`robot.on: ${slackCB}trello_list`);
        let listId = data_board.actions[0].value;
        let listName = data_board.actions[0].name;

        // call function to fetch list - provide list id
        let args = { cards: "all" };
        trello.get("/1/lists/" + listId, args, function (err, data) {
            if (err) {
                robot.logger.error(err);
                res.send(`Error: ${err}`)
                return 0;
            }
            // else !err
            // create buttons msg
            let msg = slackmsg.buttons();
            msg.text = `*${listName}* list`;
            msg.attachments[0].text = `Available Cards`;
            msg.attachments[0].callback_id = `trello_list`;

            let cardsNum = Object.keys(data.cards).length;
            robot.logger.info(`total cards: ${cardsNum}`);
            for (var i = 0; i < cardsNum; i++) {
                let card = data.cards[i].name;
                let cardId = data.cards[i].id;
                let item = { "name": card, "text": card, "type": "button", "value": cardId };
                msg.attachments[0].actions.push(item);
            }

            // respond with information for that list
            sendMessageToSlackResponseURL(response_url, msg);
        })
    })
}<commit_msg>trello token<commit_after>module.exports = function (robot) {
    'use strict'

    var slackmsg = require("./slackMsgs.js");
    var request = require('request');
    var rp = require('request-promise');
    var Trello = require('node-trello');

    // auth
    var key = process.env.HUBOT_TRELLO_KEY;
    var secret = process.env.HUBOT_TRELLO_OAUTH;
    var token = process.env.HUBOT_TRELLO_TOKEN;
    var trelloAuth = new Trello(key, token);

    var cb = `https://andreasbot.herokuapp.com/hubot/trello-token`;
    var t = new Trello.OAuth(key, secret, cb, 'App Name');
    // robot.logger.warning(t);
    t.getRequestToken(function (err, data) {
        robot.logger.warning(data)
    })

    robot.router.get('/hubot/trello-token', function (req, res) {
         robot.logger.warning(res);
         if (res==req){
             robot.logger.warning('SAME!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!1')
         }
        // t.getAccessToken(res, function (err, data) {
        //     robot.logger.warning(data)
        // })
        res.send(`
Token succesfuly received. You can now close the window.
\n
					<button onclick=window.close()>close</button>`)
    });

    // convert node-trello callbacks to promises
    const Promise = require("bluebird");
    var trello = Promise.promisifyAll(trelloAuth);

    robot.hear(/trello hooks/, function (res) {
        let boardId = 'BE7seI7e';
        let cb_url = 'https://andreasbot.herokuapp.com/hubot/trello-webhooks';
        let args = { description: "my test webhook", callbackURL: cb_url, idModel: '59245663c76f54b975558854' };

        trello.postAsync('/1/webhooks', args).then(function (data) {
            res.send(data)
        }).catch(function (err) {
            res.send();
            robot.logger.error(err.Error)
        })
    })

    robot.on('trello-webhook-event', function (data, res) {

        var room = "random";
        let payload = data.body;
        let type = payload.action.type;
        robot.logger.info(type);
        switch (type) {
            case 'updateList':
                robot.messageRoom(room, `updateList`);
                break;
            default:
                robot.messageRoom(room, `trello-webhook-event`);
                break;
        }
    })

    /*******************************************************************/
    /*                   Slack Buttons Implementation                  */
    /*******************************************************************/

    function sendMessageToSlackResponseURL(responseURL, JSONmessage) {
        var postOptions = {
            uri: responseURL,
            method: 'POST',
            headers: {
                'Content-type': 'application/json'
            },
            json: JSONmessage
        };
        request(postOptions, (error, response, body) => {
            if (error) {
                // handle errors as you see fit
            };
        })
    }

    // trello board
    robot.hear(/trello board/i, function (res_r) {
        // TODO: fetch the board id from other source (env, redis or mongodb)
        let boardId = 'BE7seI7e';
        let args = { fields: "name,url,prefs" };

        trello.get("/1/board/" + boardId, args, function (err, data) {
            if (err) {
                res.send('Error: ' + err);
                robot.logger.error(err);
                return 0;
            }
            // else !err
            let msg = slackmsg.buttons();
            msg.attachments[0].title = `<${data.url}|${data.name}>`;
            msg.attachments[0].title_url = 'www.google.com'
            msg.attachments[0].author_name = 'Board'
            msg.attachments[0].callback_id = `trello_board`;
            msg.attachments[0].color = `${data.prefs.backgroundColor}`;

            // attach the board lists to buttons
            let joinBtn = { "name": "join", "text": "Join", "type": "button", "value": "join" };
            let subBtn = { "name": "sub", "text": "Subscribe", "type": "button", "value": "sub" };
            let starBtn = { "name": "star", "text": "Star", "type": "button", "value": "star" };
            let listsBtn = { "name": "lists", "text": "Lists", "type": "button", "value": "lists" };
            let doneBtn = { "name": "done", "text": "Done", "type": "button", "value": "done", "style": "danger" };
            msg.attachments[0].actions.push(joinBtn);
            msg.attachments[0].actions.push(subBtn);
            msg.attachments[0].actions.push(starBtn);
            msg.attachments[0].actions.push(listsBtn);
            msg.attachments[0].actions.push(doneBtn);

            res_r.send(msg);
        })
    })

    var slackCB = 'slack:msg_action:';

    // responding to 'trello_board' interactive message
    robot.on(slackCB + 'trello_board', function (data, res) {
        robot.logger.info(`robot.on: ${slackCB}trello_board`);
        let btnId = data.actions[0].value;
        let btnName = data.actions[0].name;
        let response_url = data.response_url;
        let msg;

        switch (btnId) {
            case 'join':
                break;
            case 'sub':
                break;
            case 'star':
                break;
            case 'lists':
                res.status(200).end(); // best practice to respond with 200 status
                // get board info to fetch lists
                let boardId = 'BE7seI7e';
                let args = { lists: "all" };
                trello.get("1/board/" + boardId, args, function (err, data) {
                    if (err) {
                        res.send(err);
                        robot.logger.error(err);
                        return;
                    }
                    // else if (!err)
                    // create buttons msg
                    let msg = slackmsg.buttons();
                    msg.text = `*${data.name}* board`;

                    msg.attachments[0].text = `Available lists`;
                    msg.attachments[0].callback_id = `trello_list`;
                    let listsNum = Object.keys(data.lists).length;
                    for (var i = 0; i < listsNum; i++) {
                        // TODO change value to some id or something similar
                        let name = data.lists[i].name;
                        let id = data.lists[i].id;
                        let list = { "name": name, "text": name, "type": "button", "value": id };
                        msg.attachments[0].actions.push(list);
                    }
                    sendMessageToSlackResponseURL(response_url, msg);
                })
                break;
            case 'done':
                //res.status(200).end() // best practice to respond with 200 status
                msg = slackmsg.plainText();
                res.send(msg);
                //sendMessageToSlackResponseURL(response_url, msg);
                // res.send(msg);
                break;
            default:
                //Statements executed when none of the values match the value of the expression
                break;
        }
    })

    // responding to 'trello_list' interactive message
    robot.on(slackCB + 'trello_list', function (data_board, res) {
        let response_url = data_board.response_url;

        res.status(200).end() // best practice to respond with 200 status
        robot.logger.info(`robot.on: ${slackCB}trello_list`);
        let listId = data_board.actions[0].value;
        let listName = data_board.actions[0].name;

        // call function to fetch list - provide list id
        let args = { cards: "all" };
        trello.get("/1/lists/" + listId, args, function (err, data) {
            if (err) {
                robot.logger.error(err);
                res.send(`Error: ${err}`)
                return 0;
            }
            // else !err
            // create buttons msg
            let msg = slackmsg.buttons();
            msg.text = `*${listName}* list`;
            msg.attachments[0].text = `Available Cards`;
            msg.attachments[0].callback_id = `trello_list`;

            let cardsNum = Object.keys(data.cards).length;
            robot.logger.info(`total cards: ${cardsNum}`);
            for (var i = 0; i < cardsNum; i++) {
                let card = data.cards[i].name;
                let cardId = data.cards[i].id;
                let item = { "name": card, "text": card, "type": "button", "value": cardId };
                msg.attachments[0].actions.push(item);
            }

            // respond with information for that list
            sendMessageToSlackResponseURL(response_url, msg);
        })
    })
}<|endoftext|>


<commit_before>/*jslint browser: true */
/*global define */

define([
    'angular',
    'config'
], function (angular, config) {
    'use strict';

    return angular.module('voilab.components', [
        'voilab.amdTranslator', 'ngAnimate', 'ui.bootstrap', 'ch.filters', 'qtip2', 'hc.marked'
    ])
        .value('config', config.VOILAB_NG_COMPONENTS.main)
        /**
         * Décoration de uib-rating afin de pouvoir utiliser font-awesome et pas fucking-glyphiconnasse.
         */
        .config(['$provide', function ($provide) {
            $provide.decorator('uibRatingDirective', ['$delegate', function($delegate) {
                var directive = $delegate[0];

                directive.templateUrl = config.VOILAB_NG_COMPONENTS.main.basepath + "/uib-extend/views/rating.ng.html";

                return $delegate;
            }]);
        }]);
});
<commit_msg>- added ui.router module as a dependency of voilab.components module<commit_after>/*jslint browser: true */
/*global define */

define([
    'angular',
    'config'
], function (angular, config) {
    'use strict';

    return angular.module('voilab.components', [
        'voilab.amdTranslator', 'ngAnimate', 'ui.bootstrap', 'ui.router', 'ch.filters', 'qtip2', 'hc.marked'
    ])
        .value('config', config.VOILAB_NG_COMPONENTS.main)
        /**
         * Décoration de uib-rating afin de pouvoir utiliser font-awesome et pas fucking-glyphiconnasse.
         */
        .config(['$provide', function ($provide) {
            $provide.decorator('uibRatingDirective', ['$delegate', function($delegate) {
                var directive = $delegate[0];

                directive.templateUrl = config.VOILAB_NG_COMPONENTS.main.basepath + "/uib-extend/views/rating.ng.html";

                return $delegate;
            }]);
        }]);
});
<|endoftext|>