<commit_before>test('basics', function() {
	ok(overload, 'overload exists');
	ok(overload() instanceof overload, 'overload object created');

	ok(o, 'o exists');
	ok(o.any, 'o.any exists');
	ok(o.truthy, 'o.truthy exists');
	ok(o.falsy, 'o.falsy exists');
});

test('method registration', function() {
	var a = function() { return false; },
		b = function() { return true; };

	var o = overload();
	o.args().use(a);

	ok(_.isFunction(o.expose()), 'Expose is a function');
	strictEqual(o.expose()(), false, 'Method registered and called');
	strictEqual(o.expose()(), false, 'Method returns return value');
	strictEqual(o.expose()(), false, 'overload can be used without arguments');
});

test('overload paths', function() {
	var overload = overload();

	overload.args(null).use(function() { return null; })
			.args(undefined).use(function() { return undefined; })
			.args(Infinity).use(function() { return Infinity; })
			.args(Date).use(function() { return Date; })
			.args(NaN).use(function() { return NaN; })
			.args(Number).use(function() { return Number; })
			.args(String).use(function() { return String; })
			.args(Object).use(function() { return Object; })
			.args(Array).use(function() { return Array; })
			.args(RegExp).use(function() { return RegExp; })
			.args(Boolean).use(function() { return Boolean; })
			.args(Function).use(function() { return Function; })
			.args(Element).use(function() { return Element; });

	var method = overload.expose();

	var types = [
		{
			type: null,
			name: 'null',
			param: null
		},
		{
			type: undefined,
			name: 'undefined',
			param: undefined
		},
		{
			type: Infinity,
			name: 'Infinity',
			param: Infinity
		},
		{
			type: Date,
			name: 'Date',
			param: new Date()
		},
		{
			type: Number,
			name: 'Number',
			param: 0
		},
		{
			type: String,
			name: 'String',
			param: ''
		},
		{
			type: Object,
			name: 'Object',
			param: {}
		},
		{
			type: Array,
			name: 'Array',
			param: []
		},
		{
			type: RegExp,
			name: 'RegExp',
			param: /-/gi
		},
		{
			type: Boolean,
			name: 'Boolean',
			param: false
		},
		{
			type: Function,
			name: 'Function',
			param: function() {}
		},
		{
			type: Element,
			name: 'Element',
			param: document.getElementsByTagName('body')[0]
		}
	];

	var idx = types.length;
	while (idx--) {
		var type = types[idx];
		strictEqual(method(type.param), type.type, type.name + ' passed overload test');
	}

	// NaN is special because NaN !== NaN
	strictEqual(_.isNaN(method(NaN)), _.isNaN(NaN), 'NaN passed overload test');
});

test('"this" context', function() {
	var a = function() { return this; };

	var o = overload();
	o.args().use(a);

	var method = o.expose();

	equal(method.call('one'), 'one', 'Exposed method can be called with context');
	equal(method.apply('two'), 'two', 'Exposed method can be applied with context');
	equal(method.bind('three')(), 'three', 'Exposed method can be bound with context');
	equal(o.call('four'), 'four', 'overload can be called directly with context');
	equal(o.apply('five'), 'five', 'overload can be called applied with context');
	equal(o.bind('six')(), 'six', 'overload can be bound with context');
});

test('truthy', function() {
	var a = function() { return true; };

	var o = overload();
	o.err = function() { return 'error'; };
	o.args(o.truthy).use(a);

	var method = o.expose();

	strictEqual(method(1), true, 'truthy works with #1');
	strictEqual(method(true), true, 'truthy works with true');
	strictEqual(method('1'), true, 'truthy works with "1"');
	strictEqual(method({}), true, 'truthy works with Object');
	strictEqual(method([]), true, 'truthy works with Array');
	strictEqual(method(0), 'error', 'truthy throws error with falsy value');
});

test('falsy', function() {
	var a = function() { return false; };

	var o = overload();
	o.err = function() { return 'error'; };
	o.args(o.falsy).use(a);

	var method = o.expose();

	strictEqual(method(0), false, 'falsy works with #0');
	strictEqual(method(false), false, 'falsy works with false');
	strictEqual(method(''), false, 'falsy works with ""');
	strictEqual(method(null), false, 'falsy works with null');
	strictEqual(method(undefined), false, 'falsy works with undefined');
	strictEqual(method(1), 'error', 'falsy throws error with truthy value');
});

test('length', function() {
	var a = function() { return 1; },
		b = function() { return 2; },
		c = function() { return 3; };

	var o = overload();
	o.length(0).use(a);
	o.length(1).use(b);
	o.length(2).use(c);

	var method = o.expose();
	strictEqual(method(), 1, 'No params called first function');
	strictEqual(method(1), 2, 'One param called second function');
	strictEqual(method(1, 2), 3, 'Two params called third function');

	var ov = overload();
	ov.length().use(function(a, b, c, d) { return 4; });

	var method2 = ov.expose();

	strictEqual(method2(1, 2, 3, 4), 4, 'No length gets length from function');
});

test('any', function() {
	var a = function() { return 0; },
		b = function() { return 1; };

	var o = overload();
	o.err = function() { return 'error'; };
	o.args(o.any(String, Boolean, Date)).use(a);
	o.args(o.any(Array, Object, Function)).use(b);

	var method = o.expose();

	strictEqual(method(''), 0, 'Any first test passed');
	strictEqual(method(true), 0, 'Any first test passed');
	strictEqual(method(new Date()), 0, 'Any first test passed');

	strictEqual(method([]), 1, 'Any second test passed');
	strictEqual(method({}), 1, 'Any second test passed');
	strictEqual(method(function() {}), 1, 'Any second test passed');
});

test('except', function() {
	var a = function() { return 0; },
		b = function() { return 1; };

	var o = overload();
	o.err = function() { return 'error'; };
	o.args(o.except(String, Boolean, Date)).use(a);
	o.args(o.except(Array, Object, Function)).use(b);

	var method = o.expose();

	strictEqual(method(''), 1, 'Except first test passed');
	strictEqual(method(true), 1, 'Except first test passed');
	strictEqual(method(new Date()), 1, 'Except first test passed');

	strictEqual(method([]), 0, 'Except second test passed');
	strictEqual(method({}), 0, 'Except second test passed');
	strictEqual(method(function() {}), 0, 'Except second test passed');
});

test('fallback', function() {
	var a = function() { return 0; };

	var o = overload();
	o.args(String, Boolean, Date).use(function() {});
	o.fallback(a);

	var method = o.expose();

	strictEqual(method(), 0, 'Fallback function called');
});

test('passed parameters', function() {
	var a = function(param) { return param; };
	var b = function() { return 'fallback'; };
	var method = overload().args(o.any(String, Number, Boolean)).use(a).fallback(b).expose();

	equal(method('one'), 'one', 'String passed and returned');
	equal(method(2), 2, 'Number passed and returned');
	equal(method(true), true, 'Boolean passed and returned');
	equal(method(null), 'fallback', 'No items matched and defered to the fallback');
});

test('custom', function() {
	overload.defineType('$', function(val) {
		return (val instanceof jQuery);
	});

	ok(o.$, 'Custom type added');

	var a = function() { return 0; };

	var o = overload();
	o.args(o.$).use(a);

	var method1 = o.expose();
	strictEqual(method1($('body')), 0, 'Custom function works as a definition');

	var method2 = overload().args(o.any(Boolean, o.$)).use(a).expose();
	strictEqual(method2($('body')), 0, 'Custom function work inside any() custom definition');
});<commit_msg>fix broken tests<commit_after>test('basics', function() {
	ok(overload, 'overload exists');
	ok(overload() instanceof overload, 'overload object created');

	ok(o, 'o exists');
	ok(o.any, 'o.any exists');
	ok(o.truthy, 'o.truthy exists');
	ok(o.falsy, 'o.falsy exists');
});

test('method registration', function() {
	var a = function() { return false; },
		b = function() { return true; };

	var o = overload();
	o.args().use(a);

	ok(_.isFunction(o.expose()), 'Expose is a function');
	strictEqual(o.expose()(), false, 'Method registered and called');
	strictEqual(o.expose()(), false, 'Method returns return value');
	strictEqual(o.expose()(), false, 'overload can be used without arguments');
});

test('overload paths', function() {
	var ov = overload();

	ov.args(null).use(function() { return null; })
			.args(undefined).use(function() { return undefined; })
			.args(Infinity).use(function() { return Infinity; })
			.args(Date).use(function() { return Date; })
			.args(NaN).use(function() { return NaN; })
			.args(Number).use(function() { return Number; })
			.args(String).use(function() { return String; })
			.args(Object).use(function() { return Object; })
			.args(Array).use(function() { return Array; })
			.args(RegExp).use(function() { return RegExp; })
			.args(Boolean).use(function() { return Boolean; })
			.args(Function).use(function() { return Function; })
			.args(Element).use(function() { return Element; });

	var method = ov.expose();

	var types = [
		{
			type: null,
			name: 'null',
			param: null
		},
		{
			type: undefined,
			name: 'undefined',
			param: undefined
		},
		{
			type: Infinity,
			name: 'Infinity',
			param: Infinity
		},
		{
			type: Date,
			name: 'Date',
			param: new Date()
		},
		{
			type: Number,
			name: 'Number',
			param: 0
		},
		{
			type: String,
			name: 'String',
			param: ''
		},
		{
			type: Object,
			name: 'Object',
			param: {}
		},
		{
			type: Array,
			name: 'Array',
			param: []
		},
		{
			type: RegExp,
			name: 'RegExp',
			param: /-/gi
		},
		{
			type: Boolean,
			name: 'Boolean',
			param: false
		},
		{
			type: Function,
			name: 'Function',
			param: function() {}
		},
		{
			type: Element,
			name: 'Element',
			param: document.getElementsByTagName('body')[0]
		}
	];

	var idx = types.length;
	while (idx--) {
		var type = types[idx];
		strictEqual(method(type.param), type.type, type.name + ' passed overload test');
	}

	// NaN is special because NaN !== NaN
	strictEqual(_.isNaN(method(NaN)), _.isNaN(NaN), 'NaN passed overload test');
});

test('"this" context', function() {
	var a = function() { return this; };

	var o = overload();
	o.args().use(a);

	var method = o.expose();

	equal(method.call('one'), 'one', 'Exposed method can be called with context');
	equal(method.apply('two'), 'two', 'Exposed method can be applied with context');
	equal(method.bind('three')(), 'three', 'Exposed method can be bound with context');
	equal(o.call('four'), 'four', 'overload can be called directly with context');
	equal(o.apply('five'), 'five', 'overload can be called applied with context');
	equal(o.bind('six')(), 'six', 'overload can be bound with context');
});

test('truthy', function() {
	var a = function() { return true; };

	var ov = overload();
	ov.err = function() { return 'error'; };
	ov.args(o.truthy).use(a);

	var method = ov.expose();

	strictEqual(method(1), true, 'truthy works with #1');
	strictEqual(method(true), true, 'truthy works with true');
	strictEqual(method('1'), true, 'truthy works with "1"');
	strictEqual(method({}), true, 'truthy works with Object');
	strictEqual(method([]), true, 'truthy works with Array');
	strictEqual(method(0), 'error', 'truthy throws error with falsy value');
});

test('falsy', function() {
	var a = function() { return false; };

	var ov = overload();
	ov.err = function() { return 'error'; };
	ov.args(o.falsy).use(a);

	var method = ov.expose();

	strictEqual(method(0), false, 'falsy works with #0');
	strictEqual(method(false), false, 'falsy works with false');
	strictEqual(method(''), false, 'falsy works with ""');
	strictEqual(method(null), false, 'falsy works with null');
	strictEqual(method(undefined), false, 'falsy works with undefined');
	strictEqual(method(1), 'error', 'falsy throws error with truthy value');
});

