<commit_before>"use strict";

describe("define", function () {

    var test = {};

    before(function () {
        // Defines a namespace root
        gpf.context().test = test;
    });

    after(function () {
        delete gpf.context().test;
    });

    function _generateNamesValidation (typeName, Exception, names) {

        Object.keys(names).filter(function (name) {
            return !names[name];
        }).forEach(function (invalidName) {
            it("rejects invalid " + typeName + " name (" + invalidName + ")", function () {
                var exceptionCaught,
                    definition = {};
                definition["$" + typeName] = invalidName;
                try {
                    gpf.define(definition);
                } catch (e) {
                    exceptionCaught = e;
                }
                assert(exceptionCaught instanceof Exception);
            });
        });

        Object.keys(names).filter(function (name) {
            return names[name];
        }).forEach(function (validName) {
            it("accepts valid " + typeName + " name (" + validName + ")", function () {
                var exceptionCaught,
                    definition = {};
                definition["$" + typeName] = validName;
                try {
                    gpf.define(definition);
                } catch (e) {
                    exceptionCaught = e;
                }
                assert(undefined === exceptionCaught);
            });
        });

    }

    function _generateBasicValidations (descriptor) {
        it(descriptor.it, function () {
            var exceptionCaught;
            try {
                gpf.define(descriptor.definition);
            } catch (e) {
                exceptionCaught = e;
            }
            assert(exceptionCaught instanceof descriptor.exception);
        });
    }

    describe("gpf.define", function () {

        it("accepts only one parameter", function () {
            assert("function" === typeof gpf.define);
            assert(1 === gpf.define.length);
        });

        describe("Common validation", function () {

            _generateBasicValidations({
                it: "checks that the entity type is specified",
                definition: {},
                exception: gpf.Error.InvalidEntityType
            });

        });

        describe("Class definition", function () {

            describe("Validation", function () {

                _generateNamesValidation("class", gpf.Error.InvalidClassName, {
                    "1NumberAtTheBeginningIsNotOK": false,
                    "noUppercaseFirstLetterIsNotOK": false,
                    "DollarSignAnywhereIsNotOK$": false,
                    "A": true,
                    "$B": true,
                    "_C": true,
                    "Test123": true
                });

                [{
                    it: "rejects invalid $ property names",
                    definition: {
                        $class: "Test",
                        $test: false
                    },
                    exception: gpf.Error.InvalidEntity$Property

                }, {
                    it: "rejects invalid property names (reserved keywords)",
                    definition: {
                        $class: "Test",
                        "super": false
                    },
                    exception: gpf.Error.InvalidClassProperty

                }, {
                    it: "rejects constructor property if not a method",
                    definition: {
                        $class: "Test",
                        constructor: false
                    },
                    exception: gpf.Error.InvalidClassConstructor

                }].forEach(_generateBasicValidations);

            });

            describe("Implementation", function () {

                var A, a;

                before(function () {
                    A = gpf.define({
                        $class: "A",
                        _member: "defaultValue",
                        getMember: function () {
                            return this._member;
                        },
                        "constructor": function (memberValue) {
                            if (memberValue) {
                                this._member = memberValue;
                            }
                            this._constructorOfA = true;
                        },
                        funcWith3params: function (p1, p2, p3) {
                            return p1 + p2 + p3;
                        },
                        throwError: function () {
                            throw new Error("error");
                        }
                    });

                    a = new A();
                });

                it("prevents constructor functions to be used without new", function () {
                    var exceptionCaught;
                    try {
                        A(); // eslint-disable-line new-cap
                    } catch (e) {
                        exceptionCaught = e;
                    }
                    assert(exceptionCaught instanceof gpf.Error.ClassConstructorFunction);
                });

                it("creates a constructor with the same signature than the constructor property", function () {
                    assert(A.length === 1);
                });

                it("handles instanceof", function () {
                    assert(a instanceof A);
                });

                it("calls constructor property", function () {
                    assert(a._constructorOfA);
                });

                it("exposes methods", function () {
                    assert("function" === typeof a.getMember);
                    assert("defaultValue" === a.getMember());
                });

                describe("Subclassing", function () {

                    it("prevents invalid override", function () {
                        var exceptionCaught;
                        try {
                            gpf.define({
                                $class: "Test",
                                $extend: A,
                                getMember: false
                            });
                        } catch (e) {
                            exceptionCaught = e;
                        }
                        assert(exceptionCaught instanceof gpf.Error.InvalidClassOverride);
                    });

                    var B, b;

                    before(function () {
                        B = gpf.define({
                            $class: "test.B",
                            $extend: A,
                            "constructor": function (initialValue) {
                                this.$super("valueOfB");
                                this._constructorOfB = initialValue;
                            },
                            getMember: function () {
                                return this.$super() + "-inB";
                            },
                            setMember: function (newValue) {
                                this._member = newValue;
                            },
                            baseTest: function () {
                                return this.$super.getMember();
                            },
                            invalidSuperMember: function () {
                                return this.$super.doesntExist();
                            },
                            noSuperMember: function () {
                                return this.$super();
                            },
                            differentBinding: function () {
                                return this.$super.getMember.call({
                                    _member: "different"
                                });
                            },
                            checkSignature: function () {
                                assert(this.$super.funcWith3params.length === 3);
                            },
                            throwError: function () {
                                this.$super();
                            }
                        });

                        b = new B(3475);
                    });

                    it("handles instanceof", function () {
                        assert(b instanceof A);
                        assert(b instanceof B);
                    });

                    it("handles namespace", function () {
                        assert(test.B === B);
                    });

                    it("calls the constructor function", function () {
                        assert(b._constructorOfB === 3475);
                    });

                    it("calls the proper $super()", function () {
                        assert(b._constructorOfA);
                        assert(b.getMember() === "valueOfB-inB");
                    });

                    it("offers a way to call named base method", function () {
                        assert(b.baseTest() === "valueOfB");
                    });

                    it("fails when accessing an unknown $super member", function () {
                        var exceptionCaught;
                        try {
                            b.invalidSuperMember();
                        } catch (e) {
                            exceptionCaught = e;
                        }
                        assert(exceptionCaught instanceof gpf.Error.InvalidClassSuperMember);
                    });

                    it("fails when accessing inexistent $super", function () {
                        var exceptionCaught;
                        try {
                            b.noSuperMember();
                        } catch (e) {
                            exceptionCaught = e;
                        }
                        assert(exceptionCaught instanceof gpf.Error.InvalidClassSuper);
                    });

                    it("allows calling $super member with a different binding", function () {
                        assert(b.differentBinding() === "different");
                    });

                    it("respects methods signature", function () {
                        b.checkSignature();
                    });

                    it("does not leak $super", function () {
                        assert(undefined === b.$super);
                    });

                    it("does not leak $super on exception", function () {
                        try {
                            b.throwError();
                        } catch (e) {
                            // ignore
                        }
                        assert(undefined === b.$super);
                    });

                    it("handles several versions of $super", function () {
                        var C = gpf.define({
                                $class: "C",
                                $extend: B,
                                testMethod: function () {
                                    return this.$super.getMember();
                                }
                            }),
                            c = new C();
                        assert("valueOfB-inB" === c.testMethod());
                    });
                });

            });

        });

        describe("Interface definition", function () {

            describe("Validation", function () {

                _generateNamesValidation("interface", gpf.Error.InvalidInterfaceName, {
                    "1NumberAtTheBeginningIsNotOK": false,
                    "noUppercaseFirstLetterIsNotOK": false,
                    "DollarSignAnywhereIsNotOK$": false,
                    "NotStartingWithUppercaseI": false,
                    "A": false,
                    "$B": false,
                    "_C": false,
                    "Test123": false,
                    "ISample": true,
                    "IS": true
                });

                [{
                    it: "rejects interface if all members are not methods",
                    definition: {
                        $interface: "ITest",
                        member: false
                    },
                    exception: gpf.Error.InvalidInterfaceProperty

                }, {
                    it: "rejects invalid property names (reserved keywords)",
                    definition: {
                        $interface: "ITest",
                        "super": function () {
                        }
                    },
                    exception: gpf.Error.InvalidInterfaceProperty

                }, {
                    it: "rejects constructor property",
                    definition: {
                        $interface: "ITest",
                        constructor: function () {
                        }
                    },
                    exception: gpf.Error.InvalidInterfaceProperty

                }].forEach(_generateBasicValidations);

            });

            describe("Implementation", function () {

                var ITest = gpf.define({
                    $interface: "ITest",
                    test: function (value) {
                        return value;
                    }
                });

                it("can't be used as a class extend", function () {
                    var exceptionCaught;
                    try {
                        gpf.define({
                            $class: "Test",
                            $extend: ITest
                        });
                    } catch (e) {
                        exceptionCaught = e;
                    }
                    assert(exceptionCaught instanceof gpf.Error.InvalidClassExtend);
                });

            });

        });

    });

});
<commit_msg>Preparing tests (#249)<commit_after>"use strict";

describe("define", function () {

    var test = {};

    before(function () {
        // Defines a namespace root
        gpf.context().test = test;
    });

    after(function () {
        delete gpf.context().test;
    });

    function _generateNamesValidation (typeName, Exception, names) {

        Object.keys(names).filter(function (name) {
            return !names[name];
        }).forEach(function (invalidName) {
            it("rejects invalid " + typeName + " name (" + invalidName + ")", function () {
                var exceptionCaught,
                    definition = {};
                definition["$" + typeName] = invalidName;
                try {
                    gpf.define(definition);
                } catch (e) {
                    exceptionCaught = e;
                }
                assert(exceptionCaught instanceof Exception);
            });
        });

        Object.keys(names).filter(function (name) {
            return names[name];
        }).forEach(function (validName) {
            it("accepts valid " + typeName + " name (" + validName + ")", function () {
                var exceptionCaught,
                    definition = {};
                definition["$" + typeName] = validName;
                try {
                    gpf.define(definition);
                } catch (e) {
                    exceptionCaught = e;
                }
                assert(undefined === exceptionCaught);
            });
        });

    }

    function _generateBasicValidations (descriptor) {
        it(descriptor.it, function () {
            var exceptionCaught;
            try {
                gpf.define(descriptor.definition);
            } catch (e) {
                exceptionCaught = e;
            }
            assert(exceptionCaught instanceof descriptor.exception);
        });
    }

    describe("gpf.define", function () {

        it("accepts only one parameter", function () {
            assert("function" === typeof gpf.define);
            assert(1 === gpf.define.length);
        });

        describe("Common validation", function () {

            _generateBasicValidations({
                it: "checks that the entity type is specified",
                definition: {},
                exception: gpf.Error.InvalidEntityType
            });

        });

        describe("Class definition", function () {

            describe("Validation", function () {

                _generateNamesValidation("class", gpf.Error.InvalidClassName, {
                    "1NumberAtTheBeginningIsNotOK": false,
                    "noUppercaseFirstLetterIsNotOK": false,
                    "DollarSignAnywhereIsNotOK$": false,
                    "A": true,
                    "$B": true,
                    "_C": true,
                    "Test123": true
                });

                [{
                    it: "rejects invalid $ property names",
                    definition: {
                        $class: "Test",
                        $test: false
                    },
                    exception: gpf.Error.InvalidEntity$Property

                }, {
                    it: "rejects invalid property names (reserved keywords)",
                    definition: {
                        $class: "Test",
                        "super": false
                    },
                    exception: gpf.Error.InvalidClassProperty

                }, {
                    it: "rejects constructor property if not a method",
                    definition: {
                        $class: "Test",
                        constructor: false
                    },
                    exception: gpf.Error.InvalidClassConstructor

                }].forEach(_generateBasicValidations);

            });

            describe("Implementation", function () {

                var A, a;

                before(function () {
                    A = gpf.define({
                        $class: "A",
                        _member: "defaultValue",
                        getMember: function () {
                            return this._member;
                        },
                        "constructor": function (memberValue) {
                            if (memberValue) {
                                this._member = memberValue;
                            }
                            this._constructorOfA = true;
                        },
                        funcWith3params: function (p1, p2, p3) {
                            return p1 + p2 + p3;
                        },
                        throwError: function () {
                            throw new Error("error");
                        }
                    });

                    a = new A();
                });

                it("prevents constructor functions to be used without new", function () {
                    var exceptionCaught;
                    try {
                        A(); // eslint-disable-line new-cap
                    } catch (e) {
                        exceptionCaught = e;
                    }
                    assert(exceptionCaught instanceof gpf.Error.ClassConstructorFunction);
                });

                it("creates a constructor with the same signature than the constructor property", function () {
                    assert(A.length === 1);
                });

                it("handles instanceof", function () {
                    assert(a instanceof A);
                });

                it("calls constructor property", function () {
                    assert(a._constructorOfA);
                });

                it("exposes methods", function () {
                    assert("function" === typeof a.getMember);
                    assert("defaultValue" === a.getMember());
                });

                describe("Subclassing", function () {

                    it("prevents invalid override", function () {
                        var exceptionCaught;
                        try {
                            gpf.define({
                                $class: "Test",
                                $extend: A,
                                getMember: false
                            });
                        } catch (e) {
                            exceptionCaught = e;
                        }
                        assert(exceptionCaught instanceof gpf.Error.InvalidClassOverride);
                    });

                    var B, b;

                    before(function () {
                        B = gpf.define({
                            $class: "test.B",
                            $extend: A,
                            "constructor": function (initialValue) {
                                this.$super("valueOfB");
                                this._constructorOfB = initialValue;
                            },
                            getMember: function () {
                                return this.$super() + "-inB";
                            },
                            setMember: function (newValue) {
                                this._member = newValue;
                            },
                            baseTest: function () {
                                return this.$super.getMember();
                            },
                            invalidSuperMember: function () {
                                return this.$super.doesntExist();
                            },
                            noSuperMember: function () {
                                return this.$super();
                            },
                            differentBinding: function () {
                                return this.$super.getMember.call({
                                    _member: "different"
                                });
                            },
                            checkSignature: function () {
                                assert(this.$super.funcWith3params.length === 3);
                            },
                            throwError: function () {
                                this.$super();
                            }
                        });

                        b = new B(3475);
                    });

                    it("handles instanceof", function () {
                        assert(b instanceof A);
                        assert(b instanceof B);
                    });

                    it("handles namespace", function () {
                        assert(test.B === B);
                    });

                    it("calls the constructor function", function () {
                        assert(b._constructorOfB === 3475);
                    });

                    it("calls the proper $super()", function () {
                        assert(b._constructorOfA);
                        assert(b.getMember() === "valueOfB-inB");
                    });

                    it("offers a way to call named base method", function () {
                        assert(b.baseTest() === "valueOfB");
                    });

                    it("fails when accessing an unknown $super member", function () {
                        var exceptionCaught;
                        try {
                            b.invalidSuperMember();
                        } catch (e) {
                            exceptionCaught = e;
                        }
                        assert(exceptionCaught instanceof gpf.Error.InvalidClassSuperMember);
                    });

                    it("fails when accessing inexistent $super", function () {
                        var exceptionCaught;
                        try {
                            b.noSuperMember();
                        } catch (e) {
                            exceptionCaught = e;
                        }
                        assert(exceptionCaught instanceof gpf.Error.InvalidClassSuper);
                    });

                    it("allows calling $super member with a different binding", function () {
                        assert(b.differentBinding() === "different");
                    });

                    it("respects methods signature", function () {
                        b.checkSignature();
                    });

                    it("does not leak $super", function () {
                        assert(undefined === b.$super);
                    });

                    it("does not leak $super on exception", function () {
                        try {
                            b.throwError();
                        } catch (e) {
                            // ignore
                        }
                        assert(undefined === b.$super);
                    });

                    it("handles several versions of $super", function () {
                        var C = gpf.define({
                                $class: "C",
                                $extend: B,
                                testMethod: function () {
                                    return this.$super.getMember();
                                }
                            }),
                            c = new C();
                        assert("valueOfB-inB" === c.testMethod());
                    });
                });

            });

            function describe_ () {
                /* Until the implementation is working */
            }

            describe_("$abstract", function () {

                var A, B, C;

                before(function () {

                    A = gpf.define({
                        $class: "A",
                        $abstract: true,
                        _member: "defaultValue",
                        getMember: function () {
                            return this._member;
                        },
                        "constructor": function (memberValue) {
                            if (memberValue) {
                                this._member = memberValue;
                            }
                            this._constructorOfA = true;
                        }
                    });

                    B = gpf.define({
                        $class: "B",
                        $extend: A
                    });

                    C = gpf.define({
                        $class: "C",
                        $extend: B,
                        $abstract: true
                    });

                });

                function _noInstantiation (AbstractClass) {
                    it("prevents instantiation of abstract class ("
                        + AbstractClass.compatibleName() + ")", function () {
                        var exceptionCaught;
                        try {
                            var instance = new AbstractClass();
                            assert(!instance);
                        } catch (e) {
                            exceptionCaught = e;
                        }
                        assert(exceptionCaught instanceof gpf.Error.AbstractClass);
                    });
                }

                _noInstantiation(A);

                it("enables instantiation on subclass (B)", function () {
                    var b = new B();
                    assert(b);
                });

                _noInstantiation(C);

            });

        });

        describe("Interface definition", function () {

            describe("Validation", function () {

                _generateNamesValidation("interface", gpf.Error.InvalidInterfaceName, {
                    "1NumberAtTheBeginningIsNotOK": false,
                    "noUppercaseFirstLetterIsNotOK": false,
                    "DollarSignAnywhereIsNotOK$": false,
                    "NotStartingWithUppercaseI": false,
                    "A": false,
                    "$B": false,
                    "_C": false,
                    "Test123": false,
                    "ISample": true,
                    "IS": true
                });

                [{
                    it: "rejects interface if all members are not methods",
                    definition: {
                        $interface: "ITest",
                        member: false
                    },
                    exception: gpf.Error.InvalidInterfaceProperty

                }, {
                    it: "rejects invalid property names (reserved keywords)",
                    definition: {
                        $interface: "ITest",
                        "super": function () {
                        }
                    },
                    exception: gpf.Error.InvalidInterfaceProperty

                }, {
                    it: "rejects constructor property",
                    definition: {
                        $interface: "ITest",
                        constructor: function () {
                        }
                    },
                    exception: gpf.Error.InvalidInterfaceProperty

                }].forEach(_generateBasicValidations);

            });

            describe("Implementation", function () {

                var ITest = gpf.define({
                    $interface: "ITest",
                    test: function (value) {
                        return value;
                    }
                });

                it("can't be used as a class extend", function () {
                    var exceptionCaught;
                    try {
                        gpf.define({
                            $class: "Test",
                            $extend: ITest
                        });
                    } catch (e) {
                        exceptionCaught = e;
                    }
                    assert(exceptionCaught instanceof gpf.Error.InvalidClassExtend);
                });

            });

        });

    });

});
<|endoftext|>


<commit_before>var async = require('../lib');
var {expect} = require('chai');
var _ = require('lodash');

describe("detect", () => {

    function detectIteratee(call_order, x, callback) {
        setTimeout(() => {
            call_order.push(x);
            callback(null, x == 2);
        }, x*5);
    }

    it('detect', function(done){
        var call_order = [];
        async.detect([3,2,1], detectIteratee.bind(this, call_order), (err, result) => {
            call_order.push('callback');
            expect(err).to.equal(null);
            expect(result).to.equal(2);
        });
        setTimeout(() => {
            expect(call_order).to.eql([1,2,'callback',3]);
            done();
        }, 25);
    });

    it('detect - mulitple matches', function(done){
        var call_order = [];
        async.detect([3,2,2,1,2], detectIteratee.bind(this, call_order), (err, result) => {
            call_order.push('callback');
            expect(err).to.equal(null);
            expect(result).to.equal(2);
        });
        setTimeout(() => {
            expect(call_order).to.eql([1,2,'callback',2,2,3]);
            done();
        }, 25);
    });

    it('detect error', (done) => {
        async.detect([3,2,1], (x, callback) => {
            setTimeout(() => {callback('error');}, 0);
        }, (err, result) => {
            expect(err).to.equal('error');
            expect(result).to.not.exist;
            done();
        });
    });

    it('detect canceled', (done) => {
        var call_order = [];
        async.detect({'a': 3, 'b': 2, 'c': 1}, (x, callback) => {
            call_order.push(x);
            if (x === 2) {
                return callback(false);
            }
            callback(null);
        }, () => {
            throw new Error('should not get here');
        });

        setTimeout(() => {
            expect(call_order).to.eql([3, 2]);
            done();
        }, 25);
    });

    it('detectSeries', function(done){
        var call_order = [];
        async.detectSeries([3,2,1], detectIteratee.bind(this, call_order), (err, result) => {
            call_order.push('callback');
            expect(err).to.equal(null);
            expect(result).to.equal(2);

            expect(call_order).to.eql([3,2,'callback']);
            done();
        });
    });

    it('detectSeries - multiple matches', function(done){
        var call_order = [];
        async.detectSeries([3,2,2,1,2], detectIteratee.bind(this, call_order), (err, result) => {
            call_order.push('callback');
            expect(err).to.equal(null);
            expect(result).to.equal(2);

            expect(call_order).to.eql([3,2,'callback']);
            done();
        });
    });

    it('detect no callback', (done) => {
        var calls = [];

        async.detect([1, 2, 3], (val, cb) => {
            calls.push(val);
            cb();
        });

        setTimeout(() => {
            expect(calls).to.eql([1, 2, 3]);
            done();
        }, 10);
    });

    it('detectSeries - ensure stop', (done) => {
        async.detectSeries([1, 2, 3, 4, 5], (num, cb) => {
            if (num > 3) throw new Error("detectSeries did not stop iterating");
            cb(null, num === 3);
        }, (err, result) => {
            expect(err).to.equal(null);
            expect(result).to.equal(3);
            done();
        });
    });

    it('detectSeries canceled', (done) => {
        var call_order = [];
        async.detectSeries([3, 2, 1], (x, callback) => {
            async.setImmediate(() => {
                call_order.push(x);
                if (x === 2) {
                    return callback(false);
                }
                callback(null);
            });
        }, () => {
            throw new Error('should not get here');
        });

        setTimeout(() => {
            expect(call_order).to.eql([3, 2]);
            done();
        }, 50);
    });

    it('detectLimit', function(done){
        var call_order = [];
        async.detectLimit([3, 2, 1], 2, detectIteratee.bind(this, call_order), (err, result) => {
            call_order.push('callback');
            expect(err).to.equal(null);
            expect(result).to.equal(2);
        });
        setTimeout(() => {
            expect(call_order).to.eql([2, 'callback', 3]);
            done();
        }, 50);
    });

    it('detectLimit - multiple matches', function(done){
        var call_order = [];
        async.detectLimit([3,2,2,1,2], 2, detectIteratee.bind(this, call_order), (err, result) => {
            call_order.push('callback');
            expect(err).to.equal(null);
            expect(result).to.equal(2);
        });
        setTimeout(() => {
            expect(call_order).to.eql([2, 'callback', 3]);
            done();
        }, 50);
    });

    it('detectLimit - ensure stop', (done) => {
        async.detectLimit([1, 2, 3, 4, 5], 2, (num, cb) => {
            if (num > 4) throw new Error("detectLimit did not stop iterating");
            cb(null, num === 3);
        }, (err, result) => {
            expect(err).to.equal(null);
            expect(result).to.equal(3);
            done();
        });
    });

    it('detectLimit canceled', (done) => {
        var call_order = [];
        async.detectLimit([3, 3, 2, 2, 1], 2, (x, callback) => {
            async.setImmediate(() => {
                call_order.push(x);
                if (x === 2) {
                    return callback(false);
                }
                callback(null);
            });
        }, () => {
            throw new Error('should not get here');
        });

        setTimeout(() => {
            expect(call_order).to.eql([3, 3, 2, 2]);
            done();
        }, 50);
    });

    it('detectSeries doesn\'t cause stack overflow (#1293)', (done) => {
        var arr = _.range(10000);
        let calls = 0;
        async.detectSeries(arr, (data, cb) => {
            calls += 1;
            async.setImmediate(_.partial(cb, null, true));
        }, (err) => {
            expect(err).to.equal(null);
            expect(calls).to.equal(1);
            done();
        });
    });

    it('detectLimit doesn\'t cause stack overflow (#1293)', (done) => {
        var arr = _.range(10000);
        let calls = 0;
        async.detectLimit(arr, 100, (data, cb) => {
            calls += 1;
            async.setImmediate(_.partial(cb, null, true));
        }, (err) => {
            expect(err).to.equal(null);
            expect(calls).to.equal(100);
            done();
        });
    });

    it('find alias', () => {
        expect(async.find).to.equal(async.detect);
    });

    it('findLimit alias', () => {
        expect(async.findLimit).to.equal(async.detectLimit);
    });

    it('findSeries alias', () => {
        expect(async.findSeries).to.be.a('function');
        expect(async.findSeries).to.equal(async.detectSeries);
    });

});
<commit_msg>chore: Fix typo in detect.js (#1749)<commit_after>var async = require('../lib');
var {expect} = require('chai');
var _ = require('lodash');

describe("detect", () => {

    function detectIteratee(call_order, x, callback) {
        setTimeout(() => {
            call_order.push(x);
            callback(null, x == 2);
        }, x*5);
    }

    it('detect', function(done){
        var call_order = [];
        async.detect([3,2,1], detectIteratee.bind(this, call_order), (err, result) => {
            call_order.push('callback');
            expect(err).to.equal(null);
            expect(result).to.equal(2);
        });
        setTimeout(() => {
            expect(call_order).to.eql([1,2,'callback',3]);
            done();
        }, 25);
    });

    it('detect - multiple matches', function(done){
        var call_order = [];
        async.detect([3,2,2,1,2], detectIteratee.bind(this, call_order), (err, result) => {
            call_order.push('callback');
            expect(err).to.equal(null);
            expect(result).to.equal(2);
        });
        setTimeout(() => {
            expect(call_order).to.eql([1,2,'callback',2,2,3]);
            done();
        }, 25);
    });

    it('detect error', (done) => {
        async.detect([3,2,1], (x, callback) => {
            setTimeout(() => {callback('error');}, 0);
        }, (err, result) => {
            expect(err).to.equal('error');
            expect(result).to.not.exist;
            done();
        });
    });

    it('detect canceled', (done) => {
        var call_order = [];
        async.detect({'a': 3, 'b': 2, 'c': 1}, (x, callback) => {
            call_order.push(x);
            if (x === 2) {
                return callback(false);
            }
            callback(null);
        }, () => {
            throw new Error('should not get here');
        });

        setTimeout(() => {
            expect(call_order).to.eql([3, 2]);
            done();
        }, 25);
    });

    it('detectSeries', function(done){
        var call_order = [];
        async.detectSeries([3,2,1], detectIteratee.bind(this, call_order), (err, result) => {
            call_order.push('callback');
            expect(err).to.equal(null);
            expect(result).to.equal(2);

            expect(call_order).to.eql([3,2,'callback']);
            done();
        });
    });

    it('detectSeries - multiple matches', function(done){
        var call_order = [];
        async.detectSeries([3,2,2,1,2], detectIteratee.bind(this, call_order), (err, result) => {
            call_order.push('callback');
            expect(err).to.equal(null);
            expect(result).to.equal(2);

            expect(call_order).to.eql([3,2,'callback']);
            done();
        });
    });

    it('detect no callback', (done) => {
        var calls = [];

        async.detect([1, 2, 3], (val, cb) => {
            calls.push(val);
            cb();
        });

        setTimeout(() => {
            expect(calls).to.eql([1, 2, 3]);
            done();
        }, 10);
    });

    it('detectSeries - ensure stop', (done) => {
        async.detectSeries([1, 2, 3, 4, 5], (num, cb) => {
            if (num > 3) throw new Error("detectSeries did not stop iterating");
            cb(null, num === 3);
        }, (err, result) => {
            expect(err).to.equal(null);
            expect(result).to.equal(3);
            done();
        });
    });

    it('detectSeries canceled', (done) => {
        var call_order = [];
        async.detectSeries([3, 2, 1], (x, callback) => {
            async.setImmediate(() => {
                call_order.push(x);
                if (x === 2) {
                    return callback(false);
                }
                callback(null);
            });
        }, () => {
            throw new Error('should not get here');
        });

        setTimeout(() => {
            expect(call_order).to.eql([3, 2]);
            done();
        }, 50);
    });

    it('detectLimit', function(done){
        var call_order = [];
        async.detectLimit([3, 2, 1], 2, detectIteratee.bind(this, call_order), (err, result) => {
            call_order.push('callback');
            expect(err).to.equal(null);
            expect(result).to.equal(2);
        });
        setTimeout(() => {
            expect(call_order).to.eql([2, 'callback', 3]);
            done();
        }, 50);
    });

    it('detectLimit - multiple matches', function(done){
        var call_order = [];
        async.detectLimit([3,2,2,1,2], 2, detectIteratee.bind(this, call_order), (err, result) => {
            call_order.push('callback');
            expect(err).to.equal(null);
            expect(result).to.equal(2);
        });
        setTimeout(() => {
            expect(call_order).to.eql([2, 'callback', 3]);
            done();
        }, 50);
    });

    it('detectLimit - ensure stop', (done) => {
        async.detectLimit([1, 2, 3, 4, 5], 2, (num, cb) => {
            if (num > 4) throw new Error("detectLimit did not stop iterating");
            cb(null, num === 3);
        }, (err, result) => {
            expect(err).to.equal(null);
            expect(result).to.equal(3);
            done();
        });
    });

    it('detectLimit canceled', (done) => {
        var call_order = [];
        async.detectLimit([3, 3, 2, 2, 1], 2, (x, callback) => {
            async.setImmediate(() => {
                call_order.push(x);
                if (x === 2) {
                    return callback(false);
                }
                callback(null);
            });
        }, () => {
            throw new Error('should not get here');
        });

        setTimeout(() => {
            expect(call_order).to.eql([3, 3, 2, 2]);
            done();
        }, 50);
    });

    it('detectSeries doesn\'t cause stack overflow (#1293)', (done) => {
        var arr = _.range(10000);
        let calls = 0;
        async.detectSeries(arr, (data, cb) => {
            calls += 1;
            async.setImmediate(_.partial(cb, null, true));
        }, (err) => {
            expect(err).to.equal(null);
            expect(calls).to.equal(1);
            done();
        });
    });

    it('detectLimit doesn\'t cause stack overflow (#1293)', (done) => {
        var arr = _.range(10000);
        let calls = 0;
        async.detectLimit(arr, 100, (data, cb) => {
            calls += 1;
            async.setImmediate(_.partial(cb, null, true));
        }, (err) => {
            expect(err).to.equal(null);
            expect(calls).to.equal(100);
            done();
        });
    });

    it('find alias', () => {
        expect(async.find).to.equal(async.detect);
    });

    it('findLimit alias', () => {
        expect(async.findLimit).to.equal(async.detectLimit);
    });

    it('findSeries alias', () => {
        expect(async.findSeries).to.be.a('function');
        expect(async.findSeries).to.equal(async.detectSeries);
    });

});
<|endoftext|>


<commit_before>var Document = require('../lib/document');
var fs = require('fs');
var dkGreyBorder = {style: 'thin', color: 'Charcoal Gray'};
var doc = new Document({
    sheets: {
        'Summary': {
            image: {image: fs.readFileSync(__dirname + '/assets/dog.png'), filename: 'dog.png'},
            rows: [{
                cells: [
                    'foo',
                    {value: 'bar', style: 'bold'},
                    {value: 'foo', style: 'lemonBg'},
                    'baz',
                    {value: 'quux', style: 'lemonBgBold'}
                ]
            }, {
                cells: ['', {value: 'WAT?!', style: 'brick'}, {value: 'dotty', style: 'dotty'}]
            }]
        }
    },
    styles: {
        borders: [{label: 'dkGrey', left: dkGreyBorder, right: dkGreyBorder, top: dkGreyBorder, bottom: dkGreyBorder}],
        fonts: [{label: 'bold', bold: true}, {label: 'brick', color: 'Brick Red'}],
        fills: [{label: 'lemon', type: 'pattern', color: 'Lemon Glacier'}],
        cellStyles: [
            {label: 'bold', font: 'bold'},
            {label: 'brick', font: 'brick', border: 'dkGrey'},
            {label: 'lemonBg', fill: 'lemon'},
            {label: 'lemonBgBold', font: 'bold', fill: 'lemon'},
            {label: 'dotty', fill: 1}
        ]
    }
});

fs.writeFileSync(__dirname + '/test.xlsx', doc.build().toXLSX());<commit_msg>add rich text to doc test<commit_after>var Document = require('../lib/document');
var fs = require('fs');
var dkGreyBorder = {style: 'thin', color: 'Charcoal Gray'};
var doc = new Document({
    sheets: {
        'Summary': {
            image: {image: fs.readFileSync(__dirname + '/assets/dog.png'), filename: 'dog.png'},
            rows: [{
                cells: [
                    'foo',
                    {value: 'bar', style: 'bold'},
                    {value: 'foo', style: 'lemonBg'},
                    'baz',
                    {value: 'quux', style: 'lemonBgBold'},
                    {value: [{text: 'bold\n', style: 'bold'}, {text: 'brick', style: 'brick'}], style: 'wrap'}
                ]
            }, {
                cells: ['', {value: 'WAT?!', style: 'brick'}, {value: 'dotty', style: 'dotty'}]
            }]
        }
    },
    styles: {
        borders: [{label: 'dkGrey', left: dkGreyBorder, right: dkGreyBorder, top: dkGreyBorder, bottom: dkGreyBorder}],
        fonts: [{label: 'bold', bold: true}, {label: 'brick', color: 'Brick Red'}],
        fills: [{label: 'lemon', type: 'pattern', color: 'Lemon Glacier'}],
        cellStyles: [
            {label: 'bold', font: 'bold'},
            {label: 'brick', font: 'brick', border: 'dkGrey'},
            {label: 'lemonBg', fill: 'lemon'},
            {label: 'lemonBgBold', font: 'bold', fill: 'lemon'},
            {label: 'dotty', fill: 1},
            {label: 'wrap', alignment: {wrapText: 1}}
        ]
    }
}, {
    useSharedStrings: true
});

fs.writeFileSync(__dirname + '/test.xlsx', doc.build().toXLSX());<|endoftext|>


<commit_before>suite("errors", function () {

});
<commit_msg>add errors test<commit_after>var transform = require("../lib/6to5/transform");
var assert    = require("assert");

suite("errors", function () {
  test("syntax", function () {
    assert.throws(function () {
      transform.test([
        "arr.map(function () {",
        "  return $@!@#;",
        "});"
      ]);
    }, /Error: test: Line 2: Unexpected token ILLEGAL/);
  });
});
<|endoftext|>


<commit_before>var demand = require('must');

var keystone = require('../').init(),
	Types = keystone.Field.Types;

/** Test List and Fields */

// use nocreate to allow required fields without tripping `initial` validation
var Test = keystone.List('Test', { nocreate: true }),
	testItem;

before(function() {

	// Create a Test List with all the field types that will be tested
	Test.add({
		text: Types.Text,
		string_nested: {
			string: String
		},
		date: Types.Date,
		datetime: Types.Datetime,
		bool: Types.Boolean,
		location: {
			basic: Types.Location,
			customRequired: { type: Types.Location, required: ['state', 'country'] }
		}
	});
	Test.register();

	// Create a new Test Item to run tests against
	testItem = new Test.model();

});

/** Tests */

describe('Fields', function() {

	/** FieldType: Date */
	describe('Date', function() {

		it('should parse without error via underscore date', function() {
			testItem._.date.parse('20131204', 'YYYYMMDD');
		});

		it('should be the date we expect', function() {
			testItem.date = new Date(2013, 11, 4);
			demand(testItem._.date.format()).to.equal('4th Dec 2013');
			demand(testItem._.date.format('YYYYMMDD')).to.equal('20131204');
		});

		it('should be a moment object', function() {
			testItem.date = new Date(2013, 11, 4);
			demand(testItem._.date.moment()._isAMomentObject);
		});

	});

	/** FieldType: Boolean */
	describe('Boolean', function() {

		it('should be true when passed the boolean true', function() {
			Test.fields.bool.updateItem(testItem, {
				bool: true
			});
			demand(testItem.bool).be.true();
		});

		it('should be true when passed the string "true"', function() {
			Test.fields.bool.updateItem(testItem, {
				bool: 'true'
			});
			demand(testItem.bool).be.true();
		});

		it('should be false when passed the string "false"', function() {
			Test.fields.bool.updateItem(testItem, {
				bool: 'false'
			});
			demand(testItem.bool).be.false();
		});

	});

	/** FieldType: Location */
	describe('Location', function() {

		var emptyLocationValues = {
			number: '',
			name: '',
			street1: '',
			street2: '',
			suburb: '',
			state: '',
			postcode: '',
			country: '',
			geo: []
		};

		var resetLocationValues = function() {
			testItem.set('location.basic', emptyLocationValues);
			testItem.set('location.required', emptyLocationValues);
			testItem.set('location.customRequired', emptyLocationValues);
		}

		it('should update its value from flat paths', function() {
			resetLocationValues();
			Test.fields['location.basic'].updateItem(testItem, {
				'location.basic.number': 'number',
				'location.basic.name': 'name',
				'location.basic.street1': 'street 1',
				'location.basic.street2': 'street 2',
				'location.basic.suburb': 'suburb',
				'location.basic.state': 'state',
				'location.basic.postcode': 'postcode',
				'location.basic.country': 'country',
				'location.basic.geo_lat': '-33.865143',
				'location.basic.geo_lng': '151.2099'
			});
			demand(testItem.location.basic.number).be('number');
			demand(testItem.location.basic.name).be('name');
			demand(testItem.location.basic.street1).be('street 1');
			demand(testItem.location.basic.street2).be('street 2');
			demand(testItem.location.basic.suburb).be('suburb');
			demand(testItem.location.basic.state).be('state');
			demand(testItem.location.basic.postcode).be('postcode');
			demand(testItem.location.basic.country).be('country');
			demand(Array.isArray(testItem.location.basic.geo)).be.true();
			demand(testItem.location.basic.geo[0]).be(151.2099);
			demand(testItem.location.basic.geo[1]).be(-33.865143);
		});

		it('should update its value from nested paths', function() {
			resetLocationValues();
			Test.fields['location.basic'].updateItem(testItem, {
				location: {
					basic: {
						number: 'number',
						name: 'name',
						street1: 'street 1',
						street2: 'street 2',
						suburb: 'suburb',
						state: 'state',
						postcode: 'postcode',
						country: 'country',
						geo: ['151.2099', '-33.865143']
					}
				}
			});
			demand(testItem.location.basic.number).be('number');
			demand(testItem.location.basic.name).be('name');
			demand(testItem.location.basic.street1).be('street 1');
			demand(testItem.location.basic.street2).be('street 2');
			demand(testItem.location.basic.suburb).be('suburb');
			demand(testItem.location.basic.state).be('state');
			demand(testItem.location.basic.postcode).be('postcode');
			demand(testItem.location.basic.country).be('country');
			demand(Array.isArray(testItem.location.basic.geo)).be.true();
			demand(testItem.location.basic.geo[0]).be(151.2099);
			demand(testItem.location.basic.geo[1]).be(-33.865143);
		});

		it('should remove the location.geo path without valid values', function() {
			resetLocationValues();
			Test.fields['location.basic'].updateItem(testItem, {
				'location.basic.geo': ['151.2099', '-33.865143']
			});
			demand(testItem.location.basic.geo[0]).be(151.2099);
			demand(testItem.location.basic.geo[1]).be(-33.865143);
			Test.fields['location.basic'].updateItem(testItem, {
				'location.basic.geo_lat': '',
				'location.basic.geo_lng': ''
			});
			demand(testItem.location.basic.geo).be.undefined();
		});

		it('should validate required fields', function() {
			Test.fields['location.basic'].validateInput({}, true, testItem).must.be.false();
			Test.fields['location.basic'].validateInput({
				'location.basic.street1': 'street1',
				'location.basic.suburb': ''
			}, true, testItem).must.be.false();
			Test.fields['location.basic'].validateInput({
				'location.basic.street1': 'street1',
				'location.basic.suburb': 'suburb'
			}, true, testItem).must.be.true();
			Test.fields['location.basic'].validateInput({
				location: { basic: {
					street1: 'street1',
					suburb: 'suburb'
				} }
			}, true, testItem).must.be.true();
			Test.fields['location.customRequired'].validateInput({
				'location.customRequired.street1': 'street1',
				'location.customRequired.suburb': 'suburb'
			}, true, testItem).must.be.false();
			Test.fields['location.customRequired'].validateInput({
				'location.customRequired.state': 'state',
				'location.customRequired.country': 'country'
			}, true, testItem).must.be.true();
		});

	});
});
<commit_msg>Adding Text field tests<commit_after>var demand = require('must');

var keystone = require('../').init(),
	Types = keystone.Field.Types;

/** Test List and Fields */

// use nocreate to allow required fields without tripping `initial` validation
var Test = keystone.List('Test', { nocreate: true }),
	testItem;

before(function() {

	// Create a Test List with all the field types that will be tested
	Test.add({
		text: Types.Text,
		bool: Types.Boolean,
		nested: {
			text: String,
			bool: Boolean,
		},
		date: Types.Date,
		datetime: Types.Datetime,
		location: {
			basic: Types.Location,
			customRequired: { type: Types.Location, required: ['state', 'country'] }
		}
	});
	Test.register();

	// Create a new Test Item to run tests against
	testItem = new Test.model();

});

/** Tests */

describe('Fields', function() {

	/** FieldType: Text (String) */
	describe('Text', function() {
		it('should update top level fields', function() {
			Test.fields.text.updateItem(testItem, {
				text: 'value'
			});
			demand(testItem.text).be('value');
			testItem.text = undefined;
		});
		it('should update nested fields', function() {
			Test.fields['nested.text'].updateItem(testItem, {
				nested: {
					text: 'value'
				}
			});
			demand(testItem.nested.text).be('value');
			testItem.nested.text = undefined;
		});
		it('should update nested fields with flat paths', function() {
			Test.fields['nested.text'].updateItem(testItem, {
				'nested.text': 'value'
			});
			demand(testItem.nested.text).be('value');
			testItem.nested.text = undefined;
		});
	});

	/** FieldType: Date */
	describe('Date', function() {

		it('should parse without error via underscore date', function() {
			testItem._.date.parse('20131204', 'YYYYMMDD');
		});

		it('should be the date we expect', function() {
			testItem.date = new Date(2013, 11, 4);
			demand(testItem._.date.format()).to.equal('4th Dec 2013');
			demand(testItem._.date.format('YYYYMMDD')).to.equal('20131204');
		});

		it('should be a moment object', function() {
			testItem.date = new Date(2013, 11, 4);
			demand(testItem._.date.moment()._isAMomentObject);
		});

	});

	/** FieldType: Boolean */
	describe('Boolean', function() {

		it('should be true when passed the boolean true', function() {
			Test.fields.bool.updateItem(testItem, {
				bool: true
			});
			demand(testItem.bool).be.true();
		});

		it('should be true when passed the string "true"', function() {
			Test.fields.bool.updateItem(testItem, {
				bool: 'true'
			});
			demand(testItem.bool).be.true();
		});

		it('should be false when passed the string "false"', function() {
			Test.fields.bool.updateItem(testItem, {
				bool: 'false'
			});
			demand(testItem.bool).be.false();
		});

	});

	/** FieldType: Location */
	describe('Location', function() {

		var emptyLocationValues = {
			number: '',
			name: '',
			street1: '',
			street2: '',
			suburb: '',
			state: '',
			postcode: '',
			country: '',
			geo: []
		};

		var resetLocationValues = function() {
			testItem.set('location.basic', emptyLocationValues);
			testItem.set('location.required', emptyLocationValues);
			testItem.set('location.customRequired', emptyLocationValues);
		}

		it('should update its value from flat paths', function() {
			resetLocationValues();
			Test.fields['location.basic'].updateItem(testItem, {
				'location.basic.number': 'number',
				'location.basic.name': 'name',
				'location.basic.street1': 'street 1',
				'location.basic.street2': 'street 2',
				'location.basic.suburb': 'suburb',
				'location.basic.state': 'state',
				'location.basic.postcode': 'postcode',
				'location.basic.country': 'country',
				'location.basic.geo_lat': '-33.865143',
				'location.basic.geo_lng': '151.2099'
			});
			demand(testItem.location.basic.number).be('number');
			demand(testItem.location.basic.name).be('name');
			demand(testItem.location.basic.street1).be('street 1');
			demand(testItem.location.basic.street2).be('street 2');
			demand(testItem.location.basic.suburb).be('suburb');
			demand(testItem.location.basic.state).be('state');
			demand(testItem.location.basic.postcode).be('postcode');
			demand(testItem.location.basic.country).be('country');
			demand(Array.isArray(testItem.location.basic.geo)).be.true();
			demand(testItem.location.basic.geo[0]).be(151.2099);
			demand(testItem.location.basic.geo[1]).be(-33.865143);
		});

		it('should update its value from nested paths', function() {
			resetLocationValues();
			Test.fields['location.basic'].updateItem(testItem, {
				location: {
					basic: {
						number: 'number',
						name: 'name',
						street1: 'street 1',
						street2: 'street 2',
						suburb: 'suburb',
						state: 'state',
						postcode: 'postcode',
						country: 'country',
						geo: ['151.2099', '-33.865143']
					}
				}
			});
			demand(testItem.location.basic.number).be('number');
			demand(testItem.location.basic.name).be('name');
			demand(testItem.location.basic.street1).be('street 1');
			demand(testItem.location.basic.street2).be('street 2');
			demand(testItem.location.basic.suburb).be('suburb');
			demand(testItem.location.basic.state).be('state');
			demand(testItem.location.basic.postcode).be('postcode');
			demand(testItem.location.basic.country).be('country');
			demand(Array.isArray(testItem.location.basic.geo)).be.true();
			demand(testItem.location.basic.geo[0]).be(151.2099);
			demand(testItem.location.basic.geo[1]).be(-33.865143);
		});

		it('should remove the location.geo path without valid values', function() {
			resetLocationValues();
			Test.fields['location.basic'].updateItem(testItem, {
				'location.basic.geo': ['151.2099', '-33.865143']
			});
			demand(testItem.location.basic.geo[0]).be(151.2099);
			demand(testItem.location.basic.geo[1]).be(-33.865143);
			Test.fields['location.basic'].updateItem(testItem, {
				'location.basic.geo_lat': '',
				'location.basic.geo_lng': ''
			});
			demand(testItem.location.basic.geo).be.undefined();
		});

		it('should validate required fields', function() {
			Test.fields['location.basic'].validateInput({}, true, testItem).must.be.false();
			Test.fields['location.basic'].validateInput({
				'location.basic.street1': 'street1',
				'location.basic.suburb': ''
			}, true, testItem).must.be.false();
			Test.fields['location.basic'].validateInput({
				'location.basic.street1': 'street1',
				'location.basic.suburb': 'suburb'
			}, true, testItem).must.be.true();
			Test.fields['location.basic'].validateInput({
				location: { basic: {
					street1: 'street1',
					suburb: 'suburb'
				} }
			}, true, testItem).must.be.true();
			Test.fields['location.customRequired'].validateInput({
				'location.customRequired.street1': 'street1',
				'location.customRequired.suburb': 'suburb'
			}, true, testItem).must.be.false();
			Test.fields['location.customRequired'].validateInput({
				'location.customRequired.state': 'state',
				'location.customRequired.country': 'country'
			}, true, testItem).must.be.true();
		});

	});
});
<|endoftext|>


<commit_before>
var vows   = require('vows')
var assert = require('assert')
var gex    = require('gex')
var parambulator = require('../lib/parambulator.js')

vows.describe('format').addBatch({
  'happy': {
    topic: function() {
      try {
        return new parambulator.Parambulator({
          a: {format$:'datetime'},
          b: {format$:'date'},
          c: {format$:'time'},
        })
      }
      catch( e ) {
        console.log(e.stack)
        throw e
      }
    },

    'datetime': function( pb ) {
      pb.validate({},function(err,res){
        assert.isNull(err)
      })

      pb.validate({a:'2012-02-02T11:12:13Z'},function(err,res){
        assert.isNull(err)
      })

      pb.validate({a:'2012-02-02'},function(err,res){
        assert.isNotNull(err)
        assert.equal(err.parambulator.code,'format$')
      })
    },

    'date': function( pb ) {
      pb.validate({},function(err,res){
        assert.isNull(err)
      })

      pb.validate({b:'2012-02-02'},function(err,res){
        assert.isNull(err)
      })

      pb.validate({b:'2012-32-02'},function(err,res){
        assert.isNotNull(err)
        assert.equal(err.parambulator.code,'format$')
      })
    },

    'time': function( pb ) {
      pb.validate({},function(err,res){
        assert.isNull(err)
      })

      pb.validate({c:'11:12:13Z'},function(err,res){
        assert.isNull(err)
      })

      pb.validate({c:'51:12:13Z'},function(err,res){
        assert.isNotNull(err)
        assert.equal(err.parambulator.code,'format$')
      })
    },
  }
}).export(module)

<commit_msg>Implement support for format$ rule. Few formats are now available. See #7<commit_after>
var vows   = require('vows')
var assert = require('assert')
var gex    = require('gex')
var parambulator = require('../lib/parambulator.js')

vows.describe('format').addBatch({
  'happy': {
    topic: function() {
      try {
        return new parambulator.Parambulator({
          a: {format$:'datetime'},
          b: {format$:'date'},
          c: {format$:'time'},
          d: {format$:'utcmillisec'},
          e: {format$:'re'},
          f: {format$:['date', 'time']},
        })
      }
      catch( e ) {
        console.log(e.stack)
        throw e
      }
    },

    'datetime': function( pb ) {
      pb.validate({},function(err,res){
        assert.isNull(err)
      })

      pb.validate({a:'2012-02-02T11:12:13Z'},function(err,res){
        assert.isNull(err)
      })

      pb.validate({a:'2012-02-02'},function(err,res){
        assert.isNotNull(err)
        assert.equal(err.parambulator.code,'format$')
      })
    },

    'date': function( pb ) {
      pb.validate({},function(err,res){
        assert.isNull(err)
      })

      pb.validate({b:'2012-02-02'},function(err,res){
        assert.isNull(err)
      })

      pb.validate({b:'2012-32-02'},function(err,res){
        assert.isNotNull(err)
        assert.equal(err.parambulator.code,'format$')
      })
    },

    'time': function( pb ) {
      pb.validate({},function(err,res){
        assert.isNull(err)
      })

      pb.validate({c:'11:12:13Z'},function(err,res){
        assert.isNull(err)
      })

      pb.validate({c:'51:12:13Z'},function(err,res){
        assert.isNotNull(err)
        assert.equal(err.parambulator.code,'format$')
      })
    },

    'utcmillisec': function( pb ) {
      pb.validate({},function(err,res){
        assert.isNull(err)
      })

      pb.validate({d:124578},function(err,res){
        assert.isNull(err)
      })

      pb.validate({d:'test'},function(err,res){
        assert.isNotNull(err)
        assert.equal(err.parambulator.code,'format$')
      })
    },

    're': function( pb ) {
      pb.validate({},function(err,res){
        assert.isNull(err)
      })

      pb.validate({e:/([0-1]\d|2[0-4]):[0-5]\d:[0-5]\dZ/},function(err,res){
        assert.isNull(err)
      })

      pb.validate({e:124578},function(err,res){
        assert.isNotNull(err)
        assert.equal(err.parambulator.code,'format$')
      })
    },

    'date-time': function( pb ) {
      pb.validate({},function(err,res){
        assert.isNull(err)
      })

      pb.validate({f:'2012-02-02'},function(err,res){
        assert.isNull(err)
      })

      pb.validate({f:'2012-32-02'},function(err,res){
        assert.isNotNull(err)
        assert.equal(err.parambulator.code,'format$')
      })

      pb.validate({f:'11:12:13Z'},function(err,res){
        assert.isNull(err)
      })

      pb.validate({f:'51:12:13Z'},function(err,res){
        assert.isNotNull(err)
        assert.equal(err.parambulator.code,'format$')
      })

      pb.validate({f:124578},function(err,res){
        assert.isNotNull(err)
        assert.equal(err.parambulator.code,'format$')
      })

      pb.validate({f:/([0-1]\d|2[0-4]):[0-5]\d:[0-5]\dZ/},function(err,res){
        assert.isNotNull(err)
        assert.equal(err.parambulator.code,'format$')
      })

      pb.validate({f:124578},function(err,res){
        assert.isNotNull(err)
        assert.equal(err.parambulator.code,'format$')
      })

      pb.validate({f:'test'},function(err,res){
        assert.isNotNull(err)
        assert.equal(err.parambulator.code,'format$')
      })
    },

  }
}).export(module)

<|endoftext|>


<commit_before>// http://stackoverflow.com/a/16714931/861745
(new Date()).toISOString().slice(0,10)
<commit_msg>Update YYYY-MM-DD.js<commit_after>
// http://stackoverflow.com/a/16714931/861745
function fnYYYY_MM_DD(objDate) {
	if (objDate === undefined) {
		objDate = new Date();
	}
	return objDate.toISOString().slice(0,10);
}

// if this file is run directly, do the following:
if (require.main === module) {
	console.log( fnYYYY_MM_DD() );
}
<|endoftext|>


<commit_before>// ===================================================================================================
//                           _  __     _ _
//                          | |/ /__ _| | |_ _  _ _ _ __ _
//                          | ' </ _` | |  _| || | '_/ _` |
//                          |_|\_\__,_|_|\__|\_,_|_| \__,_|
//
// This file is part of the Kaltura Collaborative Media Suite which allows users
// to do with audio, video, and animation what Wiki platfroms allow them to do with
// text.
//
// Copyright (C) 2006-2019  Kaltura Inc.
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as
// published by the Free Software Foundation, either version 3 of the
// License, or (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with this program.  If not, see <http://www.gnu.org/licenses/>.
//
// @ignore
// ===================================================================================================
/**
 * The Kaltura Client - this is the facade through which all service actions should be called.
 * @param config the Kaltura configuration object holding partner credentials (type: KalturaConfiguration).
 */
var util = require('util');
var kaltura = require('./KalturaClientBase');
kaltura.services = require('./KalturaServices');
kaltura.objects = require('./KalturaModel');
kaltura.enums = require('./KalturaTypes');

class Client extends kaltura.ClientBase {

	/**
	 * @param Configuration config
	 */
	constructor(config) {
		super(config);
		this.setApiVersion('15.2.0');
		this.setClientTag('node:19-07-06');
	}
}

module.exports = kaltura;
module.exports.Client = Client;

<commit_msg>New clientlib ver<commit_after>// ===================================================================================================
//                           _  __     _ _
//                          | |/ /__ _| | |_ _  _ _ _ __ _
//                          | ' </ _` | |  _| || | '_/ _` |
//                          |_|\_\__,_|_|\__|\_,_|_| \__,_|
//
// This file is part of the Kaltura Collaborative Media Suite which allows users
// to do with audio, video, and animation what Wiki platfroms allow them to do with
// text.
//
// Copyright (C) 2006-2019  Kaltura Inc.
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as
// published by the Free Software Foundation, either version 3 of the
// License, or (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with this program.  If not, see <http://www.gnu.org/licenses/>.
//
// @ignore
// ===================================================================================================
/**
 * The Kaltura Client - this is the facade through which all service actions should be called.
 * @param config the Kaltura configuration object holding partner credentials (type: KalturaConfiguration).
 */
var util = require('util');
var kaltura = require('./KalturaClientBase');
kaltura.services = require('./KalturaServices');
kaltura.objects = require('./KalturaModel');
kaltura.enums = require('./KalturaTypes');

class Client extends kaltura.ClientBase {

	/**
	 * @param Configuration config
	 */
	constructor(config) {
		super(config);
		this.setApiVersion('15.2.0');
		this.setClientTag('node:19-07-07');
	}
}

module.exports = kaltura;
module.exports.Client = Client;

<|endoftext|>


<commit_before>// ===================================================================================================
//                           _  __     _ _
//                          | |/ /__ _| | |_ _  _ _ _ __ _
//                          | ' </ _` | |  _| || | '_/ _` |
//                          |_|\_\__,_|_|\__|\_,_|_| \__,_|
//
// This file is part of the Kaltura Collaborative Media Suite which allows users
// to do with audio, video, and animation what Wiki platforms allow them to do with
// text.
//
// Copyright (C) 2006-2022  Kaltura Inc.
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as
// published by the Free Software Foundation, either version 3 of the
// License, or (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with this program.  If not, see <http://www.gnu.org/licenses/>.
//
// @ignore
// ===================================================================================================
/**
 * The Kaltura Client - this is the facade through which all service actions should be called.
 * @param config the Kaltura configuration object holding partner credentials (type: KalturaConfiguration).
 */
var util = require('util');
var kaltura = require('./KalturaClientBase');
kaltura.services = require('./KalturaServices');
kaltura.objects = require('./KalturaModel');
kaltura.enums = require('./KalturaTypes');

class Client extends kaltura.ClientBase {

	/**
	 * @param Configuration config
	 */
	constructor(config) {
		super(config);
		this.setApiVersion('18.7.0');
		this.setClientTag('node:22-06-21');
	}
}

module.exports = kaltura;
module.exports.Client = Client;

<commit_msg>New clientlib ver<commit_after>// ===================================================================================================
//                           _  __     _ _
//                          | |/ /__ _| | |_ _  _ _ _ __ _
//                          | ' </ _` | |  _| || | '_/ _` |
//                          |_|\_\__,_|_|\__|\_,_|_| \__,_|
//
// This file is part of the Kaltura Collaborative Media Suite which allows users
// to do with audio, video, and animation what Wiki platforms allow them to do with
// text.
//
// Copyright (C) 2006-2022  Kaltura Inc.
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as
// published by the Free Software Foundation, either version 3 of the
// License, or (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with this program.  If not, see <http://www.gnu.org/licenses/>.
//
// @ignore
// ===================================================================================================
/**
 * The Kaltura Client - this is the facade through which all service actions should be called.
 * @param config the Kaltura configuration object holding partner credentials (type: KalturaConfiguration).
 */
var util = require('util');
var kaltura = require('./KalturaClientBase');
kaltura.services = require('./KalturaServices');
kaltura.objects = require('./KalturaModel');
kaltura.enums = require('./KalturaTypes');

class Client extends kaltura.ClientBase {

	/**
	 * @param Configuration config
	 */
	constructor(config) {
		super(config);
		this.setApiVersion('18.7.0');
		this.setClientTag('node:22-06-22');
	}
}

module.exports = kaltura;
module.exports.Client = Client;

<|endoftext|>


<commit_before>// ===================================================================================================
//                           _  __     _ _
//                          | |/ /__ _| | |_ _  _ _ _ __ _
//                          | ' </ _` | |  _| || | '_/ _` |
//                          |_|\_\__,_|_|\__|\_,_|_| \__,_|
//
// This file is part of the Kaltura Collaborative Media Suite which allows users
// to do with audio, video, and animation what Wiki platfroms allow them to do with
// text.
//
// Copyright (C) 2006-2020  Kaltura Inc.
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as
// published by the Free Software Foundation, either version 3 of the
// License, or (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with this program.  If not, see <http://www.gnu.org/licenses/>.
//
// @ignore
// ===================================================================================================
/**
 * The Kaltura Client - this is the facade through which all service actions should be called.
 * @param config the Kaltura configuration object holding partner credentials (type: KalturaConfiguration).
 */
var util = require('util');
var kaltura = require('./KalturaClientBase');
kaltura.services = require('./KalturaServices');
kaltura.objects = require('./KalturaModel');
kaltura.enums = require('./KalturaTypes');

class Client extends kaltura.ClientBase {

	/**
	 * @param Configuration config
	 */
	constructor(config) {
		super(config);
		this.setApiVersion('16.0.0');
		this.setClientTag('node:20-05-06');
	}
}

module.exports = kaltura;
module.exports.Client = Client;

<commit_msg>New clientlib ver<commit_after>// ===================================================================================================
//                           _  __     _ _
//                          | |/ /__ _| | |_ _  _ _ _ __ _
//                          | ' </ _` | |  _| || | '_/ _` |
//                          |_|\_\__,_|_|\__|\_,_|_| \__,_|
//
// This file is part of the Kaltura Collaborative Media Suite which allows users
// to do with audio, video, and animation what Wiki platfroms allow them to do with
// text.
//
// Copyright (C) 2006-2020  Kaltura Inc.
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as
// published by the Free Software Foundation, either version 3 of the
// License, or (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with this program.  If not, see <http://www.gnu.org/licenses/>.
//
// @ignore
// ===================================================================================================
/**
 * The Kaltura Client - this is the facade through which all service actions should be called.
 * @param config the Kaltura configuration object holding partner credentials (type: KalturaConfiguration).
 */
var util = require('util');
var kaltura = require('./KalturaClientBase');
kaltura.services = require('./KalturaServices');
kaltura.objects = require('./KalturaModel');
kaltura.enums = require('./KalturaTypes');

class Client extends kaltura.ClientBase {

	/**
	 * @param Configuration config
	 */
	constructor(config) {
		super(config);
		this.setApiVersion('16.0.0');
		this.setClientTag('node:20-05-07');
	}
}

module.exports = kaltura;
module.exports.Client = Client;

<|endoftext|>


<commit_before>// ===================================================================================================
//                           _  __     _ _
//                          | |/ /__ _| | |_ _  _ _ _ __ _
//                          | ' </ _` | |  _| || | '_/ _` |
//                          |_|\_\__,_|_|\__|\_,_|_| \__,_|
//
// This file is part of the Kaltura Collaborative Media Suite which allows users
// to do with audio, video, and animation what Wiki platfroms allow them to do with
// text.
//
// Copyright (C) 2006-2018  Kaltura Inc.
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as
// published by the Free Software Foundation, either version 3 of the
// License, or (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with this program.  If not, see <http://www.gnu.org/licenses/>.
//
// @ignore
// ===================================================================================================
/**
 * The Kaltura Client - this is the facade through which all service actions should be called.
 * @param config the Kaltura configuration object holding partner credentials (type: KalturaConfiguration).
 */
var util = require('util');
var kaltura = require('./KalturaClientBase');
kaltura.services = require('./KalturaServices');
kaltura.objects = require('./KalturaModel');
kaltura.enums = require('./KalturaTypes');

class Client extends kaltura.ClientBase {

	/**
	 * @param Configuration config
	 */
	constructor(config) {
		super(config);
		this.setApiVersion('14.6.0');
		this.setClientTag('node:18-09-29');
	}
}

module.exports = kaltura;
module.exports.Client = Client;

<commit_msg>New clientlib ver<commit_after>// ===================================================================================================
//                           _  __     _ _
//                          | |/ /__ _| | |_ _  _ _ _ __ _
//                          | ' </ _` | |  _| || | '_/ _` |
//                          |_|\_\__,_|_|\__|\_,_|_| \__,_|
//
// This file is part of the Kaltura Collaborative Media Suite which allows users
// to do with audio, video, and animation what Wiki platfroms allow them to do with
// text.
//
// Copyright (C) 2006-2018  Kaltura Inc.
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as
// published by the Free Software Foundation, either version 3 of the
// License, or (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with this program.  If not, see <http://www.gnu.org/licenses/>.
//
// @ignore
// ===================================================================================================
/**
 * The Kaltura Client - this is the facade through which all service actions should be called.
 * @param config the Kaltura configuration object holding partner credentials (type: KalturaConfiguration).
 */
var util = require('util');
var kaltura = require('./KalturaClientBase');
kaltura.services = require('./KalturaServices');
kaltura.objects = require('./KalturaModel');
kaltura.enums = require('./KalturaTypes');

class Client extends kaltura.ClientBase {

	/**
	 * @param Configuration config
	 */
	constructor(config) {
		super(config);
		this.setApiVersion('14.6.0');
		this.setClientTag('node:18-09-30');
	}
}

module.exports = kaltura;
module.exports.Client = Client;

<|endoftext|>


<commit_before>// ===================================================================================================
//                           _  __     _ _
//                          | |/ /__ _| | |_ _  _ _ _ __ _
//                          | ' </ _` | |  _| || | '_/ _` |
//                          |_|\_\__,_|_|\__|\_,_|_| \__,_|
//
// This file is part of the Kaltura Collaborative Media Suite which allows users
// to do with audio, video, and animation what Wiki platfroms allow them to do with
// text.
//
// Copyright (C) 2006-2019  Kaltura Inc.
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as
// published by the Free Software Foundation, either version 3 of the
// License, or (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with this program.  If not, see <http://www.gnu.org/licenses/>.
//
// @ignore
// ===================================================================================================
/**
 * The Kaltura Client - this is the facade through which all service actions should be called.
 * @param config the Kaltura configuration object holding partner credentials (type: KalturaConfiguration).
 */
var util = require('util');
var kaltura = require('./KalturaClientBase');
kaltura.services = require('./KalturaServices');
kaltura.objects = require('./KalturaModel');
kaltura.enums = require('./KalturaTypes');

class Client extends kaltura.ClientBase {

	/**
	 * @param Configuration config
	 */
	constructor(config) {
		super(config);
		this.setApiVersion('15.12.0');
		this.setClientTag('node:19-12-06');
	}
}

module.exports = kaltura;
module.exports.Client = Client;

<commit_msg>New clientlib ver<commit_after>// ===================================================================================================
//                           _  __     _ _
//                          | |/ /__ _| | |_ _  _ _ _ __ _
//                          | ' </ _` | |  _| || | '_/ _` |
//                          |_|\_\__,_|_|\__|\_,_|_| \__,_|
//
// This file is part of the Kaltura Collaborative Media Suite which allows users
// to do with audio, video, and animation what Wiki platfroms allow them to do with
// text.
//
// Copyright (C) 2006-2019  Kaltura Inc.
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as
// published by the Free Software Foundation, either version 3 of the
// License, or (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with this program.  If not, see <http://www.gnu.org/licenses/>.
//
// @ignore
// ===================================================================================================
/**
 * The Kaltura Client - this is the facade through which all service actions should be called.
 * @param config the Kaltura configuration object holding partner credentials (type: KalturaConfiguration).
 */
var util = require('util');
var kaltura = require('./KalturaClientBase');
kaltura.services = require('./KalturaServices');
kaltura.objects = require('./KalturaModel');
kaltura.enums = require('./KalturaTypes');

class Client extends kaltura.ClientBase {

	/**
	 * @param Configuration config
	 */
	constructor(config) {
		super(config);
		this.setApiVersion('15.12.0');
		this.setClientTag('node:19-12-07');
	}
}

module.exports = kaltura;
module.exports.Client = Client;

<|endoftext|>


<commit_before>// ===================================================================================================
//                           _  __     _ _
//                          | |/ /__ _| | |_ _  _ _ _ __ _
//                          | ' </ _` | |  _| || | '_/ _` |
//                          |_|\_\__,_|_|\__|\_,_|_| \__,_|
//
// This file is part of the Kaltura Collaborative Media Suite which allows users
// to do with audio, video, and animation what Wiki platfroms allow them to do with
// text.
//
// Copyright (C) 2006-2020  Kaltura Inc.
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as
// published by the Free Software Foundation, either version 3 of the
// License, or (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with this program.  If not, see <http://www.gnu.org/licenses/>.
//
// @ignore
// ===================================================================================================
/**
 * The Kaltura Client - this is the facade through which all service actions should be called.
 * @param config the Kaltura configuration object holding partner credentials (type: KalturaConfiguration).
 */
var util = require('util');
var kaltura = require('./KalturaClientBase');
kaltura.services = require('./KalturaServices');
kaltura.objects = require('./KalturaModel');
kaltura.enums = require('./KalturaTypes');

class Client extends kaltura.ClientBase {

	/**
	 * @param Configuration config
	 */
	constructor(config) {
		super(config);
		this.setApiVersion('15.19.0');
		this.setClientTag('node:20-03-16');
	}
}

module.exports = kaltura;
module.exports.Client = Client;

<commit_msg>New clientlib ver<commit_after>// ===================================================================================================
//                           _  __     _ _
//                          | |/ /__ _| | |_ _  _ _ _ __ _
//                          | ' </ _` | |  _| || | '_/ _` |
//                          |_|\_\__,_|_|\__|\_,_|_| \__,_|
//
// This file is part of the Kaltura Collaborative Media Suite which allows users
// to do with audio, video, and animation what Wiki platfroms allow them to do with
// text.
//
// Copyright (C) 2006-2020  Kaltura Inc.
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as
// published by the Free Software Foundation, either version 3 of the
// License, or (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with this program.  If not, see <http://www.gnu.org/licenses/>.
//
// @ignore
// ===================================================================================================
/**
 * The Kaltura Client - this is the facade through which all service actions should be called.
 * @param config the Kaltura configuration object holding partner credentials (type: KalturaConfiguration).
 */
var util = require('util');
var kaltura = require('./KalturaClientBase');
kaltura.services = require('./KalturaServices');
kaltura.objects = require('./KalturaModel');
kaltura.enums = require('./KalturaTypes');

class Client extends kaltura.ClientBase {

	/**
	 * @param Configuration config
	 */
	constructor(config) {
		super(config);
		this.setApiVersion('15.19.0');
		this.setClientTag('node:20-03-17');
	}
}

module.exports = kaltura;
module.exports.Client = Client;

<|endoftext|>


<commit_before>var frameSrc = "http://localhost:8080/assijus/popup.html";
frameSrc = "https://ittrufusion.appspot.com";
frameSrc = "https://assijus.trf2.jus.br/assijus";
frameSrc = "http://localhost:8080/assijus/index1.html";
frameSrc = "http://localhost:8080/assijus/index.html";
frameSrc = "http://localhost:8080/assijus/popup.html";

function receiveMessageAssinaturaDigital(event) {
	var iframe = document.getElementById('iframeAssinaturaDigital');
	var iframeWindow = iframe.contentWindow;

	if (event.data.command === '<READY>') {
		iframeWindow.postMessage({
			command : '<GO>',
			docs : window._AssinaturaDigitalParametros.docs
		}, '*');
	}

	if (event.data.command === '<BEGIN-REQUEST>') {
		window._AssinaturaDigitalParametros.beginCallback(function(params) {
			iframeWindow.postMessage({
				command : '<BEGIN-RESPONSE>'
			}, '*');
		})
	}

	if (event.data.command === '<HASH-REQUEST>') {
		window._AssinaturaDigitalParametros.hashCallback(event.data.id,
				function(params) {
					iframeWindow.postMessage({
						command : '<HASH-RESPONSE>',
						params : params
					}, '*');
				})
	}

	if (event.data.command === '<SAVE-REQUEST>') {
		window._AssinaturaDigitalParametros.saveCallback(event.data.id,
				event.data.sign, function(params) {
					iframeWindow.postMessage({
						command : '<SAVE-RESPONSE>',
						params : params
					}, '*');
				})
	}

	if (event.data.command === '<END-REQUEST>') {
		window._AssinaturaDigitalParametros.dismissCallback(function(params) {
			iframeWindow.postMessage({
				command : '<END-RESPONSE>'
			}, '*');
		})
	}

	if (event.data.command === '<SET-HEIGHT>') {
		iframe.style.height = event.data.height;
	}
}

var produzirAssinaturaDigital = function(params) {
	window._AssinaturaDigitalParametros = params;
	window.addEventListener("message", receiveMessageAssinaturaDigital, false);

	if (!params.beginCallback)
		params.beginCallback = function() {
		};

	if (!params.endCallback)
		params.endCallback = function() {
		};

	var popupTemplate = '
'
			+ '
'
			+ '
'
			+ '
'
			+ '        <button type="button" class="close" data-dismiss="modal">×</button>'
			+ '
Assinatura Digital
'
			+ '

'
			+ '
';

	var dlg = $(popupTemplate);
	dlg.modal({
		show : true
	});

	params.dismissCallback = function() {
		params.endCallback();
		dlg.modal('hide');
		setTimeout(function() {
			dlg.remove();
		}, 1000);
	}

}<commit_msg>Corrigindo a url no popup-api.js<commit_after>var frameSrc = "https://assijus.trf2.jus.br/assijus/popup.html";

function receiveMessageAssinaturaDigital(event) {
	var iframe = document.getElementById('iframeAssinaturaDigital');
	var iframeWindow = iframe.contentWindow;

	if (event.data.command === '<READY>') {
		iframeWindow.postMessage({
			command : '<GO>',
			docs : window._AssinaturaDigitalParametros.docs
		}, '*');
	}

	if (event.data.command === '<BEGIN-REQUEST>') {
		window._AssinaturaDigitalParametros.beginCallback(function(params) {
			iframeWindow.postMessage({
				command : '<BEGIN-RESPONSE>'
			}, '*');
		})
	}

	if (event.data.command === '<HASH-REQUEST>') {
		window._AssinaturaDigitalParametros.hashCallback(event.data.id,
				function(params) {
					iframeWindow.postMessage({
						command : '<HASH-RESPONSE>',
						params : params
					}, '*');
				})
	}

	if (event.data.command === '<SAVE-REQUEST>') {
		window._AssinaturaDigitalParametros.saveCallback(event.data.id,
				event.data.sign, function(params) {
					iframeWindow.postMessage({
						command : '<SAVE-RESPONSE>',
						params : params
					}, '*');
				})
	}

	if (event.data.command === '<END-REQUEST>') {
		window._AssinaturaDigitalParametros.dismissCallback(function(params) {
			iframeWindow.postMessage({
				command : '<END-RESPONSE>'
			}, '*');
		})
	}

	if (event.data.command === '<SET-HEIGHT>') {
		iframe.style.height = event.data.height;
	}
}

var produzirAssinaturaDigital = function(params) {
	window._AssinaturaDigitalParametros = params;
	window.addEventListener("message", receiveMessageAssinaturaDigital, false);

	if (!params.beginCallback)
		params.beginCallback = function() {
		};

	if (!params.endCallback)
		params.endCallback = function() {
		};

	var popupTemplate = '
'
			+ '
'
			+ '
'
			+ '
'
			+ '        <button type="button" class="close" data-dismiss="modal">×</button>'
			+ '
Assinatura Digital
'
			+ '

'
			+ '
';

	var dlg = $(popupTemplate);
	dlg.modal({
		show : true
	});

	params.dismissCallback = function() {
		params.endCallback();
		dlg.modal('hide');
		setTimeout(function() {
			dlg.remove();
		}, 1000);
	}

}<|endoftext|>


<commit_before>import React from 'react';
import {shallow} from 'enzyme';
import ErrorWrapper from '../ErrorWrapper.tsx';

const input = <input value='This is in an input tag' />;
const div =
This is in a div tag
;
const className = 'some-class';

const singleChildWithTypeNotHidden = {
    className,
    type: 'email',
    children: input
};

const singleChildWithTypeHidden = {
    className,
    type: 'hidden',
    children: input
};

const multipleChildrenWithTypeNotHidden = {
    className,
    type: 'number',
    children: [input, div]
};

const multipleChildrenWithTypeHidden = {
    className,
    type: 'hidden',
    children: [input, div]
};

describe('<ErrorWrapper />', () => {

    // ask shane for test description
    it('should render a single child inside the
 NOT having class name = .hidden', () => {
        const wrapper = shallow(<ErrorWrapper {...singleChildWithTypeNotHidden} />);

        expect(wrapper.is('.some-class')).toBe(true);
        expect(wrapper.is('.input-hidden')).toBe(false);

        expect(wrapper.contains(input)).toBe(true);
    });

    it('should render a single child inside the
 having class name = .hidden', () => {
        const wrapper = shallow(<ErrorWrapper {...singleChildWithTypeHidden} />);

        expect(wrapper.is('.some-class')).toBe(true);
        expect(wrapper.is('.input-hidden')).toBe(true);

        expect(wrapper.contains(input)).toBe(true);
    });

    it('should render a <input /> &
 inside the
 NOT having class name = .hidden', () => {
        const wrapper = shallow(<ErrorWrapper {...multipleChildrenWithTypeNotHidden} />);

        expect(wrapper.is('.some-class')).toBe(true);
        expect(wrapper.is('.input-hidden')).toBe(false);

        expect(wrapper.contains(input)).toBe(true);
        expect(wrapper.contains(div)).toBe(true);
    });

    it('should render a <input /> &
 inside the
 having class name = .hidden', () => {
        const wrapper = shallow(<ErrorWrapper {...multipleChildrenWithTypeHidden} />);

        expect(wrapper.is('.some-class')).toBe(true);
        expect(wrapper.is('.input-hidden')).toBe(true);

        expect(wrapper.contains(input)).toBe(true);
        expect(wrapper.contains(div)).toBe(true);
    });
});<commit_msg>individual things being tested<commit_after>import React from 'react';
import {shallow} from 'enzyme';
import ErrorWrapper from '../ErrorWrapper.tsx';

