<commit_before>const express = require('express');
const http = require('http');
const config = require('./lib/config');
const _ = require('underscore');
const DataStore = require('nedb');
const async = require('async');

function log () {
  if (config('DEV', false)) console.log.apply(null, arguments);
}

function createApp (fixtures, cb) {
  var app = express();

  app.use(express.bodyParser());
  app.use(function (req, res, next) {
    res.type('json');
    next();
  });

  var fakeAchievements = new DataStore();
  var fakeRequirements = new DataStore();
  var fakeFavs = new DataStore();

  app.fixtures = fixtures = fixtures || {};
  cb = cb || function () {};
  async.each(fixtures.achievements || [], function(achievement, cb) {
    fakeAchievements.insert(achievement, function (err, doc) {
      if (err) return cb(err);
      fixtures.achievements[fixtures.achievements.indexOf(achievement)] = doc;
      cb();
    });
  }, function (err) {
    if (err) throw err;

    async.each(fixtures.requirements || [], function (requirement, cb) {
      fakeRequirements.insert(requirement, cb);
    }, function (err) {
      if (err) throw err;

      async.each(fixtures.favorites || [], function (favorite, cb) {
        favorite.itemId = fixtures.achievements[favorite.achievementIdx]._id;
        delete favorite.achievementIdx;
        fakeFavs.insert(favorite, cb);
      }, function (err) {
        if (err) throw err;
        cb(fixtures);
      });
    });
  });

  function randomType () {
    return Math.random() < 0.5 ? 'badge' : 'pathway';
  }

  function fakeAchievement (opts) {
    opts = opts || {};
    var type = opts.type || randomType();
    var data = {
      created_at: opts.created_at,
      type: type.toLowerCase(),
      title: 'A Very Long ' + type + ' Title ' + opts.created_at,
      description: "Authentic meh Marfa Thundercats roof party Brooklyn, scenester locavore ennui wayfarers typewriter 3 wolf moon gastropub. Hi.",
      tags: ['service', 'barista', 'coffeelover', 'fake'],
      creator: 'Starbucks'
    };
    return data;
  }

  function fakeRequirement(opts) {
    return {
      pathwayId: opts.pathwayId,
      x: Math.floor(Math.random()*3),
      y: opts.row,
      name: 'Some Badge ' + opts.row,
      core: (Math.random() < 0.5)
    };
  }

  function addFavs (docs, uid, cb) {
    if (!_.isArray(docs)) docs = [docs];
    var itemIds = _.pluck(docs, '_id');
    return fakeFavs.find({userId: uid, itemId: {$in: itemIds}}, function (err, favs) {
      if (err) cb(err);
      docs.forEach(function (doc) {
        doc.favorite = !!_.findWhere(favs, {itemId: doc._id});
      });
      return cb(null, docs.length === 1 ? docs[0] : docs);
    });
  }

  app.get('/achievement', function generateData(req, res, next) {
    var after = parseInt(req.query.after || Date.now());
    var pageSize = parseInt(req.query.pageSize);

    if (!pageSize) return res.send(400);

    log('looking for created_at lt %s', after);

    fakeAchievements.find({created_at: {$lt: after}}).sort({created_at: -1}).limit(pageSize).exec(function (err, docs) {
      if (docs.length !== pageSize) {
        var fill = pageSize - docs.length;
        log('Generating %d achievements...', fill);
        docs = docs.concat(_.times(fill, function () {
          return fakeAchievement({
            created_at: --after
          });
        }));
        fakeAchievements.insert(docs, function (err, docs) {
          if (err) throw err;
          log('Inserted %d achievements...', docs.length);
          next();
        });
      }
      else next();
    });
  });

  app.get('/achievement', function getAchievements(req, res, next) {
    var after = parseInt(req.query.after || Date.now());
    var pageSize = parseInt(req.query.pageSize);
    var uid = req.session && req.session.user && req.session.user.id;

    fakeAchievements.find({created_at: {$lt: after}}).sort({created_at: -1}).limit(pageSize).exec(function (err, docs) {
      if (err) throw err;
      if (uid) {
        return addFavs(docs, uid, function (err, docs) {
          if (err) throw err;
          return res.json(docs);
        });
      }
      return res.json(docs);
    });
  });

  app.get('/badge/:id', getAchievement);
  app.get('/pathway/:id', getAchievement);
  app.get('/achievement/:id', getAchievement);
  function getAchievement(req, res, next) {
    var id = req.params.id;
    var uid = req.session && req.session.user && req.session.user.id;
    fakeAchievements.findOne({_id: id}, function (err, doc) {
      if (err) throw err;
      if (doc) {
        if (uid) {
          return addFavs(doc, uid, function (err, doc) {
            if (err) throw err;
            return res.json(doc);
          });
        }
        return res.json(doc);
      }
      return res.send(404);
    });
  }

  app.patch('/badge/:id', setFavorite);
  app.patch('/pathway/:id', setFavorite);
  app.patch('/achievement/:id', setFavorite);
  function setFavorite(req, res, next) {
    var uid = req.session && req.session.user && req.session.user.id;
    var id = req.params.id;

    if (!uid) res.send(403);

    var data = _.pick(req.body, 'favorite');
    fakeFavs.update({userId: uid, itemId: id}, {$set: data}, {upsert: true}, function (err) {
      if (err) throw err;
      return res.json({});
    });
  }

  app.get('/pathway/:id/requirement', function (req, res, next) {
    var id = req.params.id;

    fakeRequirements.find({pathwayId: id}, function (err, docs) {
      if (err) throw err;
      if (!docs.length) {
        log('Generating requirements...');
        docs = _.times(5, function (i) {
          return fakeRequirement({
            pathwayId: id,
            row: i
          });
        });
        fakeRequirements.insert(docs, function (err, docs) {
          if (err) throw err;
          log('Returning...');
          return res.json(docs);
        });
      }
      else {
        log('Returning...');
        return res.json(docs);
      }
    });
  });

  app.post('/pathway/:pid/requirement', function (req, res, next) {
    var pid = req.params.pid;
    var requirement = req.body;
    requirement.pathwayId = pid;
    fakeRequirements.insert(requirement, function (err, doc) {
      if (err) throw err;
      return res.json({_id: doc._id});
    });
  });

  app.put('/pathway/:pid/requirement/:rid', function (req, res, next) {
    var pid = req.params.pid;
    var rid = req.params.rid;

    fakeRequirements.update({_id: rid}, {$set: req.body}, {}, function (err) {
      if (err) throw err;
      return res.json({});
    });
  });

  app.get('/user/:uid/earned', function (req, res, next) {
    return res.json([]);
  });

  app.get('/user/:uid/favorite', function (req, res, next) {
    var uid = parseInt(req.params.uid);

    fakeFavs.find({userId: uid}, function (err, docs) {
      if (err) throw err;
      var ids = _.pluck(docs, 'itemId');
      fakeAchievements.find({_id: {$in: ids}}, function (err, docs) {
        docs = docs.map(function (doc) {
          doc.favorite = true;
          return doc;
        });
        return res.json(docs);
      });
    });
  });

  app.get('/user/:id/pledged', function (req, res, next) {
    var userId = parseInt(req.params.id);

    fakeAchievements.find({userId: userId}, function (err, docs) {
      if (err) throw err;
      return res.json(docs);
    });
  });

  app.post('/user/:id/pledged', function (req, res, next) {
    var cloneId = req.body.cloneId;
    var userId = parseInt(req.params.id);

    fakeAchievements.findOne({_id: cloneId}, function (err, base) {
      if (err) throw err;
      if (!base) res.send(404);
      delete base._id;
      base.userId = userId;
      base.created_at = Date.now();
      fakeAchievements.insert(base, function (err, pledged) {
        if (err) throw err;
        fakeRequirements.find({pathwayId: cloneId}, function (err, baseReqs) {
          if (err) throw err;
          var pledgedReqs = baseReqs.map(function(req) {
            delete req._id;
            req.pathwayId = pledged._id;
            return req;
          });
          fakeRequirements.insert(pledgedReqs, function (err) {
            if (err) throw err;
            return res.json(pledged);
          });
        });
      });
    });
  });

  app.get('/user/:uid/pledged/:id', function (req, res, next) {
    var id = req.params.id;

    fakeAchievements.findOne({_id: id}, function (err, doc) {
      if (err) throw err;
      return res.json(doc);
    });
  });

  app.put('/user/:uid/pledged/:id', function (req, res, next) {
    var id = req.params.id;

    fakeAchievements.update({_id: id}, {$set: req.body}, function (err, doc) {
      if (err) throw err;
      return res.json({});
    });
  });

  app.all('*', function (req, res, next) {
    return res.send(404);
  });

  return app;
}