test('length', function() {
	var a = function() { return 1; },
		b = function() { return 2; },
		c = function() { return 3; };

	var o = overload();
	o.length(0).use(a);
	o.length(1).use(b);
	o.length(2).use(c);

	var method = o.expose();
	strictEqual(method(), 1, 'No params called first function');
	strictEqual(method(1), 2, 'One param called second function');
	strictEqual(method(1, 2), 3, 'Two params called third function');

	var ov = overload();
	ov.length().use(function(a, b, c, d) { return 4; });

	var method2 = ov.expose();

	strictEqual(method2(1, 2, 3, 4), 4, 'No length gets length from function');
});

test('any', function() {
	var a = function() { return 0; },
		b = function() { return 1; };

	var ov = overload();
	ov.err = function() { return 'error'; };
	ov.args(o.any(String, Boolean, Date)).use(a);
	ov.args(o.any(Array, Object, Function)).use(b);

	var method = ov.expose();

	strictEqual(method(''), 0, 'Any first test passed');
	strictEqual(method(true), 0, 'Any first test passed');
	strictEqual(method(new Date()), 0, 'Any first test passed');

	strictEqual(method([]), 1, 'Any second test passed');
	strictEqual(method({}), 1, 'Any second test passed');
	strictEqual(method(function() {}), 1, 'Any second test passed');
});

test('except', function() {
	var a = function() { return 0; },
		b = function() { return 1; };

	var ov = overload();
	ov.err = function() { return 'error'; };
	ov.args(o.except(String, Boolean, Date)).use(a);
	ov.args(o.except(Array, Object, Function)).use(b);

	var method = ov.expose();

	strictEqual(method(''), 1, 'Except first test passed');
	strictEqual(method(true), 1, 'Except first test passed');
	strictEqual(method(new Date()), 1, 'Except first test passed');

	strictEqual(method([]), 0, 'Except second test passed');
	strictEqual(method({}), 0, 'Except second test passed');
	strictEqual(method(function() {}), 0, 'Except second test passed');
});

test('fallback', function() {
	var a = function() { return 0; };

	var o = overload();
	o.args(String, Boolean, Date).use(function() {});
	o.fallback(a);

	var method = o.expose();

	strictEqual(method(), 0, 'Fallback function called');
});

test('passed parameters', function() {
	var a = function(param) { return param; };
	var b = function() { return 'fallback'; };
	var method = overload().args(o.any(String, Number, Boolean)).use(a).fallback(b).expose();

	equal(method('one'), 'one', 'String passed and returned');
	equal(method(2), 2, 'Number passed and returned');
	equal(method(true), true, 'Boolean passed and returned');
	equal(method(null), 'fallback', 'No items matched and defered to the fallback');
});

test('custom', function() {
	overload.defineType('$', function(val) {
		return (val instanceof jQuery);
	});

	ok(o.$, 'Custom type added');

	var a = function() { return 0; };

	var ov = overload();
	ov.args(o.$).use(a);

	var method1 = ov.expose();
	strictEqual(method1($('body')), 0, 'Custom function works as a definition');

	var method2 = overload().args(o.any(Boolean, o.$)).use(a).expose();
	strictEqual(method2($('body')), 0, 'Custom function work inside any() custom definition');
});<|endoftext|>


<commit_before>import Bacon from "baconjs"
import R     from "ramda"

import {classes} from "../src/bacon.react.html"

function show(x) {
  switch (typeof x) {
  case "object":
    return JSON.stringify(x)
  default:
    return `${x}`
  }
}

function tryGet(s) {
  let result
  s.take(1).onValue(v => result = v)
  return result
}

const testEq = (expr, lambda, expected) => it(
  `${expr} equals ${show(expected)}`, () => {
    const actual = lambda()
    if (!R.equals(actual, expected))
      throw new Error(`Expected: ${show(expected)}, actual: ${show(actual)}`)
  })

describe("classes", () => {
  testEq('classes()', () => classes(), {className: ""})

  testEq('classes("a")', () => classes("a"), {className: "a"})

  testEq('classes("a", undefined, 0, false, "", "b")',
         () => classes("a", undefined, 0, false, "", "b"),
         {className: "a b"})

  testEq('R.map(tryGet, classes("a", Bacon.constant("b")))',
         () => R.map(tryGet, classes("a", Bacon.constant("b"))),
         {className: "a b"})
})
<commit_msg>fix test<commit_after>import Bacon from "baconjs"
import R     from "ramda"

import {classes} from "../src/bacon.react.native"

function show(x) {
  switch (typeof x) {
  case "object":
    return JSON.stringify(x)
  default:
    return `${x}`
  }
}

function tryGet(s) {
  let result
  s.take(1).onValue(v => result = v)
  return result
}

const testEq = (expr, lambda, expected) => it(
  `${expr} equals ${show(expected)}`, () => {
    const actual = lambda()
    if (!R.equals(actual, expected))
      throw new Error(`Expected: ${show(expected)}, actual: ${show(actual)}`)
  })

describe("classes", () => {
  testEq('classes()', () => classes(), {className: ""})

  testEq('classes("a")', () => classes("a"), {className: "a"})

  testEq('classes("a", undefined, 0, false, "", "b")',
         () => classes("a", undefined, 0, false, "", "b"),
         {className: "a b"})

  testEq('R.map(tryGet, classes("a", Bacon.constant("b")))',
         () => R.map(tryGet, classes("a", Bacon.constant("b"))),
         {className: "a b"})
})
<|endoftext|>


<commit_before>const test_app_name = 'test_mam';
const test_app_version = 1;

var assert = require('chai').assert;
var fakeredis = require('fakeredis');
var Collector = require('../lib/collector');
var Subscriber = require('../lib/subscriber');
var logger = require('../helper/logger');

describe('Testing Collector', function () {

    logger.mute();
    var redis_client = null;
    var redis_client_sub = null;
    var collector = null;
    var collector2 = null;
    var subscriber = null;

    beforeEach(function () {
        var redis_name = "random_" + Math.random() * 9999999;
        redis_client = fakeredis.createClient(redis_name, {fast: true});
        redis_client_sub = fakeredis.createClient(redis_name, {fast: true});
    });

    afterEach(function () {
        if (collector != null) {
            collector.stopCollecting();
            collector = null;
        }
        if (collector2 != null) {
            collector2.stopCollecting();
            collector2 = null;
        }
    });

    it('Should collect 5 times', function (done) {
        var call_count = 0;

        collector = new Collector(
            redis_client,
            test_app_name,
            test_app_version,
            5,
            function (saveFn) {
                call_count++;

                if (call_count == 5) {
                    done();
                }
            });

        collector.startCollecting();
    });

    it('Should collect 1 time, and then stop collection', function (done) {
        var call_count = 0;

        collector = new Collector(
            redis_client,
            test_app_name,
            test_app_version,
            5,
            function (saveFn) {
                call_count++;
                collector.stopCollecting();

                var timeout = setTimeout(function () {
                    if (call_count > 1) {
                        throw new Error("Should not be called more than 1 time. Was called " + call_count + " times.");
                    } else {
                        done();
                    }

                    clearTimeout(timeout);
                }, 10);
            });

        collector.startCollecting();
    });

    it('Should send data to Subscriptors', function (done) {
        var test_key = "key";
        var test_data = "Un Cohete a la Luna";

        collector = new Collector(
            redis_client,
            test_app_name,
            test_app_version,
            50,
            function (saveFn) {
                saveFn(test_key, test_data);
            }
        );

        var call_count = 0;

        subscriber = new Subscriber(
            redis_client,
            redis_client_sub,
            test_app_name,
            test_app_version,
            function (err, data) {
                if (call_count == 0) {//only execute 1 time
                    call_count++;
                    assert.equal(test_data, data);
                    collector.stopCollecting();

                    done();
                }
            });

        subscriber.startListening();
        collector.startCollecting();
    });

    it('Collector Should get saved value', function (done) {
        var test_key = "key";
        var test_data = "Un Cohete a la Luna";

        collector = new Collector(
            redis_client,
            test_app_name,
            test_app_version,
            100,
            function (saveFn) {
                collector.stopCollecting();

                saveFn(test_key, test_data, 50000, function (err, reply) {
                    if (err) {
                        throw err;
                    }

                    collector.getValue(test_key, function (err, value) {
                        if (err) {
                            throw err;
                        }

                        assert.equal(test_data, value);
                        done();
                    });
                });
            }
        );

        collector.startCollecting();
    });

    it('Subscriber Should get saved value', function (done) {
            var test_key = "key";
            var test_data = "Un Cohete a la Luna";

            collector = new Collector(
                redis_client,
                test_app_name,
                test_app_version,
                50,
                function (saveFn) {
                    saveFn(test_key, test_data, 5000);
                    collector.stopCollecting();
                }
            );

            subscriber = new Subscriber(
                redis_client,
                redis_client_sub,
                test_app_name,
                test_app_version,
                function (err, data) {
                    subscriber.getValue(test_key, function (err, value) {
                        if (err) {
                            throw err;
                        }

                        assert.equal(test_data, value);
                        done();
                    });
                });

            subscriber.startListening();
            collector.startCollecting();
        }
    );

    it('Collector 2 should become master', function (done) {

        var collector1_is_active = true;

        collector = new Collector(
            redis_client,
            test_app_name,
            test_app_version,
            50,
            function (saveFn) {
                logger.messageWithTitle(collector.name, "onCollect()");
            }
        );

        collector2 = new Collector(
            redis_client,
            test_app_name,
            test_app_version,
            50,
            function (saveFn) {
                if (collector1_is_active) {
                    throw new Error(collector.name + " is still active!");
                } else {
                    done();
                }
            }
        );

        logger.messageWithTitle(collector.name, "Starting");

        /** Override these parameters for testing proposes */
        collector.keep_alive_millis = 200;
        collector2.keep_alive_millis = 200;
        /** ********************************* **/

        collector.startCollecting();

        var interval = setInterval(function () {
            clearInterval(interval);
            collector2.startCollecting();
        }, 200);

        var interval2 = setInterval(function () {
            clearInterval(interval2);
            logger.messageWithTitle(collector.name, "=====> Stopping");
            collector1_is_active = false;
            collector.stopCollecting();
        }, 500);
    });

    it('Subscriptor Should recover previously saved data', function (done) {
        var test_key = "key";
        var test_data = "Un Cohete a la Luna";

        collector = new Collector(
            redis_client,
            test_app_name,
            test_app_version,
            100,
            function (saveFn) {
                collector.stopCollecting();
                saveFn(test_key, test_data, 2000);
            });

        /** Override these parameters for testing proposes */
        collector.keep_alive_millis = 100;
        /** ********************************* **/

        subscriber = new Subscriber(
            redis_client,
            redis_client_sub,
            test_app_name,
            test_app_version,
            function (err, data) {
                assert.equal(test_data, data);
                done();
            });

        collector.startCollecting();

        var interval = setInterval(function () {
            clearInterval(interval);
            subscriber.startListening();
        }, 200);
    });

    it('Collector Should respect ttl', function (done) {
        var test_key_short_ttl = "short_key";
        var test_key_long_ttl = "long_key";
        var test_data = "Un Cohete a la Luna";

        collector = new Collector(
            redis_client,
            test_app_name,
            test_app_version,
            50,
            function (saveFn) {
                collector.stopCollecting();
                saveFn(test_key_long_ttl, test_data, 2000);
                saveFn(test_key_short_ttl, test_data);
            });

        collector.default_ttl_millis = 1;
        collector.startCollecting();

        var interval = setInterval(function () {
            clearInterval(interval);
            collector.getValue(test_key_long_ttl,
                function (err, value) {
                    assert.equal(test_data, value);

                    collector.getValue(test_key_short_ttl,
                        function (err, no_value) {
                            assert.equal(null, no_value);
                            done();
                        });
                })
        }, 200);
    });

    it('Collector Should get null value safely', function (done) {
        var test_nonexisting_key = "nonexisting_key";

        collector = new Collector(
            redis_client,
            test_app_name,
            test_app_version,
            50,
            function (saveFn) {
            });

        collector.getValue(test_nonexisting_key,
            function (err, value) {
                assert.equal(null, value);
                done();
            })
    });

    it('Subscriber Should get null value safely', function (done) {
        var test_nonexisting_key = "nonexisting_key";

        subscriber = new Subscriber(
            redis_client,
            redis_client_sub,
            test_app_name,
            test_app_version,
            function (data) {
            });

        subscriber.getValue(test_nonexisting_key,
            function (err, value) {
                assert.equal(null, value);
                done();
            })
    });

    it('Subscriber Should get all values', function (done) {
        var app_key = "app_key";

        var test_key = "key_all_values_";
        var test_data = "Un Cohete a la Luna";

        var data_count = 4;

        collector = new Collector(
            redis_client,
            test_app_name,
            test_app_version,
            10,
            function (saveFn) {
                collector.stopCollecting();
                for (var x = 0; x < data_count; x++) {
                    saveFn(test_key + x, test_data, 2000);
                }
            });

        subscriber = new Subscriber(
            redis_client,
            redis_client_sub,
            test_app_name,
            test_app_version,
            function (err, data) {
            });

        var call_count = 0;
        var interval = setInterval(function () {
            clearInterval(interval);

            subscriber.getAllValues(
                function (err, value) {
                    assert.equal(test_data, value);
                    call_count++;
                    if (call_count ==  data_count - 1) {
                        done();
                    }
                })
        }, 200);

        subscriber.startListening();
        collector.startCollecting();
    });

});
<commit_msg>Changed: test to reflect te fix;<commit_after>const test_app_name = 'test_mam';
const test_app_version = 1;

