<commit_before>var _ = require('./lib/test');
    A = function() {},
    B = function() {},
    C = function() {};

A.prototype =  {
    doA: function() {
        return 'A';
    }
};

B.prototype =  {
    doB: function() {
        return 'B';
    }
};

C.prototype =  {
    doC: function() {
        return 'C';
    }
};

exports.functionName = {
    testNamed: function(test) {
        test.equals(_.functionName(function a(){}), 'a');
        test.done();
    },
    testUnnamed: function(test) {
        test.equals(_.functionName(function (){}), '');
        test.done();
    },
    testVarNamed: function(test) {
        var b = function a(){};
        test.equals(_.functionName(b), 'a');
        test.done();
    },
    testForcedNamed: function(test) {
        var b = function c(){};
        b._name = 'a';
        test.equals(_.functionName(b), 'a');
        test.done();
    }
};

exports.functionLength = {
    testNoArgs: function(test) {
        test.equals(_.functionLength(function (){}), 0);
        test.done();
    },
    testOneArg: function(test) {
        test.equals(_.functionLength(function (a){}), 1);
        test.done();
    },
    testMultiArg: function(test) {
        test.equals(_.functionLength(function (a, b, c, d){}), 4);
        test.done();
    },
    testMultiArgWithForcedLength: function(test) {
        var b = function c(x, y, z){};
        b._length = 5;
        test.equals(_.functionLength(b), 5);
        test.done();
    },
    testForcedLength: function(test) {
        var b = function c(){};
        b._length = 5;
        test.equals(_.functionLength(b), 5);
        test.done();
    }
};

exports.create = {
    testCreation: function(test) {
        var Point = function(){};
        test.ok(_.create(Point.prototype) instanceof Point);
        test.done();
    }
};

exports.getInstance = {
    testGetInstanceWithFunction: function(test) {
        var Point = function(){
            var a = _.getInstance(this, Point);
            return a;
        };
        var point = Point();
        test.ok(_.getInstance(point, Point) instanceof Point);
        test.done();
    },
    testGetInstanceWithInstance: function(test) {
        var Point = function(){
            var a = _.getInstance(this, Point);
            return a;
        };
        var point = new Point();
        test.ok(_.getInstance(point, Point) instanceof Point);
        test.done();
    },
    testGetInstanceWithFunctionArguments: function(test) {
        var Point = function(x){
            var a = _.getInstance(this, Point);
            a.x = x;
            return a;
        };
        var random = Math.random();
        var point = Point(random);
        test.ok(_.getInstance(point, Point).x, random);
        test.done();
    },
    testGetInstanceWithInstanceArguments: function(test) {
        var Point = function(x){
            var a = _.getInstance(this, Point);
            a.x = x;
            return a;
        };
        var random = Math.random();
        var point = new Point(random);
        test.ok(_.getInstance(point, Point).x, random);
        test.done();
    }
};

exports.singleton = {
    testString: function(test) {
        test.deepEqual(_.singleton('a', '1'), {'a': 1});
        test.done();
    },
    testObjectKey: function(test) {
        test.deepEqual(_.singleton({a: 1}, '1'), {'[object Object]': 1});
        test.done();
    }
};

exports.extend = {
    'when testing extend with object should create a new object': function(test) {
        test.deepEqual(_.extend({a: 1}, {b: 2}), {a: 1, b: 2});
        test.done();
    },
    'when testing extend with object should create a new object without modifying new object': function(test) {
        var a = {a: 1},
            b = {b: 2},
            c = _.extend(a, b);

        test.deepEqual(a, {a: 1});
        test.deepEqual(b, {b: 2});
        test.done();
    },
    'when extending a a object should override property correctly from the right biased': function(test) {
        test.deepEqual(_.extend({a: 1}, {a: 2}), {a: 2});
        test.done();
    },
    'when creating mixin should create a new object with all correct methods': function(test) {
        var X = function() {},
            x;

        X.prototype = _.extend(_.extend(A.prototype, B.prototype), C.prototype);

        x = new X();

        test.equal(x.doA() + x.doB() + x.doC(), 'ABC');
        test.done();
    },
    'when creating mixin should not modify original objects': function(test) {
        var X = function() {},
            x;

        X.prototype = _.extend(_.extend(A.prototype, B.prototype), C.prototype);

        x = new X();

        test.deepEqual(A.prototype, {doA: A.prototype.doA});
        test.deepEqual(B.prototype, {doB: B.prototype.doB});
        test.deepEqual(C.prototype, {doC: C.prototype.doC});
        test.done();
    }
};

exports.bind = {
    testBind: function(test) {
        var a = _.bind(function(a, b, c) {
            test.equal(a + b + c, 6);
        });

        a()(1, 2, 3);

        test.expect(1);
        test.done();
    },
    testCurryFunctionName: function(test) {
        var a = _.bind(function namedFunction(a, b, c) {})();

        test.equal(_.functionName(a), 'namedFunction');
        test.done();
    },
    testCurryFunctionLength: function(test) {
        var a = _.bind(function(a, b, c) {})();

        test.equal(_.functionLength(a), 3);
        test.done();
    }
};

exports.compose = {
    testCompose: function(test) {
        function f(x) {
            return x + 1;
        }
        function g(x) {
            return x + 2;
        }

        test.equal(_.compose(f, g)(1), f(g(1)));
        test.done();
    }
};

exports.identity = {
    testIdentity: function(test) {
        test.equal(_.identity(1), 1);
        test.done();
    }
};

exports.constant = {
    testConstant: function(test) {
        test.equal(_.constant(1)(), 1);
        test.done();
    }
};

exports.access = {
    testAccess: function(test) {
        test.equal(_.access('a')(_.singleton('a', 1)), 1);
        test.done();
    }
};

exports.andThen = {
    testAndThen: function(test) {
        function f(x) {
            return x + 1;
        }
        function g(x) {
            return x + 2;
        }

        test.equal(_.andThen(g, f)(1), f(g(1)));
        test.done();
    }
};

exports.sequence = {
    testSequence: function(test) {
        test.equal(_.sequence(_.Identity(1), _.Identity(2)).x, 2);
        test.done();
    }
};

exports.liftA2 = {
    testliftA2: function(test) {
        function f(x) {
            return x;
        }
        test.equal(_.liftA2(_.add, f, f)(1), 2);
        test.done();
    }
};

exports.arrayOf = {
    testArrayOf: function(test) {
        test.equal(_.arrayOf(Number).type, Number);
        test.done();
    }
};

exports.objectLike = {
    testObjectLike: function(test) {
        test.equal(_.objectLike({age: Number}).props.age, Number);
        test.done();
    }
};

exports.or = {
    testOr: function(test) {
        test.equal(_.or(0, 1), 1);
        test.done();
    }
};

exports.and = {
    testAnd: function(test) {
        test.equal(_.and(0, 1), false);
        test.done();
    }
};

exports.add = {
    testAdd: function(test) {
        test.equal(_.add(2, 1), 3);
        test.done();
    }
};

exports.times = {
    testTimes: function(test) {
        test.equal(_.times(2, 3), 6);
        test.done();
    }
};

exports.strictEquals = {
    testStrictEquals: function(test) {
        var a = {};
        test.equal(_.strictEquals(a, a), true);
        test.equal(_.strictEquals(a, {}), false);
        test.done();
    }
};

exports.not = {
    testNot: function(test) {
        test.equal(_.not(true), false);
        test.done();
    }
};

exports.curry = {
    testCurry: function(test) {
        var a = _.curry(function(a, b, c){
            test.equal(a + b + c, 6);
        });

        // Possible ways to complete a curry
        a(1, 2, 3);
        a(1, 2)(3);
        a(1)(2)(3);
        a(1)(2, 3);

        test.expect(4);
        test.done();
    },
    testCurryFunctionName: function(test) {
        var a = _.curry(function namedFunction(a, b, c) {});

        test.equal(_.functionName(a), 'namedFunction');
        test.equal(_.functionName(a(1)), 'namedFunction');
        test.equal(_.functionName(a(1)(2)), 'namedFunction');

        test.expect(3);
        test.done();
    },
    testCurryFunctionLength: function(test) {
        var a = _.curry(function(a, b, c) {});

        test.equal(_.functionLength(a), 3);
        test.equal(_.functionLength(a(1)), 2);
        test.equal(_.functionLength(a(1)(2)), 1);

        test.expect(3);
        test.done();
    }
};

exports.oneOf = {
    testOneOf: function(test) {
        var a = ['boolean', 'number', 'string'];
        test.ok(_.isAnyOf(a)(_.oneOf(a)));
        test.done();
    }
};

exports.randomRange = {
    testRandomRange: function(test) {
        var a = _.randomRange(10, 100);
        test.ok(a >= 10 && a <= 100);
        test.done();
    }
};

<commit_msg>Whoops!<commit_after>var _ = require('./lib/test'),
    A = function() {},
    B = function() {},
    C = function() {};

A.prototype =  {
    doA: function() {
        return 'A';
    }
};

B.prototype =  {
    doB: function() {
        return 'B';
    }
};

C.prototype =  {
    doC: function() {
        return 'C';
    }
};

exports.functionName = {
    testNamed: function(test) {
        test.equals(_.functionName(function a(){}), 'a');
        test.done();
    },
    testUnnamed: function(test) {
        test.equals(_.functionName(function (){}), '');
        test.done();
    },
    testVarNamed: function(test) {
        var b = function a(){};
        test.equals(_.functionName(b), 'a');
        test.done();
    },
    testForcedNamed: function(test) {
        var b = function c(){};
        b._name = 'a';
        test.equals(_.functionName(b), 'a');
        test.done();
    }
};

exports.functionLength = {
    testNoArgs: function(test) {
        test.equals(_.functionLength(function (){}), 0);
        test.done();
    },
    testOneArg: function(test) {
        test.equals(_.functionLength(function (a){}), 1);
        test.done();
    },
    testMultiArg: function(test) {
        test.equals(_.functionLength(function (a, b, c, d){}), 4);
        test.done();
    },
    testMultiArgWithForcedLength: function(test) {
        var b = function c(x, y, z){};
        b._length = 5;
        test.equals(_.functionLength(b), 5);
        test.done();
    },
    testForcedLength: function(test) {
        var b = function c(){};
        b._length = 5;
        test.equals(_.functionLength(b), 5);
        test.done();
    }
};

exports.create = {
    testCreation: function(test) {
        var Point = function(){};
        test.ok(_.create(Point.prototype) instanceof Point);
        test.done();
    }
};

exports.getInstance = {
    testGetInstanceWithFunction: function(test) {
        var Point = function(){
            var a = _.getInstance(this, Point);
            return a;
        };
        var point = Point();
        test.ok(_.getInstance(point, Point) instanceof Point);
        test.done();
    },
    testGetInstanceWithInstance: function(test) {
        var Point = function(){
            var a = _.getInstance(this, Point);
            return a;
        };
        var point = new Point();
        test.ok(_.getInstance(point, Point) instanceof Point);
        test.done();
    },
    testGetInstanceWithFunctionArguments: function(test) {
        var Point = function(x){
            var a = _.getInstance(this, Point);
            a.x = x;
            return a;
        };
        var random = Math.random();
        var point = Point(random);
        test.ok(_.getInstance(point, Point).x, random);
        test.done();
    },
    testGetInstanceWithInstanceArguments: function(test) {
        var Point = function(x){
            var a = _.getInstance(this, Point);
            a.x = x;
            return a;
        };
        var random = Math.random();
        var point = new Point(random);
        test.ok(_.getInstance(point, Point).x, random);
        test.done();
    }
};