if (!module.parent) {
  const PORT = config('PORT', 3001);
  var app = createApp();
  app.listen(PORT, function(err) {
    if (err) {
      throw err;
    }

    log('Listening on port ' + PORT + '.');
  });
} else {
  module.exports.createServer = function createServer (fixtures, cb) {
    var app = createApp(fixtures, cb);
    var server = http.createServer(app);
    server.fixtures = app.fixtures;
    return server;
  };
}
<commit_msg>Change Starbucks to A. Creator as dummy creator<commit_after>const express = require('express');
const http = require('http');
const config = require('./lib/config');
const _ = require('underscore');
const DataStore = require('nedb');
const async = require('async');

function log () {
  if (config('DEV', false)) console.log.apply(null, arguments);
}

function createApp (fixtures, cb) {
  var app = express();

  app.use(express.bodyParser());
  app.use(function (req, res, next) {
    res.type('json');
    next();
  });

  var fakeAchievements = new DataStore();
  var fakeRequirements = new DataStore();
  var fakeFavs = new DataStore();

  app.fixtures = fixtures = fixtures || {};
  cb = cb || function () {};
  async.each(fixtures.achievements || [], function(achievement, cb) {
    fakeAchievements.insert(achievement, function (err, doc) {
      if (err) return cb(err);
      fixtures.achievements[fixtures.achievements.indexOf(achievement)] = doc;
      cb();
    });
  }, function (err) {
    if (err) throw err;

    async.each(fixtures.requirements || [], function (requirement, cb) {
      fakeRequirements.insert(requirement, cb);
    }, function (err) {
      if (err) throw err;

      async.each(fixtures.favorites || [], function (favorite, cb) {
        favorite.itemId = fixtures.achievements[favorite.achievementIdx]._id;
        delete favorite.achievementIdx;
        fakeFavs.insert(favorite, cb);
      }, function (err) {
        if (err) throw err;
        cb(fixtures);
      });
    });
  });

  function randomType () {
    return Math.random() < 0.5 ? 'badge' : 'pathway';
  }

  function fakeAchievement (opts) {
    opts = opts || {};
    var type = opts.type || randomType();
    var data = {
      created_at: opts.created_at,
      type: type.toLowerCase(),
      title: 'A Very Long ' + type + ' Title ' + opts.created_at,
      description: "Authentic meh Marfa Thundercats roof party Brooklyn, scenester locavore ennui wayfarers typewriter 3 wolf moon gastropub. Hi.",
      tags: ['service', 'barista', 'coffeelover', 'fake'],
      creator: 'A. Creator'
    };
    return data;
  }

  function fakeRequirement(opts) {
    return {
      pathwayId: opts.pathwayId,
      x: Math.floor(Math.random()*3),
      y: opts.row,
      name: 'Some Badge ' + opts.row,
      core: (Math.random() < 0.5)
    };
  }

  function addFavs (docs, uid, cb) {
    if (!_.isArray(docs)) docs = [docs];
    var itemIds = _.pluck(docs, '_id');
    return fakeFavs.find({userId: uid, itemId: {$in: itemIds}}, function (err, favs) {
      if (err) cb(err);
      docs.forEach(function (doc) {
        doc.favorite = !!_.findWhere(favs, {itemId: doc._id});
      });
      return cb(null, docs.length === 1 ? docs[0] : docs);
    });
  }

  app.get('/achievement', function generateData(req, res, next) {
    var after = parseInt(req.query.after || Date.now());
    var pageSize = parseInt(req.query.pageSize);

    if (!pageSize) return res.send(400);

    log('looking for created_at lt %s', after);

    fakeAchievements.find({created_at: {$lt: after}}).sort({created_at: -1}).limit(pageSize).exec(function (err, docs) {
      if (docs.length !== pageSize) {
        var fill = pageSize - docs.length;
        log('Generating %d achievements...', fill);
        docs = docs.concat(_.times(fill, function () {
          return fakeAchievement({
            created_at: --after
          });
        }));
        fakeAchievements.insert(docs, function (err, docs) {
          if (err) throw err;
          log('Inserted %d achievements...', docs.length);
          next();
        });
      }
      else next();
    });
  });

  app.get('/achievement', function getAchievements(req, res, next) {
    var after = parseInt(req.query.after || Date.now());
    var pageSize = parseInt(req.query.pageSize);
    var uid = req.session && req.session.user && req.session.user.id;

    fakeAchievements.find({created_at: {$lt: after}}).sort({created_at: -1}).limit(pageSize).exec(function (err, docs) {
      if (err) throw err;
      if (uid) {
        return addFavs(docs, uid, function (err, docs) {
          if (err) throw err;
          return res.json(docs);
        });
      }
      return res.json(docs);
    });
  });

  app.get('/badge/:id', getAchievement);
  app.get('/pathway/:id', getAchievement);
  app.get('/achievement/:id', getAchievement);
  function getAchievement(req, res, next) {
    var id = req.params.id;
    var uid = req.session && req.session.user && req.session.user.id;
    fakeAchievements.findOne({_id: id}, function (err, doc) {
      if (err) throw err;
      if (doc) {
        if (uid) {
          return addFavs(doc, uid, function (err, doc) {
            if (err) throw err;
            return res.json(doc);
          });
        }
        return res.json(doc);
      }
      return res.send(404);
    });
  }

  app.patch('/badge/:id', setFavorite);
  app.patch('/pathway/:id', setFavorite);
  app.patch('/achievement/:id', setFavorite);
  function setFavorite(req, res, next) {
    var uid = req.session && req.session.user && req.session.user.id;
    var id = req.params.id;

    if (!uid) res.send(403);

    var data = _.pick(req.body, 'favorite');
    fakeFavs.update({userId: uid, itemId: id}, {$set: data}, {upsert: true}, function (err) {
      if (err) throw err;
      return res.json({});
    });
  }

  app.get('/pathway/:id/requirement', function (req, res, next) {
    var id = req.params.id;

    fakeRequirements.find({pathwayId: id}, function (err, docs) {
      if (err) throw err;
      if (!docs.length) {
        log('Generating requirements...');
        docs = _.times(5, function (i) {
          return fakeRequirement({
            pathwayId: id,
            row: i
          });
        });
        fakeRequirements.insert(docs, function (err, docs) {
          if (err) throw err;
          log('Returning...');
          return res.json(docs);
        });
      }
      else {
        log('Returning...');
        return res.json(docs);
      }
    });
  });

  app.post('/pathway/:pid/requirement', function (req, res, next) {
    var pid = req.params.pid;
    var requirement = req.body;
    requirement.pathwayId = pid;
    fakeRequirements.insert(requirement, function (err, doc) {
      if (err) throw err;
      return res.json({_id: doc._id});
    });
  });

  app.put('/pathway/:pid/requirement/:rid', function (req, res, next) {
    var pid = req.params.pid;
    var rid = req.params.rid;

    fakeRequirements.update({_id: rid}, {$set: req.body}, {}, function (err) {
      if (err) throw err;
      return res.json({});
    });
  });

  app.get('/user/:uid/earned', function (req, res, next) {
    return res.json([]);
  });

  app.get('/user/:uid/favorite', function (req, res, next) {
    var uid = parseInt(req.params.uid);

    fakeFavs.find({userId: uid}, function (err, docs) {
      if (err) throw err;
      var ids = _.pluck(docs, 'itemId');
      fakeAchievements.find({_id: {$in: ids}}, function (err, docs) {
        docs = docs.map(function (doc) {
          doc.favorite = true;
          return doc;
        });
        return res.json(docs);
      });
    });
  });

  app.get('/user/:id/pledged', function (req, res, next) {
    var userId = parseInt(req.params.id);

    fakeAchievements.find({userId: userId}, function (err, docs) {
      if (err) throw err;
      return res.json(docs);
    });
  });

  app.post('/user/:id/pledged', function (req, res, next) {
    var cloneId = req.body.cloneId;
    var userId = parseInt(req.params.id);

    fakeAchievements.findOne({_id: cloneId}, function (err, base) {
      if (err) throw err;
      if (!base) res.send(404);
      delete base._id;
      base.userId = userId;
      base.created_at = Date.now();
      fakeAchievements.insert(base, function (err, pledged) {
        if (err) throw err;
        fakeRequirements.find({pathwayId: cloneId}, function (err, baseReqs) {
          if (err) throw err;
          var pledgedReqs = baseReqs.map(function(req) {
            delete req._id;
            req.pathwayId = pledged._id;
            return req;
          });
          fakeRequirements.insert(pledgedReqs, function (err) {
            if (err) throw err;
            return res.json(pledged);
          });
        });
      });
    });
  });

  app.get('/user/:uid/pledged/:id', function (req, res, next) {
    var id = req.params.id;

    fakeAchievements.findOne({_id: id}, function (err, doc) {
      if (err) throw err;
      return res.json(doc);
    });
  });

  app.put('/user/:uid/pledged/:id', function (req, res, next) {
    var id = req.params.id;

    fakeAchievements.update({_id: id}, {$set: req.body}, function (err, doc) {
      if (err) throw err;
      return res.json({});
    });
  });

  app.all('*', function (req, res, next) {
    return res.send(404);
  });

  return app;
}