var assert = require('chai').assert;
var fakeredis = require('fakeredis');
var Collector = require('../lib/collector');
var Subscriber = require('../lib/subscriber');
var logger = require('../helper/logger');

describe('Testing Collector', function () {

    logger.mute();
    var redis_client = null;
    var redis_client_sub = null;
    var collector = null;
    var collector2 = null;
    var subscriber = null;

    beforeEach(function () {
        var redis_name = "random_" + Math.random() * 9999999;
        redis_client = fakeredis.createClient(redis_name, {fast: true});
        redis_client_sub = fakeredis.createClient(redis_name, {fast: true});
    });

    afterEach(function () {
        if (collector != null) {
            collector.stopCollecting();
            collector = null;
        }
        if (collector2 != null) {
            collector2.stopCollecting();
            collector2 = null;
        }
    });

    it('Should collect 5 times', function (done) {
        var call_count = 0;

        collector = new Collector(
            redis_client,
            test_app_name,
            test_app_version,
            5,
            function (saveFn) {
                call_count++;

                if (call_count == 5) {
                    done();
                }
            });

        collector.startCollecting();
    });

    it('Should collect 1 time, and then stop collection', function (done) {
        var call_count = 0;

        collector = new Collector(
            redis_client,
            test_app_name,
            test_app_version,
            5,
            function (saveFn) {
                call_count++;
                collector.stopCollecting();

                var timeout = setTimeout(function () {
                    if (call_count > 1) {
                        throw new Error("Should not be called more than 1 time. Was called " + call_count + " times.");
                    } else {
                        done();
                    }

                    clearTimeout(timeout);
                }, 10);
            });

        collector.startCollecting();
    });

    it('Should send data to Subscriptors', function (done) {
        var test_key = "key";
        var test_data = "Un Cohete a la Luna";

        collector = new Collector(
            redis_client,
            test_app_name,
            test_app_version,
            50,
            function (saveFn) {
                saveFn(test_key, test_data);
            }
        );

        var call_count = 0;

        subscriber = new Subscriber(
            redis_client,
            redis_client_sub,
            test_app_name,
            test_app_version,
            function (err, data) {
                if (call_count == 0) {//only execute 1 time
                    call_count++;
                    assert.equal(test_data, data);
                    collector.stopCollecting();

                    done();
                }
            });

        subscriber.startListening();
        collector.startCollecting();
    });

    it('Collector Should get saved value', function (done) {
        var test_key = "key";
        var test_data = "Un Cohete a la Luna";

        collector = new Collector(
            redis_client,
            test_app_name,
            test_app_version,
            100,
            function (saveFn) {
                collector.stopCollecting();

                saveFn(test_key, test_data, 50000, function (err, reply) {
                    if (err) {
                        throw err;
                    }

                    collector.getValue(test_key, function (err, value) {
                        if (err) {
                            throw err;
                        }

                        assert.equal(test_data, value);
                        done();
                    });
                });
            }
        );

        collector.startCollecting();
    });

    it('Subscriber Should get saved value', function (done) {
            var test_key = "key";
            var test_data = "Un Cohete a la Luna";

            collector = new Collector(
                redis_client,
                test_app_name,
                test_app_version,
                50,
                function (saveFn) {
                    saveFn(test_key, test_data, 5000);
                    collector.stopCollecting();
                }
            );

            subscriber = new Subscriber(
                redis_client,
                redis_client_sub,
                test_app_name,
                test_app_version,
                function (err, data) {
                    subscriber.getValue(test_key, function (err, value) {
                        if (err) {
                            throw err;
                        }

                        assert.equal(test_data, value);
                        done();
                    });
                });

            subscriber.startListening();
            collector.startCollecting();
        }
    );

    it('Collector 2 should become master', function (done) {

        var collector1_is_active = true;

        collector = new Collector(
            redis_client,
            test_app_name,
            test_app_version,
            50,
            function (saveFn) {
                logger.messageWithTitle(collector.name, "onCollect()");
            }
        );

        collector2 = new Collector(
            redis_client,
            test_app_name,
            test_app_version,
            50,
            function (saveFn) {
                if (collector1_is_active) {
                    throw new Error(collector.name + " is still active!");
                } else {
                    done();
                }
            }
        );

        logger.messageWithTitle(collector.name, "Starting");

        /** Override these parameters for testing proposes */
        collector.keep_alive_millis = 200;
        collector2.keep_alive_millis = 200;
        /** ********************************* **/

        collector.startCollecting();

        var interval = setInterval(function () {
            clearInterval(interval);
            collector2.startCollecting();
        }, 200);

        var interval2 = setInterval(function () {
            clearInterval(interval2);
            logger.messageWithTitle(collector.name, "=====> Stopping");
            collector1_is_active = false;
            collector.stopCollecting();
        }, 500);
    });

    it('Subscriptor Should recover previously saved data', function (done) {
        var test_key = "key";
        var test_data = "Un Cohete a la Luna";

        collector = new Collector(
            redis_client,
            test_app_name,
            test_app_version,
            100,
            function (saveFn) {
                collector.stopCollecting();
                saveFn(test_key, test_data, 2000);
            });

        /** Override these parameters for testing proposes */
        collector.keep_alive_millis = 100;
        /** ********************************* **/

        subscriber = new Subscriber(
            redis_client,
            redis_client_sub,
            test_app_name,
            test_app_version,
            function (err, data) {
                assert.equal(test_data, data);
                done();
            });

        collector.startCollecting();

        var interval = setInterval(function () {
            clearInterval(interval);
            subscriber.startListening();
        }, 200);
    });

    it('Collector Should respect ttl', function (done) {
        var test_key_short_ttl = "short_key";
        var test_key_long_ttl = "long_key";
        var test_data = "Un Cohete a la Luna";

        collector = new Collector(
            redis_client,
            test_app_name,
            test_app_version,
            50,
            function (saveFn) {
                collector.stopCollecting();
                saveFn(test_key_long_ttl, test_data, 2000);
                saveFn(test_key_short_ttl, test_data);
            });

        collector.default_ttl_millis = 1;
        collector.startCollecting();

        var interval = setInterval(function () {
            clearInterval(interval);
            collector.getValue(test_key_long_ttl,
                function (err, value) {
                    assert.equal(test_data, value);

                    collector.getValue(test_key_short_ttl,
                        function (err, no_value) {
                            assert.equal(null, no_value);
                            done();
                        });
                })
        }, 200);
    });

    it('Collector Should get null value safely', function (done) {
        var test_nonexisting_key = "nonexisting_key";

        collector = new Collector(
            redis_client,
            test_app_name,
            test_app_version,
            50,
            function (saveFn) {
            });

        collector.getValue(test_nonexisting_key,
            function (err, value) {
                assert.equal(null, value);
                done();
            })
    });

    it('Subscriber Should get null value safely', function (done) {
        var test_nonexisting_key = "nonexisting_key";

        subscriber = new Subscriber(
            redis_client,
            redis_client_sub,
            test_app_name,
            test_app_version,
            function (data) {
            });

        subscriber.getValue(test_nonexisting_key,
            function (err, value) {
                assert.equal(null, value);
                done();
            })
    });

    it('Subscriber Should get all values', function (done) {
        var app_key = "app_key";

        var test_key = "key_all_values_";
        var test_data = "Un Cohete a la Luna";

        var data_count = 40;

        collector = new Collector(
            redis_client,
            test_app_name,
            test_app_version,
            10,
            function (saveFn) {
                collector.stopCollecting();
                for (var x = 0; x < data_count; x++) {
                    saveFn(test_key + x, test_data, 2000);
                }
            });

        subscriber = new Subscriber(
            redis_client,
            redis_client_sub,
            test_app_name,
            test_app_version,
            function (err, data) {
            });

        var call_count = 0;
        var interval = setInterval(function () {
            clearInterval(interval);

            subscriber.getAllValues(
                function (err, value) {
                    assert.equal(test_data, value);
                    call_count++;
                    if (call_count ==  data_count - 1) {
                        done();
                    }
                })
        }, 200);

        subscriber.startListening();
        collector.startCollecting();
    }).timeout(5000);

});
<|endoftext|>


<commit_before>/*
	Snapper unit tests - using qUnit
*/

window.onload = function(){
	/* TESTS HERE */

	//snapper tests
	test( 'API Properties: $.fn.snapper is a function', function() {
		ok( typeof( $.fn.snapper ) === "function" );
	});

	asyncTest( 'Enhancement steps', function() {
		$(function(){
			$( ".snapper" ).snapper();
			start();
			ok($(".snapper_nextprev").length, "next prev generated");
			ok($(".snapper_nextprev a").length === 2, "2 next prev links");
		});

	});

	asyncTest( 'thumbnail clicks cause pane to scroll', function() {
		$(".snapper").snapper();
		expect(1);
		$(".snapper_pane")[0].scrollLeft = 0;
		 $(".snapper_nav a").last().trigger( "click" );
		 setTimeout(function(){
			 ok( $(".snapper_pane")[0].scrollLeft !== 0, "scroll changed" );
		 	 start();
		 },1000);
	});

	asyncTest( 'Arrows navigate', function() {
		$(".snapper").snapper();
		expect(1);
		$(".snapper_pane")[0].scrollLeft = 0;

		 setTimeout(function(){
			 ok( $(".snapper_pane")[0].scrollLeft !== 0, "scroll changed" );
		 	 start();
		 },2000);
		 setTimeout(() => {
			$(".snapper_nextprev_next").click();
		 }, 1000);
	});

	asyncTest( 'Arrows navigate back', function() {
		$(".snapper").snapper();
		expect(2);
		$(".snapper_pane")[0].scrollLeft = 0;

		setTimeout(function(){
			ok( $(".snapper_pane")[0].scrollLeft === 0, "scroll changed" );
			 start();
		},4000);

		 setTimeout(function(){
			 ok( $(".snapper_pane")[0].scrollLeft !== 0, "scroll changed" );
			 $(".snapper_nextprev_prev").click();
		 },2000);

		 setTimeout(function(){
			$(".snapper_nextprev_next").click();
		 }, 1000);
	});

	asyncTest( 'random # link clicks are ignored', function() {
		$(".snapper").snapper();
		expect(1);
		$("#testlink").trigger( "click" );
		ok( true );
		start();
	});

	asyncTest( 'get index returns correct index after goto', function(){
		var $snapper = $(".snapper").snapper();
		expect(1);

		setTimeout(function(){
			equal($snapper.snapper("getIndex"), 1);
			start();
		}, 2000);

		$snapper.snapper("goto", 1);
	});

	asyncTest( 'autoplay advances a few times once started', function(){
		expect(2);
		var eventCounter = 0;
		var checkBinding;
		var $snapperElem = $(".snapper");
		var $snapper;

		$snapperElem.attr( "data-snapper-autoplay", "500" );

		$snapperElem.bind("snapper.after-goto", checkBinding = function(){
			ok(true, "after-goto called");

			if(++eventCounter === 2){
				$snapperElem.removeAttr( "data-snapper-autoplay" );
				$(document).unbind("snapper.after-goto", checkBinding);
				start();
			}
		});

		$snapperElem.snapper();
	});

};
<commit_msg>test loops<commit_after>/*
	Snapper unit tests - using qUnit
*/