exports.singleton = {
    testString: function(test) {
        test.deepEqual(_.singleton('a', '1'), {'a': 1});
        test.done();
    },
    testObjectKey: function(test) {
        test.deepEqual(_.singleton({a: 1}, '1'), {'[object Object]': 1});
        test.done();
    }
};

exports.extend = {
    'when testing extend with object should create a new object': function(test) {
        test.deepEqual(_.extend({a: 1}, {b: 2}), {a: 1, b: 2});
        test.done();
    },
    'when testing extend with object should create a new object without modifying new object': function(test) {
        var a = {a: 1},
            b = {b: 2},
            c = _.extend(a, b);

        test.deepEqual(a, {a: 1});
        test.deepEqual(b, {b: 2});
        test.done();
    },
    'when extending a a object should override property correctly from the right biased': function(test) {
        test.deepEqual(_.extend({a: 1}, {a: 2}), {a: 2});
        test.done();
    },
    'when creating mixin should create a new object with all correct methods': function(test) {
        var X = function() {},
            x;

        X.prototype = _.extend(_.extend(A.prototype, B.prototype), C.prototype);

        x = new X();

        test.equal(x.doA() + x.doB() + x.doC(), 'ABC');
        test.done();
    },
    'when creating mixin should not modify original objects': function(test) {
        var X = function() {},
            x;

        X.prototype = _.extend(_.extend(A.prototype, B.prototype), C.prototype);

        x = new X();

        test.deepEqual(A.prototype, {doA: A.prototype.doA});
        test.deepEqual(B.prototype, {doB: B.prototype.doB});
        test.deepEqual(C.prototype, {doC: C.prototype.doC});
        test.done();
    }
};

exports.bind = {
    testBind: function(test) {
        var a = _.bind(function(a, b, c) {
            test.equal(a + b + c, 6);
        });

        a()(1, 2, 3);

        test.expect(1);
        test.done();
    },
    testCurryFunctionName: function(test) {
        var a = _.bind(function namedFunction(a, b, c) {})();

        test.equal(_.functionName(a), 'namedFunction');
        test.done();
    },
    testCurryFunctionLength: function(test) {
        var a = _.bind(function(a, b, c) {})();

        test.equal(_.functionLength(a), 3);
        test.done();
    }
};

exports.compose = {
    testCompose: function(test) {
        function f(x) {
            return x + 1;
        }
        function g(x) {
            return x + 2;
        }

        test.equal(_.compose(f, g)(1), f(g(1)));
        test.done();
    }
};

exports.identity = {
    testIdentity: function(test) {
        test.equal(_.identity(1), 1);
        test.done();
    }
};

exports.constant = {
    testConstant: function(test) {
        test.equal(_.constant(1)(), 1);
        test.done();
    }
};

exports.access = {
    testAccess: function(test) {
        test.equal(_.access('a')(_.singleton('a', 1)), 1);
        test.done();
    }
};

exports.andThen = {
    testAndThen: function(test) {
        function f(x) {
            return x + 1;
        }
        function g(x) {
            return x + 2;
        }

        test.equal(_.andThen(g, f)(1), f(g(1)));
        test.done();
    }
};

exports.sequence = {
    testSequence: function(test) {
        test.equal(_.sequence(_.Identity(1), _.Identity(2)).x, 2);
        test.done();
    }
};

exports.liftA2 = {
    testliftA2: function(test) {
        function f(x) {
            return x;
        }
        test.equal(_.liftA2(_.add, f, f)(1), 2);
        test.done();
    }
};

exports.arrayOf = {
    testArrayOf: function(test) {
        test.equal(_.arrayOf(Number).type, Number);
        test.done();
    }
};

exports.objectLike = {
    testObjectLike: function(test) {
        test.equal(_.objectLike({age: Number}).props.age, Number);
        test.done();
    }
};

exports.or = {
    testOr: function(test) {
        test.equal(_.or(0, 1), 1);
        test.done();
    }
};

exports.and = {
    testAnd: function(test) {
        test.equal(_.and(0, 1), false);
        test.done();
    }
};

exports.add = {
    testAdd: function(test) {
        test.equal(_.add(2, 1), 3);
        test.done();
    }
};

exports.times = {
    testTimes: function(test) {
        test.equal(_.times(2, 3), 6);
        test.done();
    }
};

exports.strictEquals = {
    testStrictEquals: function(test) {
        var a = {};
        test.equal(_.strictEquals(a, a), true);
        test.equal(_.strictEquals(a, {}), false);
        test.done();
    }
};

exports.not = {
    testNot: function(test) {
        test.equal(_.not(true), false);
        test.done();
    }
};

exports.curry = {
    testCurry: function(test) {
        var a = _.curry(function(a, b, c){
            test.equal(a + b + c, 6);
        });

        // Possible ways to complete a curry
        a(1, 2, 3);
        a(1, 2)(3);
        a(1)(2)(3);
        a(1)(2, 3);

        test.expect(4);
        test.done();
    },
    testCurryFunctionName: function(test) {
        var a = _.curry(function namedFunction(a, b, c) {});

        test.equal(_.functionName(a), 'namedFunction');
        test.equal(_.functionName(a(1)), 'namedFunction');
        test.equal(_.functionName(a(1)(2)), 'namedFunction');

        test.expect(3);
        test.done();
    },
    testCurryFunctionLength: function(test) {
        var a = _.curry(function(a, b, c) {});

        test.equal(_.functionLength(a), 3);
        test.equal(_.functionLength(a(1)), 2);
        test.equal(_.functionLength(a(1)(2)), 1);

        test.expect(3);
        test.done();
    }
};

exports.oneOf = {
    testOneOf: function(test) {
        var a = ['boolean', 'number', 'string'];
        test.ok(_.isAnyOf(a)(_.oneOf(a)));
        test.done();
    }
};

exports.randomRange = {
    testRandomRange: function(test) {
        var a = _.randomRange(10, 100);
        test.ok(a >= 10 && a <= 100);
        test.done();
    }
};

<|endoftext|>


<commit_before>if(typeof exports === 'object') {
	var assert = require("assert");
	var alasql = require('../alasql.js');
} else {
	__dirname = '.';
};

describe('Test 143 streamfn', function() {

	it("1. Create database", function(done){
		alasql('CREATE DATABASE test143; use test143');
		done();
	});

	it("3. INNER JOIN on stream", function(done){

		test143(true);
		alasql.databases[alasql.useid].dbversion++
		test143(false);
		alasql.databases[alasql.useid].dbversion++
//		test143(true);
//		test143(false);
//		test143(true);

//console.log(res.length);
		done();
	});

	it("99. Drop database", function(done){
		alasql('DROP DATABASE test143');
		done();
	});
});

		function test143(dontcache) {
			var nc1=0,nc2 = 0;

			var myfn = function(i) {
				nc1++;
				if(i>10) return;
				return {a:i, b:i+2};
			};
			myfn.dontcache = dontcache;

			var myfn2 = function(i) {
				nc2++;
				if(i>10) return;
				for(var k=0;k<2000;k++) {
					Math.random();
				}
				return {a:(i%50)+1, c:(i+1)*10};
			};
			myfn2.dontcache = dontcache;
		//		myfn3.dontcache = true;
				var tm = Date.now();
		//if(true) {
				var res = alasql('select q.a, q.b, t.a as ta, t.c from ? q INNER join ? t using a',[myfn,myfn2]);
		//console.table(res);
		console.log('INNER',res.length);
if(false) {
				var res = alasql('select q.a, q.b, t.a as ta, t.c from ? q SEMI join ? t using a',[myfn,myfn2]);
		//console.table(res);
		//console.log('SEMI', res.length);
		//}
				var res = alasql('select q.a, q.b, t.a as ta, t.c from ? q ANTI join ? t using a',[myfn,myfn2]);
		//console.table(res);
		//console.log('ANTI', res.length);

		//if(true) {
				var res = alasql('select q.a, q.b, t.a as ta, t.c from ? q LEFT join ? t using a',[myfn,myfn2]);
		//console.table(res);
		//console.log('LEFT',res.length);
		//		assert(res.length == 13013);

				var res = alasql('select q.a, q.b, t.a as ta, t.c from ? q RIGHT join ? t using a',[myfn,myfn2]);
		//console.table(res);
		//console.log('RIGHT',res.length);
				//assert(res.length == 13039);

				var res = alasql('select q.a, q.b, t.a as ta, t.c from ? q OUTER join ? t using a',[myfn,myfn2]);
		//console.table(res);
		//console.log('OUTER',res.length);
		//		assert(res.length == 13039);
}
		//}
				// var res = alasql('select q.a, q.b, t.c from ? q OUTER join ? t using a '+
				// 	'EXCEPT select q.a, q.b, t.c from ? q LEFT join ? t using a',[myfn,myfn2,myfn,myfn2]);
				// console.log(res);

	//		console.log(res);
			console.log(Date.now() - tm);
			console.log(dontcache, nc1,nc2);
		}

<commit_msg>test143<commit_after>if(typeof exports === 'object') {
	var assert = require("assert");
	var alasql = require('../alasql.js');
} else {
	__dirname = '.';
};

describe('Test 143 streamfn', function() {

	it("1. Create database", function(done){
		alasql('CREATE DATABASE test143; use test143');
		done();
	});

	it("3. INNER JOIN on stream", function(done){

		test143(true);
		alasql.databases[alasql.useid].dbversion++
		test143(false);
		alasql.databases[alasql.useid].dbversion++
//		test143(true);
//		test143(false);
//		test143(true);

//console.log(res.length);
		done();
	});

	it("99. Drop database", function(done){
		alasql('DROP DATABASE test143');
		done();
	});
});

		function test143(dontcache) {
			var nc1=0,nc2 = 0, nc3 = 0;

			var myfn = function(i) {
				nc1++;
				if(i>=100) return;
				return {a:i, b:i+2};
			};
			myfn.dontcache = dontcache;

			var myfn2 = function(i) {
				nc2++;
				if(i>=100) return;
				for(var k=0;k<100;k++) {
					Math.random();
				}
				return {a:(i%25)+1, c:(i+1)*10};
			};
			myfn2.dontcache = dontcache;
		//		myfn3.dontcache = true;
				var tm = Date.now();
		//if(true) {
				var res = alasql('select q.a, q.b, t.a as ta, t.c from ? q INNER join ? t using a',[myfn,myfn2]);
				nc3 += res.length;

		//console.table(res);
//		console.log('INNER',res.length);
//if(false) {
				var res = alasql('select q.a, q.b, t.a as ta, t.c from ? q SEMI join ? t using a',[myfn,myfn2]);
				nc3 += res.length;
		//console.table(res);
		//console.log('SEMI', res.length);
		//}
				var res = alasql('select q.a, q.b, t.a as ta, t.c from ? q ANTI join ? t using a',[myfn,myfn2]);
				nc3 += res.length;
		//console.table(res);
		//console.log('ANTI', res.length);

		//if(true) {
				var res = alasql('select q.a, q.b, t.a as ta, t.c from ? q LEFT join ? t using a',[myfn,myfn2]);
				nc3 += res.length;
		//console.table(res);
		//console.log('LEFT',res.length);
		//		assert(res.length == 13013);

				var res = alasql('select q.a, q.b, t.a as ta, t.c from ? q RIGHT join ? t using a',[myfn,myfn2]);
				nc3 += res.length;
		//console.table(res);
		//console.log('RIGHT',res.length);
				//assert(res.length == 13039);

				var res = alasql('select q.a, q.b, t.a as ta, t.c from ? q OUTER join ? t using a',[myfn,myfn2]);
				nc3 += res.length;
		//console.table(res);
		//console.log('OUTER',res.length);
		//		assert(res.length == 13039);
//}
		//}
				// var res = alasql('select q.a, q.b, t.c from ? q OUTER join ? t using a '+
				// 	'EXCEPT select q.a, q.b, t.c from ? q LEFT join ? t using a',[myfn,myfn2,myfn,myfn2]);
				// console.log(res);

	//		console.log(res);
			tm = Date.now() - tm;
			console.log(tm);
			console.log(dontcache, nc1,nc2, nc3, tm/nc2);
		}

