<commit_before>var promisify = require("../");
var assert = require("assert");

describe("Promisify", function() {
  it("can convert a basic async function", function() {
    function test(cb) {
      cb(null, true);
    }

    var wrappedTest = promisify(test);

    return wrappedTest().then(function(value) {
      assert.ok(value);
    });
  });

  it("exports a callbacks array", function() {
    assert(Array.isArray(promisify.callbacks));
  });
});
<commit_msg>Add tests for asynchronous method inference<commit_after>var promisify = require("../");
var assert = require("assert");

describe("Promisify", function() {
  it("can convert a basic async function", function() {
    function test(cb) {
      cb(null, true);
    }

    var wrappedTest = promisify(test);

    return wrappedTest().then(function(value) {
      assert.ok(value);
    });
  });

  it("exports a callbacks array", function() {
    assert(Array.isArray(promisify.callbacks));
  });

  describe("asynchronous method inference", function() {
    var later = function(cb) {
      setTimeout(cb(null), 0);
    };

    it("does not modify methods that do not appear to be asynchronous", function() {
      var obj = {
        a: function(probably, not, async) {}
      };
      var wrappedObj = promisify(obj);

      assert.equal(
        obj.a,
        wrappedObj.a
      );
    });

    it("can infer callback-accepting functions by argument list", function() {
      var obj = promisify({
        a: function(cb) { later(cb); }
      });

      return obj.a();
    });

    it("can infer callback-accepting functions by argument list", function() {
      var obj = promisify({
        a: function(callback) { later(callback); }
      });

      return obj.a();
    });

    it("can infer callback-accepting functions by argument list", function() {
      var obj = promisify({
        a: function(callback_) { later(callback_); }
      });

      return obj.a();
    });

    it("can infer callback-accepting functions by argument list", function() {
      var obj = promisify({
        a: function(done) { later(done); }
      });

      return obj.a();
    });
  });
});
<|endoftext|>


<commit_before>/**
 * lark-config - index.js
 * Copyright(c) 2014 larkjs-team(https://github.com/larkjs)
 * MIT Licensed
 */
'use strict';

import config   from '..';
import eql      from 'deep-eql';
import extend   from 'extend';
import should   from 'should';

const expect_base = {
    a: {
        'key-a': 'value-a',
        'key-b': {
            'key-b-1': 'content-b-1',
            'key-b-2': 'content-b-1'
        }
    },
    b: {
        'key-b': 'content-b',
        'key-c': {
            'key-c-1': 'content-c-1',
            'key-c-2': 'content-c-2'
        }
    },
    c: {
        'key-c': 'content-c',
        'key-d': {
            'key-d-1': [
                'content-d-1.0', 'content-d-1.1'
            ],
            'key-d-2': {
                'content-d-2': null
            }
        }
    },
    d: {
        e: {
            'key-e': 'content-e'
        }
    },
};

const expect_dev_en = extend(true, extend(true, {}, expect_base), {
    f : "value-f-dev",
    locales : {
        "welcome": "welcome",
        ":)": ":)",
    },
});

const expect_prod_zhCN = extend(true, extend(true, {}, expect_base), {
    f : "value-f-prod",
    locales : {
        "welcome": "欢迎",
        ":)": "^_^",
    },
});

describe('config', function () {
    it('should equal expect with env dev and locale en', function (done) {
        let configs = config('../example/configs', {
            env: 'development',
            locale: 'en',
        });
        delete configs.configPath;
        eql(configs, expect_dev_en).should.be.true;
        done();
    });

    it('should equal expect with env prod and locale zhCN', function (done) {
        let configs = config('../example/configs', {
            env: 'production',
            locale: 'zhCN',
        });
        delete configs.configPath;
        eql(configs, expect_prod_zhCN).should.be.true;
        done();
    });
});
<commit_msg>fix test<commit_after>/**
 * lark-config - index.js
 * Copyright(c) 2014 larkjs-team(https://github.com/larkjs)
 * MIT Licensed
 */
'use strict';

import config   from '..';
import eql      from 'deep-eql';
import extend   from 'extend';
import should   from 'should';

const expect_base = {
    a: {
        'key-a': 'value-a',
        'key-b': {
            'key-b-1': 'content-b-1',
            'key-b-2': 'content-b-1'
        }
    },
    b: {
        'key-b': 'content-b',
        'key-c': {
            'key-c-1': 'content-c-1',
            'key-c-2': 'content-c-2'
        }
    },
    c: {
        'key-c': 'content-c',
        'key-d': {
            'key-d-1': [
                'content-d-1.0', 'content-d-1.1'
            ],
            'key-d-2': {
                'content-d-2': null
            }
        }
    },
    d: {
        e: {
            'key-e': 'content-e'
        }
    },
};

const expect_dev_en = extend(true, extend(true, {}, expect_base), {
    f : "value-f-dev",
    locales : {
        "welcome": "welcome",
        ":)": ":)",
    },
});

const expect_prod_zhCN = extend(true, extend(true, {}, expect_base), {
    f : "value-f-prod",
    locales : {
        "welcome": "欢迎",
        ":)": "^_^",
    },
});

describe('config', function () {
    it('should equal expect with env dev and locale en', function (done) {
        let configs = config('../example/configs', {
            env: 'development',
            locale: 'en',
        });
        delete configs.configPath;
        eql(configs, expect_dev_en).should.be.exactly(true);
        done();
    });

    it('should equal expect with env prod and locale zhCN', function (done) {
        let configs = config('../example/configs', {
            env: 'production',
            locale: 'zhCN',
        });
        delete configs.configPath;
        eql(configs, expect_prod_zhCN).should.be.exactly(true);
        done();
    });
});
<|endoftext|>


<commit_before>var kvp = require('../kvp'),
	assert = require('assert');

var o = {
	a: 100,
	aa: {
		aaa: {
			x: 'ex',
			y: 'YY'
		}
	},
	c: "billi",
	d: [1,2,3,4,5],
	e: true
}

describe('Testing KVP', function () {
	var k = kvp(o);
	describe('methods', function () {
		it('should have a query method', function () {
			assert(typeof k.query === 'function');
		});
		it('should have a select method', function () {
			assert(typeof k.select === 'function');
		});
		it('should have a replace method', function () {
			assert(typeof k.replace === 'function');
		});
		it('should have a remove method', function () {
			assert(typeof k.remove === 'function');
		});
	});

	describe('query tests', function () {
		it('should return value 100', function () {
			var res = k.query(function (n) {
					if (n.key === 'a') {
						return true;
					}
			});
			assert(res === 100);
		});
		it('should return changed value', function () {
			var res = k.query(function (node) {
				if (node.key === 'c') {
					this.replace(node.pointer, 'doggy');
					return true;
				}
			});
			assert(res === 'doggy');
		});
		it('should return undefined withour error', function () {
			var res = k.query(function () {});
			assert(res === undefined);
		});
	});

	describe('select tests', function () {
		it('should return node value "YY"', function () {
			var res = k.select('/aa/aaa/y');
			assert(res === 'YY');
		});
		it('should return node value 5', function () {
			var res = k.select('/d/4');
			assert(res === 5);
		});
	});
})

<commit_msg>tests<commit_after>var kvp = require('../kvp'),
	assert = require('assert');

var o = {
	a: 100,
	aa: {
		aaa: {
			x: 'ex',
			y: 'YY'
		}
	},
	c: "billi",
	d: [1,2,3,4,5],
	e: true
}

describe('Testing KVP', function () {
	var k = kvp(o);
	describe('methods', function () {
		it('should have a query method', function () {
			assert(typeof k.query === 'function');
		});
		it('should have a select method', function () {
			assert(typeof k.select === 'function');
		});
		it('should have a replace method', function () {
			assert(typeof k.replace === 'function');
		});
		it('should have a remove method', function () {
			assert(typeof k.remove === 'function');
		});
	});

	describe('query tests', function () {
		it('should return value 100', function () {
			var res = k.query(function (n) {
					if (n.key === 'a') {
						return true;
					}
			});
			assert(res === 100);
		});
		it('should return changed value', function () {
			var res = k.query(function (node) {
				if (node.key === 'c') {
					this.replace(node.pointer, 'doggy');
					return true;
				}
			});
			assert(res === 'doggy');
		});
		it('should return changed value', function () {
			var res = k.query(function (node) {
				if (node.key === 'aaa') {
					node.value.y = 'YYY';
					return true;
				}
			});
			assert(o['aa']['aaa']['y'] === 'YYY');
		});
		it('should return undefined withour error', function () {
			var res = k.query(function () {});
			assert(res === undefined);
		});
	});

	describe('select tests', function () {
		it('should return node value "ex"', function () {
			var res = k.select('/aa/aaa/x');
			assert(res === 'ex');
		});
		it('should return node value 5', function () {
			var res = k.select('/d/4');
			assert(res === 5);
		});
	});

	describe('replace tests', function () {
		it('should return false', function () {
			k.replace('/e', false);
			assert(!o['e']);
		});
		it('should return true', function () {
			k.replace('/e', !k.select('/e'));
			var res = k.select('/e');
			assert(res);
		});
	});
})

<|endoftext|>


<commit_before>'use strict';

var should = require('should');
var clone = require('lodash.clone');
var router = require('../');
var sampleRoutes = require('./fixtures/dashboardRoutes');

beforeEach(function(){
  window.location.href = '/';
  this.container = document.createElement('article');
  this.routes = clone(sampleRoutes);
});

afterEach(function(){
  if (this.router) {
    this.router.stop();
    delete this.router;
  }
  delete this.container;
  delete this.routes;
});

describe('Router()', function() {
  it('should expose the right attributes', function(done){
    should.exist(router);
    should.exist(router.ChildView, 'childview');
    should.exist(router.Link, 'link');
    should.exist(router.mixins, 'mixins');
    should.exist(router.mixins.Navigation, 'navigation mixin');
    should.exist(router.mixins.State, 'state mixin');
    should.exist(router.locations, 'locations');
    should.exist(router.locations.History, 'history location');
    should.exist(router.locations.Hash, 'hash location');
    should.exist(router.locations.Refresh, 'refresh location');
    done();
  });

  it('should construct a router from a route object', function(done) {
    this.router = router(this.routes);
    should.exist(this.router, 'return value');
    should.exist(this.router.start, 'start fn');
    should.exist(this.router.stop, 'stop fn');
    should.exist(this.router.transitionTo, 'transitionTo fn');
    should.exist(this.router.replaceWith, 'replaceWith fn');
    done();
  });

  it('should throw on invalid route param', function(done) {
    try {
      this.router = router('lol');
    } catch (err) {
      should.exist(err);
      done();
    }
  });

  it('should throw on invalid route object', function(done) {
    try {
      this.router = router({test: 'lol'});
    } catch (err) {
      should.exist(err);
      done();
    }
  });
});