window.onload = function(){
	/* TESTS HERE */

	//snapper tests
	test( 'API Properties: $.fn.snapper is a function', function() {
		ok( typeof( $.fn.snapper ) === "function" );
	});

	asyncTest( 'Enhancement steps', function() {
		$(function(){
			$( ".snapper" ).snapper();
			start();
			ok($(".snapper_nextprev").length, "next prev generated");
			ok($(".snapper_nextprev a").length === 2, "2 next prev links");
		});

	});

	asyncTest( 'thumbnail clicks cause pane to scroll', function() {
		$(".snapper").snapper();
		expect(1);
		$(".snapper_pane")[0].scrollLeft = 0;
		 $(".snapper_nav a").last().trigger( "click" );
		 setTimeout(function(){
			 ok( $(".snapper_pane")[0].scrollLeft !== 0, "scroll changed" );
		 	 start();
		 },1000);
	});

	asyncTest( 'Arrows navigate', function() {
		$(".snapper").snapper();
		expect(1);
		$(".snapper_pane")[0].scrollLeft = 0;

		 setTimeout(function(){
			 ok( $(".snapper_pane")[0].scrollLeft !== 0, "scroll changed" );
		 	 start();
		 },2000);
		 setTimeout(() => {
			$(".snapper_nextprev_next").click();
		 }, 1000);
	});

	asyncTest( 'Arrows navigate back', function() {
		$(".snapper").snapper();
		expect(2);
		$(".snapper_pane")[0].scrollLeft = 0;

		setTimeout(function(){
			ok( $(".snapper_pane")[0].scrollLeft === 0, "scroll changed" );
			 start();
		},4000);

		 setTimeout(function(){
			 ok( $(".snapper_pane")[0].scrollLeft !== 0, "scroll changed" );
			 $(".snapper_nextprev_prev").click();
		 },2000);

		 setTimeout(function(){
			$(".snapper_nextprev_next").click();
		 }, 1000);
	});

	asyncTest( 'random # link clicks are ignored', function() {
		$(".snapper").snapper();
		expect(1);
		$("#testlink").trigger( "click" );
		ok( true );
		start();
	});

	asyncTest( 'get index returns correct index after goto', function(){
		var $snapper = $(".snapper").snapper();
		expect(1);

		setTimeout(function(){
			equal($snapper.snapper("getIndex"), 1);
			start();
		}, 2000);

		$snapper.snapper("goto", 1);
	});

	asyncTest( 'autoplay advances a few times once started', function(){
		expect(2);
		var eventCounter = 0;
		var checkBinding;
		var $snapperElem = $(".snapper");
		var $snapper;

		$snapperElem.attr( "data-snapper-autoplay", "500" );

		$snapperElem.bind("snapper.after-goto", checkBinding = function(){
			ok(true, "after-goto called");

			if(++eventCounter === 2){
				$snapperElem.removeAttr( "data-snapper-autoplay" );
				$(document).unbind("snapper.after-goto", checkBinding);
				start();
			}
		});

		$snapperElem.snapper();
	});

	asyncTest( 'looping goes endlessly forward', function(){
		expect(5);
		var eventCounter = 0;
		var checkBinding;
		var $snapperElem = $(".snapper");
		var $snapper;

		$snapperElem.attr( "data-snapper-loop", "500" );

		$snapperElem.bind("snapper.after-next", checkBinding = function(){
			ok(true, "after-next called");

			if(++eventCounter === 5){
				$snapperElem.removeAttr( "data-snapper-loop" );
				$(document).unbind("snapper.after-goto", checkBinding);
				start();
			}
			else{
				$(".snapper_nextprev_next").click();
			}
		});

		$snapperElem.snapper();
		setTimeout(() => {
			$(".snapper_nextprev_next").click();
		 }, 500);
	});

	asyncTest( 'looping goes endlessly in reverse', function(){
		expect(5);
		var eventCounter = 0;
		var checkBinding;
		var $snapperElem = $(".snapper");
		var $snapper;

		$snapperElem.attr( "data-snapper-loop", "500" );

		$snapperElem.bind("snapper.after-prev", checkBinding = function(){
			ok(true, "after-prev called");

			if(++eventCounter === 5){
				$snapperElem.removeAttr( "data-snapper-loop" );
				$(document).unbind("snapper.after-goto", checkBinding);
				start();
			}
			else{
				$(".snapper_nextprev_prev").click();
			}
		});

		$snapperElem.snapper();
		setTimeout(() => {
			$(".snapper_nextprev_prev").click();
		 }, 500);
	});

};
<|endoftext|>


<commit_before>module('read', lifecycle);

test('simple value', function () {
	expect(1);
	document.cookie = 'c=v';
	strictEqual(Cookies.get('c'), 'v', 'should return value');
});

test('empty value', function () {
	expect(1);
	// IE saves cookies with empty string as "c; ", e.g. without "=" as opposed to EOMB, which
	// resulted in a bug while reading such a cookie.
	Cookies.set('c', '');
	strictEqual(Cookies.get('c'), '', 'should return value');
});

test('not existing', function () {
	expect(1);
	strictEqual(Cookies.get('whatever'), undefined, 'return undefined');
});

// github.com/carhartl/jquery-cookie/issues/50
test('equality sign in cookie value', function () {
	expect(1);
	Cookies.set('c', 'foo=bar');
	strictEqual(Cookies.get('c'), 'foo=bar', 'should include the entire value');
});

test('percent character in cookie value', function () {
	expect(1);
	document.cookie = 'bad=foo%';
	strictEqual(Cookies.get('bad'), 'foo%', 'should read the percent character');
});

test('percent character in cookie value mixed with encoded values', function () {
	expect(1);
	document.cookie = 'bad=foo%bar%22baz%bax%3D';
	strictEqual(Cookies.get('bad'), 'foo%bar"baz%bax=', 'should read the percent character');
});

asyncTest('malformed cookie value in IE (#88, #117)', function () {
	expect(1);
	// Sandbox in an iframe so that we can poke around with document.cookie.
	var iframe = document.createElement('iframe');
	var addEvent = function (element, eventName, fn) {
		var method = "addEventListener";
		if (element.attachEvent) {
			eventName = 'on' + eventName;
			method = "attachEvent";
		}
		element[ method ](eventName, fn);
	};
	iframe.src = 'malformed_cookie.html';
	addEvent(iframe, 'load', function () {
		start();
		if (iframe.contentWindow.ok) {
			strictEqual(iframe.contentWindow.testValue, 'two', 'reads all cookie values, skipping duplicate occurences of "; "');
		} else {
			// Skip the test where we can't stub document.cookie using
			// Object.defineProperty. Seems to work fine in
			// Chrome, Firefox and IE 8+.
			ok(true, 'N/A');
		}
	});
	document.body.appendChild(iframe);
});

test('Call to read all when there are cookies', function () {
	Cookies.set('c', 'v');
	Cookies.set('foo', 'bar');
	deepEqual(Cookies.get(), { c: 'v', foo: 'bar' }, 'returns object containing all cookies');
});

test('Call to read all when there are no cookies at all', function () {
	deepEqual(Cookies.get(), {}, 'returns empty object');
});

// github.com/carhartl/jquery-cookie/pull/166
test('provide a way for decoding chinese characters', function () {
	expect(1);
	document.cookie = 'c=%u5317%u4eac';
	var actual = Cookies.get('c', function (value) {
		return unescape(value);
	});
	strictEqual(actual, '北京', 'should convert chinese characters correctly');
});

module('write', lifecycle);

test('String primitive', function () {
	expect(1);
	Cookies.set('c', 'v');
	strictEqual(Cookies.get('c'), 'v', 'should write value');
});

test('String object', function () {
	expect(1);
	Cookies.set('c', new String('v'));
	strictEqual(Cookies.get('c'), 'v', 'should write value');
});

test('value "[object Object]"', function () {
	expect(1);
	Cookies.set('c', '[object Object]');
	strictEqual(Cookies.get('c'), '[object Object]', 'should write value');
});

test('number', function () {
	expect(1);
	Cookies.set('c', 1234);
	strictEqual(Cookies.get('c'), '1234', 'should write value');
});

test('null', function () {
	expect(1);
	Cookies.set('c', null);
	strictEqual(Cookies.get('c'), 'null', 'should write value');
});

test('undefined', function () {
	expect(1);
	Cookies.set('c', undefined);
	strictEqual(Cookies.get('c'), 'undefined', 'should write value');
});

test('expires option as days from now', function () {
	expect(1);
	var sevenDaysFromNow = new Date();
	sevenDaysFromNow.setDate(sevenDaysFromNow.getDate() + 21);
	strictEqual(Cookies.set('c', 'v', { expires: 21 }), 'c=v; expires=' + sevenDaysFromNow.toUTCString(),
		'should write the cookie string with expires');
});

test('expires option as fraction of a day', function () {
	expect(1);

	var now = new Date().getTime();
	var expires = Date.parse(Cookies.set('c', 'v', { expires: 0.5 }).replace(/.+expires=/, ''));

	// When we were using Date.setDate() fractions have been ignored
	// and expires resulted in the current date. Allow 1000 milliseconds
	// difference for execution time.
	ok(expires > now + 1000, 'should write expires attribute with the correct date');
});

test('expires option as Date instance', function () {
	expect(1);
	var sevenDaysFromNow = new Date();
	sevenDaysFromNow.setDate(sevenDaysFromNow.getDate() + 7);
	strictEqual(Cookies.set('c', 'v', { expires: sevenDaysFromNow }), 'c=v; expires=' + sevenDaysFromNow.toUTCString(),
		'should write the cookie string with expires');
});

test('return value', function () {
	expect(1);
	strictEqual(Cookies.set('c', 'v'), 'c=v', 'should return written cookie string');
});

test('defaults', function () {
	expect(2);
	Cookies.defaults.path = '/foo';
	ok(Cookies.set('c', 'v').match(/path=\/foo/), 'should use options from defaults');
	ok(Cookies.set('c', 'v', { path: '/bar' }).match(/path=\/bar/), 'options argument has precedence');
});

module('removeCookie', lifecycle);

test('deletion', function () {
	expect(1);
	Cookies.set('c', 'v');
	Cookies.remove('c');
	strictEqual(document.cookie, '', 'should delete the cookie');
});

test('when sucessfully deleted', function () {
	expect(1);
	Cookies.set('c', 'v');
	strictEqual(Cookies.remove('c'), true, 'returns true');
});

test('when cookie does not exist', function () {
	expect(1);
	strictEqual(Cookies.remove('c'), true, 'returns true');
});

test('with options', function () {
	expect(1);
	var options = { path: '/' };
	Cookies.set('c', 'v', options);
	Cookies.remove('c', options);
	strictEqual(document.cookie, '', 'should delete the cookie');
});

test('passing options reference', function () {
	expect(1);
	var options = { path: '/' };
	Cookies.set('c', 'v', options);
	Cookies.remove('c', options);
	deepEqual(options, { path: '/' }, "won't alter options object");
});

// TODO: Need to handle this without the raw option because [] are not allowed in cookie-name
// github.com/carhartl/jquery-cookie/issues/155
//test('[] used in name', function () {
//	expect(1);
//	document.cookie = 'c[1]=foo';
//	Cookies.remove('c[1]');
//	strictEqual(document.cookie, '', 'delete the cookie');
//});

module('converters', lifecycle);

test('read converter', function () {
	expect(1);
	Cookies.set('c', '1');
	strictEqual(Cookies.get('c', Number), 1, 'converts read value');
});

