<commit_before>describe('Dictionary',
function() {

    var dict = null;
    var elems = 100;

    beforeEach(function() {
        dict = new collections.Dictionary();
    });

    it('Maps keys to values with string keys',
    function() {

        expect(dict.getValue("sd")).toBeUndefined();

        // test with string keys
        for (var i = 0; i < elems; i++) {
            expect(dict.setValue("" + i, i + 1)).toBeUndefined();
        }
        expect(dict.size()).toEqual(elems);

        for (var i = 0; i < elems; i++) {
            expect(dict.getValue("" + i)).toEqual(i + 1);
        }

        dict.setValue("a", 5);
        expect(dict.getValue("a")).toEqual(5);
        expect(dict.setValue("a", 21)).toEqual(5);
        expect(dict.size()).toEqual(elems + 1);
        expect(dict.getValue("a")).toEqual(21);

    });

    it('Maps keys to values with number keys',
    function() {

        // test with number keys
        for (var i = 0; i < elems; i++) {
            expect(dict.setValue(i, i + 1)).toBeUndefined();
        }

        for (var i = 0; i < elems; i++) {
            expect(dict.getValue(i)).toEqual(i + 1);
        }
    });

    it('Maps keys to values with custom keys',
    function() {

        var ts = function(obj) {
            return obj.s;
        };
        dict = new collections.Dictionary(ts);
        expect(dict.getValue("sd")).toBeUndefined();

        for (var i = 0; i < elems; i++) {
            var o = {};
            o.s = "" + i;
            expect(dict.setValue(o, i + 1)).toBeUndefined();
        }

        for (var i = 0; i < elems; i++) {
            var d = {};
            d.s = "" + i;
            expect(dict.getValue(d)).toEqual(i + 1);
        }
    });

    it('Removes existing elements from the dictionary',
    function() {

        expect(dict.remove("1")).toBeUndefined();
        for (var i = 0; i < elems; i++) {
            expect(dict.setValue("" + i, i + 1)).toBeUndefined();
        }
        expect(dict.size()).toEqual(elems);

        for (var i = 0; i < elems; i++) {
            expect(dict.remove("" + i)).toEqual(i + 1);
            expect(dict.getValue("" + i)).toBeUndefined();
            expect(dict.remove("" + i)).toBeUndefined();
        }
        expect(dict.size()).toEqual(0);
    });

    it('An empty dictionary is empty',
    function() {

        expect(dict.isEmpty()).toBeTruthy();
        dict.setValue("1", 1);
        expect(dict.isEmpty()).toBeFalsy();
        dict.remove("1");
        expect(dict.isEmpty()).toBeTruthy();
    });

	it('Clear removes all elements',
    function() {
		dict.clear();
		dict.setValue(1,1);
		dict.clear();
		expect(dict.isEmpty()).toBeTruthy();
		expect(dict.getValue(1)).toBeUndefined();
    });

    it('Contains existing keys',
    function() {

        expect(dict.containsKey(0)).toBeFalsy();
        for (var i = 0; i < 10; i++) {
            dict.setValue(i, i);
            expect(dict.containsKey(i)).toBeTruthy();
        };
        for (var i = 0; i < 10; i++) {
            dict.remove(i);
            expect(dict.containsKey(i)).toBeFalsy();
        };
    });

    it('Gives the right size',
    function() {

        expect(dict.size()).toEqual(0);
        for (var i = 0; i < 10; i++) {
            dict.setValue(i, i);
            expect(dict.size()).toEqual(i + 1);
        };

    });

    it('Gives all the stored keys',
    function() {
        var k = [];
        for (var i = 0; i < elems; i++) {
            var keys = dict.keys();
            k.sort();
            keys.sort();
            expect(collections.arrays.equals(k, keys)).toBeTruthy();
            dict.setValue("" + i, i);
            k.push("" + i);
        }
    });

    it('Gives all the stored values',
    function() {
        var v = [];
        for (var i = 0; i < elems; i++) {
            var values = dict.values();
            v.sort();
            values.sort();
            expect(collections.arrays.equals(v, values)).toBeTruthy();
            dict.setValue("" + i, i);
            v.push(i);
        }
    });

	it('For each gives all the pairs',
    function() {
        for (var i = 0; i < elems; i++) {
            dict.setValue("" + i, i);
        }
		var keys = dict.keys();
		var values = dict.values();
		dict.forEach(function(k,v) {
			expect(collections.arrays.remove(keys, k)).toBeTruthy();
			expect(collections.arrays.remove(values, v)).toBeTruthy();
		});
		expect(keys.length).toEqual(0);
		expect(values.length).toEqual(0);
    });

	it('For each can be interrupted',
    function() {
        for (var i = 0; i < elems; i++) {
            dict.setValue("" + i, i);
        }
		var t = 0;
		dict.forEach(function(k,v) {
			t++;
			return false;
		});
		expect(t).toEqual(1);
    });

});<commit_msg>Updates Dictionary tests to use certain keys that often cause problems in JavaScript dictionaries<commit_after>describe('Dictionary',
function() {

    var dict = null;
    var elems = 100;
    var elemKeys = [];
    for(var i = 0; i < elems; i++) {
        elemKeys[i] = '' + i;
    }
    // Test with some potentially problematic keys
    elemKeys[2] = 'hasOwnProperty';
    elemKeys[4] = '__proto__';
    elemKeys[6] = '';

    beforeEach(function() {
        dict = new collections.Dictionary();
    });

    it('Maps keys to values with string keys',
    function() {

        expect(dict.getValue("sd")).toBeUndefined();

        // test with string keys
        for (var i = 0; i < elems; i++) {
            expect(dict.setValue(elemKeys[i], i + 1)).toBeUndefined();
        }
        expect(dict.size()).toEqual(elems);

        for (var i = 0; i < elems; i++) {
            expect(dict.getValue(elemKeys[i])).toEqual(i + 1);
        }

        dict.setValue("a", 5);
        expect(dict.getValue("a")).toEqual(5);
        expect(dict.setValue("a", 21)).toEqual(5);
        expect(dict.size()).toEqual(elems + 1);
        expect(dict.getValue("a")).toEqual(21);

    });

    it('Maps keys to values with number keys',
    function() {

        // test with number keys
        for (var i = 0; i < elems; i++) {
            expect(dict.setValue(i, i + 1)).toBeUndefined();
        }

        for (var i = 0; i < elems; i++) {
            expect(dict.getValue(i)).toEqual(i + 1);
        }
    });

    it('Maps keys to values with custom keys',
    function() {

        var ts = function(obj) {
            return obj.s;
        };
        dict = new collections.Dictionary(ts);
        expect(dict.getValue("sd")).toBeUndefined();

        for (var i = 0; i < elems; i++) {
            var o = {};
            o.s = elemKeys[i];
            expect(dict.setValue(o, i + 1)).toBeUndefined();
        }

        for (var i = 0; i < elems; i++) {
            var d = {};
            d.s = elemKeys[i];
            expect(dict.getValue(d)).toEqual(i + 1);
        }
    });

    it('Removes existing elements from the dictionary',
    function() {

        expect(dict.remove("1")).toBeUndefined();
        for (var i = 0; i < elems; i++) {
            expect(dict.setValue(elemKeys[i], i + 1)).toBeUndefined();
        }
        expect(dict.size()).toEqual(elems);

        for (var i = 0; i < elems; i++) {
            expect(dict.remove(elemKeys[i])).toEqual(i + 1);
            expect(dict.getValue(elemKeys[i])).toBeUndefined();
            expect(dict.remove(elemKeys[i])).toBeUndefined();
        }
        expect(dict.size()).toEqual(0);
    });

    it('An empty dictionary is empty',
    function() {

        expect(dict.isEmpty()).toBeTruthy();
        dict.setValue("1", 1);
        expect(dict.isEmpty()).toBeFalsy();
        dict.remove("1");
        expect(dict.isEmpty()).toBeTruthy();
    });

	it('Clear removes all elements',
    function() {
		dict.clear();
		dict.setValue(1,1);
		dict.clear();
		expect(dict.isEmpty()).toBeTruthy();
		expect(dict.getValue(1)).toBeUndefined();
    });

    it('Contains existing keys',
    function() {

        expect(dict.containsKey(0)).toBeFalsy();
        for (var i = 0; i < 10; i++) {
            dict.setValue(elemKeys[i], i);
            expect(dict.containsKey(elemKeys[i])).toBeTruthy();
        };
        for (var i = 0; i < 10; i++) {
            dict.remove(elemKeys[i]);
            expect(dict.containsKey(elemKeys[i])).toBeFalsy();
        };
    });

    it('Gives the right size',
    function() {

        expect(dict.size()).toEqual(0);
        for (var i = 0; i < 10; i++) {
            dict.setValue(elemKeys[i], i);
            expect(dict.size()).toEqual(i + 1);
        };

    });

    it('Gives all the stored keys',
    function() {
        var k = [];
        for (var i = 0; i < elems; i++) {
            var keys = dict.keys();
            k.sort();
            keys.sort();
            expect(collections.arrays.equals(k, keys)).toBeTruthy();
            dict.setValue(elemKeys[i], i);
            k.push(elemKeys[i]);
        }
    });

    it('Gives all the stored values',
    function() {
        var v = [];
        for (var i = 0; i < elems; i++) {
            var values = dict.values();
            v.sort();
            values.sort();
            expect(collections.arrays.equals(v, values)).toBeTruthy();
            dict.setValue(elemKeys[i], i);
            v.push(i);
        }
    });

	it('For each gives all the pairs',
    function() {
        for (var i = 0; i < elems; i++) {
            dict.setValue(elemKeys[i], i);
        }
		var keys = dict.keys();
		var values = dict.values();
		dict.forEach(function(k,v) {
			expect(collections.arrays.remove(keys, k)).toBeTruthy();
			expect(collections.arrays.remove(values, v)).toBeTruthy();
		});
		expect(keys.length).toEqual(0);
		expect(values.length).toEqual(0);
    });

	it('For each can be interrupted',
    function() {
        for (var i = 0; i < elems; i++) {
            dict.setValue(elemKeys[i], i);
        }
		var t = 0;
		dict.forEach(function(k,v) {
			t++;
			return false;
		});
		expect(t).toEqual(1);
    });

});
<|endoftext|>


<commit_before>/*!
 * jQuery UI Widget @VERSION
 *
 * Copyright 2010, AUTHORS.txt (http://jqueryui.com/about)
 * Dual licensed under the MIT or GPL Version 2 licenses.
 * http://jquery.org/license
 *
 * http://docs.jquery.com/UI/Widget
 */