describe('Router.start()', function() {
  it('should render a route', function(done) {
    this.router = router(this.routes);
    this.router.replaceWith('/');
    this.router.start(this.container);

    var firstContainerNode = this.container.childNodes[0];
    var firstTextNode = firstContainerNode.childNodes[0];

    firstContainerNode.tagName.should.equal('DIV');
    firstTextNode.tagName.should.equal('SPAN');
    firstTextNode.textContent.should.equal('Test');

    done();
  });

  it('should render a route from options object', function(done) {
    router.locations.History.history = ['/login'];
    this.router = router(this.routes, {location: router.locations.History});
    this.router.start(this.container);

    var firstContainerNode = this.container.childNodes[0];
    var firstTextNode = firstContainerNode.childNodes[0];

    firstContainerNode.tagName.should.equal('DIV');
    firstTextNode.tagName.should.equal('SPAN');
    firstTextNode.textContent.should.equal('Test');

    done();
  });

  it('should render a nested route', function(done) {
    this.router = router(this.routes);
    this.router.replaceWith('/home/analytics');
    this.router.start(this.container);

    var firstContainerNode = this.container.childNodes[0];
    var firstTextNode = firstContainerNode.childNodes[0];
    var secondContainerNode = firstContainerNode.childNodes[1];
    var secondTextNode = secondContainerNode.childNodes[0];

    firstContainerNode.tagName.should.equal('DIV');
    firstTextNode.tagName.should.equal('SPAN');
    firstTextNode.textContent.should.equal('Test');

    secondContainerNode.tagName.should.equal('DIV');
    secondTextNode.tagName.should.equal('SPAN');
    secondTextNode.textContent.should.equal('Test');

    done();
  });
});<commit_msg>test for transition hooks, fix pollution between test routing instances<commit_after>'use strict';

var should = require('should');
var React = require('react');
var clone = require('lodash.clone');
var LocationActions = require('react-router/modules/actions/LocationActions');
var router = require('../');
var sampleRoutes = require('./fixtures/dashboardRoutes');

beforeEach(function(){
  window.location.href = '/';
  this.container = document.createElement('article');
  this.routes = clone(sampleRoutes);
});

afterEach(function(){
  if (this.router) {
    this.router.clearAllRoutes();
    this.router.stop();
    delete this.router;
  }
  delete this.container;
  delete this.routes;
});

describe('Router()', function() {
  it('should expose the right attributes', function(done){
    should.exist(router);
    should.exist(router.ChildView, 'childview');
    should.exist(router.Link, 'link');
    should.exist(router.mixins, 'mixins');
    should.exist(router.mixins.Navigation, 'navigation mixin');
    should.exist(router.mixins.State, 'state mixin');
    should.exist(router.locations, 'locations');
    should.exist(router.locations.History, 'history location');
    should.exist(router.locations.Hash, 'hash location');
    should.exist(router.locations.Refresh, 'refresh location');
    done();
  });

  it('should construct a router from a route object', function(done) {
    this.router = router(this.routes);
    should.exist(this.router, 'return value');
    should.exist(this.router.start, 'start fn');
    should.exist(this.router.stop, 'stop fn');
    should.exist(this.router.transitionTo, 'transitionTo fn');
    should.exist(this.router.replaceWith, 'replaceWith fn');
    done();
  });

  it('should throw on invalid route param', function(done) {
    try {
      this.router = router('lol');
    } catch (err) {
      should.exist(err);
      done();
    }
  });

  it('should throw on invalid route object', function(done) {
    try {
      this.router = router({test: 'lol'});
    } catch (err) {
      should.exist(err);
      done();
    }
  });
});

describe('Router.start()', function() {
  it('should render a route', function(done) {
    this.router = router(this.routes);
    this.router.replaceWith('/');
    this.router.start(this.container);

    var firstContainerNode = this.container.childNodes[0];
    var firstTextNode = firstContainerNode.childNodes[0];

    firstContainerNode.tagName.should.equal('DIV');
    firstTextNode.tagName.should.equal('SPAN');
    firstTextNode.textContent.should.equal('Test');

    done();
  });

  it('should call willTransitionTo', function(done) {
    var Component = React.createFactory(React.createClass({
      render: function(){
        return React.DOM.div(null, 'Test');
      },
      statics: {
        willTransitionTo: function(t, cb) {
          should.exist(t);
          should.exist(cb);
          done();
        }
      }
    }));

    this.router = router({
      splash: {
        path: '/',
        view: Component
      }
    });
    this.router.start(this.container);
    this.router.dispatch('/', LocationActions.PUSH);
  });

  it('should render a route from options object', function(done) {
    router.locations.History.history = ['/login'];
    this.router = router(this.routes, {location: router.locations.History});
    this.router.start(this.container);

    var firstContainerNode = this.container.childNodes[0];
    var firstTextNode = firstContainerNode.childNodes[0];

    firstContainerNode.tagName.should.equal('DIV');
    firstTextNode.tagName.should.equal('SPAN');
    firstTextNode.textContent.should.equal('Test');

    done();
  });

  it('should render a nested route', function(done) {
    this.router = router(this.routes);
    this.router.start(this.container);
    this.router.dispatch('/home/analytics', LocationActions.PUSH);

    var firstContainerNode = this.container.childNodes[0];
    var firstTextNode = firstContainerNode.childNodes[0];
    var secondContainerNode = firstContainerNode.childNodes[1];
    var secondTextNode = secondContainerNode.childNodes[0];

    firstContainerNode.tagName.should.equal('DIV');
    firstTextNode.tagName.should.equal('SPAN');
    firstTextNode.textContent.should.equal('Test');

    secondContainerNode.tagName.should.equal('DIV');
    secondTextNode.tagName.should.equal('SPAN');
    secondTextNode.textContent.should.equal('Test');

    done();
  });
});<|endoftext|>


<commit_before>// Dependencies
var IsSsh = require("../lib")
  , Assert = require("assert")
  ;

// Prepare the input data
var input = [
    // Secure Shell Transport Protocol (SSH)
    ["ssh://user@host.xz:port/path/to/repo.git/", true]
  , ["ssh://user@host.xz/path/to/repo.git/", true]
  , ["ssh://host.xz:port/path/to/repo.git/", true]
  , ["ssh://host.xz/path/to/repo.git/", true]
  , ["ssh://user@host.xz/path/to/repo.git/", true]
  , ["ssh://host.xz/path/to/repo.git/", true]
  , ["ssh://user@host.xz/~user/path/to/repo.git/", true]
  , ["ssh://host.xz/~user/path/to/repo.git/", true]
  , ["ssh://user@host.xz/~/path/to/repo.git", true]
  , ["ssh://host.xz/~/path/to/repo.git", true]
  , ["user@host.xz:/path/to/repo.git/", true]
  , ["user@host.xz:~user/path/to/repo.git/", true]
  , ["user@host.xz:path/to/repo.git", true]
  , ["host.xz:/path/to/repo.git/", true]
  , ["host.xz:path/to/repo.git", true]
  , ["host.xz:~user/path/to/repo.git/", true]
  , ["rsync://host.xz/path/to/repo.git/", true]

    // Git Transport Protocol
  , ["git://host.xz/path/to/repo.git/", false]
  , ["git://host.xz/~user/path/to/repo.git/", false]

    // HTTP/S Transport Protocol
  , ["http://host.xz/path/to/repo.git/", false]
  , ["https://host.xz/path/to/repo.git/", false]

    // Local (Filesystem) Transport Protocol
  , ["/path/to/repo.git/", false]
  , ["path/to/repo.git/", false]
  , ["~/path/to/repo.git", false]
  , ["file:///path/to/repo.git/", false]
  , ["file://~/path/to/repo.git/", false]
];

// Run the tests
input.forEach(function (c) {
    it(c[0] + " is supposed " + (!c[1] ? "not " : "") + "to be a ssh url", function (cb) {
        Assert.equal(IsSsh(c[0]), c[1]);
        cb();
    });
});
<commit_msg>Tests using tester<commit_after>// Dependencies
const isSsh = require("../lib")
    , tester = require("tester")
    ;

// Prepare the input data
var input = [
    // Secure Shell Transport Protocol (SSH)
    ["ssh://user@host.xz:port/path/to/repo.git/", true]
  , ["ssh://user@host.xz/path/to/repo.git/", true]
  , ["ssh://host.xz:port/path/to/repo.git/", true]
  , ["ssh://host.xz/path/to/repo.git/", true]
  , ["ssh://user@host.xz/path/to/repo.git/", true]
  , ["ssh://host.xz/path/to/repo.git/", true]
  , ["ssh://user@host.xz/~user/path/to/repo.git/", true]
  , ["ssh://host.xz/~user/path/to/repo.git/", true]
  , ["ssh://user@host.xz/~/path/to/repo.git", true]
  , ["ssh://host.xz/~/path/to/repo.git", true]
  , ["user@host.xz:/path/to/repo.git/", true]
  , ["user@host.xz:~user/path/to/repo.git/", true]
  , ["user@host.xz:path/to/repo.git", true]
  , ["host.xz:/path/to/repo.git/", true]
  , ["host.xz:path/to/repo.git", true]
  , ["host.xz:~user/path/to/repo.git/", true]
  , ["rsync://host.xz/path/to/repo.git/", true]

    // Git Transport Protocol
  , ["git://host.xz/path/to/repo.git/", false]
  , ["git://host.xz/~user/path/to/repo.git/", false]

    // HTTP/S Transport Protocol
  , ["http://host.xz/path/to/repo.git/", false]
  , ["https://host.xz/path/to/repo.git/", false]

    // Local (Filesystem) Transport Protocol
  , ["/path/to/repo.git/", false]
  , ["path/to/repo.git/", false]
  , ["~/path/to/repo.git", false]
  , ["file:///path/to/repo.git/", false]
  , ["file://~/path/to/repo.git/", false]
];

tester.describe("check urls", test => {
    // Run the tests
    input.forEach(c => {
        test.it(c[0] + " is supposed " + (!c[1] ? "not " : "") + "to be a ssh url", () => {
            test.expect(isSsh(c[0])).toBe(c[1]);
        });
    });
});
<|endoftext|>


<commit_before>/*jshint browser:true, node:false*/
/*global require, sinon*/