module('JSON handling', lifecycle);

test('Number', function () {
	expect(2);
	Cookies.set('c', 1);
	strictEqual(Cookies.getJSON('c'), 1, 'should handle a Number');
	strictEqual(Cookies.get('c'), '1', 'should return a String');
});

test('Boolean', function () {
	expect(2);
	Cookies.set('c', true);
	strictEqual(Cookies.getJSON('c'), true, 'should handle a Boolean');
	strictEqual(Cookies.get('c'), 'true', 'should return a Boolean');
});

test('Array Literal', function () {
	expect(2);
	Cookies.set('c', ['v']);
	deepEqual(Cookies.getJSON('c'), ['v'], 'should handle Array Literal');
	strictEqual(Cookies.get('c'), '["v"]', 'should return a String');
});

test('Array Constructor', function () {
	/*jshint -W009 */
	expect(2);
	var value = new Array();
	value[0] = 'v';
	Cookies.set('c', value);
	deepEqual(Cookies.getJSON('c'), ['v'], 'should handle Array Constructor');
	strictEqual(Cookies.get('c'), '["v"]', 'should return a String');
});

test('Object Literal', function () {
	expect(2);
	Cookies.set('c', {k: 'v'});
	deepEqual(Cookies.getJSON('c'), {k: 'v'}, 'should handle Object Literal');
	strictEqual(Cookies.get('c'), '{"k":"v"}', 'should return a String');
});

test('Object Constructor', function () {
	/*jshint -W010 */
	expect(2);
	var value = new Object();
	value.k = 'v';
	Cookies.set('c', value);
	deepEqual(Cookies.getJSON('c'), {k: 'v'}, 'should handle Object Constructor');
	strictEqual(Cookies.get('c'), '{"k":"v"}', 'should return a String');
});

test('Use String(value) for unsupported objects that do not stringify into JSON', function() {
	expect(4);

	Cookies.set('date', new Date(2015, 04, 13, 0, 0, 0, 0));
	strictEqual(Cookies.get('date').indexOf('"'), -1, 'should not quote the stringified Date object');
	strictEqual(Cookies.getJSON('date').indexOf('"'), -1, 'should not quote the stringified Date object');

	Cookies.set('function', function (){});
	strictEqual(Cookies.get('function'), undefined, 'should return undefined for function object');
	strictEqual(Cookies.getJSON('function'), undefined, 'should return undefined for function object');
});

test('Call to read all cookies with mixed json', function () {
	Cookies.set('c', { foo: 'bar' });
	Cookies.set('c2', 'v');
	deepEqual(Cookies.getJSON(), { c: { foo: 'bar' }, c2: 'v' }, 'returns JSON parsed cookies');
	deepEqual(Cookies.get(), { c: '{"foo":"bar"}', c2: 'v' }, 'returns unparsed cookies');
});
<commit_msg>Mode the 'cookie-octet enclosed in DQUOTE' test to tests.js<commit_after>module('read', lifecycle);

test('simple value', function () {
	expect(1);
	document.cookie = 'c=v';
	strictEqual(Cookies.get('c'), 'v', 'should return value');
});

test('empty value', function () {
	expect(1);
	// IE saves cookies with empty string as "c; ", e.g. without "=" as opposed to EOMB, which
	// resulted in a bug while reading such a cookie.
	Cookies.set('c', '');
	strictEqual(Cookies.get('c'), '', 'should return value');
});

test('not existing', function () {
	expect(1);
	strictEqual(Cookies.get('whatever'), undefined, 'return undefined');
});

// github.com/carhartl/jquery-cookie/issues/50
test('equality sign in cookie value', function () {
	expect(1);
	Cookies.set('c', 'foo=bar');
	strictEqual(Cookies.get('c'), 'foo=bar', 'should include the entire value');
});

// github.com/carhartl/jquery-cookie/issues/215
test('percent character in cookie value', function () {
	expect(1);
	document.cookie = 'bad=foo%';
	strictEqual(Cookies.get('bad'), 'foo%', 'should read the percent character');
});

test('percent character in cookie value mixed with encoded values', function () {
	expect(1);
	document.cookie = 'bad=foo%bar%22baz%bax%3D';
	strictEqual(Cookies.get('bad'), 'foo%bar"baz%bax=', 'should read the percent character');
});

// github.com/carhartl/jquery-cookie/pull/88
// github.com/carhartl/jquery-cookie/pull/117
asyncTest('malformed cookie value in IE', function () {
	expect(1);
	// Sandbox in an iframe so that we can poke around with document.cookie.
	var iframe = document.createElement('iframe');
	var addEvent = function (element, eventName, fn) {
		var method = "addEventListener";
		if (element.attachEvent) {
			eventName = 'on' + eventName;
			method = "attachEvent";
		}
		element[ method ](eventName, fn);
	};
	iframe.src = 'malformed_cookie.html';
	addEvent(iframe, 'load', function () {
		start();
		if (iframe.contentWindow.ok) {
			strictEqual(iframe.contentWindow.testValue, 'two', 'reads all cookie values, skipping duplicate occurences of "; "');
		} else {
			// Skip the test where we can't stub document.cookie using
			// Object.defineProperty. Seems to work fine in
			// Chrome, Firefox and IE 8+.
			ok(true, 'N/A');
		}
	});
	document.body.appendChild(iframe);
});

test('Call to read all when there are cookies', function () {
	Cookies.set('c', 'v');
	Cookies.set('foo', 'bar');
	deepEqual(Cookies.get(), { c: 'v', foo: 'bar' }, 'returns object containing all cookies');
});

test('Call to read all when there are no cookies at all', function () {
	deepEqual(Cookies.get(), {}, 'returns empty object');
});

// github.com/carhartl/jquery-cookie/pull/166
test('provide a way for decoding characters encoded by the escape function', function () {
	expect(1);
	document.cookie = 'c=%u5317%u4eac';
	var actual = Cookies.get('c', function (value) {
		return unescape(value);
	});
	strictEqual(actual, '北京', 'should convert chinese characters correctly');
});

test('RFC 6265 - reading cookie-octet enclosed in DQUOTE', function () {
	expect(1);
	document.cookie = 'c="v"';
	strictEqual(Cookies.get('c'), 'v', 'should simply ignore quoted strings');
});

module('write', lifecycle);

test('String primitive', function () {
	expect(1);
	Cookies.set('c', 'v');
	strictEqual(Cookies.get('c'), 'v', 'should write value');
});

test('String object', function () {
	expect(1);
	Cookies.set('c', new String('v'));
	strictEqual(Cookies.get('c'), 'v', 'should write value');
});

test('value "[object Object]"', function () {
	expect(1);
	Cookies.set('c', '[object Object]');
	strictEqual(Cookies.get('c'), '[object Object]', 'should write value');
});

test('number', function () {
	expect(1);
	Cookies.set('c', 1234);
	strictEqual(Cookies.get('c'), '1234', 'should write value');
});

test('null', function () {
	expect(1);
	Cookies.set('c', null);
	strictEqual(Cookies.get('c'), 'null', 'should write value');
});

test('undefined', function () {
	expect(1);
	Cookies.set('c', undefined);
	strictEqual(Cookies.get('c'), 'undefined', 'should write value');
});

test('expires option as days from now', function () {
	expect(1);
	var sevenDaysFromNow = new Date();
	sevenDaysFromNow.setDate(sevenDaysFromNow.getDate() + 21);
	strictEqual(Cookies.set('c', 'v', { expires: 21 }), 'c=v; expires=' + sevenDaysFromNow.toUTCString(),
		'should write the cookie string with expires');
});

test('expires option as fraction of a day', function () {
	expect(1);

	var now = new Date().getTime();
	var expires = Date.parse(Cookies.set('c', 'v', { expires: 0.5 }).replace(/.+expires=/, ''));

	// When we were using Date.setDate() fractions have been ignored
	// and expires resulted in the current date. Allow 1000 milliseconds
	// difference for execution time.
	ok(expires > now + 1000, 'should write expires attribute with the correct date');
});

test('expires option as Date instance', function () {
	expect(1);
	var sevenDaysFromNow = new Date();
	sevenDaysFromNow.setDate(sevenDaysFromNow.getDate() + 7);
	strictEqual(Cookies.set('c', 'v', { expires: sevenDaysFromNow }), 'c=v; expires=' + sevenDaysFromNow.toUTCString(),
		'should write the cookie string with expires');
});

test('return value', function () {
	expect(1);
	strictEqual(Cookies.set('c', 'v'), 'c=v', 'should return written cookie string');
});

test('defaults', function () {
	expect(2);
	Cookies.defaults.path = '/foo';
	ok(Cookies.set('c', 'v').match(/path=\/foo/), 'should use options from defaults');
	ok(Cookies.set('c', 'v', { path: '/bar' }).match(/path=\/bar/), 'options argument has precedence');
});

module('removeCookie', lifecycle);

test('deletion', function () {
	expect(1);
	Cookies.set('c', 'v');
	Cookies.remove('c');
	strictEqual(document.cookie, '', 'should delete the cookie');
});

test('when sucessfully deleted', function () {
	expect(1);
	Cookies.set('c', 'v');
	strictEqual(Cookies.remove('c'), true, 'returns true');
});

test('when cookie does not exist', function () {
	expect(1);
	strictEqual(Cookies.remove('c'), true, 'returns true');
});

test('with options', function () {
	expect(1);
	var options = { path: '/' };
	Cookies.set('c', 'v', options);
	Cookies.remove('c', options);
	strictEqual(document.cookie, '', 'should delete the cookie');
});

test('passing options reference', function () {
	expect(1);
	var options = { path: '/' };
	Cookies.set('c', 'v', options);
	Cookies.remove('c', options);
	deepEqual(options, { path: '/' }, "won't alter options object");
});

// TODO: Need to handle this without the raw option because [] are not allowed in cookie-name
// github.com/carhartl/jquery-cookie/issues/155
//test('[] used in name', function () {
//	expect(1);
//	document.cookie = 'c[1]=foo';
//	Cookies.remove('c[1]');
//	strictEqual(document.cookie, '', 'delete the cookie');
//});

module('converters', lifecycle);

test('read converter', function () {
	expect(1);
	Cookies.set('c', '1');
	strictEqual(Cookies.get('c', Number), 1, 'converts read value');
});

module('JSON handling', lifecycle);

test('Number', function () {
	expect(2);
	Cookies.set('c', 1);
	strictEqual(Cookies.getJSON('c'), 1, 'should handle a Number');
	strictEqual(Cookies.get('c'), '1', 'should return a String');
});

test('Boolean', function () {
	expect(2);
	Cookies.set('c', true);
	strictEqual(Cookies.getJSON('c'), true, 'should handle a Boolean');
	strictEqual(Cookies.get('c'), 'true', 'should return a Boolean');
});

test('Array Literal', function () {
	expect(2);
	Cookies.set('c', ['v']);
	deepEqual(Cookies.getJSON('c'), ['v'], 'should handle Array Literal');
	strictEqual(Cookies.get('c'), '["v"]', 'should return a String');
});

test('Array Constructor', function () {
	/*jshint -W009 */
	expect(2);
	var value = new Array();
	value[0] = 'v';
	Cookies.set('c', value);
	deepEqual(Cookies.getJSON('c'), ['v'], 'should handle Array Constructor');
	strictEqual(Cookies.get('c'), '["v"]', 'should return a String');
});

test('Object Literal', function () {
	expect(2);
	Cookies.set('c', {k: 'v'});
	deepEqual(Cookies.getJSON('c'), {k: 'v'}, 'should handle Object Literal');
	strictEqual(Cookies.get('c'), '{"k":"v"}', 'should return a String');
});

test('Object Constructor', function () {
	/*jshint -W010 */
	expect(2);
	var value = new Object();
	value.k = 'v';
	Cookies.set('c', value);
	deepEqual(Cookies.getJSON('c'), {k: 'v'}, 'should handle Object Constructor');
	strictEqual(Cookies.get('c'), '{"k":"v"}', 'should return a String');
});