(function( $, undefined ) {

// jQuery 1.4+
if ( $.cleanData ) {
	var _cleanData = $.cleanData;
	$.cleanData = function( elems ) {
		for ( var i = 0, elem; (elem = elems[i]) != null; i++ ) {
			$( elem ).triggerHandler( "remove" );
		}
		_cleanData( elems );
	};
} else {
	var _remove = $.fn.remove;
	$.fn.remove = function( selector, keepData ) {
		return this.each(function() {
			if ( !keepData ) {
				if ( !selector || $.filter( selector, [ this ] ).length ) {
					$( "*", this ).add( [ this ] ).each(function() {
						$( this ).triggerHandler( "remove" );
					});
				}
			}
			return _remove.call( $(this), selector, keepData );
		});
	};
}

$.widget = function( name, base, prototype ) {
	var namespace = name.split( "." )[ 0 ],
		fullName;
	name = name.split( "." )[ 1 ];
	fullName = namespace + "-" + name;

	if ( !prototype ) {
		prototype = base;
		base = $.Widget;
	}

	// create selector for plugin
	$.expr[ ":" ][ fullName ] = function( elem ) {
		return !!$.data( elem, name );
	};

	$[ namespace ] = $[ namespace ] || {};
	$[ namespace ][ name ] = function( options, element ) {
		// allow instantiation without initializing for simple inheritance
		if ( arguments.length ) {
			this._createWidget( options, element );
		}
	};

	var basePrototype = new base();
	// we need to make the options hash a property directly on the new instance
	// otherwise we'll modify the options hash on the prototype that we're
	// inheriting from
//	$.each( basePrototype, function( key, val ) {
//		if ( $.isPlainObject(val) ) {
//			basePrototype[ key ] = $.extend( {}, val );
//		}
//	});
	basePrototype.options = $.extend( true, {}, basePrototype.options );
	$[ namespace ][ name ].prototype = $.extend( true, basePrototype, {
		namespace: namespace,
		widgetName: name,
		widgetEventPrefix: $[ namespace ][ name ].prototype.widgetEventPrefix || name,
		widgetBaseClass: fullName
	}, prototype );

	$.widget.bridge( name, $[ namespace ][ name ] );
};

$.widget.bridge = function( name, object ) {
	$.fn[ name ] = function( options ) {
		var isMethodCall = typeof options === "string",
			args = Array.prototype.slice.call( arguments, 1 ),
			returnValue = this;

		// allow multiple hashes to be passed on init
		options = !isMethodCall && args.length ?
			$.extend.apply( null, [ true, options ].concat(args) ) :
			options;

		// prevent calls to internal methods
		if ( isMethodCall && options.charAt( 0 ) === "_" ) {
			return returnValue;
		}

		if ( isMethodCall ) {
			this.each(function() {
				var instance = $.data( this, name );
				if ( !instance ) {
					throw "cannot call methods on " + name + " prior to initialization; " +
						"attempted to call method '" + options + "'";
				}
				if ( !$.isFunction( instance[options] ) ) {
					throw "no such method '" + options + "' for " + name + " widget instance";
				}
				var methodValue = instance[ options ].apply( instance, args );
				if ( methodValue !== instance && methodValue !== undefined ) {
					returnValue = methodValue;
					return false;
				}
			});
		} else {
			this.each(function() {
				var instance = $.data( this, name );
				if ( instance ) {
					instance.option( options || {} )._init();
				} else {
					$.data( this, name, new object( options, this ) );
				}
			});
		}

		return returnValue;
	};
};

$.Widget = function( options, element ) {
	// allow instantiation without initializing for simple inheritance
	if ( arguments.length ) {
		this._createWidget( options, element );
	}
};

$.Widget.prototype = {
	widgetName: "widget",
	widgetEventPrefix: "",
	options: {
		disabled: false
	},
	_createWidget: function( options, element ) {
		// $.widget.bridge stores the plugin instance, but we do it anyway
		// so that it's stored even before the _create function runs
		$.data( element, this.widgetName, this );
		this.element = $( element );
		this.options = $.extend( true, {},
			this.options,
			this._getCreateOptions(),
			options );

		var self = this;
		this.element.bind( "remove." + this.widgetName, function() {
			self.destroy();
		});

		this._create();
		this._trigger( "create" );
		this._init();
	},
	_getCreateOptions: function() {
		var options = {};
		if ( $.metadata ) {
			options = $.metadata.get( element )[ this.widgetName ];
		}
		return options;
	},
	_create: function() {},
	_init: function() {},

	destroy: function() {
		this.element
			.unbind( "." + this.widgetName )
			.removeData( this.widgetName );
		this.widget()
			.unbind( "." + this.widgetName )
			.removeAttr( "aria-disabled" )
			.removeClass(
				this.widgetBaseClass + "-disabled " +
				"ui-state-disabled" );
	},

	widget: function() {
		return this.element;
	},

	option: function( key, value ) {
		var options = key;

		if ( arguments.length === 0 ) {
			// don't return a reference to the internal hash
			return $.extend( {}, this.options );
		}

		if  (typeof key === "string" ) {
			if ( value === undefined ) {
				return this.options[ key ];
			}
			options = {};
			options[ key ] = value;
		}

		this._setOptions( options );

		return this;
	},
	_setOptions: function( options ) {
		var self = this;
		$.each( options, function( key, value ) {
			self._setOption( key, value );
		});

		return this;
	},
	_setOption: function( key, value ) {
		this.options[ key ] = value;

		if ( key === "disabled" ) {
			this.widget()
				[ value ? "addClass" : "removeClass"](
					this.widgetBaseClass + "-disabled" + " " +
					"ui-state-disabled" )
				.attr( "aria-disabled", value );
		}

		return this;
	},

	enable: function() {
		return this._setOption( "disabled", false );
	},
	disable: function() {
		return this._setOption( "disabled", true );
	},

	_trigger: function( type, event, data ) {
		var callback = this.options[ type ];

		event = $.Event( event );
		event.type = ( type === this.widgetEventPrefix ?
			type :
			this.widgetEventPrefix + type ).toLowerCase();
		data = data || {};

		// copy original event properties over to the new event
		// this would happen if we could call $.event.fix instead of $.Event
		// but we don't have a way to force an event to be fixed multiple times
		if ( event.originalEvent ) {
			for ( var i = $.event.props.length, prop; i; ) {
				prop = $.event.props[ --i ];
				event[ prop ] = event.originalEvent[ prop ];
			}
		}

		this.element.trigger( event, data );

		return !( $.isFunction(callback) &&
			callback.call( this.element[0], event, data ) === false ||
			event.isDefaultPrevented() );
	}
};

})( jQuery );
<commit_msg>Widget: Simplified _getCreateOptions().<commit_after>/*!
 * jQuery UI Widget @VERSION
 *
 * Copyright 2010, AUTHORS.txt (http://jqueryui.com/about)
 * Dual licensed under the MIT or GPL Version 2 licenses.
 * http://jquery.org/license
 *
 * http://docs.jquery.com/UI/Widget
 */
(function( $, undefined ) {

// jQuery 1.4+
if ( $.cleanData ) {
	var _cleanData = $.cleanData;
	$.cleanData = function( elems ) {
		for ( var i = 0, elem; (elem = elems[i]) != null; i++ ) {
			$( elem ).triggerHandler( "remove" );
		}
		_cleanData( elems );
	};
} else {
	var _remove = $.fn.remove;
	$.fn.remove = function( selector, keepData ) {
		return this.each(function() {
			if ( !keepData ) {
				if ( !selector || $.filter( selector, [ this ] ).length ) {
					$( "*", this ).add( [ this ] ).each(function() {
						$( this ).triggerHandler( "remove" );
					});
				}
			}
			return _remove.call( $(this), selector, keepData );
		});
	};
}

$.widget = function( name, base, prototype ) {
	var namespace = name.split( "." )[ 0 ],
		fullName;
	name = name.split( "." )[ 1 ];
	fullName = namespace + "-" + name;

	if ( !prototype ) {
		prototype = base;
		base = $.Widget;
	}

	// create selector for plugin
	$.expr[ ":" ][ fullName ] = function( elem ) {
		return !!$.data( elem, name );
	};

	$[ namespace ] = $[ namespace ] || {};
	$[ namespace ][ name ] = function( options, element ) {
		// allow instantiation without initializing for simple inheritance
		if ( arguments.length ) {
			this._createWidget( options, element );
		}
	};

	var basePrototype = new base();
	// we need to make the options hash a property directly on the new instance
	// otherwise we'll modify the options hash on the prototype that we're
	// inheriting from
//	$.each( basePrototype, function( key, val ) {
//		if ( $.isPlainObject(val) ) {
//			basePrototype[ key ] = $.extend( {}, val );
//		}
//	});
	basePrototype.options = $.extend( true, {}, basePrototype.options );
	$[ namespace ][ name ].prototype = $.extend( true, basePrototype, {
		namespace: namespace,
		widgetName: name,
		widgetEventPrefix: $[ namespace ][ name ].prototype.widgetEventPrefix || name,
		widgetBaseClass: fullName
	}, prototype );

	$.widget.bridge( name, $[ namespace ][ name ] );
};

$.widget.bridge = function( name, object ) {
	$.fn[ name ] = function( options ) {
		var isMethodCall = typeof options === "string",
			args = Array.prototype.slice.call( arguments, 1 ),
			returnValue = this;

		// allow multiple hashes to be passed on init
		options = !isMethodCall && args.length ?
			$.extend.apply( null, [ true, options ].concat(args) ) :
			options;

		// prevent calls to internal methods
		if ( isMethodCall && options.charAt( 0 ) === "_" ) {
			return returnValue;
		}

		if ( isMethodCall ) {
			this.each(function() {
				var instance = $.data( this, name );
				if ( !instance ) {
					throw "cannot call methods on " + name + " prior to initialization; " +
						"attempted to call method '" + options + "'";
				}
				if ( !$.isFunction( instance[options] ) ) {
					throw "no such method '" + options + "' for " + name + " widget instance";
				}
				var methodValue = instance[ options ].apply( instance, args );
				if ( methodValue !== instance && methodValue !== undefined ) {
					returnValue = methodValue;
					return false;
				}
			});
		} else {
			this.each(function() {
				var instance = $.data( this, name );
				if ( instance ) {
					instance.option( options || {} )._init();
				} else {
					$.data( this, name, new object( options, this ) );
				}
			});
		}

		return returnValue;
	};
};

$.Widget = function( options, element ) {
	// allow instantiation without initializing for simple inheritance
	if ( arguments.length ) {
		this._createWidget( options, element );
	}
};

$.Widget.prototype = {
	widgetName: "widget",
	widgetEventPrefix: "",
	options: {
		disabled: false
	},
	_createWidget: function( options, element ) {
		// $.widget.bridge stores the plugin instance, but we do it anyway
		// so that it's stored even before the _create function runs
		$.data( element, this.widgetName, this );
		this.element = $( element );
		this.options = $.extend( true, {},
			this.options,
			this._getCreateOptions(),
			options );

		var self = this;
		this.element.bind( "remove." + this.widgetName, function() {
			self.destroy();
		});

		this._create();
		this._trigger( "create" );
		this._init();
	},
	_getCreateOptions: function() {
		return $.metadata && $.metadata.get( element )[ this.widgetName ];
	},
	_create: function() {},
	_init: function() {},

	destroy: function() {
		this.element
			.unbind( "." + this.widgetName )
			.removeData( this.widgetName );
		this.widget()
			.unbind( "." + this.widgetName )
			.removeAttr( "aria-disabled" )
			.removeClass(
				this.widgetBaseClass + "-disabled " +
				"ui-state-disabled" );
	},

	widget: function() {
		return this.element;
	},

	option: function( key, value ) {
		var options = key;

		if ( arguments.length === 0 ) {
			// don't return a reference to the internal hash
			return $.extend( {}, this.options );
		}

		if  (typeof key === "string" ) {
			if ( value === undefined ) {
				return this.options[ key ];
			}
			options = {};
			options[ key ] = value;
		}

		this._setOptions( options );

		return this;
	},
	_setOptions: function( options ) {
		var self = this;
		$.each( options, function( key, value ) {
			self._setOption( key, value );
		});

		return this;
	},
	_setOption: function( key, value ) {
		this.options[ key ] = value;

		if ( key === "disabled" ) {
			this.widget()
				[ value ? "addClass" : "removeClass"](
					this.widgetBaseClass + "-disabled" + " " +
					"ui-state-disabled" )
				.attr( "aria-disabled", value );
		}

		return this;
	},

	enable: function() {
		return this._setOption( "disabled", false );
	},
	disable: function() {
		return this._setOption( "disabled", true );
	},

	_trigger: function( type, event, data ) {
		var callback = this.options[ type ];

		event = $.Event( event );
		event.type = ( type === this.widgetEventPrefix ?
			type :
			this.widgetEventPrefix + type ).toLowerCase();
		data = data || {};

		// copy original event properties over to the new event
		// this would happen if we could call $.event.fix instead of $.Event
		// but we don't have a way to force an event to be fixed multiple times
		if ( event.originalEvent ) {
			for ( var i = $.event.props.length, prop; i; ) {
				prop = $.event.props[ --i ];
				event[ prop ] = event.originalEvent[ prop ];
			}
		}

		this.element.trigger( event, data );

		return !( $.isFunction(callback) &&
			callback.call( this.element[0], event, data ) === false ||
			event.isDefaultPrevented() );
	}
};

})( jQuery );
<|endoftext|>