<|endoftext|>


<commit_before>var app = require('cantina')
  , _ = require('underscore')
  , controller = module.exports = app.controller();

require('cantina-tokens');
require('cantina-email');

function values (req, res, next) {
  res.vars.values = req.body || {};
  next();
}

controller.add('/account-confirm*', values);
controller.get('/account-confirm/:token', [loadToken, page]);
controller.post('/account-confirm/:token', [loadToken, process, page]);
controller.post('/account-confirm/resend', resend);

controller.on('error', function (err, req, res) {
  res.renderError(err);
});

function loadToken (req, res, next) {
  if (req.user) {
    res.vars.error = 'Could not activate account. You are already logged in as another user.';
    return next();
  }

  app.tokens.check(req.params.token, 'account', function (err, userId) {
    if (err) return next(err);
    if (userId) {
      app.collections.users.load(userId, function (err, user) {
        if (err) return next(err);
        if (user) {
          if (user.status === 'deleted') {
            res.vars.error = 'Your account has been deleted.';
            return next();
          }
          else if (req.user && user.id !== req.user.id) {
            res.vars.error = 'You are already logged in with a different account. Please log out, re-send the activation email, and try again.';
            return next();
          }
          app.users.sanitize(user);
          res.vars.user = user;
          res.vars.values = _.extend({}, user, res.vars.values);
          next();
        }
        else {
          res.vars.error = 'The link you followed is invalid or expired.';
          return next();
        }
      });
    }
    else {
      res.vars.error = 'The link you followed is invalid or expired.';
      return next();
    }
  });
}

function process (req, res, next) {

  var user = res.vars.user;
  delete res.vars.user;

  var minPasswordLen = app.conf.get('users-ui:password_min_length') || 5;

  if (!req.body) {
    return next(new Error('Invalid post data'));
  }
  if (!req.body.pass) {
    res.formError('pass', 'Password is required.');
  }
  else if (req.body.pass.length < minPasswordLen) {
    res.formError('pass', 'Password must be at least ' + minPasswordLen + ' characters long.');
  }
  else if (!req.body.pass2) {
    res.formError('pass2', 'Password confirmation required.');
  }
  else if (req.body.pass !== req.body.pass2) {
    res.formError('pass2', 'Password confirmation was not entered correctly.');
  }

  app.hook('controller:form:validate:account-confirm').runSeries(req, res, function (err) {
    if (err) return res.renderError(err);
    if (res.formErrors) {
      return next();
    }
    user.status = 'active';
    app.users.setPassword(user, req.body.pass, function (err) {
      if (err) return res.renderError(err);
      var userVars = _.pick(req.body, Object.keys(app.schemas.user.properties));
      user = _.extend(user, userVars);
      app.collections.users.save(user, function (err) {

        // TODO: - db agnostic error handling
        if (err && err.code === 'ER_DUP_ENTRY') {
          if (err.message.match(/for key 'username'$/)){
            res.formError('username', 'Username already registered.');
          }
          return next();
        }

        if (err) return next(err);
        delete res.vars.values;
        app.tokens.delete(req.params.token, 'account', function (err) {
          app.auth.logIn(user, req, res, function (err) {
            if (err) return res.renderError(err);
            res.setMessage('Thank you for completing your registration. Your account is now active.', 'success');
            res.redirect('/');
          });
        });
      });
    });
  });
}

function page (req, res, next) {
  if (res.vars.error) {
    res.statusCode = 400;
    res.vars.noScripts = true;
    res.vars.message = res.vars.error;
    return res.renderStatus(400, res.vars);
  }
  delete res.vars.user;
  res.vars.title = 'Activate account';
  res.vars.noScripts = true;
  res.render('users/account_confirm', res.vars);
}

function resend (req, res, next) {
  if (!req.user) {
    res.statusCode = 401;
    res.vars.noScripts = true;
    return res.renderStatus(401, res.vars);
  }
  app.email.send('users/account_confirm', { user: req.user }, function (err) {
    if (err) {
      app.emit('error', err);
      res.json({
        status: 'error',
        error: 'Error re-sending confirmation email. Please try again.'
      });
    }
    else {
      res.json({
        status: 'ok',
        message: 'Confirmation email re-sent.'
      });
    }
  });
}<commit_msg>Adds missing error check<commit_after>var app = require('cantina')
  , _ = require('underscore')
  , controller = module.exports = app.controller();

require('cantina-tokens');
require('cantina-email');

function values (req, res, next) {
  res.vars.values = req.body || {};
  next();
}

controller.add('/account-confirm*', values);
controller.get('/account-confirm/:token', [loadToken, page]);
controller.post('/account-confirm/:token', [loadToken, process, page]);
controller.post('/account-confirm/resend', resend);

controller.on('error', function (err, req, res) {
  res.renderError(err);
});

function loadToken (req, res, next) {
  if (req.user) {
    res.vars.error = 'Could not activate account. You are already logged in as another user.';
    return next();
  }

  app.tokens.check(req.params.token, 'account', function (err, userId) {
    if (err) return next(err);
    if (userId) {
      app.collections.users.load(userId, function (err, user) {
        if (err) return next(err);
        if (user) {
          if (user.status === 'deleted') {
            res.vars.error = 'Your account has been deleted.';
            return next();
          }
          else if (req.user && user.id !== req.user.id) {
            res.vars.error = 'You are already logged in with a different account. Please log out, re-send the activation email, and try again.';
            return next();
          }
          app.users.sanitize(user);
          res.vars.user = user;
          res.vars.values = _.extend({}, user, res.vars.values);
          next();
        }
        else {
          res.vars.error = 'The link you followed is invalid or expired.';
          return next();
        }
      });
    }
    else {
      res.vars.error = 'The link you followed is invalid or expired.';
      return next();
    }
  });
}

function process (req, res, next) {

  var user = res.vars.user;
  delete res.vars.user;

  var minPasswordLen = app.conf.get('users-ui:password_min_length') || 5;

  if (!req.body) {
    return next(new Error('Invalid post data'));
  }
  if (!req.body.pass) {
    res.formError('pass', 'Password is required.');
  }
  else if (req.body.pass.length < minPasswordLen) {
    res.formError('pass', 'Password must be at least ' + minPasswordLen + ' characters long.');
  }
  else if (!req.body.pass2) {
    res.formError('pass2', 'Password confirmation required.');
  }
  else if (req.body.pass !== req.body.pass2) {
    res.formError('pass2', 'Password confirmation was not entered correctly.');
  }

  app.hook('controller:form:validate:account-confirm').runSeries(req, res, function (err) {
    if (err) return res.renderError(err);
    if (res.formErrors) {
      return next();
    }
    user.status = 'active';
    app.users.setPassword(user, req.body.pass, function (err) {
      if (err) return res.renderError(err);
      var userVars = _.pick(req.body, Object.keys(app.schemas.user.properties));
      user = _.extend(user, userVars);
      app.collections.users.save(user, function (err) {

        // TODO: - db agnostic error handling
        if (err && err.code === 'ER_DUP_ENTRY') {
          if (err.message.match(/for key 'username'$/)){
            res.formError('username', 'Username already registered.');
          }
          return next();
        }

        if (err) return next(err);
        delete res.vars.values;
        app.tokens.delete(req.params.token, 'account', function (err) {
          if (err) return res.renderError(err);
          app.auth.logIn(user, req, res, function (err) {
            if (err) return res.renderError(err);
            res.setMessage('Thank you for completing your registration. Your account is now active.', 'success');
            res.redirect('/');
          });
        });
      });
    });
  });
}

function page (req, res, next) {
  if (res.vars.error) {
    res.statusCode = 400;
    res.vars.noScripts = true;
    res.vars.message = res.vars.error;
    return res.renderStatus(400, res.vars);
  }
  delete res.vars.user;
  res.vars.title = 'Activate account';
  res.vars.noScripts = true;
  res.render('users/account_confirm', res.vars);
}

function resend (req, res, next) {
  if (!req.user) {
    res.statusCode = 401;
    res.vars.noScripts = true;
    return res.renderStatus(401, res.vars);
  }
  app.email.send('users/account_confirm', { user: req.user }, function (err) {
    if (err) {
      app.emit('error', err);
      res.json({
        status: 'error',
        error: 'Error re-sending confirmation email. Please try again.'
      });
    }
    else {
      res.json({
        status: 'ok',
        message: 'Confirmation email re-sent.'
      });
    }
  });
}<|endoftext|>


<commit_before>module.exports = exports = (function () {
    return function (req, res, next) {
        var onGetAndOptions = function () {
            res.format({
                'multipart/nav-data':function () {
                    console.dir(req.headers);
                    console.dir(res._headers);
                    res.end('');
                }
            });
        };
        res.methods({
            'GET':onGetAndOptions,
            'OPTIONS':onGetAndOptions
        });
    };
})();
<commit_msg>Removed unnecessary log statements from the entry point controller. 032013.<commit_after>module.exports = exports = (function () {
    return function (req, res, next) {
        var onGetAndOptions = function () {
            res.format({
                'multipart/nav-data':function () {
                    res.end('');
                }
            });
        };
        res.methods({
            'GET':onGetAndOptions,
            'OPTIONS':onGetAndOptions
        });
    };
})();
<|endoftext|>


<commit_before>const request = require('request');
const userController = require('./userController');
const UserSchema =require('../models/User');
// const raccoon = require('raccoon');
const nconf = require('../config/nconf.js');
const raccoon = require('../config/raccoon.js');
const _ = require('underscore');

let movieController = {};

movieController.like=(req,res)=>{
  if (!req.headers.authorization) return res.sendStatus(400, 'missing authorization header');
  const token =req.headers.authorization.split(' ')[1];
  UserSchema.find({userToken:token})
  .then(response=>{
    if (response.length>0) {
      const userId=response[0].spotifyId;
      const movieId=req.params.movieId;
      raccoon.liked(userId,movieId, ()=>{
        console.log(userId,'liked',movieId);
      });
      return res.sendStatus(200);
    }
    return res.sendStatus(401);
  });
};