test('Use String(value) for unsupported objects that do not stringify into JSON', function() {
	expect(4);

	Cookies.set('date', new Date(2015, 04, 13, 0, 0, 0, 0));
	strictEqual(Cookies.get('date').indexOf('"'), -1, 'should not quote the stringified Date object');
	strictEqual(Cookies.getJSON('date').indexOf('"'), -1, 'should not quote the stringified Date object');

	Cookies.set('function', function (){});
	strictEqual(Cookies.get('function'), undefined, 'should return undefined for function object');
	strictEqual(Cookies.getJSON('function'), undefined, 'should return undefined for function object');
});

test('Call to read all cookies with mixed json', function () {
	Cookies.set('c', { foo: 'bar' });
	Cookies.set('c2', 'v');
	deepEqual(Cookies.getJSON(), { c: { foo: 'bar' }, c2: 'v' }, 'returns JSON parsed cookies');
	deepEqual(Cookies.get(), { c: '{"foo":"bar"}', c2: 'v' }, 'returns unparsed cookies');
});
<|endoftext|>


<commit_before>/*jshint strict:false */

var
    assert = chai.assert,
    http = httpplease,
    plugins = httppleaseplugins,
    testServerUrl = 'http://localhost:4001';

describe('httpplease', function () {
    it('performs a get request', function (done) {
        http.get(testServerUrl + '/getjson', function (err, res) {
            assert.equal(res.text, JSON.stringify({
                hello: 'world'
            }));
            done();
        });
    });
    it('identifies errors', function (done) {
        http.get(testServerUrl + '/404', function (err, res) {
            assert.equal(err.status, 404);
            assert(err.isHttpError);
            done();
        });
    });
    it('obeys the errorOn404 option', function (done) {
        http.get({
            url: '' + testServerUrl + '/404',
            errorOn404: false
        }, function (err, res) {
            assert.isUndefined(err);
            assert(res.isHttpError);
            done();
        });
    });
    it('sends headers', function (done) {
        var req;
        req = {
            url: '' + testServerUrl + '/headers',
            headers: {
                hello: 'world'
            }
        };
        http.get(req, function (err, res) {
            var json;
            json = JSON.parse(res.text);
            assert.equal(json.hello, 'world');
            done();
        });
    });
    describe('defaults', function () {
        it('adds defaults', function () {
            assert.equal(http.defaults({
                dummy: 5
            }).defaults().dummy, 5);
        });
        it("doesn't mutate the http function", function () {
            http.defaults({
                dummy: 5
            });
            assert.isUndefined(http.defaults().dummy);
        });
    });
    describe('use', function () {
        it('adds a plugin', function () {
            var startCount;
            startCount = http.plugins().length;
            assert.equal(http.use({}).plugins().length, startCount + 1);
        });
        it("doesn't mutate the http function", function () {
            var startCount;
            startCount = http.plugins().length;
            http.use({});
            assert.equal(http.plugins().length, startCount);
        });
    });
    describe('bare', function () {
        it('creates a http function without plugins', function () {
            assert.equal(http.use({}).bare().plugins().length, 0);
        });
    });
});

describe('plugins', function () {
    describe('jsonparser', function () {
        it('is used for error responses', function (done) {
            http.use(plugins.jsonparser).get('' + testServerUrl + '/404', function (err, res) {
                assert.deepEqual(err.body, {
                    sad: 'panda'
                });
                done();
            });
        });
        it('parses json responses', function (done) {
            http.use(plugins.jsonparser).get('' + testServerUrl + '/getjson', function (err, res) {
                assert.deepEqual(res.body, {
                    hello: 'world'
                });
                done();
            });
        });
        function parseWithContentType(ct, isJsonType) {
            var res;
            if (isJsonType == null) {
                isJsonType = true;
            }
            res = {
                contentType: ct,
                body: '{"hello": "world"}'
            };
            plugins.jsonparser.processResponse(res);
            if (isJsonType) {
                assert.deepEqual(res.body, {
                    hello: 'world'
                });
            } else {
                assert.equal(res.body, '{"hello": "world"}');
            }
        }
        it('honors the content type', function () {
            parseWithContentType('application/json');
            parseWithContentType('text/json');
            parseWithContentType('text/json');
            parseWithContentType('text/something+json');
            parseWithContentType('application/json; charset=utf-8');
            parseWithContentType('application/jsonp', false);
        });
    });
    describe('jsonrequest', function () {
        it('formats the request', function () {
            var req;
            req = new http.Request({
                body: {
                    hello: 'world'
                }
            });
            plugins.jsonrequest.processRequest(req);
            assert.equal(req.body, '{"hello":"world"}');
            assert.equal(req.header('Content-Type'), 'application/json');
        });
    });
});
<commit_msg>Fix linter config<commit_after>/*globals chai, httpplease, httppleaseplugins, describe, it */
'use strict';

var
    assert = chai.assert,
    http = httpplease,
    plugins = httppleaseplugins,
    testServerUrl = 'http://localhost:4001';

describe('httpplease', function () {
    it('performs a get request', function (done) {
        http.get(testServerUrl + '/getjson', function (err, res) {
            assert.equal(res.text, JSON.stringify({
                hello: 'world'
            }));
            done();
        });
    });
    it('identifies errors', function (done) {
        http.get(testServerUrl + '/404', function (err, res) {
            assert.equal(err.status, 404);
            assert(err.isHttpError);
            done();
        });
    });
    it('obeys the errorOn404 option', function (done) {
        http.get({
            url: '' + testServerUrl + '/404',
            errorOn404: false
        }, function (err, res) {
            assert.isUndefined(err);
            assert(res.isHttpError);
            done();
        });
    });
    it('sends headers', function (done) {
        var req;
        req = {
            url: '' + testServerUrl + '/headers',
            headers: {
                hello: 'world'
            }
        };
        http.get(req, function (err, res) {
            var json;
            json = JSON.parse(res.text);
            assert.equal(json.hello, 'world');
            done();
        });
    });
    describe('defaults', function () {
        it('adds defaults', function () {
            assert.equal(http.defaults({
                dummy: 5
            }).defaults().dummy, 5);
        });
        it("doesn't mutate the http function", function () {
            http.defaults({
                dummy: 5
            });
            assert.isUndefined(http.defaults().dummy);
        });
    });
    describe('use', function () {
        it('adds a plugin', function () {
            var startCount;
            startCount = http.plugins().length;
            assert.equal(http.use({}).plugins().length, startCount + 1);
        });
        it("doesn't mutate the http function", function () {
            var startCount;
            startCount = http.plugins().length;
            http.use({});
            assert.equal(http.plugins().length, startCount);
        });
    });
    describe('bare', function () {
        it('creates a http function without plugins', function () {
            assert.equal(http.use({}).bare().plugins().length, 0);
        });
    });
});

describe('plugins', function () {
    describe('jsonparser', function () {
        it('is used for error responses', function (done) {
            http.use(plugins.jsonparser).get('' + testServerUrl + '/404', function (err, res) {
                assert.deepEqual(err.body, {
                    sad: 'panda'
                });
                done();
            });
        });
        it('parses json responses', function (done) {
            http.use(plugins.jsonparser).get('' + testServerUrl + '/getjson', function (err, res) {
                assert.deepEqual(res.body, {
                    hello: 'world'
                });
                done();
            });
        });
        function parseWithContentType(ct, isJsonType) {
            var res;
            if (isJsonType == null) {
                isJsonType = true;
            }
            res = {
                contentType: ct,
                body: '{"hello": "world"}'
            };
            plugins.jsonparser.processResponse(res);
            if (isJsonType) {
                assert.deepEqual(res.body, {
                    hello: 'world'
                });
            } else {
                assert.equal(res.body, '{"hello": "world"}');
            }
        }
        it('honors the content type', function () {
            parseWithContentType('application/json');
            parseWithContentType('text/json');
            parseWithContentType('text/json');
            parseWithContentType('text/something+json');
            parseWithContentType('application/json; charset=utf-8');
            parseWithContentType('application/jsonp', false);
        });
    });
    describe('jsonrequest', function () {
        it('formats the request', function () {
            var req;
            req = new http.Request({
                body: {
                    hello: 'world'
                }
            });
            plugins.jsonrequest.processRequest(req);
            assert.equal(req.body, '{"hello":"world"}');
            assert.equal(req.header('Content-Type'), 'application/json');
        });
    });
});
<|endoftext|>


<commit_before>'use strict';

const assert = require("chai").assert;
const pogo = require('../index.js'),
      race = pogo.race,
      chan = pogo.chan,
      put = pogo.put;
const wtf = x => console.log("wtf", x);
const sleep = ms => new Promise(awaken => setTimeout(awaken, ms));

describe("returning a value", () => {
  it("resolves the pogo's promise", () => {
    return pogo(function*() { return 123; }).then(v => assert.equal(v, 123)); });
});

describe("raising an exception", () => {
  it("rejects the pogo's promise", () => {
    return pogo(function*() { throw "bang!"; }).catch(e => assert.equal(e, "bang!"));
  });
});

describe("yielding a promise", () => {
  describe("that resolves", () => {
    it("resumes the pogo with the resolution", () => {
      return pogo(function*() { assert.equal(yield Promise.resolve(123), 123)});
    });
  });

  describe("that rejects", () => {
    it("throws the rejection back into the pogo", () => {
      return pogo(function*() {
        try { yield Promise.reject("bang!"); }
        catch (e) { assert.equal(e, "bang!") }
      });
    });
  });
});

describe("yielding a put or a take", () => {
  it("resumes the pogo with a corresponding take or put", () => {
    const ch = chan();
    pogo(function*() {
      for (let i = 0; i < 10; i++) {
        yield put(ch, i)
      }
    });
    return pogo(function*() {
      for (let i = 0; i < 10; i++) {
        assert.equal(i, yield ch);
      }
    });
  });
});

describe("race", () => {
  it("works with promises", () => {
    return pogo(function*() {
      const ret = yield race([sleep(1000), Promise.resolve("woot")]);
      assert.equal(ret, "woot");
    });
  });

  it("cancels slow alternatives", () => {
    const log = [];
    const ch1 = chan();
    const ch2 = chan();

    pogo(function*() {
      yield race([put(ch1, "first"), put(ch2, "second")]);
      log.push("put first");
      yield put(ch2, "deuxieme");
      log.push("put deuxieme");
    }).catch(wtf);

    return pogo(function*() {
      const r1 = yield race([ch1, ch2]);
      log.push("alted");
      assert.equal(r1.channel, ch1);
      assert.equal(r1.value, "first");

      const r2 = yield race([ch1, ch2]);
      log.push("alted");
      assert.equal(r2.channel, ch2);
      assert.equal(r2.value, "deuxieme");

      assert.deepEqual(log, ["put first", "alted", "put deuxieme", "alted"]);
    });
  });
});

describe("yielding a generator function", () => {
  it("works", () => {
    function* example(ch) {
      const x = yield Promise.resolve(123);

      let y;
      try { yield Promise.reject("bang!"); }
      catch (e) { y = 456; }

      const z = yield ch;

      return [x, y, z];
    }

    return pogo(function*() {
      const ch = chan();
      pogo(function*() {
        yield put(ch, "sup");
      });

      assert.deepEqual(yield example(ch), [123, 456, "sup"]);
    });
  });

  it("is safe even if you yield the same generator multiple times", () => {
    function* star(x) {
      const y = yield Promise.resolve("foo");
      const z = yield Promise.resolve("bar");
      return [x, y, z];
    }
    return pogo(function*() {
      const gen = star(123);
      assert.equal(123, yield race([gen, Promise.resolve(123)]));
      assert.equal(456, yield race([gen, Promise.resolve(456)]));
      assert.deepEqual(yield race([gen, Promise.resolve(789)]), [123, "foo", "bar"]);
    });
  });
});