<commit_before>var IndexPage = require('./IndexPage');

describe('Login Submission', function () {
    var page = new IndexPage();

    beforeEach(function () {
        page.get();
    });

    describe('Authentication Attempt', function () {
        it('logs in when given the correct credentials', function () {

        });
    });

    describe('Bad Authentication Attempt', function () {
        it('displays an error when given incorrect credentials', function () {

        });
    });
})
<commit_msg>Exercise 2 Answer Code<commit_after>var IndexPage = require('./IndexPage');

describe('Login Submission', function () {
    var page = new IndexPage();

    beforeEach(function () {
        page.get();
    });

    describe('Authentication Attempt', function () {
        it('logs in when given the correct credentials', function () {
            page.fillEmail();
            page.fillPassword();
            page.submitBtn.click();

            expect(browser.getLocationAbsUrl()).toBe('/landing');
        });
    });

    describe('Bad Authentication Attempt', function () {
        it('displays an error when given incorrect credentials', function () {
            page.fillEmail();
            page.passwordInput.sendKeys('incorrectPassword');
            page.submitBtn.click();

            expect(page.errorContainer.isPresent()).toBe(true);
        });
    });
})
<|endoftext|>


<commit_before>/** based on https://github.com/hustcc/timeago.js Copyright (c) 2016 hustcc License: MIT **/
lichess.timeago = (function() {

  // second, minute, hour, day, week, month, year(365 days)
  var SEC_ARRAY = [60, 60, 24, 7, 365/7/12, 12],
    SEC_ARRAY_LEN = 6;

  var intR = /^\d+$/;

  // format Date / string / timestamp to Date instance.
  function toDate(input) {
    if (input instanceof Date) return input;
    if (!isNaN(input)) return new Date(parseInt(input));
    if (intR.test(input)) return new Date(parseInt(input));
    input = (input || '').trim().replace(/\.\d+/, '') // remove milliseconds
      .replace(/-/, '/').replace(/-/, '/')
      .replace(/(\d)T(\d)/, '$1 $2').replace(/Z/, ' UTC') // 2017-2-5T3:57:52Z -> 2017-2-5 3:57:52UTC
      .replace(/([\+\-]\d\d)\:?(\d\d)/, ' $1$2'); // -04:00 -> -0400
    return new Date(input);
  }

  // format the diff second to *** time ago
  function formatDiff(diff) {
    var i = 0,
      agoin = diff < 0 ? 1 : 0, // timein or timeago
        total_sec = diff = Math.abs(diff);

      for (; diff >= SEC_ARRAY[i] && i < SEC_ARRAY_LEN; i++) {
        diff /= SEC_ARRAY[i];
      }
      diff = parseInt(diff);
    i *= 2;

    if (diff > (i === 0 ? 9 : 1)) i += 1;
    return lichess.timeagoLocale(diff, i, total_sec)[agoin].replace('%s', diff);
  }

  // calculate the diff second between date to be formatted now
  function diffSec(date) {
    return (Date.now() - toDate(date)) / 1000;
  }

  var formatterInst;

  function formatter() {
    return formatterInst = formatterInst || (window.Intl && Intl.DateTimeFormat ?
      new Intl.DateTimeFormat(document.documentElement.lang, {
        year: 'numeric',
        month: 'short',
        day: 'numeric',
        hour: 'numeric',
        minute: 'numeric'
      }).format : function(d) { return d.toLocaleString(); })
  }

  /**
   * timeago: the function to get `timeago` instance.
   *
   * How to use it?
   * var timeagoFactory = require('timeago.js');
   * var timeago = timeagoFactory(); // all use default.
   * var timeago = timeagoFactory('2016-09-10'); // the relative date is 2016-09-10, so the 2016-09-11 will be 1 day ago.
   **/
   return {
     render: function(nodes) {
       var node, cl, abs, set;
       for (var i = 0; i < nodes.length; i++) {
         node = nodes[i],
         cl = node.classList,
         abs = cl.contains('abs'),
         set = cl.contains('set');
         if (set && abs) continue;
         var date = toDate(node.getAttribute('datetime'));
         if (!set) {
           var str = formatter()(date);
           if (abs) node.textContent = str;
           else node.setAttribute('title', str);
           node.classList.add('set');
         }
         if (!abs) node.textContent = formatDiff(diffSec(date));
       }
     },
     // relative
     format: function(date) {
       return formatDiff(diffSec(date));
     },
     absolute: function(d) {
       return formatter()(toDate(d));
     }
   };
})();
<commit_msg>cache node date<commit_after>/** based on https://github.com/hustcc/timeago.js Copyright (c) 2016 hustcc License: MIT **/
lichess.timeago = (function() {

  // second, minute, hour, day, week, month, year(365 days)
  var SEC_ARRAY = [60, 60, 24, 7, 365/7/12, 12],
    SEC_ARRAY_LEN = 6;

  var intR = /^\d+$/;

  // format Date / string / timestamp to Date instance.
  function toDate(input) {
    if (input instanceof Date) return input;
    if (!isNaN(input)) return new Date(parseInt(input));
    if (intR.test(input)) return new Date(parseInt(input));
    input = (input || '').trim().replace(/\.\d+/, '') // remove milliseconds
      .replace(/-/, '/').replace(/-/, '/')
      .replace(/(\d)T(\d)/, '$1 $2').replace(/Z/, ' UTC') // 2017-2-5T3:57:52Z -> 2017-2-5 3:57:52UTC
      .replace(/([\+\-]\d\d)\:?(\d\d)/, ' $1$2'); // -04:00 -> -0400
    return new Date(input);
  }

  // format the diff second to *** time ago
  function formatDiff(diff) {
    var i = 0,
      agoin = diff < 0 ? 1 : 0, // timein or timeago
        total_sec = diff = Math.abs(diff);

      for (; diff >= SEC_ARRAY[i] && i < SEC_ARRAY_LEN; i++) {
        diff /= SEC_ARRAY[i];
      }
      diff = parseInt(diff);
    i *= 2;

    if (diff > (i === 0 ? 9 : 1)) i += 1;
    return lichess.timeagoLocale(diff, i, total_sec)[agoin].replace('%s', diff);
  }

  // calculate the diff second between date to be formatted now
  function diffSec(date) {
    return (Date.now() - toDate(date)) / 1000;
  }

  var formatterInst;

  function formatter() {
    return formatterInst = formatterInst || (window.Intl && Intl.DateTimeFormat ?
      new Intl.DateTimeFormat(document.documentElement.lang, {
        year: 'numeric',
        month: 'short',
        day: 'numeric',
        hour: 'numeric',
        minute: 'numeric'
      }).format : function(d) { return d.toLocaleString(); })
  }

  /**
   * timeago: the function to get `timeago` instance.
   *
   * How to use it?
   * var timeagoFactory = require('timeago.js');
   * var timeago = timeagoFactory(); // all use default.
   * var timeago = timeagoFactory('2016-09-10'); // the relative date is 2016-09-10, so the 2016-09-11 will be 1 day ago.
   **/
   return {
     render: function(nodes) {
       var node, cl, abs, set, date, str;
       for (var i = 0; i < nodes.length; i++) {
         node = nodes[i],
         cl = node.classList,
         abs = cl.contains('abs'),
         set = cl.contains('set');
         if (set && abs) continue;
         node.date = node.date || toDate(node.getAttribute('datetime'));
         if (!set) {
           str = formatter()(node.date);
           if (abs) node.textContent = str;
           else node.setAttribute('title', str);
           node.classList.add('set');
         }
         if (!abs) node.textContent = formatDiff(diffSec(node.date));
       }
     },
     // relative
     format: function(date) {
       return formatDiff(diffSec(date));
     },
     absolute: function(d) {
       return formatter()(toDate(d));
     }
   };
})();
<|endoftext|>