movieController.dislike=(req,res)=>{
  if (!req.headers.authorization) return res.sendStatus(400, 'missing authorization header');
  const token =req.headers.authorization.split(' ')[1];
  UserSchema.find({userToken:token})
  .then(response=>{
    if (response.length>0) {
      const userId=response[0].spotifyId;
      const movieId=req.params.movieId;
      raccoon.disliked(userId,movieId, ()=>{
        console.log(userId,'disliked',movieId);
      });
      return res.sendStatus(200);
    }
    return res.sendStatus(401);
  });
};

movieController.unlike=(req,res)=>{
  if (!req.headers.authorization) return res.sendStatus(400, 'missing authorization header');
  const token =req.headers.authorization.split(' ')[1];
  UserSchema.find({userToken:token})
  .then(response=>{
    if (response.length>0) {
      const userId=response[0].spotifyId;
      const movieId=req.params.movieId;
      raccoon.unliked(userId,movieId, ()=>{
        console.log(userId,'unliked',movieId);
      });
      return res.send(movieId);
    }
    return res.sendStatus(401);
  });
};

movieController.undislike=(req,res)=>{
  if (!req.headers.authorization) return res.sendStatus(400, 'missing authorization header');
  const token =req.headers.authorization.split(' ')[1];
  UserSchema.find({userToken:token})
  .then(response=>{
    if (response.length>0) {
      const userId=response[0].spotifyId;
      const movieId=req.params.movieId;
      raccoon.undisliked(userId,movieId, ()=>{
        console.log(userId,'undisliked',movieId);
      });
      return res.sendStatus(200);
    }
    return res.sendStatus(401);
  });
};

movieController.allLikes=(req,res)=>{

  if (!req.headers.authorization) return res.sendStatus(400, 'missing authorization header');
  const token =req.headers.authorization.split(' ')[1];
  console.log(token);
  UserSchema.find({userToken:token})
  .then(response=>{
    if (response.length>0) {
      const userId=response[0].spotifyId;
      let movie;
      raccoon.allLikedFor(userId,(results) => {
        const ratedMovies= results.filter(like =>!like.includes('SP'));
        return res.send({movies:ratedMovies});
      });
    }else{
      return res.sendStatus(401);
    }
  });
};
movieController.alldislikes=(req,res)=>{

  if (!req.headers.authorization) return res.sendStatus(400, 'missing authorization header');
  const token =req.headers.authorization.split(' ')[1];
  UserSchema.find({userToken:token})
  .then(response=>{
    if (response.length>0) {
      const userId=response[0].spotifyId;
      let movie;
      raccoon.allDislikedFor(userId,(results) => {
        const ratedMovies= results.filter(like =>!like.includes('SP'));
        return res.send({movies:ratedMovies});
      });
    }else{
      return res.sendStatus(401);
    }
  });
};

movieController.recommendation=(req,res)=>{
  if (!req.headers.authorization) return res.sendStatus(400, 'missing authorization header');
  const token =req.headers.authorization.split(' ')[1];

  UserSchema.find({userToken:token})
  .then(response=>{
    if (response.length>0) {
      const userId=response[0].spotifyId;
      const alreadyRecommended=response[0].alreadyRecommended;
      let movie;
      raccoon.recommendFor(userId, 10,rec => {
        rec=_.difference(rec,alreadyRecommended);
        alreadyRecommended.push(rec[0]);
        userController.updateUser(userId,{alreadyRecommended:alreadyRecommended});

        return res.send({
          "movieId": rec[0],
        });
      });
    }else{
      return res.sendStatus(401);
    }
  });
};

const findRatedMovies=(userId)=>{
  return new Promise((resolve,reject)=>{
    raccoon.allWatchedFor(userId,results => {
      const ratedMovies= results.filter(like =>!like.includes('SP'));
      return resolve(ratedMovies);
    });
  });
};

const handleMovies = (moviesToBeSent,n,moviesAllreadyRecommended) =>{
  moviesToBeSent=_.difference(moviesToBeSent,moviesAllreadyRecommended);
  return moviesToBeSent.slice(0,n);
};

movieController.survey=(req,res)=>{
  let url =`https://api.themoviedb.org/3/discover/movie?api_key=${nconf.get('TMDB_API_KEY')}`;
  let numberOfmovies=1;
  let moviesToBeSent=[];
  let ratedMovies=[];
  if (!req.headers.authorization) return res.sendStatus(400, 'missing authorization header');
  const token =req.headers.authorization.split(' ')[1];
  UserSchema.find({userToken:token})
  .then(user=>{
    if (user.length===0) return res.sendStatus(401);
    if(user[0].firstLogin){
      numberOfmovies=4;
    }
    const userId=user[0].spotifyId;
    userController.updateUser(userId,{firstLogin:false})
    //Handle first login
    .then(user=>{
      //======================================================
      // GET TMDB movies
      //======================================================
      let page =Math.floor(Math.random()*20+1);
      request.get(`${url}&page=${page}`, (error, response, body) => {
        let receivedMovies=JSON.parse(body).results.map((movie=>movie.id));
        findRatedMovies(userId)
        .then(response=>{
          ratedMovies=response;
          moviesToBeSent=moviesToBeSent.concat(handleMovies(receivedMovies,numberOfmovies,ratedMovies));
          ratedMovies=ratedMovies.concat(moviesToBeSent);
          //GET POPULAR MOVIES
          request.get(`${url}&sort_by=popularity.desc&page=${page}`, (error, response, body) => {
            receivedMovies=JSON.parse(body).results.map((movie=>movie.id));
            moviesToBeSent=moviesToBeSent.concat(handleMovies(receivedMovies,numberOfmovies,ratedMovies));
            ratedMovies=ratedMovies.concat(moviesToBeSent);
            //GET WEIRD MOVIES
            request.get(`${url}&sort_by=vote_average.asc&page=${page+50}`, (error, response, body) => {
              receivedMovies=JSON.parse(body).results.map((movie=>movie.id));
              moviesToBeSent=moviesToBeSent.concat(handleMovies(receivedMovies,numberOfmovies,ratedMovies));
              return res.send({movies:moviesToBeSent});
            });
          });
        });
      });
    });
  });
};

module.exports=movieController;
<commit_msg>feat recommendation<commit_after>const request = require('request');
const userController = require('./userController');
const UserSchema =require('../models/User');
// const raccoon = require('raccoon');
const nconf = require('../config/nconf.js');
const raccoon = require('../config/raccoon.js');
const _ = require('underscore');

const movieController = {};
  const url =`https://api.themoviedb.org/3/discover/movie?api_key=${nconf.get('TMDB_API_KEY')}`;

movieController.like=(req,res)=>{
  if (!req.headers.authorization) return res.sendStatus(400, 'missing authorization header');
  const token =req.headers.authorization.split(' ')[1];
  UserSchema.find({userToken:token})
  .then(response=>{
    if (response.length>0) {
      const userId=response[0].spotifyId;
      const movieId=req.params.movieId;
      raccoon.liked(userId,movieId, ()=>{
        console.log(userId,'liked',movieId);
      });
      return res.sendStatus(200);
    }
    return res.sendStatus(401);
  });
};

movieController.dislike=(req,res)=>{
  if (!req.headers.authorization) return res.sendStatus(400, 'missing authorization header');
  const token =req.headers.authorization.split(' ')[1];
  UserSchema.find({userToken:token})
  .then(response=>{
    if (response.length>0) {
      const userId=response[0].spotifyId;
      const movieId=req.params.movieId;
      raccoon.disliked(userId,movieId, ()=>{
        console.log(userId,'disliked',movieId);
      });
      return res.sendStatus(200);
    }
    return res.sendStatus(401);
  });
};

movieController.unlike=(req,res)=>{
  if (!req.headers.authorization) return res.sendStatus(400, 'missing authorization header');
  const token =req.headers.authorization.split(' ')[1];
  UserSchema.find({userToken:token})
  .then(response=>{
    if (response.length>0) {
      const userId=response[0].spotifyId;
      const movieId=req.params.movieId;
      raccoon.unliked(userId,movieId, ()=>{
        console.log(userId,'unliked',movieId);
      });
      return res.send(movieId);
    }
    return res.sendStatus(401);
  });
};

movieController.undislike=(req,res)=>{
  if (!req.headers.authorization) return res.sendStatus(400, 'missing authorization header');
  const token =req.headers.authorization.split(' ')[1];
  UserSchema.find({userToken:token})
  .then(response=>{
    if (response.length>0) {
      const userId=response[0].spotifyId;
      const movieId=req.params.movieId;
      raccoon.undisliked(userId,movieId, ()=>{
        console.log(userId,'undisliked',movieId);
      });
      return res.sendStatus(200);
    }
    return res.sendStatus(401);
  });
};

movieController.allLikes=(req,res)=>{

  if (!req.headers.authorization) return res.sendStatus(400, 'missing authorization header');
  const token =req.headers.authorization.split(' ')[1];
  UserSchema.find({userToken:token})
  .then(response=>{
    if (response.length>0) {
      const userId=response[0].spotifyId;
      let movie;
      raccoon.allLikedFor(userId,(results) => {
        const ratedMovies= results.filter(like =>!like.includes('SP'));
        return res.send({movies:ratedMovies});
      });
    }else{
      return res.sendStatus(401);
    }
  });
};

movieController.alldislikes=(req,res)=>{

  if (!req.headers.authorization) return res.sendStatus(400, 'missing authorization header');
  const token =req.headers.authorization.split(' ')[1];
  UserSchema.find({userToken:token})
  .then(response=>{
    if (response.length>0) {
      const userId=response[0].spotifyId;
      let movie;
      raccoon.allDislikedFor(userId,(results) => {
        const ratedMovies= results.filter(like =>!like.includes('SP'));
        return res.send({movies:ratedMovies});
      });
    }else{
      return res.sendStatus(401);
    }
  });
};

movieController.recommendation=(req,res)=>{
  if (!req.headers.authorization) return res.sendStatus(400, 'missing authorization header');
  const token =req.headers.authorization.split(' ')[1];

  UserSchema.find({userToken:token})
  .then(response=>{
    if (response.length>0) {
      const userId=response[0].spotifyId;
      const alreadyRecommended=response[0].alreadyRecommended;
      let movie;
      raccoon.recommendFor(userId, 100,rec => {
        rec=_.difference(rec,alreadyRecommended).filter(like =>!like.includes('SP'));
        if (rec.length===0) {
          let page =Math.floor(Math.random()*40+1);
          request.get(`${url}&page=${page}`, (error, response, body) => {
            let receivedMovies=JSON.parse(body).results.map((movie=>movie.id));
            findRatedMovies(userId)
            .then(response=>{
              const movie=(handleMovies(receivedMovies,1,response)[0]);
              console.log(movie);
              res.send({
                "movieId": movie,
              });
            });
          });

        } else {
          alreadyRecommended.push(rec[0]);
          userController.updateUser(userId,{alreadyRecommended:alreadyRecommended});
          return res.send({
            "movieId": rec[0],
          });
        }

      });
    }else{
      return res.sendStatus(401);
    }
  });
};