if (!module.parent) {
  const PORT = config('PORT', 3001);
  var app = createApp();
  app.listen(PORT, function(err) {
    if (err) {
      throw err;
    }

    log('Listening on port ' + PORT + '.');
  });
} else {
  module.exports.createServer = function createServer (fixtures, cb) {
    var app = createApp(fixtures, cb);
    var server = http.createServer(app);
    server.fixtures = app.fixtures;
    return server;
  };
}
<|endoftext|>


<commit_before>define([
  './intern',
], function(config) {

  config.capabilities = {
    project: 'ally.js',
    // 'browserstack.debug': true,
    // 'browserstack.video': true,
    // 'browserstack.ie.noFlash': true,

    // prevent download popup in chrome
    chromeOptions: {
      args: ['--multiple-automatic-downloads=1'],
    },
  };

  // https://theintern.github.io/intern/#option-environments
  // see https://www.browserstack.com/automate/capabilities
  /*eslint-disable camelcase */
  config.environments = [
    // disabled because of https://github.com/theintern/intern/issues/555
    // { browser: 'Edge', browser_version: '12.0', os: 'WINDOWS', os_version: '10', platform: 'WIN', browserName: 'Edge12' },
    // disabled because IE10 and IE11 currently don't return any results to Intern
    // { browser: 'IE', browser_version: '11', os: 'WINDOWS', os_version: '8.1', platform: 'WIN', browserName: 'IE11' },
    // { browser: 'IE', browser_version: '10', os: 'WINDOWS', os_version: '8', platform: 'WIN', browserName: 'IE10' },
    { browser: 'IE', browser_version: '9', os: 'WINDOWS', os_version: '7', platform: 'WIN', browserName: 'IE9' },

    { browser: 'Firefox', browser_version: '42', os: 'WINDOWS', os_version: '8.1', platform: 'WIN', browserName: 'Firefox 42' },
    { browser: 'Chrome', browser_version: '47', os: 'WINDOWS', os_version: '8.1', platform: 'WIN', browserName: 'Chrome 47' },

    { browser: 'Firefox', browser_version: '42', os: 'OS X', os_version: 'Yosemite', platform: 'MAC', browserName: 'Firefox 42' },
    { browser: 'Chrome', browser_version: '47', os: 'OS X', os_version: 'Yosemite', platform: 'MAC', browserName: 'Chrome 47' },

    { browser: 'Safari', browser_version: '9.0', os: 'OS X', os_version: 'El Capitan', platform: 'MAC', browserName: 'Safari 9' },
    { browser: 'Safari', browser_version: '8', os: 'OS X', os_version: 'Yosemite', platform: 'MAC', browserName: 'Safari 8' },
    { browser: 'Safari', browser_version: '7.1', os: 'OS X', os_version: 'Mavericks', platform: 'MAC', browserName: 'Safari 7' },
    { browser: 'Safari', browser_version: '6.2', os: 'OS X', os_version: 'Mountain Lion', platform: 'MAC', browserName: 'Safari 6' },
  ];
  /*eslint-enable camelcase */

  // https://theintern.github.io/intern/#option-maxConcurrency
  // OpenSauce allows 5 concurrent VMs
  //config.maxConcurrency = 5;
  config.maxConcurrency = 2;
  // https://theintern.github.io/intern/#option-tunnel
  config.tunnel = 'BrowserStackTunnel';

  return config;
});
<commit_msg>chore(browserstack): disabling IE9 until fixed by BrowserStack<commit_after>define([
  './intern',
], function(config) {

  config.capabilities = {
    project: 'ally.js',
    // 'browserstack.debug': true,
    // 'browserstack.video': true,
    // 'browserstack.ie.noFlash': true,

    // prevent download popup in chrome
    chromeOptions: {
      args: ['--multiple-automatic-downloads=1'],
    },
  };

  // https://theintern.github.io/intern/#option-environments
  // see https://www.browserstack.com/automate/capabilities
  /*eslint-disable camelcase */
  config.environments = [
    // disabled because of https://github.com/theintern/intern/issues/555
    // { browser: 'Edge', browser_version: '12.0', os: 'WINDOWS', os_version: '10', platform: 'WIN', browserName: 'Edge12' },
    // disabled because IE10 and IE11 currently don't return any results to Intern
    // { browser: 'IE', browser_version: '11', os: 'WINDOWS', os_version: '8.1', platform: 'WIN', browserName: 'IE11' },
    // { browser: 'IE', browser_version: '10', os: 'WINDOWS', os_version: '8', platform: 'WIN', browserName: 'IE10' },
    // disabled because IE9 runs but never completes
    // { browser: 'IE', browser_version: '9', os: 'WINDOWS', os_version: '7', platform: 'WIN', browserName: 'IE9' },

    { browser: 'Firefox', browser_version: '42', os: 'WINDOWS', os_version: '8.1', platform: 'WIN', browserName: 'Firefox 42' },
    { browser: 'Chrome', browser_version: '47', os: 'WINDOWS', os_version: '8.1', platform: 'WIN', browserName: 'Chrome 47' },

    { browser: 'Firefox', browser_version: '42', os: 'OS X', os_version: 'Yosemite', platform: 'MAC', browserName: 'Firefox 42' },
    { browser: 'Chrome', browser_version: '47', os: 'OS X', os_version: 'Yosemite', platform: 'MAC', browserName: 'Chrome 47' },

    { browser: 'Safari', browser_version: '9.0', os: 'OS X', os_version: 'El Capitan', platform: 'MAC', browserName: 'Safari 9' },
    { browser: 'Safari', browser_version: '8', os: 'OS X', os_version: 'Yosemite', platform: 'MAC', browserName: 'Safari 8' },
    { browser: 'Safari', browser_version: '7.1', os: 'OS X', os_version: 'Mavericks', platform: 'MAC', browserName: 'Safari 7' },
    { browser: 'Safari', browser_version: '6.2', os: 'OS X', os_version: 'Mountain Lion', platform: 'MAC', browserName: 'Safari 6' },
  ];
  /*eslint-enable camelcase */

  // https://theintern.github.io/intern/#option-maxConcurrency
  // OpenSauce allows 5 concurrent VMs
  //config.maxConcurrency = 5;
  config.maxConcurrency = 2;
  // https://theintern.github.io/intern/#option-tunnel
  config.tunnel = 'BrowserStackTunnel';

  return config;
});
<|endoftext|>