describe("async/callback-based interface", () => {
  describe("putAsync", () => {
    it("works", (done) => {
      const ch = chan();
      pogo(function*() {
        assert.equal(yield ch, 123);
      });
      ch.putAsync(123, done);
    });
  });

  describe("takeAsync", () => {
    it("works", (done) => {
      const ch = chan();
      pogo(function*() {
        yield put(ch, 123);
      });
      ch.takeAsync(v => {
        assert.equal(v, 123);
        return done();
      });
    });
  });
});

describe("sharing a channel between multiple pogos", () => {
  it("works", () => {
    const log = [];
    const ch = chan();
    pogo(function*() {
      yield put(ch, "foo");
      log.push("put foo");
    }).catch(wtf);
    pogo(function*() {
      yield put(ch, "bar");
      log.push("put bar");
    }).catch(wtf);
    pogo(function*() {
      yield put(ch, "baz");
      log.push("put baz");
    }).catch(wtf);
    return pogo(function*() {
      assert.equal(yield ch, "foo");
      log.push("took foo");
      assert.equal(yield ch, "bar");
      log.push("took bar");
      assert.equal(yield ch, "baz");
      log.push("took baz");
      assert.deepEqual(log, [
        "put foo", "took foo", "put bar", "took bar", "put baz", "took baz"
      ]);
    });
  });
});

describe("puting and taking from the same channel", () => {
  it("works", () => {
    const log = [];
    const ch = chan();

    pogo(function*() {
      const ping = yield ch;
      log.push("received " + ping);
      yield pogo.put(ch, "pong");
      log.push("sent pong");
    }).catch(wtf);

    return pogo(function*() {
      yield pogo.put(ch, "ping");
      log.push("sent ping");
      const pong = yield ch;
      log.push("received " + pong);

      assert.deepEqual(log, ["received ping", "sent ping", "sent pong", "received pong"]);
    });
  });
});

describe("fairness", () => {
  it("works for a take and then a put", () => {
    const log = [];
    const ch = chan();
    pogo(function*() {
      yield ch;
      log.push("took");
    });
    return pogo(function*() {
      yield put(ch);
      log.push("put");
    }).then(() => assert.deepEqual(log, ["took", "put"]));
  });

  it("works for a put and then a take", () => {
    const log = [];
    const ch = chan();
    pogo(function*() {
      yield put(ch);
      log.push("put");
    });
    return pogo(function*() {
      yield ch;
      log.push("took");
    }).then(() => assert.deepEqual(log, ["put", "took"]));
  });
});
<commit_msg>Style.<commit_after>'use strict';

import { assert } from 'chai'
import pogo, { chan, put, race } from '../index.js'

const wtf = x => console.log('wtf', x)
const sleep = ms => new Promise(awaken => setTimeout(awaken, ms))

describe('returning a value', () => {
  it("resolves the pogo's promise", () => {
    return pogo(function*() {
      return 123
    }).then(v => assert.equal(v, 123)) })
})

describe('raising an exception', () => {
  it("rejects the pogo's promise", () => {
    return pogo(function*() {
      throw 'bang!'
    }).catch(e => assert.equal(e, 'bang!'))
  })
})

describe('yielding a promise', () => {
  describe('that resolves', () => {
    it('resumes the pogo with the resolution', () => {
      return pogo(function*() {
        assert.equal(yield Promise.resolve(123), 123)
      })
    })
  })

  describe('that rejects', () => {
    it('throws the rejection back into the pogo', () => {
      return pogo(function*() {
        try { yield Promise.reject('bang!') }
        catch (e) { assert.equal(e, 'bang!') }
      })
    })
  })
})

describe('yielding a put or a take', () => {
  it('resumes the pogo with a corresponding take or put', () => {
    const ch = chan()
    pogo(function*() {
      for (let i = 0; i < 10; i++) {
        yield put(ch, i)
      }
    })
    return pogo(function*() {
      for (let i = 0; i < 10; i++) {
        assert.equal(i, yield ch)
      }
    })
  })
})

describe('race', () => {
  it('works with promises', () => {
    return pogo(function*() {
      const ret = yield race([sleep(1000), Promise.resolve('woot')])
      assert.equal(ret, 'woot')
    })
  })

  it('cancels slow alternatives', () => {
    const log = []
    const ch1 = chan()
    const ch2 = chan()

    pogo(function*() {
      yield race([put(ch1, 'first'), put(ch2, 'second')])
      log.push('put first')
      yield put(ch2, 'deuxieme')
      log.push('put deuxieme')
    }).catch(wtf)

    return pogo(function*() {
      const r1 = yield race([ch1, ch2])
      log.push('alted')
      assert.equal(r1.channel, ch1)
      assert.equal(r1.value, 'first')

      const r2 = yield race([ch1, ch2])
      log.push('alted')
      assert.equal(r2.channel, ch2)
      assert.equal(r2.value, 'deuxieme')

      assert.deepEqual(log, ['put first', 'alted', 'put deuxieme', 'alted'])
    })
  })
})

describe('yielding a generator function', () => {
  it('works', () => {
    function* example(ch) {
      const x = yield Promise.resolve(123)

      let y
      try { yield Promise.reject('bang!') }
      catch (e) { y = 456 }

      const z = yield ch

      return [x, y, z]
    }

    return pogo(function*() {
      const ch = chan()
      pogo(function*() {
        yield put(ch, 'sup')
      })

      assert.deepEqual(yield example(ch), [123, 456, 'sup'])
    })
  })

  it('is safe even if you yield the same generator multiple times', () => {
    function* star(x) {
      const y = yield Promise.resolve('foo')
      const z = yield Promise.resolve('bar')
      return [x, y, z]
    }
    return pogo(function*() {
      const gen = star(123)
      assert.equal(123, yield race([gen, Promise.resolve(123)]))
      assert.equal(456, yield race([gen, Promise.resolve(456)]))
      assert.deepEqual(yield race([gen, Promise.resolve(789)]), [123, 'foo', 'bar'])
    })
  })
})

describe('async/callback-based interface', () => {
  describe('putAsync', () => {
    it('works', (done) => {
      const ch = chan()
      pogo(function*() {
        assert.equal(yield ch, 123)
      })
      ch.putAsync(123, done)
    })
  })

  describe('takeAsync', () => {
    it('works', (done) => {
      const ch = chan()
      pogo(function*() {
        yield put(ch, 123)
      })
      ch.takeAsync(v => {
        assert.equal(v, 123)
        return done()
      })
    })
  })
})

describe('sharing a channel between multiple pogos', () => {
  it('works', () => {
    const log = []
    const ch = chan()
    pogo(function*() {
      yield put(ch, 'foo')
      log.push('put foo')
    }).catch(wtf)
    pogo(function*() {
      yield put(ch, 'bar')
      log.push('put bar')
    }).catch(wtf)
    pogo(function*() {
      yield put(ch, 'baz')
      log.push('put baz')
    }).catch(wtf)
    return pogo(function*() {
      assert.equal(yield ch, 'foo')
      log.push('took foo')
      assert.equal(yield ch, 'bar')
      log.push('took bar')
      assert.equal(yield ch, 'baz')
      log.push('took baz')
      assert.deepEqual(log, [
        'put foo', 'took foo', 'put bar', 'took bar', 'put baz', 'took baz'
      ])
    })
  })
})

describe('puting and taking from the same channel', () => {
  it('works', () => {
    const log = []
    const ch = chan()

    pogo(function*() {
      const ping = yield ch
      log.push('received ' + ping)
      yield pogo.put(ch, 'pong')
      log.push('sent pong')
    }).catch(wtf)

    return pogo(function*() {
      yield pogo.put(ch, 'ping')
      log.push('sent ping')
      const pong = yield ch
      log.push('received ' + pong)

      assert.deepEqual(log, ['received ping', 'sent ping', 'sent pong', 'received pong'])
    })
  })
})

describe('fairness', () => {
  it('works for a take and then a put', () => {
    const log = []
    const ch = chan()
    pogo(function*() {
      yield ch
      log.push('took')
    })
    return pogo(function*() {
      yield put(ch)
      log.push('put')
    }).then(() => assert.deepEqual(log, ['took', 'put']))
  })

  it('works for a put and then a take', () => {
    const log = []
    const ch = chan()
    pogo(function*() {
      yield put(ch)
      log.push('put')
    })
    return pogo(function*() {
      yield ch
      log.push('took')
    }).then(() => assert.deepEqual(log, ['put', 'took']))
  })
})
<|endoftext|>


<commit_before>'use strict';

var forEach = require('foreach');
var has = Object.prototype.hasOwnProperty;
var assign = require('object.assign');
var define = require('define-properties');
var entries = require('object.entries');

var hasSticky = typeof (/a/).sticky === 'boolean';

var testResults = function (t, iterator, expectedResults) {
	forEach(expectedResults, function (expected, index) {
		var result = iterator.next();
		t.equal(result.done, expected.done, 'result ' + (index + 1) + ' is ' + (expected.done ? '' : 'not ') + 'done');
		if (expected.done) {
			t.equal(result.value, null, 'result ' + (index + 1) + ' value is null');
		} else {
			t.equal(Array.isArray(result.value), true, 'result ' + (index + 1) + ' value is an array');
			t.deepEqual(entries(result.value || {}), entries(expected.value || {}), 'result ' + (index + 1) + ' has the same entries');
			t.deepEqual(result.value, expected.value, 'result ' + (index + 1) + ' value is expected value');
		}
	});
};

module.exports = function (matchAll, regexMatchAll, t) {
	t.test('non-regexes', function (st) {
		var notRegexes = [null, undefined, NaN, 42, new Date(), {}, []];
		var str = 'abc';
		forEach(notRegexes, function (notRegex) {
			testResults(st, matchAll(str, notRegex), matchAll(str, String(notRegex)));
		});
		st.end();
	});

	t.test('passing a string instead of a regex', function (st) {
		var str = 'aabcaba';
		var regex = /a/;
		testResults(st, matchAll(str, regex), matchAll(str, regex.source));
		st.end();
	});

	t.test('ToString-able objects', function (st) {
		var str = 'aabc';
		var strObj = { toString: function () { return str; } };
		var regex = /[ac]/g;
		var expectedResults = [
			{ value: assign(['a'], { index: 0, input: str }), done: false },
			{ value: assign(['a'], { index: 1, input: str }), done: false },
			{ value: assign(['c'], { index: 3, input: str }), done: false },
			{ value: null, done: true }
		];
		testResults(st, matchAll(strObj, regex), expectedResults);
		st.end();
	});

	t.test('#flags', function (st) {
		st.test('without a flags property', function (s2t) {
			var str = 'aabc';
			var regex = /[ac]/g;
			if (define.supportsDescriptors) {
				Object.defineProperty(regex, 'flags', { value: undefined });
			}
			s2t.equal(regex.flags, undefined, 'regex has an undefined "flags" property');
			var expectedResults = [
				{ value: assign(['a'], { index: 0, input: str }), done: false },
				{ value: assign(['a'], { index: 1, input: str }), done: false },
				{ value: assign(['c'], { index: 3, input: str }), done: false },
				{ value: null, done: true }
			];
			testResults(s2t, matchAll(str, regex), expectedResults);
			s2t.end();
		});

		st.test('with a static flags property', function (s2t) {
			var str = 'AaBC';
			var regex = /[ac]/;
			define(regex, { flags: 'ig' }, { flags: function () { return true; } });
			try {
				define(regex, { global: true }, { global: function () { return true; } });
				s2t.equal(regex.global, true);
			} catch (e) {
				// in node < 6, `global` is not configurable on regexes.
			}
			s2t.equal(regex.flags, 'ig');
			var expectedResults = [
				{ value: assign(['A'], { index: 0, input: str }), done: false },
				{ value: assign(['a'], { index: 1, input: str }), done: false },
				{ value: assign(['C'], { index: 3, input: str }), done: false },
				{ value: null, done: true }
			];
			testResults(s2t, matchAll(str, regex), expectedResults);
			s2t.end();
		});

		st.test('respects flags', function (s2t) {
			var str = 'A\na\nb\nC';
			var regex = /^[ac]/img;
			var expectedResults = [
				{ value: assign(['A'], { index: 0, input: str }), done: false },
				{ value: assign(['a'], { index: 2, input: str }), done: false },
				{ value: assign(['C'], { index: 6, input: str }), done: false },
				{ value: null, done: true }
			];
			testResults(s2t, matchAll(str, regex), expectedResults);
			s2t.end();
		});

		st.test('works with a non-global non-sticky regex', function (s2t) {
			var str = 'AaBbCc';
			var regex = /[bc]/i;
			var expectedResults = [
				{ value: assign(['B'], { index: 2, input: str }), done: false },
				{ value: null, done: true }
			];
			testResults(s2t, matchAll(str, regex), expectedResults);
			s2t.end();
		});
	});

	t.test('returns an iterator', function (st) {
		var str = 'aabc';
		var iterator = matchAll(str, /[ac]/g);
		st.ok(iterator, 'iterator is truthy');
		st.equal(has.call(iterator, 'next'), false, 'iterator does not have own property "next"');
		for (var key in iterator) {
			st.fail('iterator has enumerable properties: ' + key);
		}
		var expectedResults = [
			{ value: assign(['a'], { index: 0, input: str }), done: false },
			{ value: assign(['a'], { index: 1, input: str }), done: false },
			{ value: assign(['c'], { index: 3, input: str }), done: false },
			{ value: null, done: true }
		];
		testResults(st, iterator, expectedResults);
		st.end();
	});

	t.test('zero-width matches', function (st) {
		var str = 'abcde';

		st.test('global', function (s2t) {
			var expectedResults = [
				{ value: assign([''], { index: 1, input: str }), done: false },
				{ value: assign([''], { index: 2, input: str }), done: false },
				{ value: assign([''], { index: 3, input: str }), done: false },
				{ value: assign([''], { index: 4, input: str }), done: false },
				{ value: null, done: true }
			];
			testResults(s2t, matchAll(str, /\B/g), expectedResults);
			s2t.end();
		});

		st.test('sticky', { skip: !hasSticky }, function (s2t) {
			var expectedResults = [
				{ value: null, done: true }
			];
			/* eslint no-invalid-regexp: [2, { "allowConstructorFlags": ["y"] }] */
			testResults(s2t, matchAll(str, new RegExp('\\B', 'y')), expectedResults);
			s2t.end();
		});

		st.test('unflagged', function (s2t) {
			var expectedResults = [
				{ value: assign([''], { index: 1, input: str }), done: false },
				{ value: null, done: true }
			];
			testResults(s2t, matchAll(str, /\B/), expectedResults);
			s2t.end();
		});

		st.end();
	});
};
<commit_msg>[Tests] Skip static flags test on node < 6, due to configurability<commit_after>'use strict';