const findRatedMovies=(userId)=>{
  return new Promise((resolve,reject)=>{
    raccoon.allWatchedFor(userId,results => {
      const ratedMovies= results.filter(like =>!like.includes('SP'));
      return resolve(ratedMovies);
    });
  });
};

const handleMovies = (moviesToBeSent,n,moviesAllreadyRecommended) =>{
  moviesToBeSent=_.difference(moviesToBeSent,moviesAllreadyRecommended);
  return moviesToBeSent.slice(0,n);
};

movieController.survey=(req,res)=>{

  let numberOfmovies=1;
  let moviesToBeSent=[];
  let ratedMovies=[];
  if (!req.headers.authorization) return res.sendStatus(400, 'missing authorization header');
  const token =req.headers.authorization.split(' ')[1];
  UserSchema.find({userToken:token})
  .then(user=>{
    if (user.length===0) return res.sendStatus(401);
    if(user[0].firstLogin){
      numberOfmovies=4;
    }
    const userId=user[0].spotifyId;
    userController.updateUser(userId,{firstLogin:false})
    //Handle first login
    .then(user=>{
      //======================================================
      // GET TMDB movies
      //======================================================
      let page =Math.floor(Math.random()*20+1);
      request.get(`${url}&page=${page}`, (error, response, body) => {
        let receivedMovies=JSON.parse(body).results.map((movie=>movie.id));
        findRatedMovies(userId)
        .then(response=>{
          ratedMovies=response;
          moviesToBeSent=moviesToBeSent.concat(handleMovies(receivedMovies,numberOfmovies,ratedMovies));
          ratedMovies=ratedMovies.concat(moviesToBeSent);
          //GET POPULAR MOVIES
          request.get(`${url}&sort_by=popularity.desc&page=${page}`, (error, response, body) => {
            receivedMovies=JSON.parse(body).results.map((movie=>movie.id));
            moviesToBeSent=moviesToBeSent.concat(handleMovies(receivedMovies,numberOfmovies,ratedMovies));
            ratedMovies=ratedMovies.concat(moviesToBeSent);
            //GET WEIRD MOVIES
            request.get(`${url}&sort_by=vote_average.asc&page=${page+50}`, (error, response, body) => {
              receivedMovies=JSON.parse(body).results.map((movie=>movie.id));
              moviesToBeSent=moviesToBeSent.concat(handleMovies(receivedMovies,numberOfmovies,ratedMovies));
              return res.send({movies:moviesToBeSent});
            });
          });
        });
      });
    });
  });
};

module.exports=movieController;
<|endoftext|>


<commit_before>import getStream from 'get-stream';
import test from 'ava';
import pEvent from 'p-event';
import delay from 'delay';
import got from '../source';
import {createServer} from './helpers/server';

let s;
const reqDelay = 160;

test.before('setup', async () => {
	s = await createServer();

	s.on('/', async (req, res) => {
		await delay(reqDelay);
		res.statusCode = 200;
		res.end('OK');
	});

	await s.listen(s.port);
});

test('timeout option (ETIMEDOUT)', async t => {
	await t.throws(
		got(s.url, {
			timeout: 0,
			retry: 0
		}),
		{
			code: 'ETIMEDOUT'
		}
	);
});

test('timeout option (ESOCKETTIMEDOUT)', async t => {
	await t.throws(
		got(s.url, {
			timeout: reqDelay,
			retry: 0
		}),
		{
			code: 'ESOCKETTIMEDOUT'
		}
	);
});

test('timeout option as object (ETIMEDOUT)', async t => {
	await t.throws(
		got(s.url, {
			timeout: {socket: reqDelay * 2.5, request: 0},
			retry: 0
		}),
		{
			code: 'ETIMEDOUT'
		}
	);
});

test('timeout option as object (ESOCKETTIMEDOUT)', async t => {
	await t.throws(
		got(s.url, {
			timeout: {socket: reqDelay * 1.5, request: reqDelay},
			retry: 0
		}),
		{
			code: 'ESOCKETTIMEDOUT'
		}
	);
});

test('socket timeout', async t => {
	await t.throws(
		got(s.url, {
			timeout: {socket: reqDelay / 20},
			retry: 0
		}),
		{
			code: 'ESOCKETTIMEDOUT'
		}
	);
});

test.todo('connection timeout');

test('request timeout', async t => {
	await t.throws(
		got(s.url, {
			timeout: {request: reqDelay},
			retry: 0
		}),
		{
			code: 'ESOCKETTIMEDOUT'
		}
	);
});

test('retries on timeout (ESOCKETTIMEDOUT)', async t => {
	let tried = false;

	await t.throws(got(s.url, {
		timeout: reqDelay,
		retry: {
			retries: () => {
				if (tried) {
					return 0;
				}

				tried = true;
				return 1;
			}
		}
	}), {
		code: 'ESOCKETTIMEDOUT'
	});

	t.true(tried);
});

test('retries on timeout (ETIMEDOUT)', async t => {
	let tried = false;

	await t.throws(got(s.url, {
		timeout: 0,
		retry: {
			retries: () => {
				if (tried) {
					return 0;
				}

				tried = true;
				return 1;
			}
		}
	}), {code: 'ETIMEDOUT'});

	t.true(tried);
});

test('timeout with streams', async t => {
	const stream = got.stream(s.url, {
		timeout: 0,
		retry: 0
	});
	await t.throws(pEvent(stream, 'response'), {code: 'ETIMEDOUT'});
});