describe('User-List Component', function() {
  "use strict";

  var UserList = require('user-list');

  var assert = window.assert;

  var classes = require('classes');
  var _ = require('lodash');

  var testUserList;

  var sandbox;
  beforeEach(function() {
    sandbox = sinon.sandbox.create();
  });

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

  var userList;

  var fakeRoom;
  var fakeUsers;
  var fakeUserView;
  var fakeUserCache;
  var fakeLocalUser;
  var fakeLocalUserKey;
  var fakeDisplayNameKey;

  beforeEach(function() {
    fakeRoom = {};

    fakeUsers = [
      {
        displayName: 'Jose',
        id: 3
      },
      {}
    ];

    fakeLocalUser = fakeUsers[0];

    fakeDisplayNameKey = {
      set: sinon.stub().yields()
    };
    fakeLocalUserKey = {
      key: sinon.stub().withArgs('displayName').returns(fakeDisplayNameKey)
    };

    fakeUserCache = {
      initialize: sinon.stub().yields(),
      on: sinon.stub(),
      off: sinon.stub(),
      destroy: sinon.stub().yields(),
      getAll: sinon.stub().returns(fakeUsers),
      getLocalUser: sinon.stub().returns(fakeLocalUser),
      getLocalUserKey: sinon.stub().returns(fakeLocalUserKey)
    };

    fakeUserView = {
      render: sinon.stub().yields()
    };

    sandbox.stub(UserList, '_UserCache').returns(fakeUserCache);
    sandbox.stub(UserList, '_UserView').returns(fakeUserView);
    sandbox.spy(UserList._binder, 'on');
    sandbox.spy(UserList._binder, 'off');
  });

  describe('constructor', function() {

    it('returns new instance object correctly', function() {
      var options = {
        room: fakeRoom
      };

      testUserList = new UserList(options);
      testUserList._userCache.initialize = sinon.stub().yields();

      assert.isObject(testUserList);
    });

    describe('errors', function() {
      it('throws an error if options is not passed', function() {
        assert.exception(function() {
          testUserList = new UserList(null);
        }, 'UserList: Options was not found or invalid');
      });

      it('throws an error if options is not an object', function() {
        assert.exception(function() {
          testUserList = new UserList('hi');
        }, 'UserList: Options was not found or invalid');
      });

      it('throws an error if options.room is not passed', function() {
        assert.exception(function() {
          testUserList = new UserList({});
        }, 'UserList: Room was not found or invalid');
      });

      it('throws an error if options.room is not an object', function() {
        var options = {
          room: 'hi'
        };

        assert.exception(function() {
          testUserList = new UserList(options);
        }, 'UserList: Room was not found or invalid');
      });

      it('throws an error if invalid options are passed', function() {
        var invalidOptions = {
          room: fakeRoom,
          fake: 'value'
        };

        assert.exception(function() {
          testUserList = new UserList(invalidOptions);
        }, 'UserList: Invalid argument passed');
      });

      it('throws an error if collapsed is not a boolean', function() {
        var options = {
          room: fakeRoom,
          collapsed: 'True'
        };

        assert.exception(function() {
          testUserList = new UserList(options);
        }, 'UserList: collapsed value must be a boolean');
      });

      it('throws an error if container is not a DOM element', function() {
        var options = {
          room: fakeRoom,
          container: 'DOM ELEMENT'
        };

        assert.exception(function() {
          testUserList = new UserList(options);
        }, 'UserList: container must be a DOM element');
      });

      it('throws an error if position is not right || left', function() {
        var options = {
          room: fakeRoom,
          position: 'top'
        };

        assert.exception(function() {
          testUserList = new UserList(options);
        }, 'UserList: position can only be "right" or "left"');
      });

      it('throws an error if position is not a string', function() {
        var options = {
          room: fakeRoom,
          position: true
        };

        assert.exception(function() {
          testUserList = new UserList(options);
        }, 'UserList: position can only be "right" or "left"');
      });

      it('passes back an error if truncateLength is not a number', function() {
        var options = {
          room: fakeRoom,
          truncateLength: '10'
        };

        assert.exception(function() {
          testUserList = new UserList(options);
        }, 'UserList: truncateLength can only be a number');
      });

      it('passes back an error if avatars is not a boolean', function() {
        var options = {
          room: fakeRoom,
          avatars: 'true'
        };

        assert.exception(function() {
          testUserList = new UserList(options);
        }, 'UserList: avatars must be a boolean');
      });

      it('passes back an error if userOptions is not a boolean', function() {
        var options = {
          room: fakeRoom,
          userOptions: 'true'
        };

        assert.exception(function() {
          testUserList = new UserList(options);
        }, 'UserList: userOptions must be a boolean');
      });
    });
  });

  describe('initialize', function() {
    afterEach(function(done) {
      userList.destroy(function() {
        done();
      });
    });

    it('hides the options when disabled', function(done) {
      userList = new UserList({
        room: fakeRoom,
        userOptions: false
      });

      userList.initialize(function(err) {
        assert.ifError(err);

        assert.ok(classes(userList.el).has('gi-no-options'));

        done();
      });
    });

    it('uses a container and applies the relative class', function(done) {
      var container = document.createElement('div');

      userList = new UserList({
        room: fakeRoom,
        container: container
      });

      userList.initialize(function(err) {
        assert.ifError(err);

        assert.equal(userList.el, container.children[0]);
        assert.ok(classes(userList.el).has('gi-relative'));
        assert.notOk(classes(userList.el).has('gi-anchor'));

        done();
      });
    });

    it('positions on the right', function(done) {
      userList = new UserList({
        room: fakeRoom,
        position: 'right'
      });

      userList.initialize(function(err) {
        assert.ifError(err);

        assert.ok(classes(userList.el).has('gi-right'));

        done();
      });
    });

    it('positions on the left', function(done) {
      userList = new UserList({
        room: fakeRoom,
        position: 'left'
      });

      userList.initialize(function(err) {
        assert.ifError(err);

        assert.ok(classes(userList.el).has('gi-left'));

        done();
      });
    });

    it('collapses', function(done) {
      userList = new UserList({
        room: fakeRoom,
        collapsed: true
      });

      userList.initialize(function(err) {
        assert.ifError(err);

        assert.ok(classes(userList.el).has('gi-collapsed'));

        done();
      });
    });

    it('expands', function(done) {
      userList = new UserList({
        room: fakeRoom,
        collapsed: false
      });

      userList.initialize(function(err) {
        assert.ifError(err);

        assert.notOk(classes(userList.el).has('gi-collapsed'));

        done();
      });
    });

    describe('defaults', function() {
      beforeEach(function(done) {
        var options = {
          room: fakeRoom
        };

        userList = new UserList(options);
        userList.initialize(function(err) {
          assert.ifError(err);
          done();
        });
      });

      afterEach(function(done) {
        userList.destroy(function() {
          done();
        });
      });

      it('initializes and binds to the userCache', function() {
        sinon.assert.calledOnce(fakeUserCache.initialize);
        sinon.assert.calledWith(
          fakeUserCache.on,
          'join',
          userList._handleJoinEvent
        );

        sinon.assert.calledWith(
          fakeUserCache.on,
          'leave',
          userList._handleLeaveEvent
        );

        sinon.assert.calledWith(
          fakeUserCache.on,
          'change',
          userList._handleUserMeta
        );
      });

      it('binds to events for options', function() {
        sinon.assert.calledWith(
          UserList._binder.on,
          sinon.match({className: 'gi-collapse'}),
          'click',
          userList._handleCollapseToggle
        );

        sinon.assert.calledWith(
          UserList._binder.on,
          sinon.match({className: 'gi-icon'}),
          'click',
          userList._clickEditUser
        );

        sinon.assert.calledWith(
          UserList._binder.on,
          sinon.match({className: 'gi-set-name'}),
          'keydown',
          userList._keydownOptionsInput
        );
      });

      it('renders a view for each user', function() {
        sinon.assert.callCount(fakeUserView.render, fakeUsers.length);

        _.each(fakeUsers, function(u) {
          sinon.assert.calledWith(fakeUserView.render, u);
        });
      });

      it('is displayed properly', function() {
        assert.notOk(classes(userList.el).has('gi-no-options'));
        assert.ok(classes(userList.el).has('gi-anchor'));

        assert.include(document.body.children, userList.el);
      });
    });

    describe('destroy', function() {
      beforeEach(function(done) {
        userList.initialize(function(err) {
          assert.ifError(err);

          userList.destroy(function(err) {
            assert.ifError(err);

            done();
          });
        });
      });

      it('initializes and binds to the userCache', function() {
        sinon.assert.calledWith(
          userList._userCache.off,
          'join',
          userList._handleJoinEvent
        );

        sinon.assert.calledWith(
          userList._userCache.off,
          'leave',
          userList._handleLeaveEvent
        );

        sinon.assert.calledWith(
          userList._userCache.off,
          'change',
          userList._handleUserMeta
        );
      });

      it('binds to events for options', function() {
        sinon.assert.calledWith(
          UserList._binder.off,
          sinon.match({className: 'gi-collapse'}),
          'click',
          userList._handleCollapseToggle
        );

        sinon.assert.calledWith(
          UserList._binder.off,
          sinon.match({className: 'gi-icon'}),
          'click',
          userList._clickEditUser
        );

        sinon.assert.calledWith(
          UserList._binder.off,
          sinon.match({className: 'gi-set-name'}),
          'keydown',
          userList._keydownOptionsInput
        );
      });
    });
  });

  describe('user controls', function() {
    beforeEach(function(done) {
      var options = {
        room: fakeRoom
      };

      userList = new UserList(options);
      userList.initialize(function(err) {
        assert.ifError(err);
        done();
      });
    });

    it('toggles when collapse is clicked', function() {
      userList._handleCollapseToggle();

      assert.ok(classes(userList.el).has('gi-collapsed'));

      userList._handleCollapseToggle();

      assert.notOk(classes(userList.el).has('gi-collapsed'));
    });

    describe('editing your name', function() {
      it('toggles editing, and does not save when no change', function(done) {
        userList._clickEditUser({}, function() {
          assert.ok(classes(userList.el).has('gi-editing'));

          userList._clickEditUser({}, function() {
            assert.notOk(classes(userList.el).has('gi-editing'));

            sinon.assert.notCalled(fakeDisplayNameKey.set);

            done();
          });
        });
      });

      it('sets the new name when changed', function(done) {
        userList._clickEditUser({}, function() {
          assert.ok(classes(userList.el).has('gi-editing'));

          var input = userList.el.querySelector('input');
          input.value = 'cool';

          userList._clickEditUser({}, function() {
            sinon.assert.calledWith(fakeDisplayNameKey.set, 'cool');

            assert.ok(classes(userList.el).has('gi-editing'));

            // We wait until the change comes back to the local platform
            // listener before displaying it.
            var updatedFakeLocalUser = _.clone(fakeLocalUser);
            updatedFakeLocalUser.displayName = 'cool';

            var keyName =  '/.users/231232131232/displayName';

            userList._handleUserMeta(updatedFakeLocalUser, keyName, function() {
              assert.notOk(classes(userList.el).has('gi-editing'));

              sinon.assert.calledWith(
                fakeUserView.render,
                updatedFakeLocalUser
              );

              done();
            });
          });
        });

      });

      it('stops editing when collapse is clicked', function(done) {
        userList._clickEditUser({}, function() {
          assert.ok(classes(userList.el).has('gi-editing'));

          userList._handleCollapseToggle({});

          assert.notOk(classes(userList.el).has('gi-editing'));

          done();
        });
      });
    });
  });

  describe('users', function() {
    beforeEach(function(done) {
      var options = {
        room: fakeRoom
      };

      userList = new UserList(options);
      userList.initialize(function(err) {
        assert.ifError(err);

        fakeUserView.render.reset();

        done();
      });
    });

    it('are rendered when they join', function() {
      var user = {};
      userList._handleJoinEvent(user);

      sinon.assert.calledWith(fakeUserView.render, user);
    });

    it('are rendered when they change', function() {
      var user = {
        displayName: 'whatever'
      };

      userList._handleUserMeta(user, '/.users/awessdsdas/displayName');

      sinon.assert.calledWith(fakeUserView.render, user);
    });
  });
});
<commit_msg>Cleanup all the things.<commit_after>/*jshint browser:true, node:false*/
/*global require, sinon*/