<commit_before>/***********************************************************************
 *                                                                   _
 *       _____  _                           ____  _                 |_|
 *      |  _  |/ \   ____  ____ __ ___     / ___\/ \   __   _  ____  _
 *      | |_| || |  / __ \/ __ \\ '_  \ _ / /    | |___\ \ | |/ __ \| |
 *      |  _  || |__. ___/. ___/| | | ||_|\ \___ |  _  | |_| |. ___/| |
 *      |_/ \_|\___/\____|\____||_| |_|    \____/|_| |_|_____|\____||_|
 *
 *      ================================================================
 *                 More than a coder, More than a designer
 *      ================================================================
 *
 *
 *      - Document: load.js
 *      - Author: aleen42
 *      - Description: a script for loading file name from a directory,
 *      			   and converted into a json.
 *      - Create Time: Aug 25th, 2016
 *      - Update Time: Aug 26th, 2016
 *
 *
 **********************************************************************/

const fs = require('fs');
const base = [
	'./assets/songs/'
];

var songlist = [];
for (var i = 0; i < base.length; i++) {
	songlist = songlist.concat(fs.readdirSync(base[i]).map(function (item) {
			return base[i] + item;
		}).filter(function (item) {
			return item.substr(-4).toLowerCase() === '.mp3';
		}));
}

fs.writeFile('./assets/songlist.json', JSON.stringify({
	data: songlist
}));
<commit_msg>update<commit_after>/***********************************************************************
 *                                                                   _
 *       _____  _                           ____  _                 |_|
 *      |  _  |/ \   ____  ____ __ ___     / ___\/ \   __   _  ____  _
 *      | |_| || |  / __ \/ __ \\ '_  \ _ / /    | |___\ \ | |/ __ \| |
 *      |  _  || |__. ___/. ___/| | | ||_|\ \___ |  _  | |_| |. ___/| |
 *      |_/ \_|\___/\____|\____||_| |_|    \____/|_| |_|_____|\____||_|
 *
 *      ================================================================
 *                 More than a coder, More than a designer
 *      ================================================================
 *
 *
 *      - Document: load.js
 *      - Author: aleen42
 *      - Description: a script for loading file name from a directory,
 *      			   and converted into a json.
 *      - Create Time: Aug 25th, 2016
 *      - Update Time: Aug 26th, 2016
 *
 *
 **********************************************************************/

const fs = require('fs');
const base = [
	'./assets/songs/'
];

var songlist = [];
for (var i = 0; i < base.length; i++) {
	songlist = songlist.concat(fs.readdirSync(base[i]).map(function (item) {
			return base[i] + '/' + item;
		}).filter(function (item) {
			return item.substr(-4).toLowerCase() === '.mp3';
		}));
}

fs.writeFile('./assets/songlist.json', JSON.stringify({
	data: songlist
}));
<|endoftext|>


<commit_before>'use strict'

module.exports = {

}

/* global actor */

let I

module.exports = {
  splash: '.home',
  header: '.header',
  hamburger: '.navbar-burger',
  _init () {
    I = actor()
  },

  signout () {
    I.amOnPage('/home')
    I.click('Log off')
  }
}
<commit_msg>fixed spacing<commit_after>'use strict'

/* global actor */

let I

module.exports = {
  splash: '.home',
  header: '.header',
  hamburger: '.navbar-burger',
  _init () {
    I = actor()
  },

  signout () {
    I.amOnPage('/home')
    I.click('Log off')
  }

}
<|endoftext|>


<commit_before>var fs = require("fs");
var util = require("util");
var q = require("q");

var incorporate = function (headers, data, validations) {
	var o = {};
	var bad = false;
	headers.forEach(function (header, i) {
		if (i < data.length && data[i] != "") {
			if (validations && validations[header] && !data[i].match(validations[header])) {
				console.log(data[i] + " does not conform to " + validations[header]);
				bad = true;
			}
			o[header] = data[i];
		}
	}.bind(this));
	if (bad) return false;
	else return o;
}