test('no error emitted when timeout is not breached', async t => {
	const stream = got.stream(s.url, {
		retry: 0,
		timeout: {
			request: reqDelay * 2
		}
	});
	stream.on('error', err => {
		t.fail(`error was emitted: ${err}`);
	});
	await getStream(stream);
	await delay(reqDelay * 3);
	t.pass();
});
<commit_msg>Test that timeout error is not erroneously emitted using promise interface (#529)<commit_after>import getStream from 'get-stream';
import test from 'ava';
import pEvent from 'p-event';
import delay from 'delay';
import got from '../source';
import {createServer} from './helpers/server';

let s;
const reqDelay = 160;

test.before('setup', async () => {
	s = await createServer();

	s.on('/', async (req, res) => {
		await delay(reqDelay);
		res.statusCode = 200;
		res.end('OK');
	});

	await s.listen(s.port);
});

test('timeout option (ETIMEDOUT)', async t => {
	await t.throws(
		got(s.url, {
			timeout: 0,
			retry: 0
		}),
		{
			code: 'ETIMEDOUT'
		}
	);
});

test('timeout option (ESOCKETTIMEDOUT)', async t => {
	await t.throws(
		got(s.url, {
			timeout: reqDelay,
			retry: 0
		}),
		{
			code: 'ESOCKETTIMEDOUT'
		}
	);
});

test('timeout option as object (ETIMEDOUT)', async t => {
	await t.throws(
		got(s.url, {
			timeout: {socket: reqDelay * 2.5, request: 0},
			retry: 0
		}),
		{
			code: 'ETIMEDOUT'
		}
	);
});

test('timeout option as object (ESOCKETTIMEDOUT)', async t => {
	await t.throws(
		got(s.url, {
			timeout: {socket: reqDelay * 1.5, request: reqDelay},
			retry: 0
		}),
		{
			code: 'ESOCKETTIMEDOUT'
		}
	);
});

test('socket timeout', async t => {
	await t.throws(
		got(s.url, {
			timeout: {socket: reqDelay / 20},
			retry: 0
		}),
		{
			code: 'ESOCKETTIMEDOUT'
		}
	);
});

test.todo('connection timeout');

test('request timeout', async t => {
	await t.throws(
		got(s.url, {
			timeout: {request: reqDelay},
			retry: 0
		}),
		{
			code: 'ESOCKETTIMEDOUT'
		}
	);
});

test('retries on timeout (ESOCKETTIMEDOUT)', async t => {
	let tried = false;

	await t.throws(got(s.url, {
		timeout: reqDelay,
		retry: {
			retries: () => {
				if (tried) {
					return 0;
				}

				tried = true;
				return 1;
			}
		}
	}), {
		code: 'ESOCKETTIMEDOUT'
	});

	t.true(tried);
});

test('retries on timeout (ETIMEDOUT)', async t => {
	let tried = false;

	await t.throws(got(s.url, {
		timeout: 0,
		retry: {
			retries: () => {
				if (tried) {
					return 0;
				}

				tried = true;
				return 1;
			}
		}
	}), {code: 'ETIMEDOUT'});

	t.true(tried);
});

test('timeout with streams', async t => {
	const stream = got.stream(s.url, {
		timeout: 0,
		retry: 0
	});
	await t.throws(pEvent(stream, 'response'), {code: 'ETIMEDOUT'});
});

test('no error emitted when timeout is not breached (stream)', async t => {
	const stream = got.stream(s.url, {
		retry: 0,
		timeout: {
			request: reqDelay * 2
		}
	});
	stream.on('error', err => {
		t.fail(`error was emitted: ${err}`);
	});
	await getStream(stream);
	await delay(reqDelay * 3);
	t.pass();
});

test('no error emitted when timeout is not breached (promise)', async t => {
	await got(s.url, {
		retry: 0,
		timeout: {
			request: reqDelay * 2
		}
	}).on('request', req => {
		// 'error' events are not emitted by the Promise interface, so attach
		// directly to the request object
		req.on('error', err => {
			t.fail(`error was emitted: ${err}`);
		});
	});
	await delay(reqDelay * 3);
	t.pass();
});
<|endoftext|>


<commit_before>if (!process.env.ALL_6TO5_TESTS) return;

var fs = require("fs");
var _  = require("lodash");

var traceurLoc = __dirname + "/../vendor/traceur";
if (!fs.existsSync(traceurLoc)) {
  console.error("No vendor/traceur - run `make bootstrap`");
  process.exit(1);
}

require("./_transformation-helper")({
  name: "traceur",
  loc: traceurLoc + "/test/feature",

  ignoreSuites: [
    "ObjectMixin",
    "Annotations",
    "TestRunner",
    "Tools",
    "TempVarTransformer",
    "AtScript",
    "FreeVariableChecker",
    "TypeAssertions",
    "MemberVariables",
    "Types"
  ],

  ignoreTasks: [
    // core.js doesn't support due to a perf hit and having to override a lot
    // of native methods
    "Symbol/GetOwnPropertySymbols",

    // traceur doesn't name methods and has an incorrect test asserting that
    // they have no names
    "PropertyMethodAssignment/PropertyMethodAssignment",

    // 6to5 assumes that all code transformed is a module
    "Strict",
    "Syntax/UseStrictEscapeSequence",
    "Syntax/UseStrictLineContinuation",

    // the spec for these doesn't define syntax (as far as i could tell)
    // these both fail because of filter between blocks
    "ArrayComprehension/Simple",
    "GeneratorComprehension/Simple"
  ]
}, {
  optional: ["typeofSymbol"],
  experimental: true,
  after: function () {
    // StringExtras/StarsWith
    delete Object.prototype[1];
  }
}, function (opts, task) {
  if (!_.contains(task.exec.loc, "module.js")) {
    opts.blacklist = ["useStrict"];
  }
});
<commit_msg>clarify traceur ignore tests<commit_after>if (!process.env.ALL_6TO5_TESTS) return;

var fs = require("fs");
var _  = require("lodash");

var traceurLoc = __dirname + "/../vendor/traceur";
if (!fs.existsSync(traceurLoc)) {
  console.error("No vendor/traceur - run `make bootstrap`");
  process.exit(1);
}

require("./_transformation-helper")({
  name: "traceur",
  loc: traceurLoc + "/test/feature",

  ignoreSuites: [
    // these are all internal traceur tests or non-standard features
    "ObjectMixin",
    "Annotations",
    "TestRunner",
    "Tools",
    "TempVarTransformer",
    "AtScript",
    "FreeVariableChecker",
    "TypeAssertions",
    "MemberVariables",
    "Types"
  ],

  ignoreTasks: [
    // core.js doesn't support due to a perf hit and having to override a lot
    // of native methods
    "Symbol/GetOwnPropertySymbols",

    // traceur doesn't name methods and has an incorrect test asserting that
    // they have no names
    "PropertyMethodAssignment/PropertyMethodAssignment",

    // 6to5 assumes that all code transformed is a module
    "Strict",
    "Syntax/UseStrictEscapeSequence",
    "Syntax/UseStrictLineContinuation",

    // experimental es7 - the spec hasn't been finalised yet
    // these both fail because of filter between blocks
    "ArrayComprehension/Simple",
    "GeneratorComprehension/Simple",

    // yield has been added as a keyword in ES6 so this test is actually incorrect
    "Yield/YieldIdentifier"
  ]
}, {
  optional: ["typeofSymbol"],
  experimental: true,
  after: function () {
    // StringExtras/StarsWith
    delete Object.prototype[1];
  }
}, function (opts, task) {
  if (!_.contains(task.exec.loc, "module.js")) {
    opts.blacklist = ["useStrict"];
  }
});
<|endoftext|>


<commit_before>'use strict';

var assert = require('assert'),
    path = require('path'),
    TestHelper = require('danf/lib/server/test/test-helper')
;

var configuration = TestHelper.utils.merge(
        TestHelper.builder.buildSideConfiguration(
            path.join(__dirname, '../..'),
            'server'
        ),
        {
            config: {
                this: {
                    // Define the list of connections.
                    connections: {
                        // Define a connection of name "forum" on the database "test".
                        forum: {
                            // Define the mongodb connection URL and additional options.
                            // (https://mongodb.github.io/node-mongodb-native/driver-articles/mongoclient.html#the-url-connection-format)
                            url: 'mongodb://localhost:27017/test',
                            options: {
                                server: {
                                    poolSize: 2
                                }
                            },
                            // Define the collections in the database.
                            collections: {
                                // Define a collection of name "forums".
                                forums: {
                                    // Define a danf contract in order to validate inserted documents.
                                    document: {
                                        title: {
                                            type: 'string',
                                            required: true
                                        }
                                    }
                                },
                                topics: {
                                    document: {
                                        title: {
                                            type: 'string',
                                            required: true
                                        },
                                        forum: {
                                            type: 'string|gnuckiMongodb:document.forum.forums',
                                            required: true
                                        },
                                        views: {
                                            type: 'number',
                                            default: 0
                                        }
                                    },
                                    // Define the collection indexes.
                                    indexes: {
                                        // Define an index of name "forum" on the key "forum"
                                        // with some options.
                                        forum: {
                                            keys: {forum: 1},
                                            options: {
                                                background: true
                                            }
                                        }
                                    }
                                },
                                // Define a simple collection without schema validation.
                                posts: {}
                            }
                        },
                        // Define a connection of name "user" on the database "test".
                        user: {
                            url: 'mongodb://127.0.0.1:27017/test',
                            collections: {
                                users: {
                                    // Override the default collection name of "users"
                                    // with "authors".
                                    name: 'authors',
                                    document: {
                                        username: {
                                            type: 'string',
                                            required: true
                                        },
                                        password: {
                                            type: 'string',
                                            required: true
                                        }
                                    }
                                },
                                connections: {
                                    document: {
                                        ip: {
                                            type: 'string',
                                            required: true
                                        },
                                        date: {
                                            type: 'date',
                                            required: true
                                        },
                                        user: {
                                            type: 'string|gnuckiMongodb:document.user.users',
                                            required: true
                                        }
                                    },
                                    // Define some options for the creation and fetching
                                    // of the collection (used for capped collections for instance).
                                    options: {
                                        capped: true,
                                        size: 1000000,
                                        max: 1000,
                                        w: 1
                                    }
                                }
                            }
                        }
                    }
                }
            }
        },
        true
    ),
    context = {}
;

TestHelper.use(configuration, context, function(testHelper) {
    describe('Db', function() {
        it('method "..." should ...', function() {
            var db = testHelper.getService('db.forum');

            db.driver.listCollections().toArray(function(err, items) {
                console.log(items);
            });
        })
    })

    run();
})<commit_msg>Remove deprecated call<commit_after>'use strict';

var assert = require('assert'),
    path = require('path'),
    TestHelper = require('danf/lib/server/test/test-helper')
;

var configuration = TestHelper.utils.merge(
        TestHelper.builder.buildSideConfiguration(
            path.join(__dirname, '../..'),
            'server'
        ),
        {
            config: {
                this: {
                    // Define the list of connections.
                    connections: {
                        // Define a connection of name "forum" on the database "test".
                        forum: {
                            // Define the mongodb connection URL and additional options.
                            // (https://mongodb.github.io/node-mongodb-native/driver-articles/mongoclient.html#the-url-connection-format)
                            url: 'mongodb://localhost:27017/test',
                            options: {
                                server: {
                                    poolSize: 2
                                }
                            },
                            // Define the collections in the database.
                            collections: {
                                // Define a collection of name "forums".
                                forums: {
                                    // Define a danf contract in order to validate inserted documents.
                                    document: {
                                        title: {
                                            type: 'string',
                                            required: true
                                        }
                                    }
                                },
                                topics: {
                                    document: {
                                        title: {
                                            type: 'string',
                                            required: true
                                        },
                                        forum: {
                                            type: 'string|gnuckiMongodb:document.forum.forums',
                                            required: true
                                        },
                                        views: {
                                            type: 'number',
                                            default: 0
                                        }
                                    },
                                    // Define the collection indexes.
                                    indexes: {
                                        // Define an index of name "forum" on the key "forum"
                                        // with some options.
                                        forum: {
                                            keys: {forum: 1},
                                            options: {
                                                background: true
                                            }
                                        }
                                    }
                                },
                                // Define a simple collection without schema validation.
                                posts: {}
                            }
                        },
                        // Define a connection of name "user" on the database "test".
                        user: {
                            url: 'mongodb://127.0.0.1:27017/test',
                            collections: {
                                users: {
                                    // Override the default collection name of "users"
                                    // with "authors".
                                    name: 'authors',
                                    document: {
                                        username: {
                                            type: 'string',
                                            required: true
                                        },
                                        password: {
                                            type: 'string',
                                            required: true
                                        }
                                    }
                                },
                                connections: {
                                    document: {
                                        ip: {
                                            type: 'string',
                                            required: true
                                        },
                                        date: {
                                            type: 'date',
                                            required: true
                                        },
                                        user: {
                                            type: 'string|gnuckiMongodb:document.user.users',
                                            required: true
                                        }
                                    },
                                    // Define some options for the creation and fetching
                                    // of the collection (used for capped collections for instance).
                                    options: {
                                        capped: true,
                                        size: 1000000,
                                        max: 1000,
                                        w: 1
                                    }
                                }
                            }
                        }
                    }
                }
            }
        },
        true
    ),
    context = {}
;

TestHelper.use(configuration, context, function(testHelper) {
    describe('Db', function() {
        it('method "..." should ...', function() {
            var db = testHelper.getService('db.forum');

            db.driver.listCollections().toArray(function(err, items) {
                console.log(items);
            });
        })
    })
})<|endoftext|>


<commit_before>/*
 * Copyright (c) 2015-2016 PointSource, LLC.
 * MIT Licensed
 */
//Some utilities to help with testing services

var di = require('../lib/di'),
    _ = require('lodash'),
    fs = require('fs'),
    path = require('path'),
    stripJsonComments = require('strip-json-comments');

//creates a mock config service
function getConfigService(cfg) {
    return {
        get: function(id) {
            return cfg[id] || {};
        }
    };
}

//create a mock logger
var logger = require('./mocks/logger');

//create a mock monitor
var monitor = require('./mocks/monitor');

//This will simulate the normal dependency injection
//pass in a service module, a set of config to inject into the config service,
//and an optional mapping of additional injections
//config, logger, and monitor are handled automatically, anything else needs to be included in the injections map
//callback is optional as well
exports.initService = function(module, config, injections, callback) {
    //injections is optional
    if (!injections) {
        injections = {};
    }

    if (_.isFunction(injections)) {
        callback = injections;
        injections = {};
    }

    if (!callback) {
        callback = function() {};
    }

    injections.config = getConfigService(config);
    injections.logger = logger;
    injections.monitor = monitor;

    var args = [];
    di.getParamNames(module.init).forEach(function(name) {
        args.push(injections[name]);
    });

    if (di.hasCallback(module.init)) {
        args.push(callback);
        module.init.apply(null, args);
    } else {
        module.init.apply(null, args);
        return callback();
    }

};

/*
 * This method lets you include unmodified BO services into your tests. One use case is
 * when testing your own service that depends on BO services, but the particular method
 * you want to test does not.  Rather than replicating mocked/stubbed functionality that already
 * exists in the core services, you can just inject the core services themselves so
 * init() and logic/calls within init() doesn't break.
 *
 * @param {Array|String} modules - An single name of a module or an array of module names
 * @param {String|Object} config - A configuration file path or required()'d object.  Any necessary
                                   config properties that aren't present will be included with
                                   BO defaults.
 * @param {function} callback - Called after all modules are required and init()'d. An object with
 *                              the mapping, `{ <module_name>: <module>, ... }` is returned.
 */
exports.injectCore = function (modules, config, callback) {
    var coreModules = fs.readdirSync(path.join(__dirname, '/../services/')),
        servicePattern = /^[a-z]+(.js)$/i,
        initializedModules = {},
        initializedCount = 0;

    if (typeof config === 'string') {
        config = loadJson(config);
    }

    config = augmentConfigWithDefaults(config);

    for (var i = 0; i < coreModules.length; i++) {
        if (!servicePattern.test(coreModules[i])) {
            coreModules.splice(i, 1);
        }

        coreModules[i] = coreModules[i].split('.')[0];
    }

    if (!(modules instanceof Array)) {
        modules = [modules];
    }

    for (var i = 0; i < modules.length; i++) {

        if (coreModules.indexOf(modules[i]) === -1) {
            throw new Error('Given module name is not a core service');
        }

        initializedModules[modules[i]] = require('../services/' + modules[i]);

        this.initService(initializedModules[modules[i]], config, function (error) {
            if (error) {
                throw new Error('Unable to inject core service');
            }

            initializedCount++;
            if (initializedCount === modules.length) {
                return callback(initializedModules);
            }
        });
    }
};

/*
 * Load defaults.json from blueoak-server to merge with a given config to ensure core services
 * function as intended.
 */
function augmentConfigWithDefaults (config) {
    var defaultConfig = loadJson(path.join(__dirname, '/../defaults.json'));

    return populateMissingProperties(defaultConfig, config);
}

/*
 * Recursively populate missing properties and values in the given injectCore() configuration
 */
function populateMissingProperties (defaultConfig, config) {
    for (var property in defaultConfig) {
        if (typeof defaultConfig[property] === 'object' && !(defaultConfig[property] instanceof Array)) {
            if (!config[property]) {
                config[property] = {};
            }

            populateMissingProperties(defaultConfig[property], config[property]);
        } else {
            if (!config[property]) {
                config[property] = defaultConfig[property];
            }
        }
    }

    return config;
}

/*
 * Return an object from a JSON file containing comments
 */
function loadJson (path) {
    var json = fs.readFileSync(path, 'utf-8');
    json = stripJsonComments(json);
    json = JSON.parse(json);

    return json;
}

/* This is a new init method to replace initService
 * mod: the module to init
 * serviceMap (optional) - a map of name to module
 * serviceCallback - a callback once the service stubs have been loaded to give
 *   an opportunity to stub out the methods calls
 * callback - a callback once init has completed
 */
exports.init = function(mod, serviceMap, serviceCallback, callback) {
    if (!callback) { //no opts
        callback = serviceCallback;
        serviceCallback = serviceMap;
        serviceMap = {};
    }

    global.services = {
        get: function (name) {
            console.log('Get', name);
            return serviceMap[name];
        }
    };

    var paramNames = di.getParamNames(mod.init);
    var mockParams = [];
    paramNames.forEach(function(paramName) {
        if (!serviceMap[paramName]) {

            //since it's possible that this has already been loaded once and
            //has stubbed out methods, delete it from the cache
            var modPath = require.resolve('./mocks/' + paramName);
            delete require.cache[modPath];

            serviceMap[paramName] = require('./mocks/' + paramName);
        }
        mockParams.push(serviceMap[paramName]);
    });
    serviceCallback(serviceMap);
    if (di.hasCallback(mod.init)) {
        mockParams.push(callback);
        mod.init.apply(global, mockParams);
    } else {
        var thrownError = null;
        try {
            mod.init.apply(global, mockParams);
        } catch (err) {
            thrownError = err;
        }
        return callback(thrownError);
    }
};

exports.restore = function() {
};
<commit_msg>Properly normalize param names in test util<commit_after>/*
 * Copyright (c) 2015-2016 PointSource, LLC.
 * MIT Licensed
 */
//Some utilities to help with testing services

var di = require('../lib/di'),
    _ = require('lodash'),
    fs = require('fs'),
    path = require('path'),
    stripJsonComments = require('strip-json-comments');

//creates a mock config service
function getConfigService(cfg) {
    return {
        get: function(id) {
            return cfg[id] || {};
        }
    };
}

//create a mock logger
var logger = require('./mocks/logger');

//create a mock monitor
var monitor = require('./mocks/monitor');

//This will simulate the normal dependency injection
//pass in a service module, a set of config to inject into the config service,
//and an optional mapping of additional injections
//config, logger, and monitor are handled automatically, anything else needs to be included in the injections map
//callback is optional as well
exports.initService = function(module, config, injections, callback) {
    //injections is optional
    if (!injections) {
        injections = {};
    }

    if (_.isFunction(injections)) {
        callback = injections;
        injections = {};
    }

    if (!callback) {
        callback = function() {};
    }

    injections.config = getConfigService(config);
    injections.logger = logger;
    injections.monitor = monitor;

    var args = [];
    di.getParamNames(module.init).forEach(function(name) {
        args.push(injections[normalizeServiceName(name)]);
    });

    if (di.hasCallback(module.init)) {
        args.push(callback);
        module.init.apply(null, args);
    } else {
        module.init.apply(null, args);
        return callback();
    }

};

//Copied from loader.js
function normalizeServiceName(str) {
    if (/^_.+_$/.test(str)) {
        str = str.slice(1, str.length);
        str = str.slice(0, str.length - 1);
    }

    return str.replace(/([A-Z])/g, '-$1').replace(/[-_\s]+/g, '-').toLowerCase();
}

/*
 * This method lets you include unmodified BO services into your tests. One use case is
 * when testing your own service that depends on BO services, but the particular method
 * you want to test does not.  Rather than replicating mocked/stubbed functionality that already
 * exists in the core services, you can just inject the core services themselves so
 * init() and logic/calls within init() doesn't break.
 *
 * @param {Array|String} modules - An single name of a module or an array of module names
 * @param {String|Object} config - A configuration file path or required()'d object.  Any necessary
                                   config properties that aren't present will be included with
                                   BO defaults.
 * @param {function} callback - Called after all modules are required and init()'d. An object with
 *                              the mapping, `{ <module_name>: <module>, ... }` is returned.
 */
exports.injectCore = function (modules, config, callback) {
    var coreModules = fs.readdirSync(path.join(__dirname, '/../services/')),
        servicePattern = /^[a-z]+(.js)$/i,
        initializedModules = {},
        initializedCount = 0;

    if (typeof config === 'string') {
        config = loadJson(config);
    }

    config = augmentConfigWithDefaults(config);

    for (var i = 0; i < coreModules.length; i++) {
        if (!servicePattern.test(coreModules[i])) {
            coreModules.splice(i, 1);
        }

        coreModules[i] = coreModules[i].split('.')[0];
    }

    if (!(modules instanceof Array)) {
        modules = [modules];
    }

    for (var i = 0; i < modules.length; i++) {

        if (coreModules.indexOf(modules[i]) === -1) {
            throw new Error('Given module name is not a core service');
        }

        initializedModules[modules[i]] = require('../services/' + modules[i]);

        this.initService(initializedModules[modules[i]], config, function (error) {
            if (error) {
                throw new Error('Unable to inject core service');
            }

            initializedCount++;
            if (initializedCount === modules.length) {
                return callback(initializedModules);
            }
        });
    }
};

/*
 * Load defaults.json from blueoak-server to merge with a given config to ensure core services
 * function as intended.
 */
function augmentConfigWithDefaults (config) {
    var defaultConfig = loadJson(path.join(__dirname, '/../defaults.json'));

    return populateMissingProperties(defaultConfig, config);
}

/*
 * Recursively populate missing properties and values in the given injectCore() configuration
 */
function populateMissingProperties (defaultConfig, config) {
    for (var property in defaultConfig) {
        if (typeof defaultConfig[property] === 'object' && !(defaultConfig[property] instanceof Array)) {
            if (!config[property]) {
                config[property] = {};
            }

            populateMissingProperties(defaultConfig[property], config[property]);
        } else {
            if (!config[property]) {
                config[property] = defaultConfig[property];
            }
        }
    }

    return config;
}

/*
 * Return an object from a JSON file containing comments
 */
function loadJson (path) {
    var json = fs.readFileSync(path, 'utf-8');
    json = stripJsonComments(json);
    json = JSON.parse(json);

    return json;
}

/* This is a new init method to replace initService
 * mod: the module to init
 * serviceMap (optional) - a map of name to module
 * serviceCallback - a callback once the service stubs have been loaded to give
 *   an opportunity to stub out the methods calls
 * callback - a callback once init has completed
 */
exports.init = function(mod, serviceMap, serviceCallback, callback) {
    if (!callback) { //no opts
        callback = serviceCallback;
        serviceCallback = serviceMap;
        serviceMap = {};
    }

    global.services = {
        get: function (name) {
            console.log('Get', name);
            return serviceMap[name];
        }
    };

    var paramNames = di.getParamNames(mod.init);
    var mockParams = [];
    paramNames.forEach(function(paramName) {
        if (!serviceMap[paramName]) {

            //since it's possible that this has already been loaded once and
            //has stubbed out methods, delete it from the cache
            var modPath = require.resolve('./mocks/' + paramName);
            delete require.cache[modPath];

            serviceMap[paramName] = require('./mocks/' + paramName);
        }
        mockParams.push(serviceMap[paramName]);
    });
    serviceCallback(serviceMap);
    if (di.hasCallback(mod.init)) {
        mockParams.push(callback);
        mod.init.apply(global, mockParams);
    } else {
        var thrownError = null;
        try {
            mod.init.apply(global, mockParams);
        } catch (err) {
            thrownError = err;
        }
        return callback(thrownError);
    }
};

exports.restore = function() {
};
<|endoftext|>


<commit_before>var fs = require('fs')
var http = require('http')
var test = require('tape')
var cuid = require('cuid')
var nimoy = require('../_nimoy')
var hash = require('crypto').createHash
var emitter = require('events').EventEmitter
var multilevel = require('multilevel').client()
var es = require('engine.io-stream/client')

var conf = require('../config.json')
console.log(conf)
var pass = hash('sha256').update(conf.pass,'utf8').digest('hex')

test('NIMOY COMPILE MODULES', function (t) {
  t.plan(1)
  nimoy.compile(conf, function (e, res) {
    t.ok(res, 'modules compiled!')
  })
})

test('NIMOY BOOT SERVER', function (t) {
  t.plan(3)
  nimoy.boot(conf, function (kill) {

    var indexHTML = fs.readFileSync('./static/index.html',{encoding:'utf8'})
    var getIndex = http.request({
      hostname:conf.host,
      port:conf.port,
      path:'/'
    }, function (res) {
      res.on('data', function (d) {
        t.equal(d.toString(),indexHTML, 'server request ok')
      })
    })
    getIndex.end()

    var ws = es({path:':9999/ws',transports:['websocket']})
    ws.pipe(multilevel.createRpcStream()).pipe(ws)

    var creds = {
      name : 'edit',
      pass : pass
    }

    multilevel.auth(creds, function (e, res) {
      t.equal(isCuid(res.value), true, 'login ok')
      creds.pass = res.value
    })

    setTimeout(function () {
      multilevel.auth(creds, function (e,r) {
        t.equal(isCuid(r.value), true, 'session exists!')
      })
    }, 30)
  })
})

function isCuid (id) {
  var r = (typeof id==='string' && id.length===25 && id[0]==='c') ? true : false
  return r
}
<commit_msg>remove log<commit_after>var fs = require('fs')
var http = require('http')
var test = require('tape')
var cuid = require('cuid')
var nimoy = require('../_nimoy')
var hash = require('crypto').createHash
var emitter = require('events').EventEmitter
var multilevel = require('multilevel').client()
var es = require('engine.io-stream/client')

var conf = require('../config.json')
var pass = hash('sha256').update(conf.pass,'utf8').digest('hex')

test('NIMOY COMPILE MODULES', function (t) {
  t.plan(1)
  nimoy.compile(conf, function (e, res) {
    t.ok(res, 'modules compiled!')
  })
})

test('NIMOY BOOT SERVER', function (t) {
  t.plan(3)
  nimoy.boot(conf, function (kill) {

    var indexHTML = fs.readFileSync('./static/index.html',{encoding:'utf8'})
    var getIndex = http.request({
      hostname:conf.host,
      port:conf.port,
      path:'/'
    }, function (res) {
      res.on('data', function (d) {
        t.equal(d.toString(),indexHTML, 'server request ok')
      })
    })
    getIndex.end()

    var ws = es({path:':9999/ws',transports:['websocket']})
    ws.pipe(multilevel.createRpcStream()).pipe(ws)

    var creds = {
      name : 'edit',
      pass : pass
    }

    multilevel.auth(creds, function (e, res) {
      t.equal(isCuid(res.value), true, 'login ok')
      creds.pass = res.value
    })

    setTimeout(function () {
      multilevel.auth(creds, function (e,r) {
        t.equal(isCuid(r.value), true, 'session exists!')
      })
    }, 30)
  })
})

function isCuid (id) {
  var r = (typeof id==='string' && id.length===25 && id[0]==='c') ? true : false
  return r
}
<|endoftext|>


<commit_before>var assert = require("assert");
var spawn = require('child_process').spawn;

describe('Start docker container', function () {
    it('should show M2 version', function (next) {
        var process = spawn("docker", ["run", "-t", "fhinkel/macaulay2", "/bin/bash", "/usr/bin/M2", "--version"]);
        process.stdout.setEncoding("utf8");
        process.stderr.setEncoding("utf8");
        var result= '';
        process.stdout.on('data', function (data) {
            result += data;
            console.log('Version: ' + result);
            process.kill('SIGKILL');
        });
        process.stderr.on('data', function (data) {
            result += data;
            console.log('Version: ' + result);
            process.kill('SIGKILL');
        });
        process.on('error', function (error) {
            console.log('on error');
        });
        process.on('exit', function (error) {
            console.log('EXIT for -t version');
            if (result.match(/1\.\d/)) {
                assert(true);
                next()
            } else if (result.match(/no such file or directory. Are you trying to connect to a TLS-enabled daemon without TLS/)) {
                assert(false, 'Error starting Docker container, is docker installed?\n' + result);
                next();
            } else if (result.match(/\/run\/docker.sock: permission denied/)) {
                assert(false, 'Error starting Docker container, permission denied. Maybe run test as root?\n' + result);
                next();
            }
            else {
                assert(false, 'M2 version: ' + result);
                next();
            }
        });
        process.on('close', function() {
            console.log('on close in version' + result);
        });
    });
    it('should show M2 version without -t', function (next) {
        var process = spawn("docker", ["run", "fhinkel/macaulay2", "/bin/bash", "/usr/bin/M2", "--version"]);
        process.stdout.setEncoding("utf8");
        var result= '';
        process.stdout.on('data', function (data) {
            result += data;
            console.log('Version: ' + result);
        });
        process.stderr.on('data', function (data) {
            result += data;
            console.log('Version: ' + result);
        });
        process.on('error', function (error) {
            console.log('on error');
        });
        process.on('exit', function() {
            console.log('on exit in version without -t' + result);
            if (result.match(/1\.\d/)) {
                assert(true);
                next()
            } else if (result.match(/no such file or directory. Are you trying to connect to a TLS-enabled daemon without TLS/)) {
                assert(false, 'Error starting Docker container, is docker installed?\n' + result);
                next();
            } else if (result.match(/\/run\/docker.sock: permission denied/)) {
                assert(false, 'Error starting Docker container, permission denied. Maybe run test as root?\n' + result);
                next();
            }
            else {
                assert(false, 'M2 version: ' + result);
                next();
            }
        });
    });

    it('should return after echo', function (next) {
        var process = spawn("docker", ["run", "fhinkel/macaulay2", "/bin/echo", "hello"]);
        process.stdout.setEncoding("utf8");
        var result;
        process.stdout.on('data', function (data) {
            result += data;
        });
        process.on('disconnected', function (error) {
            console.log('DISCONNECTED for preamble');
        });
        process.on('error', function (error) {
            console.log('on error');
        });
        process.on('exit', function() {
            console.log('on exit in echo');
            if (result.match(/hello/)) {
                assert(true);
                next()
            }
            else {
                assert(false, 'echo hello failed: ' + result);
                next();
            }
        });
    });

    it('should show M2 preamble', function (next) {
        var process = spawn("docker", ["run", "fhinkel/macaulay2", "M2", "-e",  "exit 0;"]);
        process.stderr.setEncoding("utf8");
        process.stdout.setEncoding("utf8");
        var result = '';
        process.stdout.on('data', function (data) {
            result += data;
            console.log('first try out: ' + data);
        });
        process.stderr.on('data', function (data) {
            result += data;
            console.log('first try err: ' + data);
            process.kill('SIGKILL');
        });
        process.on('error', function (error) {
            console.log('on error');
        });
        process.on('exit', function() {
            console.log('In exit in preamble');
            if (result.match(/Macaulay2, version 1\.\d/)) {
                assert(true);
                next()
            } else if (result.match(/no such file or directory. Are you trying to connect to a TLS-enabled daemon without TLS/)) {
                assert(false, 'Error starting Docker container, is docker installed?\n' + result);
                next();
            } else if (result.match(/\/run\/docker.sock: permission denied/)) {
                assert(false, 'Error starting Docker container, permission denied. Maybe run test as root?\n' + result);
                next();
            }
            else {
                assert(false, 'M2 preamble did not match: ' + result);
                next();
            }
        });
        process.on('close', function() {
            console.log('Close in preamble');
            if (result.match(/Macaulay2, version 1\.\d/)) {
                assert(true);
            } else if (result.match(/no such file or directory. Are you trying to connect to a TLS-enabled daemon without TLS/)) {
                assert(false, 'Error starting Docker container, is docker installed?\n' + result);
            } else if (result.match(/\/run\/docker.sock: permission denied/)) {
                assert(false, 'Error starting Docker container, permission denied. Maybe run test as root?\n' + result);
            }
            else {
                assert(false, 'M2 preamble did not match: ' + result);
            }
        });
    });
});

<commit_msg>with -rm=true<commit_after>var assert = require("assert");
var spawn = require('child_process').spawn;

describe('Start docker container', function () {
    it('should show M2 version', function (next) {
        var process = spawn("docker", ["run", "-t", "--rm=true", "fhinkel/macaulay2", "/bin/bash", "/usr/bin/M2", "--version"]);
        process.stdout.setEncoding("utf8");
        process.stderr.setEncoding("utf8");
        var result= '';
        process.stdout.on('data', function (data) {
            result += data;
            console.log('Version: ' + result);
            process.kill('SIGKILL');
        });
        process.stderr.on('data', function (data) {
            result += data;
            console.log('Version: ' + result);
            process.kill('SIGKILL');
        });
        process.on('error', function (error) {
            console.log('on error');
        });
        process.on('exit', function (error) {
            console.log('EXIT for -t version');
            if (result.match(/1\.\d/)) {
                assert(true);
                next()
            } else if (result.match(/no such file or directory. Are you trying to connect to a TLS-enabled daemon without TLS/)) {
                assert(false, 'Error starting Docker container, is docker installed?\n' + result);
                next();
            } else if (result.match(/\/run\/docker.sock: permission denied/)) {
                assert(false, 'Error starting Docker container, permission denied. Maybe run test as root?\n' + result);
                next();
            }
            else {
                assert(false, 'M2 version: ' + result);
                next();
            }
        });
        process.on('close', function() {
            console.log('on close in version' + result);
        });
    });
    it('should show M2 version without -t', function (next) {
        var process = spawn("docker", ["run", "--rm=true", "fhinkel/macaulay2", "/bin/bash", "/usr/bin/M2", "--version"]);
        process.stdout.setEncoding("utf8");
        process.stderr.setEncoding("utf8");
        var result= '';
        process.stdout.on('data', function (data) {
            result += data;
            console.log('***Version: ' + result);
        });
        process.stderr.on('data', function (data) {
            result += data;
            console.log('***Version: ' + result);
        });
        process.on('error', function (error) {
            console.log('***on error');
        });
        process.on('close', function() {
            console.log('*** in close');
        });
        process.on('disconnect', function() {
            console.log('*** in disconnect');
        });
        process.on('exit', function() {
            console.log('***on exit in version without -t' + result);
            if (result.match(/1\.\d/)) {
                assert(true);
                next()
            } else if (result.match(/no such file or directory. Are you trying to connect to a TLS-enabled daemon without TLS/)) {
                assert(false, 'Error starting Docker container, is docker installed?\n' + result);
                next();
            } else if (result.match(/\/run\/docker.sock: permission denied/)) {
                assert(false, 'Error starting Docker container, permission denied. Maybe run test as root?\n' + result);
                next();
            }
            else {
                assert(false, '***M2 version: ' + result);
                next();
            }
        });
    });

    it('should return after echo', function (next) {
        var process = spawn("docker", ["run", "fhinkel/macaulay2", "/bin/echo", "hello"]);
        process.stdout.setEncoding("utf8");
        var result;
        process.stdout.on('data', function (data) {
            result += data;
        });
        process.on('disconnected', function (error) {
            console.log('DISCONNECTED for preamble');
        });
        process.on('error', function (error) {
            console.log('on error');
        });
        process.on('exit', function() {
            console.log('on exit in echo');
            if (result.match(/hello/)) {
                assert(true);
                next()
            }
            else {
                assert(false, 'echo hello failed: ' + result);
                next();
            }
        });
    });

    it('should show M2 preamble', function (next) {
        var process = spawn("docker", ["run", "fhinkel/macaulay2", "M2", "-e",  "exit 0;"]);
        process.stderr.setEncoding("utf8");
        process.stdout.setEncoding("utf8");
        var result = '';
        process.stdout.on('data', function (data) {
            result += data;
            console.log('first try out: ' + data);
        });
        process.stderr.on('data', function (data) {
            result += data;
            console.log('first try err: ' + data);
            process.kill('SIGKILL');
        });
        process.on('error', function (error) {
            console.log('on error');
        });
        process.on('exit', function() {
            console.log('In exit in preamble');
            if (result.match(/Macaulay2, version 1\.\d/)) {
                assert(true);
                next()
            } else if (result.match(/no such file or directory. Are you trying to connect to a TLS-enabled daemon without TLS/)) {
                assert(false, 'Error starting Docker container, is docker installed?\n' + result);
                next();
            } else if (result.match(/\/run\/docker.sock: permission denied/)) {
                assert(false, 'Error starting Docker container, permission denied. Maybe run test as root?\n' + result);
                next();
            }
            else {
                assert(false, 'M2 preamble did not match: ' + result);
                next();
            }
        });
        process.on('close', function() {
            console.log('Close in preamble');
            if (result.match(/Macaulay2, version 1\.\d/)) {
                assert(true);
            } else if (result.match(/no such file or directory. Are you trying to connect to a TLS-enabled daemon without TLS/)) {
                assert(false, 'Error starting Docker container, is docker installed?\n' + result);
            } else if (result.match(/\/run\/docker.sock: permission denied/)) {
                assert(false, 'Error starting Docker container, permission denied. Maybe run test as root?\n' + result);
            }
            else {
                assert(false, 'M2 preamble did not match: ' + result);
            }
        });
    });
});

<|endoftext|>