describe('User-List Component', function() {
  "use strict";

  var UserList = require('user-list');

  var assert = window.assert;

  var classes = require('classes');
  var _ = require('lodash');

  var testUserList;

  var sandbox;
  beforeEach(function() {
    sandbox = sinon.sandbox.create();
  });

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

  var userList;

  var fakeRoom;
  var fakeUsers;
  var fakeUserView;
  var fakeUserCache;
  var fakeLocalUser;
  var fakeLocalUserKey;
  var fakeDisplayNameKey;

  beforeEach(function() {
    fakeRoom = {};

    fakeUsers = [
      {
        displayName: 'Jose',
        id: 3
      },
      {}
    ];

    fakeLocalUser = fakeUsers[0];

    fakeDisplayNameKey = {
      set: sinon.stub().yields()
    };
    fakeLocalUserKey = {
      key: sinon.stub().withArgs('displayName').returns(fakeDisplayNameKey)
    };

    fakeUserCache = {
      initialize: sinon.stub().yields(),
      on: sinon.stub(),
      off: sinon.stub(),
      destroy: sinon.stub().yields(),
      getAll: sinon.stub().returns(fakeUsers),
      getLocalUser: sinon.stub().returns(fakeLocalUser),
      getLocalUserKey: sinon.stub().returns(fakeLocalUserKey)
    };

    fakeUserView = {
      render: sinon.stub().yields()
    };

    sandbox.stub(UserList, '_UserCache').returns(fakeUserCache);
    sandbox.stub(UserList, '_UserView').returns(fakeUserView);
    sandbox.spy(UserList._binder, 'on');
    sandbox.spy(UserList._binder, 'off');
  });

  describe('constructor', function() {

    it('returns new instance object correctly', function() {
      var options = {
        room: fakeRoom
      };

      testUserList = new UserList(options);
      testUserList._userCache.initialize = sinon.stub().yields();

      assert.isObject(testUserList);
    });

    describe('errors', function() {
      it('throws an error if options is not passed', function() {
        assert.exception(function() {
          testUserList = new UserList(null);
        }, 'UserList: Options was not found or invalid');
      });

      it('throws an error if options is not an object', function() {
        assert.exception(function() {
          testUserList = new UserList('hi');
        }, 'UserList: Options was not found or invalid');
      });

      it('throws an error if options.room is not passed', function() {
        assert.exception(function() {
          testUserList = new UserList({});
        }, 'UserList: Room was not found or invalid');
      });

      it('throws an error if options.room is not an object', function() {
        var options = {
          room: 'hi'
        };

        assert.exception(function() {
          testUserList = new UserList(options);
        }, 'UserList: Room was not found or invalid');
      });

      it('throws an error if invalid options are passed', function() {
        var invalidOptions = {
          room: fakeRoom,
          fake: 'value'
        };

        assert.exception(function() {
          testUserList = new UserList(invalidOptions);
        }, 'UserList: Invalid argument passed');
      });

      it('throws an error if collapsed is not a boolean', function() {
        var options = {
          room: fakeRoom,
          collapsed: 'True'
        };

        assert.exception(function() {
          testUserList = new UserList(options);
        }, 'UserList: collapsed value must be a boolean');
      });

      it('throws an error if container is not a DOM element', function() {
        var options = {
          room: fakeRoom,
          container: 'DOM ELEMENT'
        };

        assert.exception(function() {
          testUserList = new UserList(options);
        }, 'UserList: container must be a DOM element');
      });

      it('throws an error if position is not right || left', function() {
        var options = {
          room: fakeRoom,
          position: 'top'
        };

        assert.exception(function() {
          testUserList = new UserList(options);
        }, 'UserList: position can only be "right" or "left"');
      });

      it('throws an error if position is not a string', function() {
        var options = {
          room: fakeRoom,
          position: true
        };

        assert.exception(function() {
          testUserList = new UserList(options);
        }, 'UserList: position can only be "right" or "left"');
      });

      it('passes back an error if truncateLength is not a number', function() {
        var options = {
          room: fakeRoom,
          truncateLength: '10'
        };

        assert.exception(function() {
          testUserList = new UserList(options);
        }, 'UserList: truncateLength can only be a number');
      });

      it('passes back an error if avatars is not a boolean', function() {
        var options = {
          room: fakeRoom,
          avatars: 'true'
        };

        assert.exception(function() {
          testUserList = new UserList(options);
        }, 'UserList: avatars must be a boolean');
      });

      it('passes back an error if userOptions is not a boolean', function() {
        var options = {
          room: fakeRoom,
          userOptions: 'true'
        };

        assert.exception(function() {
          testUserList = new UserList(options);
        }, 'UserList: userOptions must be a boolean');
      });
    });
  });

  describe('initialize', function() {
    afterEach(function(done) {
      userList.destroy(function() {
        done();
      });
    });

    it('hides the options when disabled', function(done) {
      userList = new UserList({
        room: fakeRoom,
        userOptions: false
      });

      userList.initialize(function(err) {
        assert.ifError(err);

        assert.ok(classes(userList.el).has('gi-no-options'));

        done();
      });
    });

    it('uses a container and applies the relative class', function(done) {
      var container = document.createElement('div');

      userList = new UserList({
        room: fakeRoom,
        container: container
      });

      userList.initialize(function(err) {
        assert.ifError(err);

        assert.equal(userList.el, container.children[0]);
        assert.ok(classes(userList.el).has('gi-relative'));
        assert.notOk(classes(userList.el).has('gi-anchor'));

        done();
      });
    });

    it('positions on the right', function(done) {
      userList = new UserList({
        room: fakeRoom,
        position: 'right'
      });

      userList.initialize(function(err) {
        assert.ifError(err);

        assert.ok(classes(userList.el).has('gi-right'));

        done();
      });
    });

    it('positions on the left', function(done) {
      userList = new UserList({
        room: fakeRoom,
        position: 'left'
      });

      userList.initialize(function(err) {
        assert.ifError(err);

        assert.ok(classes(userList.el).has('gi-left'));

        done();
      });
    });

    it('collapses', function(done) {
      userList = new UserList({
        room: fakeRoom,
        collapsed: true
      });

      userList.initialize(function(err) {
        assert.ifError(err);

        assert.ok(classes(userList.el).has('gi-collapsed'));

        done();
      });
    });

    it('expands', function(done) {
      userList = new UserList({
        room: fakeRoom,
        collapsed: false
      });

      userList.initialize(function(err) {
        assert.ifError(err);

        assert.notOk(classes(userList.el).has('gi-collapsed'));

        done();
      });
    });

    describe('defaults', function() {
      beforeEach(function(done) {
        var options = {
          room: fakeRoom
        };

        userList = new UserList(options);
        userList.initialize(function(err) {
          assert.ifError(err);
          done();
        });
      });

      afterEach(function(done) {
        userList.destroy(function() {
          done();
        });
      });

      it('initializes and binds to the userCache', function() {
        sinon.assert.calledOnce(fakeUserCache.initialize);
        sinon.assert.calledWith(
          fakeUserCache.on,
          'join',
          userList._handleJoinEvent
        );

        sinon.assert.calledWith(
          fakeUserCache.on,
          'leave',
          userList._handleLeaveEvent
        );

        sinon.assert.calledWith(
          fakeUserCache.on,
          'change',
          userList._handleUserMeta
        );
      });

      it('binds to events for options', function() {
        sinon.assert.calledWith(
          UserList._binder.on,
          sinon.match({className: 'gi-collapse'}),
          'click',
          userList._handleCollapseToggle
        );

        sinon.assert.calledWith(
          UserList._binder.on,
          sinon.match({className: 'gi-icon'}),
          'click',
          userList._clickEditUser
        );

        sinon.assert.calledWith(
          UserList._binder.on,
          sinon.match({className: 'gi-set-name'}),
          'keydown',
          userList._keydownOptionsInput
        );
      });

      it('renders a view for each user', function() {
        sinon.assert.callCount(fakeUserView.render, fakeUsers.length);

        _.each(fakeUsers, function(u) {
          sinon.assert.calledWith(fakeUserView.render, u);
        });
      });

      it('is displayed properly', function() {
        assert.notOk(classes(userList.el).has('gi-no-options'));
        assert.ok(classes(userList.el).has('gi-anchor'));

        assert.include(document.body.children, userList.el);
      });
    });

    describe('destroy', function() {
      beforeEach(function(done) {
        userList.initialize(function(err) {
          assert.ifError(err);

          userList.destroy(function(err) {
            assert.ifError(err);

            done();
          });
        });
      });

      it('initializes and binds to the userCache', function() {
        sinon.assert.calledWith(
          userList._userCache.off,
          'join',
          userList._handleJoinEvent
        );

        sinon.assert.calledWith(
          userList._userCache.off,
          'leave',
          userList._handleLeaveEvent
        );

        sinon.assert.calledWith(
          userList._userCache.off,
          'change',
          userList._handleUserMeta
        );
      });

      it('binds to events for options', function() {
        sinon.assert.calledWith(
          UserList._binder.off,
          sinon.match({className: 'gi-collapse'}),
          'click',
          userList._handleCollapseToggle
        );

        sinon.assert.calledWith(
          UserList._binder.off,
          sinon.match({className: 'gi-icon'}),
          'click',
          userList._clickEditUser
        );

        sinon.assert.calledWith(
          UserList._binder.off,
          sinon.match({className: 'gi-set-name'}),
          'keydown',
          userList._keydownOptionsInput
        );
      });
    });
  });

  describe('user controls', function() {
    beforeEach(function(done) {
      var options = {
        room: fakeRoom
      };

      userList = new UserList(options);
      userList.initialize(function(err) {
        assert.ifError(err);
        done();
      });
    });

    afterEach(function(done) {
      userList.destroy(function() {
        done();
      });
    });

    it('toggles when collapse is clicked', function() {
      userList._handleCollapseToggle();

      assert.ok(classes(userList.el).has('gi-collapsed'));

      userList._handleCollapseToggle();

      assert.notOk(classes(userList.el).has('gi-collapsed'));
    });

    describe('editing your name', function() {
      it('toggles editing, and does not save when no change', function(done) {
        userList._clickEditUser({}, function() {
          assert.ok(classes(userList.el).has('gi-editing'));

          userList._clickEditUser({}, function() {
            assert.notOk(classes(userList.el).has('gi-editing'));

            sinon.assert.notCalled(fakeDisplayNameKey.set);

            done();
          });
        });
      });

      it('sets the new name when changed', function(done) {
        userList._clickEditUser({}, function() {
          assert.ok(classes(userList.el).has('gi-editing'));

          var input = userList.el.querySelector('input');
          input.value = 'cool';

          userList._clickEditUser({}, function() {
            sinon.assert.calledWith(fakeDisplayNameKey.set, 'cool');

            assert.ok(classes(userList.el).has('gi-editing'));

            // We wait until the change comes back to the local platform
            // listener before displaying it.
            var updatedFakeLocalUser = _.clone(fakeLocalUser);
            updatedFakeLocalUser.displayName = 'cool';

            var keyName =  '/.users/231232131232/displayName';

            userList._handleUserMeta(updatedFakeLocalUser, keyName, function() {
              assert.notOk(classes(userList.el).has('gi-editing'));

              sinon.assert.calledWith(
                fakeUserView.render,
                updatedFakeLocalUser
              );

              done();
            });
          });
        });

      });

      it('stops editing when collapse is clicked', function(done) {
        userList._clickEditUser({}, function() {
          assert.ok(classes(userList.el).has('gi-editing'));

          userList._handleCollapseToggle({});

          assert.notOk(classes(userList.el).has('gi-editing'));

          done();
        });
      });
    });
  });

  describe('users', function() {
    beforeEach(function(done) {
      var options = {
        room: fakeRoom
      };

      userList = new UserList(options);
      userList.initialize(function(err) {
        assert.ifError(err);

        fakeUserView.render.reset();

        done();
      });
    });

    afterEach(function(done) {
      userList.destroy(function() {
        done();
      });
    });

    it('are rendered when they join', function() {
      var user = {};
      userList._handleJoinEvent(user);

      sinon.assert.calledWith(fakeUserView.render, user);
    });

    it('are rendered when they change', function() {
      var user = {
        displayName: 'whatever'
      };

      userList._handleUserMeta(user, '/.users/awessdsdas/displayName');

      sinon.assert.calledWith(fakeUserView.render, user);
    });
  });
});
<|endoftext|>