var datafile_generate_query = function (start_node, filename) {
	var deferred = q.defer();

	fs.readFile(filename, {encoding : "utf8"}, function (err, file_contents) {
		var id = 1;
		var base = { // already exists
			id : 0,
			base : true,
			children : []
		};
		var path = [base];

		var errors = [];
		file_contents.split("\n").forEach(function (line, lineno) {
			if (line.trim().length) {

				var indent = line.match(/^\t*/g)[0].length + 1;
				while (indent < path.length) path.pop();
				var area = path[path.length - 1];
				if (area === undefined) {
					errors.push("Indentation error on line " + lineno + ".");
					return;
				}

				line = line.trim();
				var type = line[0];
				var data = line.slice(1).match(/([^,\"]+|\"[^\"]+\"|)(,|$)/g);
				data = data.map(function (datum) {
					if (datum.slice(-1) == ",") datum = datum.slice(0,-1);
					return datum.replace(/([^\\]|^)\"/g, "$1").replace(/\\/g, "");
				});

				var phone_number_like = /^x?(\+?[0-9 ]+(\)[0-9 ]+)?)?$/;
				var name_like = /^[^0-9]+$/;
				validations = {
					first_name : name_like,
					last_name : name_like,
					phone : phone_number_like,
					fax : phone_number_like,
					email : /^((?:[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*|"(?:[\x01-\x08\x0b\x0c\x0e-\x1f\x21\x23-\x5b\x5d-\x7f]|\\[\x01-\x09\x0b\x0c\x0e-\x7f])*")@(?:(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?|\[(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?|[a-z0-9-]*[a-z0-9]:(?:[\x01-\x08\x0b\x0c\x0e-\x1f\x21-\x5a\x53-\x7f]|\\[\x01-\x09\x0b\x0c\x0e-\x7f])+)\]))?$/,
				}

				// need this -> ' <- otherwise syntax highligter very confused

				switch (type) {
					case "$": // area
						var new_area = {
							id : id++,
							data : incorporate(["name", "note"], data),
							contacts : [],
							children : []
						};
						area.children.push(new_area);
						path.push(new_area);
						break;
					case "#": // contact
						var incorporated = incorporate(
							["first_name", "last_name", "position", "phone", "email", "address", "note", "url", "fax"],
						data, validations);
						if (!incorporated) {
							errors.push("Validation error with on line " + lineno + ": " + line);
						} else {
							var new_contact = {
								id : id++,
								data : incorporated
							};
							area.contacts.push(new_contact);
						}
						break;
					default:
						errors.push("Line " + lineno + " has no type marker.");
						break;
				}
			}
		});

		if (errors.length) {
			deferred.reject(errors);
			return;
		}

		var print_data = function (json) {
			var props = [];
			for (key in json) {
				props.push(util.format("%s: '%s'", key, json[key].replace(/'/g, "\\'")));
			}
			return util.format("{%s}", props.join(","));
		}
		var gen_node = function (id, type, data) {
			return {
				id : id,
				type : type,
				data : data || {}
			};
		};
		var print_node = function (node) {
			return util.format(
				"(n%d:%s %s)", node.id, node.type,
				print_data(node.data)
			);
		}

		var gen_rel = function (from_id, type, to_id, data) {
			return {
				from_id : from_id,
				to_id : to_id,
				type : type,
				data : data || {}
			};
		};
		var print_rel = function (rel) {
			return util.format(
				"(n%d)-[:%s %s]->(n%d)",
				rel.from_id, rel.type,
				print_data(rel.data),
				rel.to_id
			);
		}

		var gen_cypher = function (node_acc, rel_acc, area, parent) {
			if (!area.base) {
				node_acc.push(gen_node(area.id, "Area", area.data));
				rel_acc.push(gen_rel(parent, "PARENT_OF", area.id));
				if (area.contacts.length) {
					var collection_id = id++;
					node_acc.push(gen_node(collection_id, "Collection"));
					rel_acc.push(gen_rel(collection_id, "RESPONSIBLE_FOR", area.id));
					area.contacts.forEach(function (contact) {
						node_acc.push(gen_node(contact.id, "Contact", contact.data));
						rel_acc.push(gen_rel(contact.id, "IN_COLLECTION", collection_id));
					});
				}
			}
			area.children.forEach(function (child) {
				gen_cypher(node_acc, rel_acc, child, area.id);
			});
		}

		var nodes = [];
		var rels = [];
		gen_cypher(nodes, rels, base, null);

		var node_cypher = (
			util.format("START n0=node(%s) ", start_node) +
			"CREATE " +
			//"(n0:Area { name: 'ROOT'}), " +
			nodes.map(print_node).concat(rels.map(print_rel)).join(",")
		);
		deferred.resolve(node_cypher);

	});
	return deferred.promise;
};

module.exports = datafile_generate_query;<commit_msg>Changed phone number regular expression to allow ([0-9 ]+)[0-9 ]+<commit_after>var fs = require("fs");
var util = require("util");
var q = require("q");

var incorporate = function (headers, data, validations) {
	var o = {};
	var bad = false;
	headers.forEach(function (header, i) {
		if (i < data.length && data[i] != "") {
			if (validations && validations[header] && !data[i].match(validations[header])) {
				console.log(data[i] + " does not conform to " + validations[header]);
				bad = true;
			}
			o[header] = data[i];
		}
	}.bind(this));
	if (bad) return false;
	else return o;
}

var datafile_generate_query = function (start_node, filename) {
	var deferred = q.defer();

	fs.readFile(filename, {encoding : "utf8"}, function (err, file_contents) {
		var id = 1;
		var base = { // already exists
			id : 0,
			base : true,
			children : []
		};
		var path = [base];

		var errors = [];
		file_contents.split("\n").forEach(function (line, lineno) {
			if (line.trim().length) {

				var indent = line.match(/^\t*/g)[0].length + 1;
				while (indent < path.length) path.pop();
				var area = path[path.length - 1];
				if (area === undefined) {
					errors.push("Indentation error on line " + lineno + ".");
					return;
				}

				line = line.trim();
				var type = line[0];
				var data = line.slice(1).match(/([^,\"]+|\"[^\"]+\"|)(,|$)/g);
				data = data.map(function (datum) {
					if (datum.slice(-1) == ",") datum = datum.slice(0,-1);
					return datum.replace(/([^\\]|^)\"/g, "$1").replace(/\\/g, "");
				});

				var phone_number_like = /^((\+|x|\(?[0-9 ]+\))?([0-9 ]+)?)?$/;
				var name_like = /^[^0-9]+$/;
				validations = {
					first_name : name_like,
					last_name : name_like,
					phone : phone_number_like,
					fax : phone_number_like,
					email : /^((?:[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*|"(?:[\x01-\x08\x0b\x0c\x0e-\x1f\x21\x23-\x5b\x5d-\x7f]|\\[\x01-\x09\x0b\x0c\x0e-\x7f])*")@(?:(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?|\[(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?|[a-z0-9-]*[a-z0-9]:(?:[\x01-\x08\x0b\x0c\x0e-\x1f\x21-\x5a\x53-\x7f]|\\[\x01-\x09\x0b\x0c\x0e-\x7f])+)\]))?$/,
				}

				// need this -> ' <- otherwise syntax highligter very confused

				switch (type) {
					case "$": // area
						var new_area = {
							id : id++,
							data : incorporate(["name", "note"], data),
							contacts : [],
							children : []
						};
						area.children.push(new_area);
						path.push(new_area);
						break;
					case "#": // contact
						var incorporated = incorporate(
							["first_name", "last_name", "position", "phone", "email", "address", "note", "url", "fax"],
						data, validations);
						if (!incorporated) {
							errors.push("Validation error with on line " + lineno + ": " + line);
						} else {
							var new_contact = {
								id : id++,
								data : incorporated
							};
							area.contacts.push(new_contact);
						}
						break;
					default:
						errors.push("Line " + lineno + " has no type marker.");
						break;
				}
			}
		});

		if (errors.length) {
			deferred.reject(errors);
			return;
		}

		var print_data = function (json) {
			var props = [];
			for (key in json) {
				props.push(util.format("%s: '%s'", key, json[key].replace(/'/g, "\\'")));
			}
			return util.format("{%s}", props.join(","));
		}
		var gen_node = function (id, type, data) {
			return {
				id : id,
				type : type,
				data : data || {}
			};
		};
		var print_node = function (node) {
			return util.format(
				"(n%d:%s %s)", node.id, node.type,
				print_data(node.data)
			);
		}

		var gen_rel = function (from_id, type, to_id, data) {
			return {
				from_id : from_id,
				to_id : to_id,
				type : type,
				data : data || {}
			};
		};
		var print_rel = function (rel) {
			return util.format(
				"(n%d)-[:%s %s]->(n%d)",
				rel.from_id, rel.type,
				print_data(rel.data),
				rel.to_id
			);
		}

		var gen_cypher = function (node_acc, rel_acc, area, parent) {
			if (!area.base) {
				node_acc.push(gen_node(area.id, "Area", area.data));
				rel_acc.push(gen_rel(parent, "PARENT_OF", area.id));
				if (area.contacts.length) {
					var collection_id = id++;
					node_acc.push(gen_node(collection_id, "Collection"));
					rel_acc.push(gen_rel(collection_id, "RESPONSIBLE_FOR", area.id));
					area.contacts.forEach(function (contact) {
						node_acc.push(gen_node(contact.id, "Contact", contact.data));
						rel_acc.push(gen_rel(contact.id, "IN_COLLECTION", collection_id));
					});
				}
			}
			area.children.forEach(function (child) {
				gen_cypher(node_acc, rel_acc, child, area.id);
			});
		}

		var nodes = [];
		var rels = [];
		gen_cypher(nodes, rels, base, null);

		var node_cypher = (
			util.format("START n0=node(%s) ", start_node) +
			"CREATE " +
			//"(n0:Area { name: 'ROOT'}), " +
			nodes.map(print_node).concat(rels.map(print_rel)).join(",")
		);
		deferred.resolve(node_cypher);

	});
	return deferred.promise;
};

module.exports = datafile_generate_query;<|endoftext|>


<commit_before>/**
 * The loads happen much quicker than Nightwatch can pull, so we're testing the aftermath of the successive loads
 */
module.exports = {

	'poster should render and load': function (browser) { browser
		.url('http://localhost:8080/assets/')
		.waitForElementVisible('#app', 1000)

		.assert.attributeContains('.test-poster .vv-poster', 'src', 'poster.png')
	},

	'image should render and load': function (browser) { browser
		.assert.attributeContains('.test-image .vv-image', 'src', 'image.png')
		.assert.elementNotPresent('.test-image .vv-poster')
	},

	'video should render and load': function (browser) { browser
		.assert.attributeContains('.test-video .vv-video source', 'src', 'video.mp4')
		.assert.visible('.test-video .vv-video')
		.assert.elementNotPresent('.test-video .vv-poster')
		.assert.elementNotPresent('.test-video .vv-image')
	},

	'fallback should render and load': function (browser) { browser
		.assert.attributeContains('.test-fallback .vv-fallback', 'src', 'fallback.png')
		.assert.elementNotPresent('.test-fallback .vv-poster')
		.assert.elementNotPresent('.test-fallback .vv-image')
		.assert.elementNotPresent('.test-fallback .vv-video')

		.end()
	},

}
<commit_msg>Fix source for load tests<commit_after>/**
 * The loads happen much quicker than Nightwatch can pull, so we're testing the aftermath of the successive loads
 */
module.exports = {

	'poster should render and load': function (browser) { browser
		.url('http://localhost:8080/load/')
		.waitForElementVisible('#app', 1000)

		.assert.attributeContains('.test-poster .vv-poster', 'src', 'poster.png')
	},

	'image should render and load': function (browser) { browser
		.assert.attributeContains('.test-image .vv-image', 'src', 'image.png')
		.assert.elementNotPresent('.test-image .vv-poster')
	},

	'video should render and load': function (browser) { browser
		.assert.attributeContains('.test-video .vv-video source', 'src', 'video.mp4')
		.assert.visible('.test-video .vv-video')
		.assert.elementNotPresent('.test-video .vv-poster')
		.assert.elementNotPresent('.test-video .vv-image')
	},

	'fallback should render and load': function (browser) { browser
		.assert.attributeContains('.test-fallback .vv-fallback', 'src', 'fallback.png')
		.assert.elementNotPresent('.test-fallback .vv-poster')
		.assert.elementNotPresent('.test-fallback .vv-image')
		.assert.elementNotPresent('.test-fallback .vv-video')

		.end()
	},

}
<|endoftext|>


<commit_before>var server = require('../server');
var registry = require('../lib/registry');

var http = require('http');
var should = require('should');
var request = require('supertest');
var assert = require('assert');
var models = require('../lib/models');
var store = require('../lib/store');
var testData = require('./testdata');

xdescribe('ForwarderServlet', function() {
    var app;
    before(function() {
        app = server();
    });

    after(function(done) {
        app.destroy(done);
    });

    describe('requesting a capability not currently on the grid', function() {
        beforeEach(function() {
            return store.flushdb();
        });

        var nodeServerMock;
        afterEach(function(done) {
            this.timeout(2000);

            request(app)
                .get('/grid/unregister?id=http://127.0.0.1:5558')
                .end(function(err, res) {
                    res.statusCode.should.equal(200);
                    res.text.should.equal('OK - Bye');
                    nodeServerMock.close(done);
                });
        });

        it('should put a request with a capability we currently do not have in a pending state, once a node is available, the request should use the node', function(done) {
            this.timeout(2000);

            var sessionID = testData.getSessionID();
            request(app)
                .get('/selenium-server/driver?cmd=getNewBrowserSession&1=firefox&client_key=' + testData.CLIENT_KEY + '&client_secret=' + testData.CLIENT_SECRET)
                .end(function(err, res) {
                    // this should be triggered after the setTimeout() below.
                    // we simulate a request, and a new node coming online after the request
                    res.statusCode.should.equal(200);
                    res.text.should.equal('OK,' + sessionID);
                    done();
                });

            setTimeout(function() {
                nodeServerMock = http
                    .createServer(function(req, res) {
                        var url = req.url.toString();
                        if (url.indexOf('getNewBrowserSession') > -1) {
                            res.writeHead(200, {'Content-Type': 'text/plain'});
                            res.end('OK,' + sessionID);
                        }
                    })
                    .listen(5558, '127.0.0.1', function() {
                        var postData = '{"class":"org.openqa.grid.common.RegistrationRequest","capabilities":[{"platform":"WINDOWS","seleniumProtocol":"Selenium","browserName":"firefox","maxInstances":1,"version":"9","alias":"FF9"}],"configuration":{"port":5558,"nodeConfig":"config.json","host":"127.0.0.1","cleanUpCycle":10000,"browserTimeout":20000,"hubHost":"10.0.1.6","registerCycle":5000,"debug":"","hub":"http://10.0.1.6:4444/grid/register","log":"test.log","url":"http://127.0.0.1:5558","remoteHost":"http://127.0.0.1:5558","register":true,"proxy":"org.openqa.grid.selenium.proxy.DefaultRemoteProxy","maxSession":1,"role":"node","hubPort":4444}}';

                        request(app)
                            .post('/grid/register')
                            .send(postData)
                            .end(function(err, res) {
                                res.statusCode.should.equal(200);
                                res.text.should.equal('OK - Welcome');
                            });
                    });
            }, 1000);
        });
    });

    describe('make sure available nodes are correctly registered', function() {
        var nodes;
        beforeEach(function(done) {
            nodes = [];
            for (var i = 0; i < 10; i++) {
                (function(i) {
                    var port = 5656 + i,
                        node = http
                            .createServer(function(req, res) {
                                var url = req.url.toString();
                                if (url.indexOf('getNewBrowserSession') > -1) {
                                    res.writeHead(200, {'Content-Type': 'text/plain'});
                                    res.end('OK,' + testData.getSessionID());
                                } else if (url.indexOf('testComplete') > -1) {
                                    res.writeHead(200, {'Content-Type': 'text/plain'});
                                    res.end('OK');
                                }
                            })
                            .listen(port, '127.0.0.1', function() {
                                var postData = '{"class":"org.openqa.grid.common.RegistrationRequest","capabilities":[{"platform":"WINDOWS","seleniumProtocol":"Selenium","browserName":"firefox","maxInstances":1,"version":"9","alias":"FF9"}],"configuration":{"port":' + port + ',"nodeConfig":"config.json","host":"127.0.0.1","cleanUpCycle":10000,"browserTimeout":20000,"hubHost":"10.0.1.6","registerCycle":5000,"debug":"","hub":"http://10.0.1.6:4444/grid/register","log":"test.log","url":"http://127.0.0.1:' + port + '","remoteHost":"http://127.0.0.1:' + port + '","register":true,"proxy":"org.openqa.grid.selenium.proxy.DefaultRemoteProxy","maxSession":1,"role":"node","hubPort":4444}}';

                                request(app)
                                    .post('/grid/register')
                                    .send(postData)
                                    .end(function(err, res) {
                                        res.statusCode.should.equal(200);
                                        res.text.should.equal('OK - Welcome');
                                        nodes.push(node);
                                        if (nodes.length == 10) {
                                            done();
                                        }
                                    });
                            });
                })(i);
            }
        });

        afterEach(function(done) {
            this.timeout(5000);

            var processed = 0;
            for (var i = 0; i < nodes.length; i++) {
                (function(i) {
                    var port = 5656 + i;
                    request(app)
                        .get('/grid/unregister?id=http://127.0.0.1:' + port)
                        .end(function(err, res) {
                            res.statusCode.should.equal(200);
                            res.text.should.equal('OK - Bye');

                            nodes[i].close(function() {
                                ++processed;
                                if (processed >= nodes.length) {
                                    done();
                                }
                            });
                        });
                })(i);
            }
        });

        it('should correctly indicate nodes as available or unavailable', function(done) {
            this.timeout(5000);

            var processed = 0;
            for (var i = 0; i < nodes.length; i++) {
                store.getAvailableNodes(function(err, nodes) {
                    var nodeLength = nodes.length;
                    request(app)
                        .get('/selenium-server/driver?cmd=getNewBrowserSession&1=firefox&client_key=' + testData.CLIENT_KEY + "&client_secret=" + testData.CLIENT_SECRET)
                        .end(function(err, res) {
                            var sessionID = res.text.replace('OK,', '');
                            store.getAvailableNodes(function(err, nodes) {
                                assert.ok(nodes.length < nodeLength);

                                // stop session, the next one should start
                                request(app)
                                    .get('/selenium-server/driver?cmd=testComplete&sessionId=' + sessionID)
                                    .end(function(err, res) {
                                        processed += 1;
                                        if (processed >= 10) {
                                            return done();
                                        }
                                    });
                            });
                        });
                });
            }

        });
    });

    describe("start two tests in parallel with only one node to handle the requests", function() {
        var nodeServerMock;
        beforeEach(function(done) {
            store.flushdb();

            // mimick an RC node
            nodeServerMock = http
                .createServer(function(req, res) {
                    var url = req.url.toString();
                    if (url.indexOf('getNewBrowserSession') > -1) {
                        res.writeHead(200, {'Content-Type': 'text/plain'});
                        var sid = testData.getSessionID();
                        res.end("OK," + sid);
                    } else if (url.indexOf('testComplete') > -1) {
                        res.writeHead(200, {'Content-Type': 'text/plain'});
                        res.end("OK");
                    }
                })
                .listen(5560, '127.0.0.1');

            var postData = '{"class":"org.openqa.grid.common.RegistrationRequest","capabilities":[{"platform":"WINDOWS","seleniumProtocol":"Selenium","browserName":"firefox","maxInstances":1,"version":"9","alias":"FF9"}],"configuration":{"port":5560,"nodeConfig":"config.json","host":"127.0.0.1","cleanUpCycle":10000,"browserTimeout":20000,"hubHost":"10.0.1.6","registerCycle":5000,"debug":"","hub":"http://10.0.1.6:4444/grid/register","log":"test.log","url":"http://127.0.0.1:5560","remoteHost":"http://127.0.0.1:5560","register":true,"proxy":"org.openqa.grid.selenium.proxy.DefaultRemoteProxy","maxSession":1,"role":"node","hubPort":4444}}';

            request(app)
                .post('/grid/register')
                .send(postData)
                .end(function(err, res) {
                    res.statusCode.should.equal(200);
                    res.text.should.equal("OK - Welcome");
                    done();
                });
        });

        afterEach(function(done) {
            this.timeout(2000);

            request(app)
                .get('/grid/unregister?id=http://127.0.0.1:5560')
                .end(function(err, res) {
                    res.statusCode.should.equal(200);
                    res.text.should.equal('OK - Bye');

                    nodeServerMock.close(done);
                });
        });

        it('should handle both requests successfully, one after the other. the second request will be pending until the first one is processed', function(done) {
            // launch two requests at the same time
            this.timeout(5000);

            setTimeout(function() {
                request(app)
                    .get('/selenium-server/driver?cmd=getNewBrowserSession&1=firefox&client_key=' + testData.CLIENT_KEY + "&client_secret=" + testData.CLIENT_SECRET)
                    .end(function(err, res) {
                        var sid = res.text.replace('OK,', '');
                        // stop session, the next one should start
                        request(app)
                            .get('/selenium-server/driver?cmd=testComplete&sessionId=' + sid)
                            .end(function(err, res) {});
                    });
            }, 50);

            setTimeout(function() {
                request(app)
                    .get('/selenium-server/driver?cmd=getNewBrowserSession&1=firefox&client_key=' + testData.CLIENT_KEY + '&client_secret=' + testData.CLIENT_SECRET)
                    .end(function(err, res) {
                        done(err);
                    });
            }, 100);
        });
    });

    describe('it should retry forwarding to the node when at some point a forward fails due to a connection failure', function() {
        var nodeServerMock;
        beforeEach(function(done) {
            store.flushdb();
            // mimick an RC node
            nodeServerMock = http
                .createServer(function(req, res) {
                    var url = req.url.toString();
                    if (url.indexOf('getNewBrowserSession') > -1) {
                        res.writeHead(200, {'Content-Type': 'text/plain'});
                        var sid = testData.getSessionID();
                        res.end('OK,' + sid);
                    } else if (url.indexOf('testComplete') > -1) {
                        res.writeHead(200, {'Content-Type': 'text/plain'});
                        res.end('OK');
                    }
                })
                .listen(5561, '127.0.0.1');

            var postData = '{"class":"org.openqa.grid.common.RegistrationRequest","capabilities":[{"platform":"WINDOWS","seleniumProtocol":"Selenium","browserName":"firefox","maxInstances":1,"version":"9","alias":"FF9"}],"configuration":{"port":5561,"nodeConfig":"config.json","host":"127.0.0.1","cleanUpCycle":10000,"browserTimeout":20000,"hubHost":"10.0.1.6","registerCycle":5000,"debug":"","hub":"http://10.0.1.6:4444/grid/register","log":"test.log","url":"http://127.0.0.1:5561","remoteHost":"http://127.0.0.1:5561","register":true,"proxy":"org.openqa.grid.selenium.proxy.DefaultRemoteProxy","maxSession":1,"role":"node","hubPort":4444}}';

            request(app)
                .post('/grid/register')
                .send(postData)
                .end(function(err, res) {
                    res.statusCode.should.equal(200);
                    res.text.should.equal('OK - Welcome');
                    done();
                });
        });

        afterEach(function(done) {
            this.timeout(30000);
            request(app)
                .get('/grid/unregister?id=http://127.0.0.1:5561')
                .end(function(err, res) {
                    res.statusCode.should.equal(200);
                    res.text.should.equal('OK - Bye');
                    try {
                        // TODO: async close
                        nodeServerMock.close();
                    } catch (e) {}
                    done();
                });
        });

        it('should end gracefully when a bad connection occurs and the xx retries did not help', function(done) {
            this.timeout(30000);

            request(app)
                .get('/selenium-server/driver?cmd=getNewBrowserSession&1=firefox&client_key=' + testData.CLIENT_KEY + '&client_secret=' + testData.CLIENT_SECRET)
                .end(function(err, res) {
                    res.statusCode.should.equal(200);

                    var sessionID = res.text.replace('OK,', '');
                    // should be in the registry
                    registry.getSessionById(sessionID, function(err, session) {
                        session.should.be.an.instanceof(models.Session);

                        // the node is suddenly unreachable
                        nodeServerMock.close(function() {
                            // send a command now
                            request(app)
                                .get('/selenium-server/driver?cmd=open&1=/&sessionId=' + sessionID)
                                .end(function(err, res) {
                                    res.statusCode.should.equal(500);
                                    res.text.should.equal('FORWARDING_ERROR: connect ECONNREFUSED');
                                    done(err);
                                });
                        });
                    });
                });
        });

        it('should retry a connection, this simulates bad connection between hub and node', function(done) {
            this.timeout(30000);

            request(app)
                .get('/selenium-server/driver?cmd=getNewBrowserSession&1=firefox&client_key=' + testData.CLIENT_KEY + "&client_secret=" + testData.CLIENT_SECRET)
                .end(function(err, res) {
                    res.statusCode.should.equal(200);

                    var sessionID = res.text.replace('OK,', '');
                    // should be in the registry
                    registry.getSessionById(sessionID, function(err, session) {
                        session.should.be.an.instanceof(models.Session);

                        // the node is suddenly unreachable
                        nodeServerMock.close(function() {
                            // the node will be reachable again in 3 seconds
                            setTimeout(function() {
                                nodeServerMock = http
                                    .createServer(function(req, res) {
                                        var url = req.url.toString();
                                        if (url.indexOf('getNewBrowserSession') > -1) {
                                            res.writeHead(200, {'Content-Type': 'text/plain'});
                                            res.end('OK,' + sessionID);
                                        } else if (url.indexOf('cmd=open') > -1) {
                                            res.writeHead(200, {'Content-Type': 'text/plain'});
                                            res.end('OK,CONNECTION');
                                        }
                                    })
                                    .listen(5561, '127.0.0.1');

                                var postData = '{"class":"org.openqa.grid.common.RegistrationRequest","capabilities":[{"platform":"WINDOWS","seleniumProtocol":"Selenium","browserName":"firefox","maxInstances":1,"version":"9","alias":"FF9"}],"configuration":{"port":5561,"nodeConfig":"config.json","host":"127.0.0.1","cleanUpCycle":10000,"browserTimeout":20000,"hubHost":"10.0.1.6","registerCycle":5000,"debug":"","hub":"http://10.0.1.6:4444/grid/register","log":"test.log","url":"http://127.0.0.1:5561","remoteHost":"http://127.0.0.1:5561","register":true,"proxy":"org.openqa.grid.selenium.proxy.DefaultRemoteProxy","maxSession":1,"role":"node","hubPort":4444}}';

                                request(app)
                                    .post('/grid/register')
                                    .send(postData)
                                    .end(function(err, res) {
                                        res.statusCode.should.equal(200);
                                        res.text.should.equal('OK - Welcome');
                                    });
                            }, 3000);

                            request(app)
                                .get('/selenium-server/driver?cmd=open&1=/&sessionId=' + sessionID)
                                .end(function(err, res) {
                                    res.statusCode.should.equal(200);
                                    res.text.should.equal('OK,CONNECTION');
                                    done(err);
                                });
                        });
                    });
                });
        });
    });
});
<commit_msg>Remove useless forwarder_test<commit_after><|endoftext|>


<commit_before>describe.only('Get Core', function() {
    require('./missing.spec');
    require('./values.spec');
    require('./references.spec');
    require('./errors.spec');
    require('./deref.spec');
    require('./edges.spec');
});
<commit_msg>removed the .only.<commit_after>describe('Get Core', function() {
    require('./missing.spec');
    require('./values.spec');
    require('./references.spec');
    require('./errors.spec');
    require('./deref.spec');
    require('./edges.spec');
});
<|endoftext|>


<commit_before>// group-api-test.js
//
// Test group API
//
// Copyright 2013, E14N https://e14n.com/
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

var assert = require("assert"),
    vows = require("vows"),
    Step = require("step"),
    _ = require("underscore"),
    http = require("http"),
    urlparse = require("url").parse,
    httputil = require("./lib/http"),
    oauthutil = require("./lib/oauth"),
    actutil = require("./lib/activity"),
    pj = httputil.postJSON,
    gj = httputil.getJSON,
    validActivity = actutil.validActivity,
    validActivityObject = actutil.validActivityObject,
    validFeed = actutil.validFeed,
    setupApp = oauthutil.setupApp,
    newCredentials = oauthutil.newCredentials;

var suite = vows.describe("Group API test");

// A batch for testing the read-write access to the API

suite.addBatch({
    "When we set up the app": {
        topic: function() {
            setupApp(this.callback);
        },
        teardown: function(app) {
            if (app && app.close) {
                app.close();
            }
        },
        "it works": function(err, app) {
            assert.ifError(err);
        },
        "and we get make a new user": {
            topic: function() {
                newCredentials("fafhrd", "lankhmar+1", this.callback);
            },
            "it works": function(err, cred) {
                assert.ifError(err);
                assert.isObject(cred);
            },
            "and they create a group": {
                topic: function(cred) {
                    var callback = this.callback,
                        url = "http://localhost:4815/api/user/fafhrd/feed",
                        act = {
                            verb: "create",
                            object: {
                                objectType: "group",
                                displayName: "Barbarians",
                                summary: "A safe place for barbarians to share their feelings"
                            }
                        };

                    pj(url, cred, act, function(err, data, resp) {
                        callback(err, data);
                    });
                },
                "it works": function(err, data) {
                    assert.ifError(err);
                    validActivity(data);
                },
                "and we retrieve that group with the REST API": {
                    topic: function(act, cred) {
                        var callback = this.callback,
                            url = act.object.links.self.href;

                        gj(url, cred, function(err, data, resp) {
                            callback(err, data);
                        });
                    },
                    "it works": function(err, group) {
                        assert.ifError(err);
                        assert.isObject(group);
                    },
                    "it looks right": function(err, group) {
                        assert.ifError(err);
                        validActivityObject(group);
                    },
                    "it has a members feed": function(err, group) {
                        assert.ifError(err);
                        assert.isObject(group);
                        assert.include(group, "members");
                        assert.isObject(group.members);
                        assert.include(group.members, "url");
                        assert.isString(group.members.url);
                        assert.include(group.members, "totalItems");
                        assert.isNumber(group.members.totalItems);
                        assert.equal(group.members.totalItems, 0);
                    },
                    "it has an inbox feed": function(err, group) {
                        assert.ifError(err);
                        assert.isObject(group);
                        assert.include(group, "links");
                        assert.isObject(group.links);
                        assert.include(group.links, "activity-inbox");
                        assert.isObject(group.links["activity-inbox"]);
                        assert.include(group.links["activity-inbox"], "href");
                        assert.isString(group.links["activity-inbox"].href);
                    },
                    "and we get the members feed": {
                        topic: function(group, act, cred) {
                            var callback = this.callback,
                                url = group.members.url;

                            gj(url, cred, function(err, data, resp) {
                                callback(err, data);
                            });
                        },
                        "it works": function(err, feed) {
                            assert.ifError(err);
                            validFeed(feed);
                        },
                        "it's empty": function(err, feed) {
                            assert.ifError(err);
                            assert.equal(feed.totalItems, 0);
                            assert.isTrue(!_.has(feed, "items") || (_.isArray(feed.items) && feed.items.length === 0));
                        }
                    },
                    "and we get the group inbox feed": {
                        topic: function(group, act, cred) {
                            var callback = this.callback,
                                url = group.links["activity-inbox"].href;

                            gj(url, cred, function(err, data, resp) {
                                callback(err, data);
                            });
                        },
                        "it works": function(err, feed) {
                            assert.ifError(err);
                            validFeed(feed);
                        },
                        "it's empty": function(err, feed) {
                            assert.ifError(err);
                            assert.equal(feed.totalItems, 0);
                            assert.isTrue(!_.has(feed, "items") || (_.isArray(feed.items) && feed.items.length === 0));
                        }
                    }
                }
            }
        }
    }
});

suite["export"](module);
<commit_msg>Join a new group<commit_after>// group-api-test.js
//
// Test group API
//
// Copyright 2013, E14N https://e14n.com/
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

var assert = require("assert"),
    vows = require("vows"),
    Step = require("step"),
    _ = require("underscore"),
    http = require("http"),
    urlparse = require("url").parse,
    httputil = require("./lib/http"),
    oauthutil = require("./lib/oauth"),
    actutil = require("./lib/activity"),
    pj = httputil.postJSON,
    gj = httputil.getJSON,
    validActivity = actutil.validActivity,
    validActivityObject = actutil.validActivityObject,
    validFeed = actutil.validFeed,
    setupApp = oauthutil.setupApp,
    newCredentials = oauthutil.newCredentials;

var suite = vows.describe("Group API test");

// A batch for testing the read-write access to the API

suite.addBatch({
    "When we set up the app": {
        topic: function() {
            setupApp(this.callback);
        },
        teardown: function(app) {
            if (app && app.close) {
                app.close();
            }
        },
        "it works": function(err, app) {
            assert.ifError(err);
        },
        "and we make a new user": {
            topic: function() {
                newCredentials("fafhrd", "lankhmar+1", this.callback);
            },
            "it works": function(err, cred) {
                assert.ifError(err);
                assert.isObject(cred);
            },
            "and they create a group": {
                topic: function(cred) {
                    var callback = this.callback,
                        url = "http://localhost:4815/api/user/fafhrd/feed",
                        act = {
                            verb: "create",
                            object: {
                                objectType: "group",
                                displayName: "Barbarians",
                                summary: "A safe place for barbarians to share their feelings"
                            }
                        };

                    pj(url, cred, act, function(err, data, resp) {
                        callback(err, data);
                    });
                },
                "it works": function(err, data) {
                    assert.ifError(err);
                    validActivity(data);
                },
                "and we retrieve that group with the REST API": {
                    topic: function(act, cred) {
                        var callback = this.callback,
                            url = act.object.links.self.href;

                        gj(url, cred, function(err, data, resp) {
                            callback(err, data);
                        });
                    },
                    "it works": function(err, group) {
                        assert.ifError(err);
                        assert.isObject(group);
                    },
                    "it looks right": function(err, group) {
                        assert.ifError(err);
                        validActivityObject(group);
                    },
                    "it has a members feed": function(err, group) {
                        assert.ifError(err);
                        assert.isObject(group);
                        assert.include(group, "members");
                        assert.isObject(group.members);
                        assert.include(group.members, "url");
                        assert.isString(group.members.url);
                        assert.include(group.members, "totalItems");
                        assert.isNumber(group.members.totalItems);
                        assert.equal(group.members.totalItems, 0);
                    },
                    "it has an inbox feed": function(err, group) {
                        assert.ifError(err);
                        assert.isObject(group);
                        assert.include(group, "links");
                        assert.isObject(group.links);
                        assert.include(group.links, "activity-inbox");
                        assert.isObject(group.links["activity-inbox"]);
                        assert.include(group.links["activity-inbox"], "href");
                        assert.isString(group.links["activity-inbox"].href);
                    },
                    "and we get the members feed": {
                        topic: function(group, act, cred) {
                            var callback = this.callback,
                                url = group.members.url;

                            gj(url, cred, function(err, data, resp) {
                                callback(err, data);
                            });
                        },
                        "it works": function(err, feed) {
                            assert.ifError(err);
                            validFeed(feed);
                        },
                        "it's empty": function(err, feed) {
                            assert.ifError(err);
                            assert.equal(feed.totalItems, 0);
                            assert.isTrue(!_.has(feed, "items") || (_.isArray(feed.items) && feed.items.length === 0));
                        }
                    },
                    "and we get the group inbox feed": {
                        topic: function(group, act, cred) {
                            var callback = this.callback,
                                url = group.links["activity-inbox"].href;

                            gj(url, cred, function(err, data, resp) {
                                callback(err, data);
                            });
                        },
                        "it works": function(err, feed) {
                            assert.ifError(err);
                            validFeed(feed);
                        },
                        "it's empty": function(err, feed) {
                            assert.ifError(err);
                            assert.equal(feed.totalItems, 0);
                            assert.isTrue(!_.has(feed, "items") || (_.isArray(feed.items) && feed.items.length === 0));
                        }
                    }
                }
            }
        },
        "and we make another group": {
            topic: function() {
                var callback = this.callback,
                    url = "http://localhost:4815/api/user/graymouser/feed",
                    act = {
                        verb: "create",
                        object: {
                            objectType: "group",
                            displayName: "Magicians",
                            summary: "Let's talk sorcery!"
                        }
                    },
                    cred;

                Step(
                    function() {
                        newCredentials("graymouser", "swords+_+_", this);
                    },
                    function(err, results) {
                        if (err) throw err;
                        cred = results;
                        pj(url, cred, act, this);
                    },
                    function(err, data, resp) {
                        if (err) {
                            callback(err, null, null);
                        } else {
                            callback(null, data, cred);
                        }
                    }
                );
            },
            "it works": function(err, data, cred) {
                assert.ifError(err);
                validActivity(data);
            },
            "and another user tries to join it": {
                topic: function(created, cred) {
                    var callback = this.callback,
                        url = "http://localhost:4815/api/user/ningauble/feed",
                        act = {
                            verb: "join",
                            object: {
                                id: created.object.id,
                                objectType: created.object.objectType
                            }
                        },
                        newCred;

                    Step(
                        function() {
                            newCredentials("ningauble", "*iiiiiii*", this);
                        },
                        function(err, results) {
                            if (err) throw err;
                            newCred = results;
                            pj(url, newCred, act, this);
                        },
                        function(err, data, resp) {
                            if (err) {
                                callback(err, null, null);
                            } else {
                                callback(null, data, newCred);
                            }
                        }
                    );
                },
                "it works": function(err, data, cred) {
                    assert.ifError(err);
                    validActivity(data);
                }
            }
        }
    }
});

suite["export"](module);
<|endoftext|>


<commit_before>(function(win, doc){

  scroll(0, 0);
  var playground = document.createElement('div');
  playground.id = 'playground';
  playground.innerHTML = '

';
  doc.body.insertBefore(playground, doc.body.childNodes[0]);

  var style = document.createElement('style');
  var content = '#playground {position:absolute;top:0;left:0;line-height:0;font-size:0}\n.scrollTrigger {position:relative;width:5px;height:5px;background:#000;top:20000px;left:20000px;}';
  style.setAttribute("type", "text/css");
  if (style.styleSheet) {
      style.styleSheet.cssText = content;
  } else {
      style.appendChild(document.createTextNode(content));
  }
  document.getElementsByTagName("head")[0].appendChild(style);

  win['createTest'] = function createTest(params) {
    params = params || {};

    var test = document.createElement(params.tagName || 'div');

    for (var attr in params.attributes) {
      test.setAttribute(attr, params.attributes[attr]);
    }

    for(var prop in params.style) {
      test.style[prop] = params.style[prop];
    }

    return test;
  }

  win['insertTest'] = function insertTest(test, parent) {
    parent = parent || playground;
    parent.insertBefore(test, parent.childNodes[0]);
  }

  win['clean'] = function clean(node, parent) {
    parent = parent || playground;

    return function() {
      parent.removeChild(node);
      scroll(0, 0);
    }
  }

  win['scroller'] = function scroller(x, y, container, cb) {
    if (typeof cb === 'function') {
      setTimeout(function() {
        smartScroll(x, y, container);
        setTimeout(cb, 100);
      }, 4);
    } else {
      return function(cb) {
        setTimeout(function() {
          smartScroll(x, y, container);
          setTimeout(cb, 100);
        }, 4);
      }
    }
  }

  win['wait'] = function wait(ms) {

    return function(done) {
      setTimeout(done, ms);
    }
  }

  function smartScroll(x, y, container) {
    if (!container) {
      scroll(x || 0, y || 0);
    } else {
      // tricky, on IE8 this will triggers TWO scroll events
      container.scrollLeft = x;
      container.scrollTop = y;
    }
  }

})(window, document);<commit_msg>Higher wait time for scroll tests<commit_after>(function(win, doc){

  scroll(0, 0);
  var playground = document.createElement('div');
  playground.id = 'playground';
  playground.innerHTML = '

';
  doc.body.insertBefore(playground, doc.body.childNodes[0]);

  var style = document.createElement('style');
  var content = '#playground {position:absolute;top:0;left:0;line-height:0;font-size:0}\n.scrollTrigger {position:relative;width:5px;height:5px;background:#000;top:20000px;left:20000px;}';
  style.setAttribute("type", "text/css");
  if (style.styleSheet) {
      style.styleSheet.cssText = content;
  } else {
      style.appendChild(document.createTextNode(content));
  }
  document.getElementsByTagName("head")[0].appendChild(style);

  win['createTest'] = function createTest(params) {
    params = params || {};

    var test = document.createElement(params.tagName || 'div');

    for (var attr in params.attributes) {
      test.setAttribute(attr, params.attributes[attr]);
    }

    for(var prop in params.style) {
      test.style[prop] = params.style[prop];
    }

    return test;
  }

  win['insertTest'] = function insertTest(test, parent) {
    parent = parent || playground;
    parent.insertBefore(test, parent.childNodes[0]);
  }

  win['clean'] = function clean(node, parent) {
    parent = parent || playground;

    return function() {
      parent.removeChild(node);
      scroll(0, 0);
    }
  }

  win['scroller'] = function scroller(x, y, container, cb) {
    if (typeof cb === 'function') {
      setTimeout(function() {
        smartScroll(x, y, container);
        setTimeout(cb, 300);
      }, 4);
    } else {
      return function(cb) {
        setTimeout(function() {
          smartScroll(x, y, container);
          setTimeout(cb, 300);
        }, 4);
      }
    }
  }

  win['wait'] = function wait(ms) {

    return function(done) {
      setTimeout(done, ms);
    }
  }

  function smartScroll(x, y, container) {
    if (!container) {
      scroll(x || 0, y || 0);
    } else {
      // tricky, on IE8 this will triggers TWO scroll events
      container.scrollLeft = x;
      container.scrollTop = y;
    }
  }

})(window, document);<|endoftext|>


<commit_before>"use strict";

let assert = require( 'assert' );
let mockery = require( 'mockery' );

let pki = require( './mocks/pki.js' );

describe( "Class HormoneSource", function() {

	let time, definition;
	let HormoneSource;

	before( () => {

		mockery.enable( {
			useCleanCache: true,
			warnOnReplace: false,
			warnOnUnregistered: false
		} );

		// Install all mocks
		let TimeMock = require( './mocks/time.js' );
		mockery.registerMock( './time.js', new TimeMock( 1452974164 ) );

		// require all librarys required for tests
		let DefinitionSource = require( '../lib/definition-source.js' );
		HormoneSource = require( '../lib/hormone-source.js' );
		time = require( './time.js' );
		definition = new DefinitionSource( pki.key, {
			cert: pki.cert,
			description: "Test Definition",
			check: "err=0;",
			freshness: 1,
			dataFormat: [ {
				name: "String",
				type: 'string',
				description: "Funny stuff"
			}, {
				name: "Boolean",
				type: 'boolean'
			}, {
				name: "Number",
				type: 'number',
				unit: "V"
			} ]
		} );

	} );

	after( () => {

		mockery.disable();

	} );

	it( "should not create new hormone due to missing private key", ( done ) => {
		try {

			let h = new HormoneSource();

		} catch( e ) { /*console.log(e);*/ done(); }
	} );

	it( "should not create new hormone due to missing definition", ( done ) => {
		try {

			let h = new HormoneSource( pki.key );

		} catch( e ) { /*console.log(e);*/ done(); }
	} );

	it( "should not create new hormone due to missing data", ( done ) => {
		try {

			let h = new HormoneSource( pki.key, definition );

		} catch( e ) { /*console.log(e);*/ done(); }
	} );

	it( "should not create new definition due to unkown option", ( done ) => {
		try {

			let h = new HormoneSource( pki.key, definition, {
				'String': "test",
				'Number': 123,
				'Boolean': true,
				'Unkown': 1
			} );

		} catch( e ) { /*console.log(e);*/ done(); }
	} );

	it( "should create new hormone", ( done ) => {

		let data = {
			'String': "test",
			'Number': 123,
			'Boolean': true
		};

		let h = new HormoneSource( pki.key, definition, data );

		assert.deepEqual( h.data, data );

		assert.deepEqual( h.definition, definition.data );

		done();

	} );

	it( "should create new fresh hormone", ( done ) => {

		let h = new HormoneSource( pki.key, definition, {
			'String': "test",
			'Number': 123,
			'Boolean': true
		} );

		assert.equal( h.isFresh, true );

		done();

	} );

	it( "should create new expired hormone", ( done ) => {

		let h = new HormoneSource( pki.key, definition, {
			'String': "test",
			'Number': 123,
			'Boolean': true
		} );

		time.addSeconds( 3 );

		assert.equal( h.isFresh, false );

		done();

	} );

} );
<commit_msg>Cleaned up test of hormone class at source<commit_after>"use strict";

let assert = require( 'assert' );
let mockery = require( 'mockery' );

describe( "Class HormoneSource", () => {

	let time, pki, definition;
	let HormoneSource;

	before( () => {

		mockery.enable( {
			useCleanCache: true,
			warnOnReplace: false,
			warnOnUnregistered: false
		} );

		// Install all mocks
		let TimeMock = require( './mocks/time.js' );
		mockery.registerMock( './time.js', new TimeMock( 1452974164 ) );

		// require all librarys required for tests
		pki = require( './mocks/pki.js' );
		time = require( './time.js' );
		HormoneSource = require( '../lib/hormone-source.js' );
		let DefinitionSource = require( '../lib/definition-source.js' );
		definition = new DefinitionSource( pki.key, {
			cert: pki.cert,
			description: "Test Definition",
			check: "err=0;",
			freshness: 1,
			dataFormat: [ {
				name: "String",
				type: 'string',
				description: "Funny stuff"
			}, {
				name: "Boolean",
				type: 'boolean'
			}, {
				name: "Number",
				type: 'number',
				unit: "V"
			} ]
		} );

	} );

	after( () => {

		mockery.disable();

	} );

	it( "should not create new hormone due to missing private key", ( done ) => {
		try {

			let h = new HormoneSource();

		} catch( e ) { /*console.log(e);*/ done(); }
	} );

	it( "should not create new hormone due to missing definition", ( done ) => {
		try {

			let h = new HormoneSource( pki.key );

		} catch( e ) { /*console.log(e);*/ done(); }
	} );

	it( "should not create new hormone due to missing data", ( done ) => {
		try {

			let h = new HormoneSource( pki.key, definition );

		} catch( e ) { /*console.log(e);*/ done(); }
	} );

	it( "should not create new definition due to unkown option", ( done ) => {
		try {

			let h = new HormoneSource( pki.key, definition, {
				'String': "test",
				'Number': 123,
				'Boolean': true,
				'Unkown': 1
			} );

		} catch( e ) { /*console.log(e);*/ done(); }
	} );

	it( "should create new hormone", ( done ) => {

		let data = {
			'String': "test",
			'Number': 123,
			'Boolean': true
		};

		let h = new HormoneSource( pki.key, definition, data );

		assert.deepEqual( h.data, data );

		assert.deepEqual( h.definition, definition.data );

		done();

	} );

	it( "should create new fresh hormone", ( done ) => {

		let h = new HormoneSource( pki.key, definition, {
			'String': "test",
			'Number': 123,
			'Boolean': true
		} );

		assert.equal( h.isFresh, true );

		done();

	} );

	it( "should create new expired hormone", ( done ) => {

		let h = new HormoneSource( pki.key, definition, {
			'String': "test",
			'Number': 123,
			'Boolean': true
		} );

		time.addSeconds( 3 );

		assert.equal( h.isFresh, false );

		done();

	} );

} );
<|endoftext|>