var forEach = require('foreach');
var has = Object.prototype.hasOwnProperty;
var assign = require('object.assign');
var define = require('define-properties');
var entries = require('object.entries');

var hasSticky = typeof (/a/).sticky === 'boolean';

var testResults = function (t, iterator, expectedResults) {
	forEach(expectedResults, function (expected, index) {
		var result = iterator.next();
		t.equal(result.done, expected.done, 'result ' + (index + 1) + ' is ' + (expected.done ? '' : 'not ') + 'done');
		if (expected.done) {
			t.equal(result.value, null, 'result ' + (index + 1) + ' value is null');
		} else {
			t.equal(Array.isArray(result.value), true, 'result ' + (index + 1) + ' value is an array');
			t.deepEqual(entries(result.value || {}), entries(expected.value || {}), 'result ' + (index + 1) + ' has the same entries');
			t.deepEqual(result.value, expected.value, 'result ' + (index + 1) + ' value is expected value');
		}
	});
};

module.exports = function (matchAll, regexMatchAll, t) {
	t.test('non-regexes', function (st) {
		var notRegexes = [null, undefined, NaN, 42, new Date(), {}, []];
		var str = 'abc';
		forEach(notRegexes, function (notRegex) {
			testResults(st, matchAll(str, notRegex), matchAll(str, String(notRegex)));
		});
		st.end();
	});

	t.test('passing a string instead of a regex', function (st) {
		var str = 'aabcaba';
		var regex = /a/;
		testResults(st, matchAll(str, regex), matchAll(str, regex.source));
		st.end();
	});

	t.test('ToString-able objects', function (st) {
		var str = 'aabc';
		var strObj = { toString: function () { return str; } };
		var regex = /[ac]/g;
		var expectedResults = [
			{ value: assign(['a'], { index: 0, input: str }), done: false },
			{ value: assign(['a'], { index: 1, input: str }), done: false },
			{ value: assign(['c'], { index: 3, input: str }), done: false },
			{ value: null, done: true }
		];
		testResults(st, matchAll(strObj, regex), expectedResults);
		st.end();
	});

	t.test('#flags', function (st) {
		st.test('without a flags property', function (s2t) {
			var str = 'aabc';
			var regex = /[ac]/g;
			if (define.supportsDescriptors) {
				Object.defineProperty(regex, 'flags', { value: undefined });
			}
			s2t.equal(regex.flags, undefined, 'regex has an undefined "flags" property');
			var expectedResults = [
				{ value: assign(['a'], { index: 0, input: str }), done: false },
				{ value: assign(['a'], { index: 1, input: str }), done: false },
				{ value: assign(['c'], { index: 3, input: str }), done: false },
				{ value: null, done: true }
			];
			testResults(s2t, matchAll(str, regex), expectedResults);
			s2t.end();
		});

		st.test('with a static flags property', function (s2t) {
			var str = 'AaBC';
			var regex = /[ac]/;
			define(regex, { flags: 'ig' }, { flags: function () { return true; } });
			try {
				define(regex, { global: true }, { global: function () { return true; } });
				s2t.equal(regex.global, true);
			} catch (e) {
				s2t.comment('# SKIP in node < 6, `global` is not configurable on regexes');
				return s2t.end();
			}
			s2t.equal(regex.flags, 'ig');
			var expectedResults = [
				{ value: assign(['A'], { index: 0, input: str }), done: false },
				{ value: assign(['a'], { index: 1, input: str }), done: false },
				{ value: assign(['C'], { index: 3, input: str }), done: false },
				{ value: null, done: true }
			];
			testResults(s2t, matchAll(str, regex), expectedResults);
			return s2t.end();
		});

		st.test('respects flags', function (s2t) {
			var str = 'A\na\nb\nC';
			var regex = /^[ac]/img;
			var expectedResults = [
				{ value: assign(['A'], { index: 0, input: str }), done: false },
				{ value: assign(['a'], { index: 2, input: str }), done: false },
				{ value: assign(['C'], { index: 6, input: str }), done: false },
				{ value: null, done: true }
			];
			testResults(s2t, matchAll(str, regex), expectedResults);
			s2t.end();
		});

		st.test('works with a non-global non-sticky regex', function (s2t) {
			var str = 'AaBbCc';
			var regex = /[bc]/i;
			var expectedResults = [
				{ value: assign(['B'], { index: 2, input: str }), done: false },
				{ value: null, done: true }
			];
			testResults(s2t, matchAll(str, regex), expectedResults);
			s2t.end();
		});
	});

	t.test('returns an iterator', function (st) {
		var str = 'aabc';
		var iterator = matchAll(str, /[ac]/g);
		st.ok(iterator, 'iterator is truthy');
		st.equal(has.call(iterator, 'next'), false, 'iterator does not have own property "next"');
		for (var key in iterator) {
			st.fail('iterator has enumerable properties: ' + key);
		}
		var expectedResults = [
			{ value: assign(['a'], { index: 0, input: str }), done: false },
			{ value: assign(['a'], { index: 1, input: str }), done: false },
			{ value: assign(['c'], { index: 3, input: str }), done: false },
			{ value: null, done: true }
		];
		testResults(st, iterator, expectedResults);
		st.end();
	});

	t.test('zero-width matches', function (st) {
		var str = 'abcde';

		st.test('global', function (s2t) {
			var expectedResults = [
				{ value: assign([''], { index: 1, input: str }), done: false },
				{ value: assign([''], { index: 2, input: str }), done: false },
				{ value: assign([''], { index: 3, input: str }), done: false },
				{ value: assign([''], { index: 4, input: str }), done: false },
				{ value: null, done: true }
			];
			testResults(s2t, matchAll(str, /\B/g), expectedResults);
			s2t.end();
		});

		st.test('sticky', { skip: !hasSticky }, function (s2t) {
			var expectedResults = [
				{ value: null, done: true }
			];
			/* eslint no-invalid-regexp: [2, { "allowConstructorFlags": ["y"] }] */
			testResults(s2t, matchAll(str, new RegExp('\\B', 'y')), expectedResults);
			s2t.end();
		});

		st.test('unflagged', function (s2t) {
			var expectedResults = [
				{ value: assign([''], { index: 1, input: str }), done: false },
				{ value: null, done: true }
			];
			testResults(s2t, matchAll(str, /\B/), expectedResults);
			s2t.end();
		});

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


<commit_before>import React from 'react';

import Module from 'Parser/Core/Module';
import Combatants from 'Parser/Core/Modules/Combatants';

import SPELLS from 'common/SPELLS';
import SpellIcon from 'common/SpellIcon';
import SpellLink from 'common/SpellLink';

const CALL_DREADSTALKERS_COOLDOWN = 15000;

class T20_2set extends Module {
  static dependencies = {
    combatants: Combatants,
  };

  _expectedCooldownEnd = null;
  procs = 0;

  on_initialized() {
    this.active = this.combatants.selected.hasBuff(SPELLS.WARLOCK_DEMO_T20_2P_BONUS.id);
  }

  on_byPlayer_cast(event) {
    if (event.ability.guid !== SPELLS.CALL_DREADSTALKERS.id) {
      return;
    }
    if (this._expectedCooldownEnd && event.timestamp < this._expectedCooldownEnd) {
      this.procs += 1;
    }
    this._expectedCooldownEnd = event.timestamp + CALL_DREADSTALKERS_COOLDOWN;
  }

  item() {
    return {
      id: `spell-${SPELLS.WARLOCK_DEMO_T20_2P_BONUS.id}`,
      icon: <SpellIcon id={SPELLS.WARLOCK_DEMO_T20_2P_BONUS.id} />,
      title: <SpellLink id={SPELLS.WARLOCK_DEMO_T20_2P_BONUS.id} />,
      result: `${this.procs} resetted cooldowns on Call Dreadstalkers`,
    };
  }
}

export default T20_2set;
<commit_msg>Reword the T20 2pc item result<commit_after>import React from 'react';

import Module from 'Parser/Core/Module';
import Combatants from 'Parser/Core/Modules/Combatants';

import SPELLS from 'common/SPELLS';
import SpellIcon from 'common/SpellIcon';
import SpellLink from 'common/SpellLink';

const CALL_DREADSTALKERS_COOLDOWN = 15000;

class T20_2set extends Module {
  static dependencies = {
    combatants: Combatants,
  };

  _expectedCooldownEnd = null;
  procs = 0;

  on_initialized() {
    this.active = this.combatants.selected.hasBuff(SPELLS.WARLOCK_DEMO_T20_2P_BONUS.id);
  }

  on_byPlayer_cast(event) {
    if (event.ability.guid !== SPELLS.CALL_DREADSTALKERS.id) {
      return;
    }
    if (this._expectedCooldownEnd && event.timestamp < this._expectedCooldownEnd) {
      this.procs += 1;
    }
    this._expectedCooldownEnd = event.timestamp + CALL_DREADSTALKERS_COOLDOWN;
  }

  item() {
    return {
      id: `spell-${SPELLS.WARLOCK_DEMO_T20_2P_BONUS.id}`,
      icon: <SpellIcon id={SPELLS.WARLOCK_DEMO_T20_2P_BONUS.id} />,
      title: <SpellLink id={SPELLS.WARLOCK_DEMO_T20_2P_BONUS.id} />,
      result: <span>{this.procs} resets of <SpellLink id={SPELLS.CALL_DREADSTALKERS.id} /> cooldown.</span>,
    };
  }
}

export default T20_2set;
<|endoftext|>