<commit_before>var assert = require('assert');
var fs = require('fs');
var join = require('path').join;

var transform = require('../');

var failed = false;

function assertEqual(output, expected) {
  console.log('\tOutput:', JSON.stringify(output));
  console.log('\tExpected:', JSON.stringify(expected));
  if (output !== expected) {
    console.log('\tFAILED');
    failed = true;
  } else {
    console.log('\tPASSED');
  }
}

function test(file, desc) {
  file = join(__dirname, 'THING-' + file + '.txt');
  var input = fs.readFileSync(file.replace('THING', 'sample'), 'utf8');
  var expected = fs.readFileSync(file.replace('THING', 'expected'), 'utf8');
  try {
    console.log('\n' + desc + ':');
    output = transform.render(input);
    assertEqual(output, expected);
  } catch (e) {
    failed = true;
    console.error(e.stack);
  }
}
test('a', 'Regular input');
test('b', 'Input with `]]>`');

console.log('\nTests ' + (failed ? 'FAILED' : 'PASSED'));

if (failed) process.exit(1);
<commit_msg>test: Use strict mode<commit_after>'use strict';

var assert = require('assert');
var fs = require('fs');
var join = require('path').join;

var transform = require('../');

var output;
var failed = false;

function assertEqual(output, expected) {
  console.log('\tOutput:', JSON.stringify(output));
  console.log('\tExpected:', JSON.stringify(expected));
  if (output !== expected) {
    console.log('\tFAILED');
    failed = true;
  } else {
    console.log('\tPASSED');
  }
}

function test(file, desc) {
  file = join(__dirname, 'THING-' + file + '.txt');
  var input = fs.readFileSync(file.replace('THING', 'sample'), 'utf8');
  var expected = fs.readFileSync(file.replace('THING', 'expected'), 'utf8');
  try {
    console.log('\n' + desc + ':');
    output = transform.render(input);
    assertEqual(output, expected);
  } catch (e) {
    failed = true;
    console.error(e.stack);
  }
}
test('a', 'Regular input');
test('b', 'Input with `]]>`');

console.log('\nTests ' + (failed ? 'FAILED' : 'PASSED'));

if (failed) process.exit(1);
<|endoftext|>


<commit_before>'use strict';

const Serverless = require('serverless'),
  s = new Serverless(),
  path = require('path'),
  chai = require('chai'),
  should = chai.should(),
  chaiAsPromised = require('chai-as-promised');

chai.use(chaiAsPromised);

const SERVERLESS_PATH = path.join(process.cwd(), 'node_modules', 'serverless', 'lib');

const CorsPlugin = require('..')(
  require(path.join(SERVERLESS_PATH, 'ServerlessPlugin')),
  SERVERLESS_PATH
);

describe('ServerlessCors', function() {
  describe('#getName()', function() {
    it('should return the correct name', function() {
      CorsPlugin.getName().should.equal('com.serverless.ServerlessCors');
    });
  });

  describe('#registerHooks()', function() {
    it('should register hooks', function() {
      s.addPlugin(new CorsPlugin(s));
      s.hooks.endpointBuildApiGatewayPre.should.have.length(1);
      s.hooks.endpointBuildApiGatewayPre[0].name.should.equal('bound addCorsHeaders');
      s.hooks.endpointDeployPost.should.have.length(1);
      s.hooks.endpointDeployPost[0].name.should.equal('bound addPreflightRequests');
    });
  });

  describe('#addCorsHeaders()', function() {
    it('should not add any headers when cors is not configured', function(done) {
      let plugin = new CorsPlugin(s);

      plugin.addCorsHeaders({
        endpoint: {
          module: { custom: {} },
          function: { custom: {} },
          responses: {
            default: { statusCode: '200', responseParameters: { 'Some-Header': 'Some-Value' } }
          }
        }
      }).then(function(evt) {
        let headers = evt.endpoint.responses.default.responseParameters;
        headers['Some-Header'].should.equal('Some-Value');
        headers.should.not.contain.key('method.response.header.Access-Control-Allow-Origin');
        done();
      })
    });

    it('should fail when cors configuration does not contain an `origin` value', function() {
      let plugin = new CorsPlugin(s);

      plugin.addCorsHeaders({
        endpoint: {
          module: { custom: {} },
          function: { custom: { cors: {} } },
          responses: {}
        }
      }).should.be.rejected;
    });

    it('should add allow-origin header when cors is configured for function', function(done) {
      let plugin = new CorsPlugin(s);

      plugin.addCorsHeaders({
        endpoint: {
          module: { custom: {} },
          function: { custom: {
            cors: { allowOrigin: '*', allowHeaders: ['Header-X', 'Header-Y'] }
          }},
          responses: {
            default: { statusCode: '200' }
          }
        }
      }).then(function(evt) {
        let headers = evt.endpoint.responses.default.responseParameters;
        headers['method.response.header.Access-Control-Allow-Origin'].should.equal('\'*\'');
        headers.should.not.contain.key('method.response.header.Access-Control-Allow-Methods');
        headers.should.not.contain.key('method.response.header.Access-Control-Allow-Headers');
        done();
      })
    });

    it('should preserve existing headers when cors is configured for function', function(done) {
      let plugin = new CorsPlugin(s);

      plugin.addCorsHeaders({
        endpoint: {
          module: { custom: {} },
          function: { custom: {
            cors: { allowOrigin: '*', allowHeaders: ['Header-X', 'Header-Y'] }
          }},
          responses: {
            default: { statusCode: '200', responseParameters: { 'Some-Header': 'Some-Value' } }
          }
        }
      }).then(function(evt) {
        let headers = evt.endpoint.responses.default.responseParameters;
        headers['Some-Header'].should.equal('Some-Value');
        headers['method.response.header.Access-Control-Allow-Origin'].should.equal('\'*\'');
        headers.should.not.contain.key('method.response.header.Access-Control-Allow-Methods');
        headers.should.not.contain.key('method.response.header.Access-Control-Allow-Headers');
        done();
      })
    });
  });

  describe('#addPreflightRequests()', function() {
    // @todo write test after https://github.com/serverless/serverless/issues/441 is fixed
  });
});
<commit_msg>Fix test dependency<commit_after>'use strict';

const path = require('path');
const SERVERLESS_PATH = path.join(process.cwd(), 'node_modules', 'serverless', 'lib');

const Serverless = require(path.join(SERVERLESS_PATH, 'Serverless')),
  s = new Serverless(),
  chai = require('chai'),
  should = chai.should(),
  chaiAsPromised = require('chai-as-promised');

chai.use(chaiAsPromised);

const CorsPlugin = require('..')(
  require(path.join(SERVERLESS_PATH, 'ServerlessPlugin')),
  SERVERLESS_PATH
);

describe('ServerlessCors', function() {
  describe('#getName()', function() {
    it('should return the correct name', function() {
      CorsPlugin.getName().should.equal('com.serverless.ServerlessCors');
    });
  });

  describe('#registerHooks()', function() {
    it('should register hooks', function() {
      s.addPlugin(new CorsPlugin(s));
      s.hooks.endpointBuildApiGatewayPre.should.have.length(1);
      s.hooks.endpointBuildApiGatewayPre[0].name.should.equal('bound addCorsHeaders');
      s.hooks.endpointDeployPost.should.have.length(1);
      s.hooks.endpointDeployPost[0].name.should.equal('bound addPreflightRequests');
    });
  });

  describe('#addCorsHeaders()', function() {
    it('should not add any headers when cors is not configured', function(done) {
      let plugin = new CorsPlugin(s);

      plugin.addCorsHeaders({
        endpoint: {
          module: { custom: {} },
          function: { custom: {} },
          responses: {
            default: { statusCode: '200', responseParameters: { 'Some-Header': 'Some-Value' } }
          }
        }
      }).then(function(evt) {
        let headers = evt.endpoint.responses.default.responseParameters;
        headers['Some-Header'].should.equal('Some-Value');
        headers.should.not.contain.key('method.response.header.Access-Control-Allow-Origin');
        done();
      })
    });

    it('should fail when cors configuration does not contain an `origin` value', function() {
      let plugin = new CorsPlugin(s);

      plugin.addCorsHeaders({
        endpoint: {
          module: { custom: {} },
          function: { custom: { cors: {} } },
          responses: {}
        }
      }).should.be.rejected;
    });

    it('should add allow-origin header when cors is configured for function', function(done) {
      let plugin = new CorsPlugin(s);

      plugin.addCorsHeaders({
        endpoint: {
          module: { custom: {} },
          function: { custom: {
            cors: { allowOrigin: '*', allowHeaders: ['Header-X', 'Header-Y'] }
          }},
          responses: {
            default: { statusCode: '200' }
          }
        }
      }).then(function(evt) {
        let headers = evt.endpoint.responses.default.responseParameters;
        headers['method.response.header.Access-Control-Allow-Origin'].should.equal('\'*\'');
        headers.should.not.contain.key('method.response.header.Access-Control-Allow-Methods');
        headers.should.not.contain.key('method.response.header.Access-Control-Allow-Headers');
        done();
      })
    });

    it('should preserve existing headers when cors is configured for function', function(done) {
      let plugin = new CorsPlugin(s);

      plugin.addCorsHeaders({
        endpoint: {
          module: { custom: {} },
          function: { custom: {
            cors: { allowOrigin: '*', allowHeaders: ['Header-X', 'Header-Y'] }
          }},
          responses: {
            default: { statusCode: '200', responseParameters: { 'Some-Header': 'Some-Value' } }
          }
        }
      }).then(function(evt) {
        let headers = evt.endpoint.responses.default.responseParameters;
        headers['Some-Header'].should.equal('Some-Value');
        headers['method.response.header.Access-Control-Allow-Origin'].should.equal('\'*\'');
        headers.should.not.contain.key('method.response.header.Access-Control-Allow-Methods');
        headers.should.not.contain.key('method.response.header.Access-Control-Allow-Headers');
        done();
      })
    });
  });

  describe('#addPreflightRequests()', function() {
    // @todo write test after https://github.com/serverless/serverless/issues/441 is fixed
  });
});
<|endoftext|>


<commit_before>'use strict'

require('./f1_test')
require('./people_test')
<commit_msg>Removing useless test/index.js<commit_after><|endoftext|>


<commit_before>'use strict';

let path = require('path');
let gutil = require('gulp-util');
let through2 = require('through2');
let File = gutil.File;

let bemDepsOrder = require('../build');
let expect = require('chai').expect;
let collectStreamFiles = require('../lib/collect-stream-files');
let getFileStem = require('../lib/get-file-stem');

function fillDeps(filename, stream) {
    let files = require(`./${filename}`);

    Object.keys(files).forEach(file => {
        let vinylFile = new File({
            path: path.resolve(__dirname, `${file}.deps.js`),
            contents: new Buffer(`(${JSON.stringify(files[file])})`)
        });

        stream.write(vinylFile);
    });

    stream.end();
}

function fillInputFiles(files, stream) {
    for (let file of files) {
        let vinylFile = new File({
            path: path.resolve(__dirname, `${file}.css`),
            contents: new Buffer('')
        });

        stream.write(vinylFile);
    }

    stream.end();
}