const input = <input value='This is in an input tag' />;
const div =
This is in a div tag
;
const className = 'some-class';

const singleChildWithTypeNotHidden = {
    className,
    type: 'email',
    children: input
};

const singleChildWithTypeHidden = {
    className,
    type: 'hidden',
    children: input
};

const multipleChildrenWithTypeNotHidden = {
    className,
    type: 'number',
    children: [input, div]
};

const multipleChildrenWithTypeHidden = {
    className,
    type: 'hidden',
    children: [input, div]
};

describe('<ErrorWrapper />', () => {

    // wrapper div
    it('should render a
 having specified classnames', () => {
        const wrapper = shallow(<ErrorWrapper {...singleChildWithTypeNotHidden} />);

        expect(wrapper.is('.some-class')).toBe(true);
    });

    // wrapper div with hidden class
    it('should render a
 having specified classnames with additional .input-hidden class', () => {
        const wrapper = shallow(<ErrorWrapper {...singleChildWithTypeHidden} />);

        expect(wrapper.is('.input-hidden')).toBe(true);
    });

    // single child
    it('should render a single child inside the wrapper', () => {
        const wrapperNotHidden = shallow(<ErrorWrapper {...singleChildWithTypeNotHidden} />);
        const wrapperHidden = shallow(<ErrorWrapper {...singleChildWithTypeHidden} />);

        expect(wrapperNotHidden.contains(input)).toBe(true);
        expect(wrapperHidden.contains(input)).toBe(true);
    });

    // multiple children
    it('should render a single child inside the wrapper', () => {
        const wrapperNotHidden = shallow(<ErrorWrapper {...multipleChildrenWithTypeNotHidden} />);
        const wrapperHidden = shallow(<ErrorWrapper {...multipleChildrenWithTypeHidden} />);

        expect(wrapperNotHidden.contains(input)).toBe(true);
        expect(wrapperNotHidden.contains(div)).toBe(true);

        expect(wrapperHidden.contains(input)).toBe(true);
        expect(wrapperHidden.contains(div)).toBe(true);
    });
});<|endoftext|>