<commit_before>'use strict';
var path = require('path');
require('chai').should();
var supertest = require('supertest');
var uut = require('../../lib/api');

var recipe = {
  name: 'file',
  input: {
    channel: 'gulp',
    glob: path.join(__dirname, '..', 'fixtures', 'file.json')
  },
  output: {
    channel: 'gulp',
    glob: path.join(__dirname, '..', 'fixtures', 'output')
  }
};
var connections = {};
var channels = require('../../lib/channels')(connections, [recipe]);

let api;
let request;

describe('api', function() {
  afterEach(() => {
    api.server.close();
  });

  it('return file using recipe', function(done) {
    api = uut([recipe], connections, channels)();
    request = supertest(api.app);

    request
    .get('/file')
    .expect(200, {hello: 'world'}, done)
    ;
  });

  it('return different file by overriding parameter', function(done) {
    api = uut([recipe], connections, channels)();
    request = supertest(api.app);

    request
    .get(`/file?override=input.glob=${path.join(__dirname, '..', 'fixtures', 'file2.json')}`)
    .expect(200, {hello: 'there'}, done)
    ;
  });

  describe('cors', function() {
    let saveCors = {};

    before(() => {
      ['CORS_ENABLED', 'CORS_ORIGIN', 'CORS_CREDENTIALS']
      .forEach(param => {
        saveCors[param] = process.env[param];
        delete process.env[param];
      });
    });

    after(() => {
      Object.keys(saveCors)
      .forEach(param => {
        process.env[param] = saveCors[param];
      });
    });

    it('does not return a CORS header by default', function(done) {
      api = uut([recipe], connections, channels)();
      request = supertest(api.app);

      request
      .get('/file')
      .set('Origin', 'localhost')
      .expect(res => {

        /**
         * Be careful here...when using SuperTest's expect() method then the
         * header can be 'Access-Control-Allow-Origin', but when testing a
         * property directly, we have to be sure to use the same case as
         * SuperTest:
         */

        res.headers
        .should.not.have.property('access-control-allow-origin');
      })
      .end(done)
      ;
    });

    it('returns a wildcard CORS header', function(done) {
      process.env.CORS_ENABLED = true;
      process.env.CORS_ORIGIN = '*';
      api = uut([recipe], connections, channels)();
      request = supertest(api.app);

      request
      .get('/file')
      .set('Origin', 'localhost')
      .expect('Access-Control-Allow-Origin', '*')
      .end(done)
      ;
    });

    it('returns an origin-mirroring CORS header', function(done) {
      process.env.CORS_ENABLED = true;
      process.env.CORS_ORIGIN = 'http://localhost';
      api = uut([recipe], connections, channels)();
      request = supertest(api.app);

      request
      .get('/file')
      .set('Origin', 'localhost')
      .expect('Access-Control-Allow-Origin', 'localhost')
      .end(done)
      ;
    });

    it('returns a credentials CORS header', function(done) {
      process.env.CORS_ENABLED = true;
      process.env.CORS_ORIGIN = 'http://localhost';
      process.env.CORS_CREDENTIALS = true;
      api = uut([recipe], connections, channels)();
      request = supertest(api.app);

      request
      .get('/file')
      .set('Origin', 'localhost')
      .expect('Access-Control-Allow-Credentials', 'true')
      .end(done)
      ;
    });
  });
});
<commit_msg>[#19] origin should include protocol<commit_after>'use strict';
var path = require('path');
require('chai').should();
var supertest = require('supertest');
var uut = require('../../lib/api');

var recipe = {
  name: 'file',
  input: {
    channel: 'gulp',
    glob: path.join(__dirname, '..', 'fixtures', 'file.json')
  },
  output: {
    channel: 'gulp',
    glob: path.join(__dirname, '..', 'fixtures', 'output')
  }
};
var connections = {};
var channels = require('../../lib/channels')(connections, [recipe]);

let api;
let request;

describe('api', function() {
  afterEach(() => {
    api.server.close();
  });

  it('return file using recipe', function(done) {
    api = uut([recipe], connections, channels)();
    request = supertest(api.app);

    request
    .get('/file')
    .expect(200, {hello: 'world'}, done)
    ;
  });

  it('return different file by overriding parameter', function(done) {
    api = uut([recipe], connections, channels)();
    request = supertest(api.app);

    request
    .get(`/file?override=input.glob=${path.join(__dirname, '..', 'fixtures', 'file2.json')}`)
    .expect(200, {hello: 'there'}, done)
    ;
  });

  describe('cors', function() {
    let saveCors = {};

    before(() => {
      ['CORS_ENABLED', 'CORS_ORIGIN', 'CORS_CREDENTIALS']
      .forEach(param => {
        saveCors[param] = process.env[param];
        delete process.env[param];
      });
    });

    after(() => {
      Object.keys(saveCors)
      .forEach(param => {
        process.env[param] = saveCors[param];
      });
    });

    it('does not return a CORS header by default', function(done) {
      api = uut([recipe], connections, channels)();
      request = supertest(api.app);

      request
      .get('/file')
      .set('Origin', 'localhost')
      .expect(res => {

        /**
         * Be careful here...when using SuperTest's expect() method then the
         * header can be 'Access-Control-Allow-Origin', but when testing a
         * property directly, we have to be sure to use the same case as
         * SuperTest:
         */

        res.headers
        .should.not.have.property('access-control-allow-origin');
      })
      .end(done)
      ;
    });

    it('returns a wildcard CORS header', function(done) {
      process.env.CORS_ENABLED = true;
      process.env.CORS_ORIGIN = '*';
      api = uut([recipe], connections, channels)();
      request = supertest(api.app);

      request
      .get('/file')
      .set('Origin', 'localhost')
      .expect('Access-Control-Allow-Origin', '*')
      .end(done)
      ;
    });

    it('returns an origin-mirroring CORS header', function(done) {
      process.env.CORS_ENABLED = true;
      process.env.CORS_ORIGIN = 'http://localhost';
      api = uut([recipe], connections, channels)();
      request = supertest(api.app);

      request
      .get('/file')
      .set('Origin', 'localhost')
      .expect('Access-Control-Allow-Origin', 'http://localhost')
      .end(done)
      ;
    });

    it('returns a credentials CORS header', function(done) {
      process.env.CORS_ENABLED = true;
      process.env.CORS_ORIGIN = 'http://localhost';
      process.env.CORS_CREDENTIALS = true;
      api = uut([recipe], connections, channels)();
      request = supertest(api.app);

      request
      .get('/file')
      .set('Origin', 'localhost')
      .expect('Access-Control-Allow-Credentials', 'true')
      .end(done)
      ;
    });
  });
});
<|endoftext|>


<commit_before>/*global describe, it, before, after */
var TestEnv = require('./helper/testenv'),
    assert = TestEnv.assert;

var _      = require('lodash/core'),
    sf     = require('../lib/jsforce'),
    config = require('./config/salesforce');

var testEnv = new TestEnv(config);

/**
 *
 */
describe("chatter", function() {

  this.timeout(20000); // set timeout to 20 sec.

  var conn = testEnv.createConnection();

  /**
   *
   */
  before(function(done) {
    this.timeout(600000); // set timeout to 10 min.
    testEnv.establishConnection(conn, done);
  });

  /**
   *
   */
  describe("chatter api info", function() {
    it("should get chatter api info", function(done) {
      conn.chatter.resource("/").retrieve(function(err, result) {
        if (err) { throw err; }
        assert.ok(_.isString(result.users));
        assert.ok(_.isString(result.groups));
        assert.ok(_.isString(result.feeds));
      }.check(done));
    });
  });

  /**
   *
   */
  describe("users", function() {
    it("should get users list", function(done) {
      conn.chatter.resource("/users").retrieve(function(err, result) {
        if (err) { throw err; }
        assert.ok(_.isString(result.currentPageUrl));
        assert.ok(_.isArray(result.users));
        _.forEach(result.users, function(user) {
          assert.ok(_.isString(user.id));
          assert.ok(_.isString(user.url) && user.url[0] === '/');
          assert.ok(_.isString(user.username));
        });
      }.check(done));
    });

    it("should get current user info", function(done) {
      conn.chatter.resource("/users/me").retrieve(function(err, result) {
        if (err) { throw err; }
        assert.ok(_.isString(result.id));
        assert.ok(_.isString(result.url) && result.url[0] === '/');
        assert.ok(_.isString(result.username));
      }.check(done));
    });
  });

  /**
   *
   */
  describe("groups", function() {
    it("should get groups list", function(done) {
      conn.chatter.resource("/groups").retrieve(function(err, result) {
        if (err) { throw err; }
        assert.ok(_.isString(result.currentPageUrl));
        assert.ok(_.isArray(result.groups));
        _.forEach(result.groups, function(group) {
          assert.ok(_.isString(group.id));
          assert.ok(_.isString(group.url));
          assert.ok(_.isString(group.name));
        });
      }.check(done));
    });
  });

  /**
   *
   */
  describe("feeds", function() {
    var feedElementUrl;

    it("should get feeds list", function(done) {
      conn.chatter.resource("/feeds").retrieve(function(err, result) {
        if (err) { throw err; }
        assert.ok(_.isArray(result.feeds));
        assert.ok(_.isArray(result.favorites));
        _.forEach(result.feeds, function(feed) {
          assert.ok(_.isString(feed.label));
          assert.ok(_.isString(feed.feedUrl) && feed.feedUrl[0] === '/');
          assert.ok(_.isString(feed.feedElementsUrl) && feed.feedElementsUrl[0] === '/');
        });
      }.check(done));
    });

    it("should get items from feed items", function(done) {
      conn.chatter.resource("/feeds/company/feed-elements").retrieve(function(err, result) {
        assert.ok(_.isArray(result.elements));
        _.forEach(result.elements, function(element) {
          assert.ok(_.isString(element.id));
          assert.ok(_.isString(element.type));
          assert.ok(_.isString(element.url) && element.url[0] === '/');
          assert.ok(_.isObject(element.body));
          if (element.type === 'TextPost') {
            assert.ok(_.isObject(element.body));
            assert.ok(_.isString(element.body.text));
          } else if (element.type === 'LinkPost') {
            assert.ok(_.isObject(element.capabilities.link));
            assert.ok(_.isString(element.capabilities.link.url));
            assert.ok(_.isString(element.capabilities.link.urlName));
          }
          assert.ok(_.isObject(element.capabilities));
          assert.ok(_.isObject(element.capabilities.comments));
          assert.ok(_.isObject(element.capabilities.comments.page));
          assert.ok(_.isArray(element.capabilities.comments.page.items));
          assert.ok(element.capabilities.comments.page.total >= 0);
          assert.ok(_.isObject(element.capabilities));
          assert.ok(_.isObject(element.capabilities.chatterLikes));
          assert.ok(_.isObject(element.capabilities.chatterLikes.page));
          assert.ok(_.isArray(element.capabilities.chatterLikes.page.items));
          assert.ok(element.capabilities.chatterLikes.page.total >= 0);
          assert.ok(_.isObject(element.actor));
          assert.ok(_.isString(element.actor.id));
          assert.ok(_.isString(element.actor.type));
          assert.ok(_.isString(element.actor.name));
          assert.ok(_.isString(element.actor.url) && element.url[0] === '/');
          assert.ok(_.isObject(element.actor.photo));
          assert.ok(_.isString(element.actor.photo.url));
          assert.ok(_.isString(element.actor.photo.smallPhotoUrl));
          assert.ok(_.isString(element.actor.photo.largePhotoUrl));
        });
      }.check(done));
    });

    it("should create new item", function(done) {
      conn.chatter.resource("/feed-elements").create({
        body: {
          messageSegments: [{
            type: 'Text',
            text: 'This is new post'
          }]
        },
        feedElementType : "FeedItem",
        subjectId: "me"
      }, function(err, result) {
        if (err) { throw err; }
        assert.ok(_.isString(result.id));
        assert.ok(result.type === 'TextPost');
        assert.ok(_.isString(result.url) && result.url[0] === '/');
        assert.ok(_.isObject(result.body));
        feedElementUrl = result.url;
      }.check(done));
    });

    it("should delete feed item", function(done) {
      conn.chatter.resource(feedElementUrl).delete(function(err, result) {
        if (err) { throw err; }
        assert.ok(_.isUndefined(result));
      }.check(done));
    });

  });

  /**
   *
   */
  describe("feed comments", function() {
    var feedElementUrl, commentsUrl;

    before(function(done) {
      conn.chatter.resource("/feed-elements").create({
        body: {
          messageSegments: [{
            type: 'Text',
            text: 'A new post with comments'
          }],
        },
        feedElementType : "FeedItem",
        subjectId: "me"
      }, function(err, result) {
        if (err) { throw err; }
        feedElementUrl = result.url;
        commentsUrl = result.capabilities.comments.page.currentPageUrl;
      }.check(done));
    });

    it("should create new comment post", function(done) {
      conn.chatter.resource(commentsUrl).create({
        body: {
          messageSegments: [{
            type: 'Text',
            text: 'This is new comment #1'
          }]
        }
      }, function(err, result) {
        if (err) { throw err; }
      }.check(done));
    });

    after(function(done) {
      conn.chatter.resource(feedElementUrl).delete(function(err, result) {
        if (err) { throw err; }
      }.check(done));
    });

  });

  /**
   *
   */
  describe("feed likes", function() {
    var feedElementUrl, commentUrl, itemLikesUrl, commentLikesUrl;

    before(function(done) {
      conn.chatter.resource("/feed-elements").create({
        body: {
          messageSegments: [{
            type: 'Text',
            text: 'A new post with likes'
          }]
        },
        feedElementType : "FeedItem",
        subjectId: "me"
      }).then(function(result) {
        feedElementUrl = result.url;
        itemLikesUrl = result.capabilities.chatterLikes.page.currentPageUrl;
        return conn.chatter.resource(result.capabilities.comments.page.currentPageUrl).create({
          body: {
            messageSegments: [{
              type: 'Text',
              text: 'A new comment with likes'
            }]
          }
        });
      }).thenCall(function(err, result) {
        if (err) { throw err; }
        commentUrl = result.url;
        commentLikesUrl = result.likes.currentPageUrl;
      }.check(done));
    });

    var likeUrl;

    it("should add like to item post", function(done) {
      conn.chatter.resource(itemLikesUrl).create("", function(err, result) {
        if (err) { throw err; }
        likeUrl = result.url;
      }.check(done));
    });

    it("should remove like from item post", function(done) {
      conn.chatter.resource(likeUrl).delete(function(err, result) {
        if (err) { throw err; }
      }.check(done));
    });

    it("should add like to comment post", function(done) {
      conn.chatter.resource(commentLikesUrl).create("", function(err, result) {
        if (err) { throw err; }
        likeUrl = result.url;
      }.check(done));
    });

    it("should remove like from comment post", function(done) {
      conn.chatter.resource(likeUrl).delete(function(err, result) {
        if (err) { throw err; }
      }.check(done));
    });

    after(function(done) {
      conn.chatter.resource(feedElementUrl).delete(function(err, result) {
        if (err) { throw err; }
      }.check(done));
    });

  });

  /**
   *
   */
  describe("batch", function() {
    var chatter = conn.chatter;
    var feeds;
    var urls = [];

    before(function(done) {
      chatter.resource('/feeds').retrieve(function(err, result) {
        if (err) { throw err; }
        feeds = result.feeds.filter(function(feed) {
          // Exclude PendingReview feed type, which raise 403 error in feed-elements GET request
          return feed.feedType !== 'PendingReview';
        });
      }.check(done));
    });

    it("should get all feed items", function(done) {
      var resources = _.map(feeds, function(feed) {
        return chatter.resource(feed.feedElementsUrl);
      });
      chatter.batch(resources, function(err, result) {
        if (err) { throw err; }
        assert.ok(result.hasErrors === false);
        assert.ok(_.isArray(result.results) && result.results.length === feeds.length);
        _.forEach(result.results, function(result) {
          var res = result.result;
          assert.ok(_.isString(res.currentPageUrl));
          assert.ok(_.isArray(res.elements));
        });
      }.check(done));
    });

    it("should create new item post and get feed items", function(done) {
      chatter.batch([
        chatter.resource('/feed-elements').create({
          body: {
            messageSegments: [{
              type: 'Text',
              text: 'This is a post text'
            }]
          },
          feedElementType: "FeedItem",
          subjectId: "me"
        }),
        chatter.resource('/feed-elements').create({
          body: {
            messageSegments: [{
              type: 'Text',
              text: 'This is another post text, following to previous.'
            }]
          },
          feedElementType: "FeedItem",
          subjectId: "me"
        }),
        chatter.resource('/feeds/news/me/feed-elements', { pageSize: 2, sort: "CreatedDateDesc" }),
      ], function(err, result) {
        assert.ok(result.hasErrors === false);
        assert.ok(_.isArray(result.results) && result.results.length === 3);
        var elem1 = result.results[0].result;
        var elem2 = result.results[1].result;
        var elems = result.results[2].result;
        urls.push(elem1.url);
        urls.push(elem2.url);
        assert.ok(elems.elements[1].id === elem1.id);
        assert.ok(elems.elements[0].id === elem2.id);
      }.check(done));
    });

    it("should delete all created resources", function(done) {
      if (urls.length > 0) {
        chatter.batch(_.map(urls, function(url) {
          return chatter.resource(url).delete();
        }), function(err, result) {
          if (err) { throw err; }
        }.check(done));
      } else {
        done();
      }
    });

  });

  /**
   *
   */
  after(function(done) {
    testEnv.closeConnection(conn, done);
  });

});
<commit_msg>test: add a simple update test for chatter api<commit_after>/*global describe, it, before, after */
var TestEnv = require('./helper/testenv'),
    assert = TestEnv.assert;

var _      = require('lodash/core'),
    sf     = require('../lib/jsforce'),
    config = require('./config/salesforce');

var testEnv = new TestEnv(config);

/**
 *
 */
describe("chatter", function() {

  this.timeout(20000); // set timeout to 20 sec.

  var conn = testEnv.createConnection();

  /**
   *
   */
  before(function(done) {
    this.timeout(600000); // set timeout to 10 min.
    testEnv.establishConnection(conn, done);
  });

  /**
   *
   */
  describe("chatter api info", function() {
    it("should get chatter api info", function(done) {
      conn.chatter.resource("/").retrieve(function(err, result) {
        if (err) { throw err; }
        assert.ok(_.isString(result.users));
        assert.ok(_.isString(result.groups));
        assert.ok(_.isString(result.feeds));
      }.check(done));
    });
  });

  /**
   *
   */
  describe("users", function() {
    it("should get users list", function(done) {
      conn.chatter.resource("/users").retrieve(function(err, result) {
        if (err) { throw err; }
        assert.ok(_.isString(result.currentPageUrl));
        assert.ok(_.isArray(result.users));
        _.forEach(result.users, function(user) {
          assert.ok(_.isString(user.id));
          assert.ok(_.isString(user.url) && user.url[0] === '/');
          assert.ok(_.isString(user.username));
        });
      }.check(done));
    });

    it("should get current user info", function(done) {
      conn.chatter.resource("/users/me").retrieve(function(err, result) {
        if (err) { throw err; }
        assert.ok(_.isString(result.id));
        assert.ok(_.isString(result.url) && result.url[0] === '/');
        assert.ok(_.isString(result.username));
      }.check(done));
    });
  });

  /**
   *
   */
  describe("groups", function() {
    it("should get groups list", function(done) {
      conn.chatter.resource("/groups").retrieve(function(err, result) {
        if (err) { throw err; }
        assert.ok(_.isString(result.currentPageUrl));
        assert.ok(_.isArray(result.groups));
        _.forEach(result.groups, function(group) {
          assert.ok(_.isString(group.id));
          assert.ok(_.isString(group.url));
          assert.ok(_.isString(group.name));
        });
      }.check(done));
    });
  });

  /**
   *
   */
  describe("feeds", function() {
    var feedElementUrl;

    it("should get feeds list", function(done) {
      conn.chatter.resource("/feeds").retrieve(function(err, result) {
        if (err) { throw err; }
        assert.ok(_.isArray(result.feeds));
        assert.ok(_.isArray(result.favorites));
        _.forEach(result.feeds, function(feed) {
          assert.ok(_.isString(feed.label));
          assert.ok(_.isString(feed.feedUrl) && feed.feedUrl[0] === '/');
          assert.ok(_.isString(feed.feedElementsUrl) && feed.feedElementsUrl[0] === '/');
        });
      }.check(done));
    });

    it("should get items from feed items", function(done) {
      conn.chatter.resource("/feeds/company/feed-elements").retrieve(function(err, result) {
        assert.ok(_.isArray(result.elements));
        _.forEach(result.elements, function(element) {
          assert.ok(_.isString(element.id));
          assert.ok(_.isString(element.type));
          assert.ok(_.isString(element.url) && element.url[0] === '/');
          assert.ok(_.isObject(element.body));
          if (element.type === 'TextPost') {
            assert.ok(_.isObject(element.body));
            assert.ok(_.isString(element.body.text));
          } else if (element.type === 'LinkPost') {
            assert.ok(_.isObject(element.capabilities.link));
            assert.ok(_.isString(element.capabilities.link.url));
            assert.ok(_.isString(element.capabilities.link.urlName));
          }
          assert.ok(_.isObject(element.capabilities));
          assert.ok(_.isObject(element.capabilities.comments));
          assert.ok(_.isObject(element.capabilities.comments.page));
          assert.ok(_.isArray(element.capabilities.comments.page.items));
          assert.ok(element.capabilities.comments.page.total >= 0);
          assert.ok(_.isObject(element.capabilities));
          assert.ok(_.isObject(element.capabilities.chatterLikes));
          assert.ok(_.isObject(element.capabilities.chatterLikes.page));
          assert.ok(_.isArray(element.capabilities.chatterLikes.page.items));
          assert.ok(element.capabilities.chatterLikes.page.total >= 0);
          assert.ok(_.isObject(element.actor));
          assert.ok(_.isString(element.actor.id));
          assert.ok(_.isString(element.actor.type));
          assert.ok(_.isString(element.actor.name));
          assert.ok(_.isString(element.actor.url) && element.url[0] === '/');
          assert.ok(_.isObject(element.actor.photo));
          assert.ok(_.isString(element.actor.photo.url));
          assert.ok(_.isString(element.actor.photo.smallPhotoUrl));
          assert.ok(_.isString(element.actor.photo.largePhotoUrl));
        });
      }.check(done));
    });

    it("should create new item", function(done) {
      conn.chatter.resource("/feed-elements").create({
        body: {
          messageSegments: [{
            type: 'Text',
            text: 'This is new post'
          }]
        },
        feedElementType : "FeedItem",
        subjectId: "me"
      }, function(err, result) {
        if (err) { throw err; }
        assert.ok(_.isString(result.id));
        assert.ok(result.type === 'TextPost');
        assert.ok(_.isString(result.url) && result.url[0] === '/');
        assert.ok(_.isObject(result.body));
        feedElementUrl = result.url;
      }.check(done));
    });

    it("should delete feed item", function(done) {
      conn.chatter.resource(feedElementUrl).delete(function(err, result) {
        if (err) { throw err; }
        assert.ok(_.isUndefined(result));
      }.check(done));
    });

  });

  /**
   *
   */
  describe("feed comments", function() {
    var feedElementUrl, commentsUrl;

    before(function(done) {
      conn.chatter.resource("/feed-elements").create({
        body: {
          messageSegments: [{
            type: 'Text',
            text: 'A new post with comments'
          }],
        },
        feedElementType : "FeedItem",
        subjectId: "me"
      }, function(err, result) {
        if (err) { throw err; }
        feedElementUrl = result.url;
        commentsUrl = result.capabilities.comments.page.currentPageUrl;
      }.check(done));
    });

    it("should create new comment post", function(done) {
      conn.chatter.resource(commentsUrl).create({
        body: {
          messageSegments: [{
            type: 'Text',
            text: 'This is new comment #1'
          }]
        }
      }, function(err, result) {
        if (err) { throw err; }
      }.check(done));
    });

    it("should update a comment post", function(done) {
      conn.chatter.resource(feedElementUrl).update({
        body: {
          messageSegments: [{
            type: 'Text',
            text: 'This is an updated comment #1'
          }]
        }
      }, function(err, result) {
        if (err) { throw err; }
      }.check(done));
    });

    after(function(done) {
      conn.chatter.resource(feedElementUrl).delete(function(err, result) {
        if (err) { throw err; }
      }.check(done));
    });

  });

  /**
   *
   */
  describe("feed likes", function() {
    var feedElementUrl, commentUrl, itemLikesUrl, commentLikesUrl;

    before(function(done) {
      conn.chatter.resource("/feed-elements").create({
        body: {
          messageSegments: [{
            type: 'Text',
            text: 'A new post with likes'
          }]
        },
        feedElementType : "FeedItem",
        subjectId: "me"
      }).then(function(result) {
        feedElementUrl = result.url;
        itemLikesUrl = result.capabilities.chatterLikes.page.currentPageUrl;
        return conn.chatter.resource(result.capabilities.comments.page.currentPageUrl).create({
          body: {
            messageSegments: [{
              type: 'Text',
              text: 'A new comment with likes'
            }]
          }
        });
      }).thenCall(function(err, result) {
        if (err) { throw err; }
        commentUrl = result.url;
        commentLikesUrl = result.likes.currentPageUrl;
      }.check(done));
    });

    var likeUrl;

    it("should add like to item post", function(done) {
      conn.chatter.resource(itemLikesUrl).create("", function(err, result) {
        if (err) { throw err; }
        likeUrl = result.url;
      }.check(done));
    });

    it("should remove like from item post", function(done) {
      conn.chatter.resource(likeUrl).delete(function(err, result) {
        if (err) { throw err; }
      }.check(done));
    });

    it("should add like to comment post", function(done) {
      conn.chatter.resource(commentLikesUrl).create("", function(err, result) {
        if (err) { throw err; }
        likeUrl = result.url;
      }.check(done));
    });

    it("should remove like from comment post", function(done) {
      conn.chatter.resource(likeUrl).delete(function(err, result) {
        if (err) { throw err; }
      }.check(done));
    });

    after(function(done) {
      conn.chatter.resource(feedElementUrl).delete(function(err, result) {
        if (err) { throw err; }
      }.check(done));
    });

  });

  /**
   *
   */
  describe("batch", function() {
    var chatter = conn.chatter;
    var feeds;
    var urls = [];

    before(function(done) {
      chatter.resource('/feeds').retrieve(function(err, result) {
        if (err) { throw err; }
        feeds = result.feeds.filter(function(feed) {
          // Exclude PendingReview feed type, which raise 403 error in feed-elements GET request
          return feed.feedType !== 'PendingReview';
        });
      }.check(done));
    });

    it("should get all feed items", function(done) {
      var resources = _.map(feeds, function(feed) {
        return chatter.resource(feed.feedElementsUrl);
      });
      chatter.batch(resources, function(err, result) {
        if (err) { throw err; }
        assert.ok(result.hasErrors === false);
        assert.ok(_.isArray(result.results) && result.results.length === feeds.length);
        _.forEach(result.results, function(result) {
          var res = result.result;
          assert.ok(_.isString(res.currentPageUrl));
          assert.ok(_.isArray(res.elements));
        });
      }.check(done));
    });

    it("should create new item post and get feed items", function(done) {
      chatter.batch([
        chatter.resource('/feed-elements').create({
          body: {
            messageSegments: [{
              type: 'Text',
              text: 'This is a post text'
            }]
          },
          feedElementType: "FeedItem",
          subjectId: "me"
        }),
        chatter.resource('/feed-elements').create({
          body: {
            messageSegments: [{
              type: 'Text',
              text: 'This is another post text, following to previous.'
            }]
          },
          feedElementType: "FeedItem",
          subjectId: "me"
        }),
        chatter.resource('/feeds/news/me/feed-elements', { pageSize: 2, sort: "CreatedDateDesc" }),
      ], function(err, result) {
        assert.ok(result.hasErrors === false);
        assert.ok(_.isArray(result.results) && result.results.length === 3);
        var elem1 = result.results[0].result;
        var elem2 = result.results[1].result;
        var elems = result.results[2].result;
        urls.push(elem1.url);
        urls.push(elem2.url);
        assert.ok(elems.elements[1].id === elem1.id);
        assert.ok(elems.elements[0].id === elem2.id);
      }.check(done));
    });

    it("should delete all created resources", function(done) {
      if (urls.length > 0) {
        chatter.batch(_.map(urls, function(url) {
          return chatter.resource(url).delete();
        }), function(err, result) {
          if (err) { throw err; }
        }.check(done));
      } else {
        done();
      }
    });

  });

  /**
   *
   */
  after(function(done) {
    testEnv.closeConnection(conn, done);
  });

});
<|endoftext|>


<commit_before>const path = require('path')
const fs = require('fs')
const should = require('should')
const { init, clean, cwd, exec } = require('./utils')

describe('cli', () => {
  before(init)
  beforeEach(clean)

  it('should fail when passing unknown option', () => {
    should(() => {
      exec('--unknown-arg value')
    }).throw(/Unknown argument/)
  })

  it('--version should return version', () => {
    exec('--version').should.match(/cli version/)
  })

  it('--help should return message', () => {
    exec('--help').should.match(/Usage:\n\njsreport/)
  })

  it('should fail when command receives unknown option', () => {
    should(() => {
      exec('help --unknown-arg value')
    }).throw(/Unknown argument/)
  })

  it('"help config" should return message', () => {
    const result = exec('help config')

    result.should.match(/Configuration format description/)
    result.should.match(/"extensions": <object> {/)
  })

  it('render should write to output file', () => {
    fs.writeFileSync(path.join(cwd, 'test.html'), 'foo')
    exec('render --template.content=test.html --template.engine=none --template.recipe=html --out=out.html')
    fs.readFileSync(path.join(cwd, 'out.html')).toString().should.be.eql('foo')
  })

  it('render failing instance should provide init error', () => {
    fs.writeFileSync(path.join(cwd, 'jsreport.config.json'), 'intention')
    fs.writeFileSync(path.join(cwd, 'test.html'), 'foo')
    should(() => {
      exec('render --template.content=test.html --template.engine=none --template.recipe=html --out=out.html')
    }).throw(/Error parsing your configuration file/)
  })

  it('render with keepAlive and failing instance should provide init error', () => {
    fs.writeFileSync(path.join(cwd, 'jsreport.config.json'), 'intention')
    fs.writeFileSync(path.join(cwd, 'test.html'), 'foo')
    should(() => {
      exec('render --keepAlive --template.content=test.html --template.engine=none --template.recipe=html --out=out.html')
    }).throw(/Error parsing your configuration file/)
  })
})
<commit_msg>add tests cases for unknown args<commit_after>const path = require('path')
const fs = require('fs')
const should = require('should')
const { init, clean, cwd, exec } = require('./utils')

describe('cli', () => {
  before(init)
  beforeEach(clean)

  it('should fail when passing unknown option', () => {
    should(() => {
      exec('--unknown value')
    }).throw(/Unknown argument/)
  })

  it('should fail when passing unknown dashed option', () => {
    should(() => {
      exec('--unknown-arg value')
    }).throw(/Unknown argument/)
  })

  it('--version should return version', () => {
    exec('--version').should.match(/cli version/)
  })

  it('--help should return message', () => {
    exec('--help').should.match(/Usage:\n\njsreport/)
  })

  it('should fail when command receives unknown option', () => {
    should(() => {
      exec(' --unknown value')
    }).throw(/Unknown argument/)
  })

  it('should fail when command receives unknown dashed option', () => {
    should(() => {
      exec(' --unknown-args value')
    }).throw(/Unknown argument/)
  })

  it('"help config" should return message', () => {
    const result = exec('help config')

    result.should.match(/Configuration format description/)
    result.should.match(/"extensions": <object> {/)
  })

  it('render should write to output file', () => {
    fs.writeFileSync(path.join(cwd, 'test.html'), 'foo')
    exec('render --template.content=test.html --template.engine=none --template.recipe=html --out=out.html')
    fs.readFileSync(path.join(cwd, 'out.html')).toString().should.be.eql('foo')
  })

  it('render failing instance should provide init error', () => {
    fs.writeFileSync(path.join(cwd, 'jsreport.config.json'), 'intention')
    fs.writeFileSync(path.join(cwd, 'test.html'), 'foo')
    should(() => {
      exec('render --template.content=test.html --template.engine=none --template.recipe=html --out=out.html')
    }).throw(/Error parsing your configuration file/)
  })

  it('render with keepAlive and failing instance should provide init error', () => {
    fs.writeFileSync(path.join(cwd, 'jsreport.config.json'), 'intention')
    fs.writeFileSync(path.join(cwd, 'test.html'), 'foo')
    should(() => {
      exec('render --keepAlive --template.content=test.html --template.engine=none --template.recipe=html --out=out.html')
    }).throw(/Error parsing your configuration file/)
  })
})
<|endoftext|>


<commit_before>/*
 * This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/.
 */

/*
 * Copyright (c) 2015, Joyent, Inc.
 */

var test = require('tape').test;

///--- Globals

var parse;
var compare;

///--- Tests

test('load library', function (t) {
  var lib = require('../ip6addr.js');
  t.ok(parse = lib.parse);
  t.ok(compare = lib.compare);
  t.end();
});

test('compare ipv4', function (t) {
  t.equal(compare(parse('1.2.3.4'), parse('1.2.3.4')), 0);
  t.equal(compare(parse('1.2.3.3'), parse('1.2.3.4')), -1);
  t.equal(compare(parse('1.2.3.5'), parse('1.2.3.4')), 1);

  t.equal(compare(parse('1.2.3.3'), parse('2.1.1.1')), -1);
  t.equal(compare(parse('1.2.3.5'), parse('0.9.9.9')), 1);
  t.end();
});

test('compare ipv6', function (t) {
  t.equal(compare(parse('2001:db8::1'), parse('2001:db8::1')), 0);
  t.equal(compare(parse('2001:db8::'), parse('2001:db8::1')), -1);
  t.equal(compare(parse('2001:db8::1'), parse('2001:db8::')), 1);
  t.end();
});
<commit_msg>Add more comparison tests<commit_after>/*
 * This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/.
 */

/*
 * Copyright (c) 2015, Joyent, Inc.
 */

var test = require('tape').test;

///--- Globals

var parse;
var compare;

///--- Tests

test('load library', function (t) {
  var lib = require('../ip6addr.js');
  t.ok(parse = lib.parse);
  t.ok(compare = lib.compare);
  t.end();
});

test('compare ipv4', function (t) {
  var ipv4comp = [
    ['1.2.3.4', '1.2.3.4', 0],
    ['1.2.3.3', '1.2.3.4', -1],
    ['1.2.3.5', '1.2.3.4', 1],
    ['1.2.3.1', '1.2.3.10', -1],
    ['1.2.3.3', '2.1.1.1', -1],
    ['1.2.3.5', '0.9.9.9', 1],
    ['1.2.3.0', '1.2.2.255', 1],
    ['1.2.255.255', '1.3.0.0', -1],
    ['2.0.0.0', '1.255.255.255', 1]
  ];

  for (var i in ipv4comp) {
    t.equal(compare(parse(ipv4comp[i][0]), parse(ipv4comp[i][1])),
        ipv4comp[i][2], 'compare: ' + ipv4comp[i][0] + ' - ' + ipv4comp[i][1]);
  }

  t.end();
});

test('compare ipv6', function (t) {
  var ipv6comp = [
    ['2001:db8::1', '2001:db8::1', 0],
    ['2001:db8::', '2001:db8::1', -1],
    ['2001:db8::1', '2001:db8::', 1],
    ['::ffff:1.2.3.0', '::ffff:1.2.2.255', 1],
    ['::ffff:8.8.8.8', '::ffff:8.8.7.7', 1],
    ['0:0:0:0:0:ffff:808:808', '0:0:0:0:0:ffff:808:807', 1],
    [' 2001:db8:1:0:0:0:0:0', '2001:db8:0:ffff:ffff:ffff:ffff:ffff', 1]
  ];

  for (var i in ipv6comp) {
    t.equal(compare(parse(ipv6comp[i][0]), parse(ipv6comp[i][1])),
        ipv6comp[i][2], 'compare: ' + ipv6comp[i][0] + ' - ' + ipv6comp[i][1]);
  }

  t.end();
});
<|endoftext|>