describe('gulp-order-bemdeps', () => {
    it('should not change order of files if no deps.js exist', () => {
        let stream = through2.obj();
        let myBemDepsOrder = bemDepsOrder(stream);

        // fill dependencies
        fillDeps('deps-empty', stream);

        // now pipe input files
        fillInputFiles(['block1', 'block2', 'block3'], myBemDepsOrder);

        return collectStreamFiles(myBemDepsOrder).then(files => {
            for (let file of files) {
                expect(file.isBuffer()).to.be.true;
            }

            // files number should stay the same
            expect(files).to.have.length(3);

            // files order should be the same
            expect(getFileStem(files[0].path)).to.equal('block1');
            expect(getFileStem(files[1].path)).to.equal('block2');
            expect(getFileStem(files[2].path)).to.equal('block3');
        });
    });

    it('should reorder files even if no deps.js are supported but files need this', () => {
        let stream = through2.obj();
        let myBemDepsOrder = bemDepsOrder(stream);

        // fill dependencies
        fillDeps('deps-empty', stream);

        // now pipe input files
        fillInputFiles(['block1__elem', 'block1', 'block2'], myBemDepsOrder);

        return collectStreamFiles(myBemDepsOrder).then(files => {
            let blockIndex;
            let blockElemIndex;

            files.forEach((file, index) => {
                let stem = getFileStem(file.path);

                if (stem === 'block1') {
                    blockIndex = index;
                } else if (stem === 'block1__elem') {
                    blockElemIndex = index;
                }
            });

            expect(blockIndex).to.be.below(blockElemIndex);
        });
    });

    it('should reorder files in accordance to blocks dependencies', () => {
        let stream = through2.obj();
        let myBemDepsOrder = bemDepsOrder(stream);

        // fill dependencies
        fillDeps('deps-simple-tree', stream);

        // now pipe input files
        fillInputFiles(['mixins', 'block', 'variables'], myBemDepsOrder);

        return collectStreamFiles(myBemDepsOrder).then(files => {
            expect(getFileStem(files[0].path)).to.equal('variables');
            expect(getFileStem(files[1].path)).to.equal('mixins');
            expect(getFileStem(files[2].path)).to.equal('block');
        });
    });

    it('should reorder files even if distance to root is different', () => {
        let stream = through2.obj();
        let myBemDepsOrder = bemDepsOrder(stream);

        // fill dependencies
        fillDeps('deps-multiple', stream);

        // now pipe input files
        fillInputFiles(['block', 'mixins', 'variables'], myBemDepsOrder);

        return collectStreamFiles(myBemDepsOrder).then(files => {
            expect(getFileStem(files[0].path)).to.equal('variables');
            expect(getFileStem(files[1].path)).to.equal('mixins');
            expect(getFileStem(files[2].path)).to.equal('block');
        });
    });

    it('should reorder files even if its dependency block is not listed inside source files', () => {
        let stream = through2.obj();
        let myBemDepsOrder = bemDepsOrder(stream);

        // fill dependencies
        fillDeps('deps-hidden-dependency', stream);

        // now pipe input files
        fillInputFiles(['block__elem', 'variables', 'block'], myBemDepsOrder);

        return collectStreamFiles(myBemDepsOrder).then(files => {
            expect(getFileStem(files[0].path)).to.equal('variables');
            expect(getFileStem(files[1].path)).to.equal('block');
            expect(getFileStem(files[2].path)).to.equal('block__elem');
        });
    });

    it('should stop piping data and show stack if bem naming is invalid', () => {
        let stream = through2.obj();
        let myBemDepsOrder = bemDepsOrder(stream);

        // fill dependencies
        fillDeps('deps-invalid-bem-naming', stream);

        // now pipe input files
        fillInputFiles(['sample-block'], myBemDepsOrder);

        return collectStreamFiles(myBemDepsOrder).catch(err => {
            expect(err.message).to.be.equal('Invalid bem naming used: invalid-block____foo');
        });
    });

    it('should calculate tree nodes weight using depth traversal, not width', () => {
        let stream = through2.obj();
        let myBemDepsOrder = bemDepsOrder(stream);

        // fill dependencies
        fillDeps('deps-multiple-copy-set', stream);

        // now pipe input files
        fillInputFiles(['admin-post', 'variables', 'mixins', 'button', 'i-bem__dom'], myBemDepsOrder);

        return collectStreamFiles(myBemDepsOrder);
    });

    it('should show error if circular dependency is detected', () => {
        let stream = through2.obj();
        let myBemDepsOrder = bemDepsOrder(stream);

        // fill dependencies
        fillDeps('deps-circular', stream);

        // now pipe input files
        fillInputFiles(['some-block'], myBemDepsOrder);

        return collectStreamFiles(myBemDepsOrder).catch(err => {
            expect(err.message).to.match(new RegExp('^Circular dependency detected'));
        });
    });
});
<commit_msg>use gutil.noop to create stream for testing<commit_after>'use strict';

let path = require('path');
let gutil = require('gulp-util');
let File = gutil.File;

let bemDepsOrder = require('../build');
let expect = require('chai').expect;
let collectStreamFiles = require('../lib/collect-stream-files');
let getFileStem = require('../lib/get-file-stem');

function fillDeps(filename, stream) {
    let files = require(`./${filename}`);

    Object.keys(files).forEach(file => {
        let vinylFile = new File({
            path: path.resolve(__dirname, `${file}.deps.js`),
            contents: new Buffer(`(${JSON.stringify(files[file])})`)
        });

        stream.write(vinylFile);
    });

    stream.end();
}

function fillInputFiles(files, stream) {
    for (let file of files) {
        let vinylFile = new File({
            path: path.resolve(__dirname, `${file}.css`),
            contents: new Buffer('')
        });

        stream.write(vinylFile);
    }

    stream.end();
}

describe('gulp-order-bemdeps', () => {
    it('should not change order of files if no deps.js exist', () => {
        let stream = gutil.noop();
        let myBemDepsOrder = bemDepsOrder(stream);

        // fill dependencies
        fillDeps('deps-empty', stream);

        // now pipe input files
        fillInputFiles(['block1', 'block2', 'block3'], myBemDepsOrder);

        return collectStreamFiles(myBemDepsOrder).then(files => {
            for (let file of files) {
                expect(file.isBuffer()).to.be.true;
            }

            // files number should stay the same
            expect(files).to.have.length(3);

            // files order should be the same
            expect(getFileStem(files[0].path)).to.equal('block1');
            expect(getFileStem(files[1].path)).to.equal('block2');
            expect(getFileStem(files[2].path)).to.equal('block3');
        });
    });

    it('should reorder files even if no deps.js are supported but files need this', () => {
        let stream = gutil.noop();
        let myBemDepsOrder = bemDepsOrder(stream);

        // fill dependencies
        fillDeps('deps-empty', stream);

        // now pipe input files
        fillInputFiles(['block1__elem', 'block1', 'block2'], myBemDepsOrder);

        return collectStreamFiles(myBemDepsOrder).then(files => {
            let blockIndex;
            let blockElemIndex;

            files.forEach((file, index) => {
                let stem = getFileStem(file.path);

                if (stem === 'block1') {
                    blockIndex = index;
                } else if (stem === 'block1__elem') {
                    blockElemIndex = index;
                }
            });

            expect(blockIndex).to.be.below(blockElemIndex);
        });
    });

    it('should reorder files in accordance to blocks dependencies', () => {
        let stream = gutil.noop();
        let myBemDepsOrder = bemDepsOrder(stream);

        // fill dependencies
        fillDeps('deps-simple-tree', stream);

        // now pipe input files
        fillInputFiles(['mixins', 'block', 'variables'], myBemDepsOrder);

        return collectStreamFiles(myBemDepsOrder).then(files => {
            expect(getFileStem(files[0].path)).to.equal('variables');
            expect(getFileStem(files[1].path)).to.equal('mixins');
            expect(getFileStem(files[2].path)).to.equal('block');
        });
    });

    it('should reorder files even if distance to root is different', () => {
        let stream = gutil.noop();
        let myBemDepsOrder = bemDepsOrder(stream);

        // fill dependencies
        fillDeps('deps-multiple', stream);

        // now pipe input files
        fillInputFiles(['block', 'mixins', 'variables'], myBemDepsOrder);

        return collectStreamFiles(myBemDepsOrder).then(files => {
            expect(getFileStem(files[0].path)).to.equal('variables');
            expect(getFileStem(files[1].path)).to.equal('mixins');
            expect(getFileStem(files[2].path)).to.equal('block');
        });
    });

    it('should reorder files even if its dependency block is not listed inside source files', () => {
        let stream = gutil.noop();
        let myBemDepsOrder = bemDepsOrder(stream);

        // fill dependencies
        fillDeps('deps-hidden-dependency', stream);

        // now pipe input files
        fillInputFiles(['block__elem', 'variables', 'block'], myBemDepsOrder);

        return collectStreamFiles(myBemDepsOrder).then(files => {
            expect(getFileStem(files[0].path)).to.equal('variables');
            expect(getFileStem(files[1].path)).to.equal('block');
            expect(getFileStem(files[2].path)).to.equal('block__elem');
        });
    });

    it('should stop piping data and show stack if bem naming is invalid', () => {
        let stream = gutil.noop();
        let myBemDepsOrder = bemDepsOrder(stream);

        // fill dependencies
        fillDeps('deps-invalid-bem-naming', stream);

        // now pipe input files
        fillInputFiles(['sample-block'], myBemDepsOrder);

        return collectStreamFiles(myBemDepsOrder).catch(err => {
            expect(err.message).to.be.equal('Invalid bem naming used: invalid-block____foo');
        });
    });

    it('should calculate tree nodes weight using depth traversal, not width', () => {
        let stream = gutil.noop();
        let myBemDepsOrder = bemDepsOrder(stream);

        // fill dependencies
        fillDeps('deps-multiple-copy-set', stream);

        // now pipe input files
        fillInputFiles(['admin-post', 'variables', 'mixins', 'button', 'i-bem__dom'], myBemDepsOrder);

        return collectStreamFiles(myBemDepsOrder);
    });

    it('should show error if circular dependency is detected', () => {
        let stream = gutil.noop();
        let myBemDepsOrder = bemDepsOrder(stream);

        // fill dependencies
        fillDeps('deps-circular', stream);

        // now pipe input files
        fillInputFiles(['some-block'], myBemDepsOrder);

        return collectStreamFiles(myBemDepsOrder).catch(err => {
            expect(err.message).to.match(new RegExp('^Circular dependency detected'));
        });
    });
});
<|endoftext|>


<commit_before>GLOBAL.projRequire = function (module) {
	return require('../' + module);
}

const log	 = projRequire('lib');
const tc     = require('test-console');
const test   = require('tape');

test('log.info() prints correctly', function (t) {
	var err = tc.stdout.inspectSync(function () { log.info("test-error") });
	console.log(err[0]);
	var matchreg = /^info *: test-error/;

	t.equal(err[0].search(matchreg), 0);
	t.end();
});

test('log.warn() prints correctly', function (t) {
	var err = tc.stdout.inspectSync(function () { log.warn("test-error") });
	console.log(err[0]);
	var matchreg = /^warn *: test-error/;

	t.equal(err[0].search(matchreg), 0);
	t.end();
});

test('log.error() prints correctly', function (t) {
	var err = tc.stdout.inspectSync(function () { log.error("test-error") });
	console.log(err[0]);
	var matchreg = /^error *: test-error/;

	t.equal(err[0].search(matchreg), 0);
	t.end();
});

test('log prints JSON correctly', function (t) {
	var err = tc.stdout.inspectSync(function () { log.error("test-error", { a: "b", c: "d" }); });
	console.log(err[0]);
	var matchreg = /^error *: test-error\s*{((\s*\"a\"\s*:\s*\"b\"\s*|\s*\"c\"\s*:\s*"d"\s*),?){2}}/;

	t.equal(err[0].search(matchreg), 0);
	t.end();
});
<commit_msg>Added debug/fatal checks<commit_after>GLOBAL.projRequire = function (module) {
	return require('../' + module);
};

const log = projRequire('lib');
const tc = require('test-console');
const test = require('tape');

test('log.debug() prints correctly', function (t) {
	var err = tc.stdout.inspectSync(function () {
		log.debug('test-error');
	});

	t.assert(err[0].match(/^debug *: test-error/));
	t.end();
});

test('log.info() prints correctly', function (t) {
	var err = tc.stdout.inspectSync(function () {
		log.info('test-error');
	});

	t.assert(err[0].match(/^info *: test-error/));
	t.end();
});

test('log.warn() prints correctly', function (t) {
	var err = tc.stdout.inspectSync(function () {
		log.warn('test-error');
	});

	t.assert(err[0].match(/^warn *: test-error/));
	t.end();
});

test('log.error() prints correctly', function (t) {
	var err = tc.stdout.inspectSync(function () {
		log.error('test-error');
	});

	t.assert(err[0].match(/^error *: test-error/));
	t.end();
});

test('log.fatal() prints correctly', function (t) {
	var err = tc.stdout.inspectSync(function () {
		log.fatal('test-error');
	});

	t.assert(err[0].match(/^fatal *: test-error/));
	t.end();
});

test('log prints JSON correctly', function (t) {
	var err = tc.stdout.inspectSync(function () {
		log.error('test-error', { a: 'b', c: 'd' });
	});

	var matchreg = /^error *: test-error\s*{((\s*\"a\"\s*:\s*\"b\"\s*|\s*\"c\"\s*:\s*"d"\s*),?){2}}/;
	t.assert(err[0].match(matchreg));
	t.end();
});
<|endoftext|>


<commit_before>var templater = require("./../src/templater.js"),
    chai = require("chai"),
    assert = chai.assert;

/**
 * Basic tests.
*/
describe("Basic Tests", function() {
  it("should return a function when called with a template", function() {
    var template = templater("A string.");

    assert.equal(typeof template, "function");
  });

  it("should replace values in template with respective values in context", function() {
    var template = templater("{{name}}"),
        context = {
          name: "Paul"
        };

    assert.equal(template(context), "Paul");
  });

  it("should not replace values in template that don't exist in the context", function() {
    var template = templater("Hi, I'm {{name}}. I'm {{age}} years old."),
        context = {
          age: 20
        };

    assert.equal(template(context), "Hi, I'm {{name}}. I'm 20 years old.");
  });

  it("should escape certain characters when replacing template expressions", function() {
    var template = templater("{{foo}}"),
        context = {
          foo: "<html> tag with 'single' & \"double\" quotes"
        };

    assert.equal(template(context), "<html> tag with 'single' & "double" quotes");
  });
});

/**
 * Conditional tests.
*/
describe("Conditional Tests", function() {
  it("renders conditional body if the arguments are truthy", function() {
    var template = templater([
      "{{#if (name, age)}}",
      "Hi, I'm {{name}}, I'm {{age}} years old.",
      "{{/if}}"
      ].join("")),
        context = {
          name: "Paul",
          age: 20
        };

    assert.equal(template(context), "Hi, I'm Paul, I'm 20 years old.");
  });

  it("doesn't render conditional body if one or more of the args are falsy", function() {
    var template = templater([
      "{{#if (name, age)}}",
      "Hi, I'm {{name}}, I'm {{age}} years old.",
      "{{/if}}"
      ].join("")),
        context = {
          name: "Paul",
          age: 0
        };

    assert.equal(template(context), "");
  });

  it("inverts (nots) the evaluation of truthy arguments", function() {
    var template = templater([
      "{{#if !(name, age)}}",
      "Hi, I'm {{name}}, I'm {{age}} years old.",
      "{{/if}}"
      ].join("")),
        context = {
          name: "Paul",
          age: 20
        };

    assert.equal(template(context), "");
  });

  it("inverts (nots) the evaluation of falsy arguments", function() {
    var template = templater([
      "{{#if !(name, age)}}",
      "Hi, I'm {{name}}, I'm {{age}} years old.",
      "{{/if}}"
      ].join("")),
        context = {
          name: "Paul"
        };

    assert.equal(template(context), "Hi, I'm Paul, I'm {{age}} years old.");
  });
});
<commit_msg>Add unit tests<commit_after>var templater = require("./../src/templater.js"),
    chai = require("chai"),
    assert = chai.assert;

/**
* Basic tests.
*/
describe("Basic Tests", function() {
  it("should return a function when called with a template", function() {
    var template = templater("A string.");

    assert.equal(typeof template, "function");
  });

  it("should replace values in template with respective values in context (non-function)", function() {
    var template = templater("{{name}}"),
    context = {
      name: "Paul"
    };

    assert.equal(template(context), "Paul");
  });

  it("should replace values in template with respective values in context (function)", function() {
    var template = templater("{{number}}"),
    context = {
      number: function() {
        return 2 + 2;
      }
    };

    assert.equal(template(context), 4);
  });

  it("should not replace values in template that don't exist in the context", function() {
    var template = templater("Hi, I'm {{name}}. I'm {{age}} years old."),
    context = {
      age: 21
    };

    assert.equal(template(context), "Hi, I'm {{name}}. I'm 21 years old.");
  });

  it("should escape certain characters when replacing template expressions", function() {
    var template = templater("{{foo}}"),
    context = {
      foo: "<html> tag with 'single' & \"double\" quotes"
    };

    assert.equal(template(context), "<html> tag with 'single' & "double" quotes");
  });
});

/**
* Conditional tests.
*/
describe("Conditional Tests", function() {
  it("renders conditional body if the arguments are truthy", function() {
    var template = templater([
      "{{#if (name, age)}}",
      "Hi, I'm {{name}}, I'm {{age}} years old.",
      "{{/if}}"
    ].join("")),
    context = {
      name: "Paul",
      age: 21
    };

    assert.equal(template(context), "Hi, I'm Paul, I'm 21 years old.");
  });

  it("doesn't render conditional body if one or more of the args are falsy", function() {
    var template = templater([
      "{{#if (name, age)}}",
      "Hi, I'm {{name}}, I'm {{age}} years old.",
      "{{/if}}"
    ].join("")),
    context = {
      name: "Paul",
      age: 0
    };

    assert.equal(template(context), "");
  });

  it("inverts (nots) the evaluation of truthy arguments", function() {
    var template = templater([
      "{{#if !(name, age)}}",
      "Hi, I'm {{name}}, I'm {{age}} years old.",
      "{{/if}}"
    ].join("")),
    context = {
      name: "Paul",
      age: 21
    };

    assert.equal(template(context), "");
  });

  it("inverts (nots) the evaluation of falsy arguments", function() {
    var template = templater([
      "{{#if !(name, age)}}",
      "Hi, I'm {{name}}, I'm {{age}} years old.",
      "{{/if}}"
    ].join("")),
    context = {
      name: "Paul"
    };

    assert.equal(template(context), "Hi, I'm Paul, I'm {{age}} years old.");
  });
});

/**
* Nested properties.
*/
describe("Nested Properties", function() {
  it("should replace values in template with respective values in context", function() {
    var template = templater("{{person.name}}, {{person.age}}"),
    context = {
      person: {
        name: "Paul",
        age: 21
      }
    };

    assert.equal(template(context), "Paul, 21");
  });

  it("should replace values in template with respective values in context (array)", function() {
    var template = templater("{{people.0.name}}, {{people.0.age}}"),
    context = {
      people: [
        {
          name: "Paul",
          age: 21
        }
      ]
    };

    assert.equal(template(context), "Paul, 21");
  });

  it("should not replace values in template that don't exist in the context", function() {
    var template = templater("Hi, I'm {{person.name}}. I'm {{person.age}} years old."),
    context = {
      person: {
        age: 21
      }
    };

    assert.equal(template(context), "Hi, I'm {{person.name}}. I'm 21 years old.");
  });

  it("should replace values in template with respective values in context (function)", function() {
    var template = templater("{{exp.x}} + {{exp.y}} = {{exp.z}}"),
    context = {
      exp: {
        x: 2,
        y: 2,
        z: function() {
          return 2 + 2;
        }
      }
    };

    assert.equal(template(context), "2 + 2 = 4");
  });
});

/**
* Conditional (nested property) tests.
*/
describe("Conditional (Nested Property) Tests", function() {
  it("renders conditional body if the arguments are truthy", function() {
    var template = templater([
      "{{#if (person.name, person.age)}}",
      "Hi, I'm {{person.name}}, I'm {{person.age}} years old.",
      "{{/if}}"
    ].join("")),
    context = {
      person: {
        name: "Paul",
        age: 21
      }
    };

    assert.equal(template(context), "Hi, I'm Paul, I'm 21 years old.");
  });

  it("doesn't render conditional body if one or more of the args are falsy", function() {
    var template = templater([
      "{{#if (person.name, person.age)}}",
      "Hi, I'm {{person.name}}, I'm {{person.age}} years old.",
      "{{/if}}"
    ].join("")),
    context = {
      person: {
        name: "Paul",
        age: 0
      }
    };

    assert.equal(template(context), "");
  });

  it("inverts (nots) the evaluation of truthy arguments", function() {
    var template = templater([
      "{{#if !(person.name, person.age)}}",
      "Hi, I'm {{person.name}}, I'm {{person.age}} years old.",
      "{{/if}}"
    ].join("")),
    context = {
      person: {
        name: "Paul",
        age: 21
      }
    };

    assert.equal(template(context), "");
  });

  it("inverts (nots) the evaluation of falsy arguments", function() {
    var template = templater([
      "{{#if !(person.name, person.age)}}",
      "Hi, I'm {{person.name}}, I'm {{person.age}} years old.",
      "{{/if}}"
    ].join("")),
    context = {
      person: {
        name: "Paul"
      }
    };

    assert.equal(template(context), "Hi, I'm Paul, I'm {{person.age}} years old.");
  });
});
<|endoftext|>


<commit_before>var ML = require('../lib');
var Lab = require('lab');
var Code = require('code');
var Async = require('async');
var Batch = require('../lib/batchLayer');
var mongo = require('../lib/mongo');

// Declare internals
var internals = {};
// Test shortcuts
var lab = exports.lab = Lab.script();
var before = lab.before;
var beforeEach = lab.beforeEach;
var after = lab.after;
var describe = lab.describe;
var it = lab.it;
var expect = Code.expect;

var testReports = internals.testReports = [{
        name: "report1",
        agg: [{ $group: {_id: '$ua', count: { $sum: 1 }}}],
        cron: "*/5 * * * * *",
        timezone: "US"
    },
    {
        name: "report2",
        agg: [{ $group: {_id: '$ua', count: { $sum: 1 }}}],
        cron: "*/5 * * * * *",
        timezone: "US"
    },
    {
        name: "report3",
        agg: [{ $group: {_id: '$ua', count: { $sum: 1 }}}],
        cron: "*/5 * * * * *",
        timezone: "US"
    },
    {
        name: "report4",
        agg: [{ $group: {_id: '$ua', count: { $sum: 1 }}}],
        cron: "*/5 * * * * *",
        timezone: "US"
}];

internals.scrubMaster = function(next) {
    mongo.db.collection('master').remove({}, function(err, noDocs) {
        expect(err).to.not.exist();
        next(err);
    })
}

internals.scrubSpeed = function(next) {

    testReports.forEach(function(report) {
        mongo.db.collection(report.name+'_delta').remove({}, function(err, noDocs) {
            expect(err).to.not.exist();
        })
    })

    next();

}

internals.scrubBatches = function(next) {

    testReports.forEach(function(report) {
        mongo.db.collection(report.name+'_batches').remove({}, function(err, noDocs) {
            expect(err).to.not.exist();
        })
    })

    next();

}

describe('Mongo Lambda API', function () {

    var config = {
        host: 'localhost',
        port: 27017,
        db: 'mongo-lambda-test',
        masterColl: "master"
    };

    beforeEach(function(done) {
        Async.series({
            insertReports: Async.apply(Batch.insertReports, testReports),
            mongoInit: Async.apply(mongo.init, config),
            scrubMaster: internals.scrubMaster,
            scrubSpeed: internals.scrubSpeed,
            scrubBatches: internals.scrubBatches
        }, function(err, results) {
            expect(err).to.not.exist();
            done();
        });
    });

    it('validates good configuration', function (done) {
        var instance = function () {
            var lambda = new ML.Lambda(config);
        };
        expect(instance).to.not.throw();
        done()
    });

    it('invalidates bad configuration', function (done) {
        var badConfig = {};
        var instance = function () {
            var lambda = new ML.Lambda(badConfig);
        };
        expect(instance).to.throw();
        done()
    });

    it('can start', function (done) {
        var start = function () {
            var lambda = new ML.Lambda(config);

            lambda.reports([testReports[0]]);

            lambda.start(function() {})
        };
        expect(start).to.not.throw();
        done();
    });

    it('inserts data into master collections', function (done) {
        var lambda = new ML.Lambda(config);

        lambda.reports([testReports[1]]);

        lambda.start(function() {
            lambda.insert({ua: "specific"}, function(err, results) {
                mongo.master.find({ua: "specific"}).toArray(function(err, doc) {
                    expect(err).to.not.exist();
                    expect(doc).to.exist();
                    expect(doc.length).to.equal(1);
                    done();
                })
            });
        })
    });

    it('inserts array of data into master collections', function (done) {
        var lambda = new ML.Lambda(config);

        lambda.reports([testReports[1]]);

        lambda.start(function() {
            lambda.insert([{ua: "specific2"}, {ua: "specific2"}], function(err, results) {
                mongo.master.find({ua: "specific2"}).toArray(function(err, doc) {
                    expect(err).to.not.exist();
                    expect(doc).to.exist();
                    expect(doc.length).to.equal(2);
                    done();
                })
            });
        })
    });

    it('inserts data into speed collections', function (done) {
        var lambda = new ML.Lambda(config);

        lambda.reports([testReports[2]]);

        lambda.start(function() {
            lambda.insert({ua: "specific"}, function(err, results) {
                mongo.speed['report3'].find({ua: "specific"}).toArray(function(err, doc) {
                    expect(err).to.not.exist();
                    expect(doc).to.exist();
                    expect(doc.length).to.equal(1);
                    done();
                })
            });
        })
    });

    it('inserts array of data into speed collections', function (done) {
        var lambda = new ML.Lambda(config);

        lambda.reports([testReports[2]]);

        lambda.start(function() {
            lambda.insert([{ua: "specific2"}, {ua: "specific2"}], function(err, results) {
                mongo.speed['report3'].find({ua: "specific2"}).toArray(function(err, doc) {
                    expect(err).to.not.exist();
                    expect(doc).to.exist();
                    expect(doc.length).to.equal(2);
                    done();
                })
            });
        })
    });

    it('gets bactches and live data', { timeout: 60*1000 +1000}, function (done) {
        var lambda = new ML.Lambda(config);
        lambda.reports([testReports[3]]);

        lambda.start(function() {
            //Drip data
            var i = 0;
            setInterval(function() {
                lambda.insert({ua: "iphone"}, function(err, results) {

                    // console.log(' imp!');
                    // console.log('---------------------');

                    lambda.getResults('report4', function(err, batches, onTheFly) {
                        i++;
                        // expect(err).to.not.exist();
                        var total = 0;

                        batches.forEach(function(batch) {
                            if (batch.data.length > 0) {
                                total = total + batch.data[0].count;
                            }

                        })
                        // console.log('batch layer: '+ total)

                        if(onTheFly.length > 0) {
                            // console.log('speed layer: '+ onTheFly[0].count)
                            total = total + onTheFly[0].count;
                        }

                        // console.log('---------------------');
                        // console.log('TOTAL COUNT: '+total)
                        // console.log('---------------------\n');
                        // console.log(new Date());

                        expect(total).to.equal(i);
                    });

                });
            }, 500);

            setTimeout(function() {
                done();
            }, 10*1000 + 500);

        })
    });

});
<commit_msg>changed timezone in tests<commit_after>var ML = require('../lib');
var Lab = require('lab');
var Code = require('code');
var Async = require('async');
var Batch = require('../lib/batchLayer');
var mongo = require('../lib/mongo');

// Declare internals
var internals = {};
// Test shortcuts
var lab = exports.lab = Lab.script();
var before = lab.before;
var beforeEach = lab.beforeEach;
var after = lab.after;
var describe = lab.describe;
var it = lab.it;
var expect = Code.expect;

var testReports = internals.testReports = [{
        name: "report1",
        agg: [{ $group: {_id: '$ua', count: { $sum: 1 }}}],
        cron: "*/5 * * * * *",
        timezone: "EST"
    },
    {
        name: "report2",
        agg: [{ $group: {_id: '$ua', count: { $sum: 1 }}}],
        cron: "*/5 * * * * *",
        timezone: "EST"
    },
    {
        name: "report3",
        agg: [{ $group: {_id: '$ua', count: { $sum: 1 }}}],
        cron: "*/5 * * * * *",
        timezone: "EST"
    },
    {
        name: "report4",
        agg: [{ $group: {_id: '$ua', count: { $sum: 1 }}}],
        cron: "*/5 * * * * *",
        timezone: "EST"
}];

internals.scrubMaster = function(next) {
    mongo.db.collection('master').remove({}, function(err, noDocs) {
        expect(err).to.not.exist();
        next(err);
    })
}

internals.scrubSpeed = function(next) {

    testReports.forEach(function(report) {
        mongo.db.collection(report.name+'_delta').remove({}, function(err, noDocs) {
            expect(err).to.not.exist();
        })
    })

    next();

}

internals.scrubBatches = function(next) {

    testReports.forEach(function(report) {
        mongo.db.collection(report.name+'_batches').remove({}, function(err, noDocs) {
            expect(err).to.not.exist();
        })
    })

    next();

}

describe('Mongo Lambda API', function () {

    var config = {
        host: 'localhost',
        port: 27017,
        db: 'mongo-lambda-test',
        masterColl: "master"
    };

    beforeEach(function(done) {
        Async.series({
            insertReports: Async.apply(Batch.insertReports, testReports),
            mongoInit: Async.apply(mongo.init, config),
            scrubMaster: internals.scrubMaster,
            scrubSpeed: internals.scrubSpeed,
            scrubBatches: internals.scrubBatches
        }, function(err, results) {
            expect(err).to.not.exist();
            done();
        });
    });

    it('validates good configuration', function (done) {
        var instance = function () {
            var lambda = new ML.Lambda(config);
        };
        expect(instance).to.not.throw();
        done()
    });

    it('invalidates bad configuration', function (done) {
        var badConfig = {};
        var instance = function () {
            var lambda = new ML.Lambda(badConfig);
        };
        expect(instance).to.throw();
        done()
    });

    it('can start', function (done) {
        var start = function () {
            var lambda = new ML.Lambda(config);

            lambda.reports([testReports[0]]);

            lambda.start(function() {})
        };
        expect(start).to.not.throw();
        done();
    });

    it('inserts data into master collections', function (done) {
        var lambda = new ML.Lambda(config);

        lambda.reports([testReports[1]]);

        lambda.start(function() {
            lambda.insert({ua: "specific"}, function(err, results) {
                mongo.master.find({ua: "specific"}).toArray(function(err, doc) {
                    expect(err).to.not.exist();
                    expect(doc).to.exist();
                    expect(doc.length).to.equal(1);
                    done();
                })
            });
        })
    });

    it('inserts array of data into master collections', function (done) {
        var lambda = new ML.Lambda(config);

        lambda.reports([testReports[1]]);

        lambda.start(function() {
            lambda.insert([{ua: "specific2"}, {ua: "specific2"}], function(err, results) {
                mongo.master.find({ua: "specific2"}).toArray(function(err, doc) {
                    expect(err).to.not.exist();
                    expect(doc).to.exist();
                    expect(doc.length).to.equal(2);
                    done();
                })
            });
        })
    });

    it('inserts data into speed collections', function (done) {
        var lambda = new ML.Lambda(config);

        lambda.reports([testReports[2]]);

        lambda.start(function() {
            lambda.insert({ua: "specific"}, function(err, results) {
                mongo.speed['report3'].find({ua: "specific"}).toArray(function(err, doc) {
                    expect(err).to.not.exist();
                    expect(doc).to.exist();
                    expect(doc.length).to.equal(1);
                    done();
                })
            });
        })
    });

    it('inserts array of data into speed collections', function (done) {
        var lambda = new ML.Lambda(config);

        lambda.reports([testReports[2]]);

        lambda.start(function() {
            lambda.insert([{ua: "specific2"}, {ua: "specific2"}], function(err, results) {
                mongo.speed['report3'].find({ua: "specific2"}).toArray(function(err, doc) {
                    expect(err).to.not.exist();
                    expect(doc).to.exist();
                    expect(doc.length).to.equal(2);
                    done();
                })
            });
        })
    });

    it('gets bactches and live data', { timeout: 60*1000 +1000}, function (done) {
        var lambda = new ML.Lambda(config);
        lambda.reports([testReports[3]]);

        lambda.start(function() {
            //Drip data
            var i = 0;
            setInterval(function() {
                lambda.insert({ua: "iphone"}, function(err, results) {

                    // console.log(' imp!');
                    // console.log('---------------------');

                    lambda.getResults('report4', function(err, batches, onTheFly) {
                        i++;
                        // expect(err).to.not.exist();
                        var total = 0;

                        batches.forEach(function(batch) {
                            if (batch.data.length > 0) {
                                total = total + batch.data[0].count;
                            }

                        })
                        // console.log('batch layer: '+ total)

                        if(onTheFly.length > 0) {
                            // console.log('speed layer: '+ onTheFly[0].count)
                            total = total + onTheFly[0].count;
                        }

                        // console.log('---------------------');
                        // console.log('TOTAL COUNT: '+total)
                        // console.log('---------------------\n');
                        // console.log(new Date());

                        expect(total).to.equal(i);
                    });

                });
            }, 500);

            setTimeout(function() {
                done();
            }, 10*1000 + 500);

        })
    });

});
<|endoftext|>