<commit_before>module("support", { teardown: moduleTeardown });

test("boxModel", function() {
	expect( 1 );

	equal( jQuery.support.boxModel, document.compatMode === "CSS1Compat" , "jQuery.support.boxModel is sort of tied to quirks mode but unstable since 1.8" );
});

if ( jQuery.css ) {
	testIframeWithCallback( "body background is not lost if set prior to loading jQuery (#9238)", "support/bodyBackground.html", function( color, support ) {
		expect( 2 );
		var i,
			passed = true,
			okValue = {
				"#000000": true,
				"rgb(0, 0, 0)": true
			};
		ok( okValue[ color ], "color was not reset (" + color + ")" );

		for ( i in jQuery.support ) {
			if ( jQuery.support[ i ] !== support[ i ] ) {
				passed = false;
				strictEqual( jQuery.support[ i ], support[ i ], "Support property " + i + " is different" );
			}
		}
		for ( i in support ) {
			if ( !( i in jQuery.support ) ) {
				passed = false;
				strictEqual( jQuery.support[ i ], support[ i ], "Unexpected property: " + i );
			}
		}
		ok( passed, "Same support properties" );
	});
}

testIframeWithCallback( "A background on the testElement does not cause IE8 to crash (#9823)", "support/testElementCrash.html", function() {
	expect(1);
	ok( true, "IE8 does not crash" );
});

(function() {

	var userAgent = window.navigator.userAgent,
		expected;

	// These tests do not have to stay
	// They are here to help with upcoming support changes for 1.8
	if ( /chrome\/19\.0/i.test(userAgent) ) {
		expected = {
			"leadingWhitespace":true,
			"tbody":true,
			"htmlSerialize":true,
			"style":true,
			"hrefNormalized":true,
			"opacity":true,
			"cssFloat":true,
			"checkOn":true,
			"optSelected":true,
			"getSetAttribute":true,
			"enctype":true,
			"html5Clone":true,
			"submitBubbles":true,
			"changeBubbles":true,
			"focusinBubbles":false,
			"deleteExpando":true,
			"noCloneEvent":true,
			"inlineBlockNeedsLayout":false,
			"shrinkWrapBlocks":false,
			"reliableMarginRight":true,
			"noCloneChecked":true,
			"optDisabled":true,
			"radioValue":true,
			"checkClone":true,
			"appendChecked":true,
			"boxModel":true,
			"reliableHiddenOffsets":true,
			"ajax":true,
			"cors":true,
			"doesNotIncludeMarginInBodyOffset":true
		};
	} else if ( /msie 8\.0/i.test(userAgent) ) {
		expected = {
			"leadingWhitespace":false,
			"tbody":true,
			"htmlSerialize":false,
			"style":false,
			"hrefNormalized":true,
			"opacity":false,
			"cssFloat":false,
			"checkOn":true,
			"optSelected":false,
			"getSetAttribute":true,
			"enctype":true,
			"html5Clone":false,
			"submitBubbles":false,
			"changeBubbles":false,
			"focusinBubbles":true,
			"deleteExpando":false,
			"noCloneEvent":false,
			"inlineBlockNeedsLayout":false,
			"shrinkWrapBlocks":false,
			"reliableMarginRight":true,
			"noCloneChecked":false,
			"optDisabled":true,
			"radioValue":false,
			"checkClone":true,
			"appendChecked":true,
			"boxModel":true,
			"reliableHiddenOffsets":false,
			"ajax":true,
			"cors":false,
			"doesNotIncludeMarginInBodyOffset":true
		};
	} else if ( /msie 7\.0/i.test(userAgent) ) {
		expected = {
			"ajax": true,
			"appendChecked": false,
			"boxModel": true,
			"changeBubbles": false,
			"checkClone": false,
			"checkOn": true,
			"cors": false,
			"cssFloat": false,
			"deleteExpando": false,
			"doesNotIncludeMarginInBodyOffset": true,
			"enctype": true,
			"focusinBubbles": true,
			"getSetAttribute": false,
			"hrefNormalized": false,
			"html5Clone": false,
			"htmlSerialize": false,
			"inlineBlockNeedsLayout": true,
			"leadingWhitespace": false,
			"noCloneChecked": false,
			"noCloneEvent": false,
			"opacity": false,
			"optDisabled": true,
			"optSelected": false,
			"radioValue": false,
			"reliableHiddenOffsets": false,
			"reliableMarginRight": true,
			"shrinkWrapBlocks": false,
			"submitBubbles": false,
			"tbody": false,
			"style": false
		};
	} else if ( /msie 6\.0/i.test(userAgent) ) {
		expected = {
			"leadingWhitespace":false,
			"tbody":false,
			"htmlSerialize":false,
			"style":false,
			"hrefNormalized":false,
			"opacity":false,
			"cssFloat":false,
			"checkOn":true,
			"optSelected":false,
			"getSetAttribute":false,
			"enctype":true,
			"html5Clone":false,
			"submitBubbles":false,
			"changeBubbles":false,
			"focusinBubbles":true,
			"deleteExpando":false,
			"noCloneEvent":false,
			"inlineBlockNeedsLayout":true,
			"shrinkWrapBlocks":true,
			"reliableMarginRight":true,
			"noCloneChecked":false,
			"optDisabled":true,
			"radioValue":false,
			"checkClone":false,
			"appendChecked":false,
			"boxModel":true,
			"reliableHiddenOffsets":false,
			"ajax":true,
			"cors":false,
			"doesNotIncludeMarginInBodyOffset":true
		};
	} else if ( /5\.1\.1 safari/i.test(userAgent) ) {
		expected = {
			"leadingWhitespace":true,
			"tbody":true,
			"htmlSerialize":true,
			"style":true,
			"hrefNormalized":true,
			"opacity":true,
			"cssFloat":true,
			"checkOn":false,
			"optSelected":true,
			"getSetAttribute":true,
			"enctype":true,
			"html5Clone":true,
			"submitBubbles":true,
			"changeBubbles":true,
			"focusinBubbles":false,
			"deleteExpando":true,
			"noCloneEvent":true,
			"inlineBlockNeedsLayout":false,
			"shrinkWrapBlocks":false,
			"reliableMarginRight":true,
			"noCloneChecked":true,
			"optDisabled":true,
			"radioValue":true,
			"checkClone":false,
			"appendChecked":false,
			"boxModel":true,
			"reliableHiddenOffsets":true,
			"ajax":true,
			"cors":true,
			"doesNotIncludeMarginInBodyOffset":true
		};
	} else if ( /firefox\/3\.6/i.test(userAgent) ) {
		expected = {
			"leadingWhitespace":true,
			"tbody":true,
			"htmlSerialize":true,
			"style":true,
			"hrefNormalized":true,
			"opacity":true,
			"cssFloat":true,
			"checkOn":true,
			"optSelected":true,
			"getSetAttribute":true,
			"enctype":false,
			"html5Clone":true,
			"submitBubbles":true,
			"changeBubbles":true,
			"focusinBubbles":false,
			"deleteExpando":true,
			"noCloneEvent":true,
			"inlineBlockNeedsLayout":false,
			"shrinkWrapBlocks":false,
			"reliableMarginRight":true,
			"noCloneChecked":true,
			"optDisabled":true,
			"radioValue":true,
			"checkClone":true,
			"appendChecked":true,
			"boxModel":true,
			"reliableHiddenOffsets":true,
			"ajax":true,
			"cors":true,
			"doesNotIncludeMarginInBodyOffset":true
		};
	}

	if ( expected ) {
		test("Verify that the support tests resolve as expected per browser", function() {
			for ( var i in expected ) {
				if ( jQuery.ajax || i !== "ajax" && i !== "cors" ) {
					equal( jQuery.support[i], expected[i], "jQuery.support['" + i + "']: " + jQuery.support[i] + ", expected['" + i + "']: " + expected[i]);
				}
			}
		});
	}

})();
<commit_msg>Adds missing expect() call in test/unit/support.js, fixes failing IE tests<commit_after>module("support", { teardown: moduleTeardown });

test("boxModel", function() {
	expect( 1 );

	equal( jQuery.support.boxModel, document.compatMode === "CSS1Compat" , "jQuery.support.boxModel is sort of tied to quirks mode but unstable since 1.8" );
});

if ( jQuery.css ) {
	testIframeWithCallback( "body background is not lost if set prior to loading jQuery (#9238)", "support/bodyBackground.html", function( color, support ) {
		expect( 2 );
		var i,
			passed = true,
			okValue = {
				"#000000": true,
				"rgb(0, 0, 0)": true
			};
		ok( okValue[ color ], "color was not reset (" + color + ")" );

		for ( i in jQuery.support ) {
			if ( jQuery.support[ i ] !== support[ i ] ) {
				passed = false;
				strictEqual( jQuery.support[ i ], support[ i ], "Support property " + i + " is different" );
			}
		}
		for ( i in support ) {
			if ( !( i in jQuery.support ) ) {
				passed = false;
				strictEqual( jQuery.support[ i ], support[ i ], "Unexpected property: " + i );
			}
		}
		ok( passed, "Same support properties" );
	});
}

testIframeWithCallback( "A background on the testElement does not cause IE8 to crash (#9823)", "support/testElementCrash.html", function() {
	expect(1);
	ok( true, "IE8 does not crash" );
});

(function() {

	var userAgent = window.navigator.userAgent,
		expected;

	// These tests do not have to stay
	// They are here to help with upcoming support changes for 1.8
	if ( /chrome\/19\.0/i.test(userAgent) ) {
		expected = {
			"leadingWhitespace":true,
			"tbody":true,
			"htmlSerialize":true,
			"style":true,
			"hrefNormalized":true,
			"opacity":true,
			"cssFloat":true,
			"checkOn":true,
			"optSelected":true,
			"getSetAttribute":true,
			"enctype":true,
			"html5Clone":true,
			"submitBubbles":true,
			"changeBubbles":true,
			"focusinBubbles":false,
			"deleteExpando":true,
			"noCloneEvent":true,
			"inlineBlockNeedsLayout":false,
			"shrinkWrapBlocks":false,
			"reliableMarginRight":true,
			"noCloneChecked":true,
			"optDisabled":true,
			"radioValue":true,
			"checkClone":true,
			"appendChecked":true,
			"boxModel":true,
			"reliableHiddenOffsets":true,
			"ajax":true,
			"cors":true,
			"doesNotIncludeMarginInBodyOffset":true
		};
	} else if ( /msie 8\.0/i.test(userAgent) ) {
		expected = {
			"leadingWhitespace":false,
			"tbody":true,
			"htmlSerialize":false,
			"style":false,
			"hrefNormalized":true,
			"opacity":false,
			"cssFloat":false,
			"checkOn":true,
			"optSelected":false,
			"getSetAttribute":true,
			"enctype":true,
			"html5Clone":false,
			"submitBubbles":false,
			"changeBubbles":false,
			"focusinBubbles":true,
			"deleteExpando":false,
			"noCloneEvent":false,
			"inlineBlockNeedsLayout":false,
			"shrinkWrapBlocks":false,
			"reliableMarginRight":true,
			"noCloneChecked":false,
			"optDisabled":true,
			"radioValue":false,
			"checkClone":true,
			"appendChecked":true,
			"boxModel":true,
			"reliableHiddenOffsets":false,
			"ajax":true,
			"cors":false,
			"doesNotIncludeMarginInBodyOffset":true
		};
	} else if ( /msie 7\.0/i.test(userAgent) ) {
		expected = {
			"ajax": true,
			"appendChecked": false,
			"boxModel": true,
			"changeBubbles": false,
			"checkClone": false,
			"checkOn": true,
			"cors": false,
			"cssFloat": false,
			"deleteExpando": false,
			"doesNotIncludeMarginInBodyOffset": true,
			"enctype": true,
			"focusinBubbles": true,
			"getSetAttribute": false,
			"hrefNormalized": false,
			"html5Clone": false,
			"htmlSerialize": false,
			"inlineBlockNeedsLayout": true,
			"leadingWhitespace": false,
			"noCloneChecked": false,
			"noCloneEvent": false,
			"opacity": false,
			"optDisabled": true,
			"optSelected": false,
			"radioValue": false,
			"reliableHiddenOffsets": false,
			"reliableMarginRight": true,
			"shrinkWrapBlocks": false,
			"submitBubbles": false,
			"tbody": false,
			"style": false
		};
	} else if ( /msie 6\.0/i.test(userAgent) ) {
		expected = {
			"leadingWhitespace":false,
			"tbody":false,
			"htmlSerialize":false,
			"style":false,
			"hrefNormalized":false,
			"opacity":false,
			"cssFloat":false,
			"checkOn":true,
			"optSelected":false,
			"getSetAttribute":false,
			"enctype":true,
			"html5Clone":false,
			"submitBubbles":false,
			"changeBubbles":false,
			"focusinBubbles":true,
			"deleteExpando":false,
			"noCloneEvent":false,
			"inlineBlockNeedsLayout":true,
			"shrinkWrapBlocks":true,
			"reliableMarginRight":true,
			"noCloneChecked":false,
			"optDisabled":true,
			"radioValue":false,
			"checkClone":false,
			"appendChecked":false,
			"boxModel":true,
			"reliableHiddenOffsets":false,
			"ajax":true,
			"cors":false,
			"doesNotIncludeMarginInBodyOffset":true
		};
	} else if ( /5\.1\.1 safari/i.test(userAgent) ) {
		expected = {
			"leadingWhitespace":true,
			"tbody":true,
			"htmlSerialize":true,
			"style":true,
			"hrefNormalized":true,
			"opacity":true,
			"cssFloat":true,
			"checkOn":false,
			"optSelected":true,
			"getSetAttribute":true,
			"enctype":true,
			"html5Clone":true,
			"submitBubbles":true,
			"changeBubbles":true,
			"focusinBubbles":false,
			"deleteExpando":true,
			"noCloneEvent":true,
			"inlineBlockNeedsLayout":false,
			"shrinkWrapBlocks":false,
			"reliableMarginRight":true,
			"noCloneChecked":true,
			"optDisabled":true,
			"radioValue":true,
			"checkClone":false,
			"appendChecked":false,
			"boxModel":true,
			"reliableHiddenOffsets":true,
			"ajax":true,
			"cors":true,
			"doesNotIncludeMarginInBodyOffset":true
		};
	} else if ( /firefox\/3\.6/i.test(userAgent) ) {
		expected = {
			"leadingWhitespace":true,
			"tbody":true,
			"htmlSerialize":true,
			"style":true,
			"hrefNormalized":true,
			"opacity":true,
			"cssFloat":true,
			"checkOn":true,
			"optSelected":true,
			"getSetAttribute":true,
			"enctype":false,
			"html5Clone":true,
			"submitBubbles":true,
			"changeBubbles":true,
			"focusinBubbles":false,
			"deleteExpando":true,
			"noCloneEvent":true,
			"inlineBlockNeedsLayout":false,
			"shrinkWrapBlocks":false,
			"reliableMarginRight":true,
			"noCloneChecked":true,
			"optDisabled":true,
			"radioValue":true,
			"checkClone":true,
			"appendChecked":true,
			"boxModel":true,
			"reliableHiddenOffsets":true,
			"ajax":true,
			"cors":true,
			"doesNotIncludeMarginInBodyOffset":true
		};
	}

	if ( expected ) {
		test("Verify that the support tests resolve as expected per browser", function() {

      expect( jQuery(expected).size() );

			for ( var i in expected ) {
				if ( jQuery.ajax || i !== "ajax" && i !== "cors" ) {
					equal( jQuery.support[i], expected[i], "jQuery.support['" + i + "']: " + jQuery.support[i] + ", expected['" + i + "']: " + expected[i]);
				}
			}
		});
	}

})();
<|endoftext|>


<commit_before>$(function() {
	'use strict';

	module('Utility Functions');

	test('isSvgElement', function() {
		var div = $('
'),
			rect = $(document.createElementNS('http://www.w3.org/2000/svg', 'rect'));

		strictEqual(isSvgElement(rect), true, 'rect is an SVG element');
		strictEqual(isSvgElement(div), false, 'div is not an SVG element');
	});

	test('initTracking', function() {
		session.currentX = 1;
		session.currentY = 1;

		initTracking();

		$(document).trigger($.Event('mousemove', { pageX: 2, pageY: 3 }));

		strictEqual(session.currentX, 2, 'currentX updated with correct value on mousemove');
		strictEqual(session.currentY, 3, 'currentY updated with correct value on mousemove');
	});

	test('trackMouse', function() {
		session.currentX = 1;
		session.currentY = 1;

		trackMouse($.Event('mousemove', { pageX: 4, pageY: 5 }));

		strictEqual(session.currentX, 4, 'currentX updated with correct value on mousemove');
		strictEqual(session.currentY, 5, 'currentY updated with correct value on mousemove');
	});

	test('isMouseOver', function() {
		var div = $('
')
			.css({
				position: 'absolute',
				top: '10px',
				left: '30px',
				width: '50px',
				height: '20px'
			})
			.appendTo('body');

		session.currentX = 30;
		session.currentY = 10;
		ok(isMouseOver(div), 'top/left hover detected');

		session.currentX = 55;
		session.currentY = 15;
		ok(isMouseOver(div), 'center hover detected');

		session.currentX = 80;
		session.currentY = 30;
		ok(isMouseOver(div), 'bottom/right hover detected');

		session.currentX = 9;
		session.currentY = 29;
		ok(!isMouseOver(div), 'no hover detected');

		session.currentX = 81;
		session.currentY = 31;
		ok(!isMouseOver(div), 'no hover detected');

		div.remove();
	});

	test('getTooltipContent', function() {
		var powertip = $('
').data(DATA_POWERTIP, 'powertip'),
			powertipFunc = $('
').data(DATA_POWERTIP, function() { return 'powertipFunc'; }),
			jqObject = $('
powertipjq
'),
			powertipjq = $('
').data(DATA_POWERTIPJQ, jqObject),
			powertipjqFunc = $('
').data(DATA_POWERTIPJQ, function() { return jqObject; }),
			powertiptarget = $('
').data(DATA_POWERTIPTARGET, 'tiptargettest'),
			targetDiv = $('
').attr('id', 'tiptargettest').text('tiptargettest');

		// add powertiptarget to body
		targetDiv.appendTo($('body'));

		strictEqual(getTooltipContent(powertip), 'powertip', 'data-powertip text parsed');
		strictEqual(getTooltipContent(powertipFunc), 'powertipFunc', 'data-powertip function parsed');
		strictEqual(getTooltipContent(powertipjq).find('b').text(), 'powertipjq', 'data-powertipjq object parsed');
		strictEqual(getTooltipContent(powertipjqFunc).find('b').text(), 'powertipjq', 'data-powertipjq function parsed');
		strictEqual(getTooltipContent(powertiptarget), 'tiptargettest', 'data-powertiptarget reference parsed');

		// remove target test div
		targetDiv.remove();
	});

	test('countFlags', function() {
		var zero = Collision.none,
			one = Collision.top,
			two = Collision.top | Collision.left,
			three = Collision.top | Collision.left | Collision.right,
			four = Collision.top | Collision.left | Collision.right | Collision.bottom;

		strictEqual(countFlags(zero), 0, 'Found zero flags.');
		strictEqual(countFlags(one), 1, 'Found one flag.');
		strictEqual(countFlags(two), 2, 'Found two flags.');
		strictEqual(countFlags(three), 3, 'Found three flags.');
		strictEqual(countFlags(four), 4, 'Found four flags.');
	});

	test('getViewportCollisions', function() {
		var windowWidth = $(window).width(),
			windowHeight = $(window).height(),
			none, right, bottom, bottomRight, top, left, topLeft;

		function doTests() {
			strictEqual(none, Collision.none, 'no collisions detected');
			strictEqual(countFlags(right), 1, 'exactly one collision detected for right test');
			strictEqual(right & Collision.right, Collision.right, 'right collision detected for right test');
			strictEqual(countFlags(bottom), 1, 'exactly one collision detected for bottom test');
			strictEqual(bottom & Collision.bottom, Collision.bottom, 'bottom collision detected for bottom test');
			strictEqual(countFlags(bottomRight), 2, 'exactly two collisions detected for bottom-right test');
			strictEqual(bottomRight & Collision.bottom, Collision.bottom, 'bottom collision detected for bottom-right test');
			strictEqual(bottomRight & Collision.right, Collision.right, 'right collision detected for bottom-right test');
			strictEqual(countFlags(top), 1, 'exactly one collision detected for top test');
			strictEqual(top & Collision.top, Collision.top, 'top collision detected for top test');
			strictEqual(countFlags(left), 1, 'exactly one collision detected for left test');
			strictEqual(left & Collision.left, Collision.left, 'left collision detected for left test');
			strictEqual(countFlags(topLeft), 2, 'exactly two collisions detected for top-left test');
			strictEqual(topLeft & Collision.top, Collision.top, 'top collision detected for top-left test');
			strictEqual(topLeft & Collision.left, Collision.left, 'left collision detected for top-left test');
		}

		// need to make sure initTracking() has been invoked to populate the
		// viewport dimensions cache
		initTracking();

		// top/left placement
		none = getViewportCollisions({ top: 0, left: 0 }, 200, 100);
		right = getViewportCollisions({ top: 0, left: windowWidth - 199 }, 200, 100);
		bottom = getViewportCollisions({ top: windowHeight - 99, left: 0 }, 200, 100);
		bottomRight = getViewportCollisions({ top: windowHeight - 99, left: windowWidth - 199 }, 200, 100);
		top = getViewportCollisions({ top: -1, left: 0 }, 200, 100);
		left = getViewportCollisions({ top: 0, left: -1 }, 200, 100);
		topLeft = getViewportCollisions({ top: -1, left: -1 }, 200, 100);

		doTests();

		// bottom/right placement
		none = getViewportCollisions({ bottom: 0, right: 0 }, 200, 100);
		right = getViewportCollisions({ bottom: 0, right: -1 }, 200, 100);
		bottom = getViewportCollisions({ bottom: -1, right: 0 }, 200, 100);
		bottomRight = getViewportCollisions({ bottom: -1, right: -1 }, 200, 100);
		top = getViewportCollisions({ bottom: windowHeight - 99, right: 0 }, 200, 100);
		left = getViewportCollisions({ bottom: 0, right: windowWidth - 199 }, 200, 100);
		topLeft = getViewportCollisions({ bottom: windowHeight - 99, right: windowWidth - 199 }, 200, 100);

		doTests();
	});

});
<commit_msg>Reordered getViewportCollisions() tests.<commit_after>$(function() {
	'use strict';

	module('Utility Functions');

	test('isSvgElement', function() {
		var div = $('
'),
			rect = $(document.createElementNS('http://www.w3.org/2000/svg', 'rect'));

		strictEqual(isSvgElement(rect), true, 'rect is an SVG element');
		strictEqual(isSvgElement(div), false, 'div is not an SVG element');
	});

	test('initTracking', function() {
		session.currentX = 1;
		session.currentY = 1;

		initTracking();

		$(document).trigger($.Event('mousemove', { pageX: 2, pageY: 3 }));

		strictEqual(session.currentX, 2, 'currentX updated with correct value on mousemove');
		strictEqual(session.currentY, 3, 'currentY updated with correct value on mousemove');
	});

	test('trackMouse', function() {
		session.currentX = 1;
		session.currentY = 1;

		trackMouse($.Event('mousemove', { pageX: 4, pageY: 5 }));

		strictEqual(session.currentX, 4, 'currentX updated with correct value on mousemove');
		strictEqual(session.currentY, 5, 'currentY updated with correct value on mousemove');
	});

	test('isMouseOver', function() {
		var div = $('
')
			.css({
				position: 'absolute',
				top: '10px',
				left: '30px',
				width: '50px',
				height: '20px'
			})
			.appendTo('body');

		session.currentX = 30;
		session.currentY = 10;
		ok(isMouseOver(div), 'top/left hover detected');

		session.currentX = 55;
		session.currentY = 15;
		ok(isMouseOver(div), 'center hover detected');

		session.currentX = 80;
		session.currentY = 30;
		ok(isMouseOver(div), 'bottom/right hover detected');

		session.currentX = 9;
		session.currentY = 29;
		ok(!isMouseOver(div), 'no hover detected');

		session.currentX = 81;
		session.currentY = 31;
		ok(!isMouseOver(div), 'no hover detected');

		div.remove();
	});

	test('getTooltipContent', function() {
		var powertip = $('
').data(DATA_POWERTIP, 'powertip'),
			powertipFunc = $('
').data(DATA_POWERTIP, function() { return 'powertipFunc'; }),
			jqObject = $('
powertipjq
'),
			powertipjq = $('
').data(DATA_POWERTIPJQ, jqObject),
			powertipjqFunc = $('
').data(DATA_POWERTIPJQ, function() { return jqObject; }),
			powertiptarget = $('
').data(DATA_POWERTIPTARGET, 'tiptargettest'),
			targetDiv = $('
').attr('id', 'tiptargettest').text('tiptargettest');

		// add powertiptarget to body
		targetDiv.appendTo($('body'));

		strictEqual(getTooltipContent(powertip), 'powertip', 'data-powertip text parsed');
		strictEqual(getTooltipContent(powertipFunc), 'powertipFunc', 'data-powertip function parsed');
		strictEqual(getTooltipContent(powertipjq).find('b').text(), 'powertipjq', 'data-powertipjq object parsed');
		strictEqual(getTooltipContent(powertipjqFunc).find('b').text(), 'powertipjq', 'data-powertipjq function parsed');
		strictEqual(getTooltipContent(powertiptarget), 'tiptargettest', 'data-powertiptarget reference parsed');

		// remove target test div
		targetDiv.remove();
	});

	test('countFlags', function() {
		var zero = Collision.none,
			one = Collision.top,
			two = Collision.top | Collision.left,
			three = Collision.top | Collision.left | Collision.right,
			four = Collision.top | Collision.left | Collision.right | Collision.bottom;

		strictEqual(countFlags(zero), 0, 'Found zero flags.');
		strictEqual(countFlags(one), 1, 'Found one flag.');
		strictEqual(countFlags(two), 2, 'Found two flags.');
		strictEqual(countFlags(three), 3, 'Found three flags.');
		strictEqual(countFlags(four), 4, 'Found four flags.');
	});

	test('getViewportCollisions', function() {
		var windowWidth = $(window).width(),
			windowHeight = $(window).height(),
			none, right, bottom, bottomRight, top, left, topLeft;

		function doTests() {
			strictEqual(none, Collision.none, 'no collisions detected');
			strictEqual(right & Collision.right, Collision.right, 'right collision detected for right test');
			strictEqual(countFlags(right), 1, 'exactly one collision detected for right test');
			strictEqual(bottom & Collision.bottom, Collision.bottom, 'bottom collision detected for bottom test');
			strictEqual(countFlags(bottom), 1, 'exactly one collision detected for bottom test');
			strictEqual(bottomRight & Collision.bottom, Collision.bottom, 'bottom collision detected for bottom-right test');
			strictEqual(bottomRight & Collision.right, Collision.right, 'right collision detected for bottom-right test');
			strictEqual(countFlags(bottomRight), 2, 'exactly two collisions detected for bottom-right test');
			strictEqual(top & Collision.top, Collision.top, 'top collision detected for top test');
			strictEqual(countFlags(top), 1, 'exactly one collision detected for top test');
			strictEqual(left & Collision.left, Collision.left, 'left collision detected for left test');
			strictEqual(countFlags(left), 1, 'exactly one collision detected for left test');
			strictEqual(topLeft & Collision.top, Collision.top, 'top collision detected for top-left test');
			strictEqual(topLeft & Collision.left, Collision.left, 'left collision detected for top-left test');
			strictEqual(countFlags(topLeft), 2, 'exactly two collisions detected for top-left test');
		}

		// need to make sure initTracking() has been invoked to populate the
		// viewport dimensions cache
		initTracking();

		// top/left placement
		none = getViewportCollisions({ top: 0, left: 0 }, 200, 100);
		right = getViewportCollisions({ top: 0, left: windowWidth - 199 }, 200, 100);
		bottom = getViewportCollisions({ top: windowHeight - 99, left: 0 }, 200, 100);
		bottomRight = getViewportCollisions({ top: windowHeight - 99, left: windowWidth - 199 }, 200, 100);
		top = getViewportCollisions({ top: -1, left: 0 }, 200, 100);
		left = getViewportCollisions({ top: 0, left: -1 }, 200, 100);
		topLeft = getViewportCollisions({ top: -1, left: -1 }, 200, 100);

		doTests();

		// bottom/right placement
		none = getViewportCollisions({ bottom: 0, right: 0 }, 200, 100);
		right = getViewportCollisions({ bottom: 0, right: -1 }, 200, 100);
		bottom = getViewportCollisions({ bottom: -1, right: 0 }, 200, 100);
		bottomRight = getViewportCollisions({ bottom: -1, right: -1 }, 200, 100);
		top = getViewportCollisions({ bottom: windowHeight - 99, right: 0 }, 200, 100);
		left = getViewportCollisions({ bottom: 0, right: windowWidth - 199 }, 200, 100);
		topLeft = getViewportCollisions({ bottom: windowHeight - 99, right: windowWidth - 199 }, 200, 100);

		doTests();
	});

});
<|endoftext|>


<commit_before>var ksensejs = {
    initialize : function() {
        // Create a plugin object and append to the <body> element
        var plugin_object = document.createElement('object');
        plugin_object.setAttribute('id', 'plugin0');
        plugin_object.setAttribute('type', 'application/x-ksensejs');
        document.body.appendChild(plugin_object);

        document.getElementById('plugin0').addEventListener("newskeletondata", ksensejs.handle_new_data, false);
    },

    skeleton_data : null,
    velocity_data : null,
    callback : null,

    plugin : function() {
        return document.getElementById('plugin0');
    },

    handle_new_data : function() {
        ksensejs.skeleton_data = ksensejs.plugin().getSkeletonData();
        ksensejs.velocity_data = ksensejs.plugin().getVelocityData();

        if( !(ksensejs.callback === null) ) {
            ksensejs.callback();
        }
    },

    is_tracking : function() {
        if( Object.keys(ksensejs.skeleton_data).length > 0 ) {
            return true;
        }
        return false;
    },

    get_tracking_ids : function() {
        if( ksensejs.skeleton_data === null ) {
            return [];
        } else {
            return Object.keys(ksensejs.skeleton_data);
        }
    },

    get_skeleton_data : function(id) {
        if( typeof ksensejs.skeleton_data[id] === "undefined" ) {
            throw "Invalid tracking ID.";
        } else {
            return ksensejs.skeleton_data[id];
        }
    },

    get_velocity_data : function(id) {
        if( typeof ksensejs.velocity_data[id] === "undefined" ) {
            throw "Invalid tracking ID.";
        } else {
            return ksensejs.velocity_data[id];
        }
    },

    get_joint_location : function(id, name) {
        if( typeof ksensejs.skeleton_data[id] === "undefined" ) {
            throw "Invalid tracking ID.";
        } else {
            return ksensejs.skeleton_data[id][name];
        }
    },

    get_joint_velocity : function(id, name) {
        if( typeof ksensejs.velocity_data[id] === "undefined" ) {
            throw "Invalid tracking ID.";
        } else {
            return ksensejs.velocity_data[id][name][0];
        }
    },

    get_joint_velocity_vector : function(id, name) {
        if( typeof ksensejs.velocity_data[id] === "undefined" ) {
            throw "Invalid tracking ID.";
        } else {
            return ksensejs.velocity_data[id][name].slice(1,4);
        }
    },

    set_new_data_callback : function(callback) {
        if( typeof callback === "function" ) {
            ksensejs.callback = callback;
        }
    },

    unset_new_data_callback : function() {
        ksensejs.callback = null;
    },

    scale_data : function(init_coord, scale_coord) {
        var x = init_coord[0];
        var y = init_coord[1];
        var z = init_coord[2];

        x += 2.2;
        if ( x < 0 ) {
            x = 0;
        }
        x = (x/4.4) * scale_coord[0];

        y += 1.6;
        if ( y < 0 ) {
            y = 0;
        }
        y = (y/3.2) * scale_coord[1];

        if ( z < 0 ) {
            z = 0;
        }
        z = (z/4.0) * scale_coord[2];
        return [x,y,z];
    }
};
<commit_msg>Only initialize kinect if it has not been done before<commit_after>var ksensejs = {
    skeleton_data : null,
    velocity_data : null,
    callback : null,
    initialized: false,

    initialize : function() {
        if(!ksensejs.initialized) {
            // Create a plugin object and append to the <body> element
            var plugin_object = document.createElement('object');
            plugin_object.setAttribute('id', 'plugin0');
            plugin_object.setAttribute('type', 'application/x-ksensejs');
            document.body.appendChild(plugin_object);

            document.getElementById('plugin0').addEventListener("newskeletondata", ksensejs.handle_new_data, false);
            ksensejs.initialized = true;
        }
    },

    plugin : function() {
        return document.getElementById('plugin0');
    },

    handle_new_data : function() {
        ksensejs.skeleton_data = ksensejs.plugin().getSkeletonData();
        ksensejs.velocity_data = ksensejs.plugin().getVelocityData();

        if( !(ksensejs.callback === null) ) {
            ksensejs.callback();
        }
    },

    is_tracking : function() {
        if( Object.keys(ksensejs.skeleton_data).length > 0 ) {
            return true;
        }
        return false;
    },

    get_tracking_ids : function() {
        if( ksensejs.skeleton_data === null ) {
            return [];
        } else {
            return Object.keys(ksensejs.skeleton_data);
        }
    },

    get_skeleton_data : function(id) {
        if( typeof ksensejs.skeleton_data[id] === "undefined" ) {
            throw "Invalid tracking ID.";
        } else {
            return ksensejs.skeleton_data[id];
        }
    },

    get_velocity_data : function(id) {
        if( typeof ksensejs.velocity_data[id] === "undefined" ) {
            throw "Invalid tracking ID.";
        } else {
            return ksensejs.velocity_data[id];
        }
    },

    get_joint_location : function(id, name) {
        if( typeof ksensejs.skeleton_data[id] === "undefined" ) {
            throw "Invalid tracking ID.";
        } else {
            return ksensejs.skeleton_data[id][name];
        }
    },

    get_joint_velocity : function(id, name) {
        if( typeof ksensejs.velocity_data[id] === "undefined" ) {
            throw "Invalid tracking ID.";
        } else {
            return ksensejs.velocity_data[id][name][0];
        }
    },

    get_joint_velocity_vector : function(id, name) {
        if( typeof ksensejs.velocity_data[id] === "undefined" ) {
            throw "Invalid tracking ID.";
        } else {
            return ksensejs.velocity_data[id][name].slice(1,4);
        }
    },

    set_new_data_callback : function(callback) {
        if( typeof callback === "function" ) {
            ksensejs.callback = callback;
        }
    },

    unset_new_data_callback : function() {
        ksensejs.callback = null;
    },

    scale_data : function(init_coord, scale_coord) {
        var x = init_coord[0];
        var y = init_coord[1];
        var z = init_coord[2];

        x += 2.2;
        if ( x < 0 ) {
            x = 0;
        }
        x = (x/4.4) * scale_coord[0];

        y += 1.6;
        if ( y < 0 ) {
            y = 0;
        }
        y = (y/3.2) * scale_coord[1];

        if ( z < 0 ) {
            z = 0;
        }
        z = (z/4.0) * scale_coord[2];
        return [x,y,z];
    }
};
<|endoftext|>


<commit_before>/**
 * __init.test.js is run before every test case.
 */
window.debug = true;

var AScene = require('aframe').AScene;

require('../').registerAll();

setup(function () {
  this.sinon = sinon.sandbox.create();
  // Stubs to not create a WebGL context since Travis CI runs headless.
  this.sinon.stub(AScene.prototype, 'render');
  this.sinon.stub(AScene.prototype, 'resize');
  this.sinon.stub(AScene.prototype, 'setupRenderer');
});

teardown(function () {
  // Clean up any attached elements.
  ['canvas', 'a-assets', 'a-scene'].forEach(function (tagName) {
    var els = document.querySelectorAll(tagName);
    for (var i = 0; i < els.length; i++) {
      els[i].parentNode.removeChild(els[i]);
    }
  });
  this.sinon.restore();
});
<commit_msg>Fix tests failing against v0.2.0<commit_after>/**
 * __init.test.js is run before every test case.
 */
window.debug = true;

var AScene = require('aframe').AScene;
var extras = require('../');

extras.controls.registerAll();
extras.math.registerAll();

setup(function () {
  this.sinon = sinon.sandbox.create();
  // Stubs to not create a WebGL context since Travis CI runs headless.
  this.sinon.stub(AScene.prototype, 'render');
  this.sinon.stub(AScene.prototype, 'resize');
  this.sinon.stub(AScene.prototype, 'setupRenderer');
});

teardown(function () {
  // Clean up any attached elements.
  ['canvas', 'a-assets', 'a-scene'].forEach(function (tagName) {
    var els = document.querySelectorAll(tagName);
    for (var i = 0; i < els.length; i++) {
      els[i].parentNode.removeChild(els[i]);
    }
  });
  this.sinon.restore();
});
<|endoftext|>


<commit_before>// module:
//		delite/tests/boilerplate
// description:
//		A <script src="boilerplate.js"> on your test page will
//		load the loader (i.e. define the require() method)
//
//		In addition, by URL flags you can specify:
//			- locale=... to set the locale
//			- dir=rtl to turn on the has("bidi") flag and set the page to RTL mode
//
//		You should NOT be using this in a production environment.  Rather, load
//		the AMD loader directly, for example:
//
//		<script src="requirejs/require.js">

// Parse the URL, get parameters
var dir = "",
	testMode = null,
	locale;
if (window.location.href.indexOf("?") > -1) {
	var str = window.location.href.substr(window.location.href.indexOf("?") + 1).split(/#/);
	var ary = str[0].split(/&/);
	for (var i = 0; i < ary.length; i++) {
		var split = ary[i].split("="),
			key = split[0],
			value = (split[1] || "").replace(/[^\w]/g, "");	// replace() to prevent XSS attack
		switch (key) {
			case "locale":
				// locale string | null
				locale = value;
				break;
			case "dir":
				// rtl | null
				dir = value;
				break;
		}
	}
}

// Find the <script src="boilerplate.js"> tag, to get test directory and data-config argument
var scripts = document.getElementsByTagName("script"), script, overrides = {}, testDir;
for (i = 0; (script = scripts[i]); i++) {
	var src = script.getAttribute("src"),
		match = src && src.match(/(.*|^)boilerplate\.js/i);
	if (match) {
		// Sniff location of delite/tests directory relative to this test file.  testDir will be an empty string if
		// it's the same directory, or a string including a slash, ex: "../", if the test is in a subdirectory.
		testDir = match[1];

		// Sniff configuration on attribute in script element.
		// Allows syntax like <script src="boilerplate.js data-dojo-config="parseOnLoad: true">, where the settings
		// specified override the default settings.
		var attr = script.getAttribute("data-config");
		if (attr) {
			/* jshint evil:true */
			overrides = eval("({ " + attr + " })");
		}
		break;
	}
}

// Setup configuration options for the loader
/* global require:true */
require = {
	baseUrl: testDir + "../../",
	// TODO: when all tests converted from DOH to intern, remove this packages map
	packages: [
		{name: "dcl", location: "dcl"},
		{name: "dojo", location: "dojo"},
		{name: "delite", location: "delite"},
		{name: "deliteful", location: "deliteful"},
		{name: "dojox", location: "dojox"},
		{name: "doh", location: "util/doh"}
	],
	locale: locale || "en-us",
	config: {
		"dojo/has": {
			"bidi": dir === "rtl"
		}
	}
};
for (var key in overrides) {
	require[key] = overrides[key];
}

// Output the boilerplate text to load the loader.
document.write("<script type='text/javascript' src='" + testDir + "../../requirejs/require.js'></script>");

// On IE9 the following inlined script will run before dojo has finished loading, leading to an error because require()
// isn't defined yet.  Workaround it by putting the code in a separate file.
//document.write('<script type="text/javascript">require(["dojo/domReady!"], boilerplateOnLoad);</script>');
document.write("<script type='text/javascript' src='" + testDir + "boilerplateOnload.js'></script>");

/* global boilerplateOnLoad:true */
boilerplateOnLoad = function () {
	// This function is the first registered domReady() callback.

	// BIDI
	if(dir === "rtl") {
		// set dir=rtl on <html> node
		document.body.parentNode.setAttribute("dir", "rtl");

		// pretend all the labels are in an RTL language, because
		// that affects how they lay out relative to inline form widgets
		var labels = document.body.querySelectorAll("label");
		for(var i = 0; i < labels.length; i++){
			labels[i].setAttribute("dir", "rtl");
		}
	}
};
<commit_msg>woops, cleanup jshint errors from 9baec9b200fcc9726d058f3fe1dacfd3209f41e8<commit_after>// module:
//		delite/tests/boilerplate
// description:
//		A <script src="boilerplate.js"> on your test page will
//		load the loader (i.e. define the require() method)
//
//		In addition, by URL flags you can specify:
//			- locale=... to set the locale
//			- dir=rtl to turn on the has("bidi") flag and set the page to RTL mode
//
//		You should NOT be using this in a production environment.  Rather, load
//		the AMD loader directly, for example:
//
//		<script src="requirejs/require.js">

// Parse the URL, get parameters
var dir = "",
	locale;
if (window.location.href.indexOf("?") > -1) {
	var str = window.location.href.substr(window.location.href.indexOf("?") + 1).split(/#/);
	var ary = str[0].split(/&/);
	for (var i = 0; i < ary.length; i++) {
		var split = ary[i].split("="),
			key = split[0],
			value = (split[1] || "").replace(/[^\w]/g, "");	// replace() to prevent XSS attack
		switch (key) {
		case "locale":
			// locale string | null
			locale = value;
			break;
		case "dir":
			// rtl | null
			dir = value;
			break;
		}
	}
}

// Find the <script src="boilerplate.js"> tag, to get test directory and data-config argument
var scripts = document.getElementsByTagName("script"), script, overrides = {}, testDir;
for (i = 0; (script = scripts[i]); i++) {
	var src = script.getAttribute("src"),
		match = src && src.match(/(.*|^)boilerplate\.js/i);
	if (match) {
		// Sniff location of delite/tests directory relative to this test file.  testDir will be an empty string if
		// it's the same directory, or a string including a slash, ex: "../", if the test is in a subdirectory.
		testDir = match[1];

		// Sniff configuration on attribute in script element.
		// Allows syntax like <script src="boilerplate.js data-dojo-config="parseOnLoad: true">, where the settings
		// specified override the default settings.
		var attr = script.getAttribute("data-config");
		if (attr) {
			/* jshint evil:true */
			overrides = eval("({ " + attr + " })");
		}
		break;
	}
}

// Setup configuration options for the loader
/* global require:true */
require = {
	baseUrl: testDir + "../../",
	// TODO: when all tests converted from DOH to intern, remove this packages map
	packages: [
		{name: "dcl", location: "dcl"},
		{name: "dojo", location: "dojo"},
		{name: "delite", location: "delite"},
		{name: "deliteful", location: "deliteful"},
		{name: "dojox", location: "dojox"},
		{name: "doh", location: "util/doh"}
	],
	locale: locale || "en-us",
	config: {
		"dojo/has": {
			"bidi": dir === "rtl"
		}
	}
};
for (var key in overrides) {
	require[key] = overrides[key];
}

// Output the boilerplate text to load the loader.
document.write("<script type='text/javascript' src='" + testDir + "../../requirejs/require.js'></script>");

// On IE9 the following inlined script will run before dojo has finished loading, leading to an error because require()
// isn't defined yet.  Workaround it by putting the code in a separate file.
//document.write('<script type="text/javascript">require(["dojo/domReady!"], boilerplateOnLoad);</script>');
document.write("<script type='text/javascript' src='" + testDir + "boilerplateOnload.js'></script>");

/* global boilerplateOnLoad:true */
boilerplateOnLoad = function () {
	// This function is the first registered domReady() callback.

	// BIDI
	if (dir === "rtl") {
		// set dir=rtl on <html> node
		document.body.parentNode.setAttribute("dir", "rtl");

		// pretend all the labels are in an RTL language, because
		// that affects how they lay out relative to inline form widgets
		var labels = document.body.querySelectorAll("label");
		for (var i = 0; i < labels.length; i++) {
			labels[i].setAttribute("dir", "rtl");
		}
	}
};
<|endoftext|>


<commit_before>// Load the engineine and describe tests.
define(['engine/engine'], function(engine){

    if (!Function.prototype.bind) {
        Function.prototype.bind = function () {
            var fn = this,
                args = Array.prototype.slice.call(arguments),
                context = args.shift();
            return function () {
                fn.apply(context, args);
            };
        };
    }

    console.log(engine);
    describe('Engine API tests', function () {
        var game = {};
        before(function () {

            /* if (window.__html__) {
                document.body.innerHTML = window.__html__['index.html'];
            }*/

            game.worldView = new engine.worldView('guiLayer', {zIndex:1});
        });

        describe('Geo.Point test', function () {
            before(function () {
               this.x = -50;
               this.y = 50;
               this.radius = 2;
               this.colour = engine.Colour.red;
            });

            it('should throw an error if a non-numeric value is used for x or y', function () {
                (function(){
                  new engine.Geo.Point(game.worldView, this.x, 'a', this.radius, engine.Colour.red)
                }).should.throw(Error('x, y of Point must be integers'));

                (function(){
                  new engine.Geo.Point(game.worldView, 'b', this.y, this.radius, engine.Colour.red)
                }).should.throw(Error('x, y of Point must be integers'));
            });

            it('should throw an error if a non-numeric value is used for radius', function () {
                (function(){
                    new engine.Geo.Point(game.worldView, this.x, this.y, 'nt', engine.Colour.red);
                }).should.throw(Error('radius of Point must be an integer'));
            });

            it('should throw an error if a negative value is used for radius', function () {
                (function(){
                    new engine.Geo.Point(game.worldView, this.x, this.y, -2, engine.Colour.red);
                }).should.throw(Error('radius of Point must be greater than 0'));
            });

            it('should throw an error if a non-engine.WorldView value is used for viewPort', function () {
                (function(){
                    new engine.Geo.Point(null, this.x, this.y, this.radius, engine.Colour.red);
                }).should.throw(Error('viewPort of Point must be a engine.WorldView type object'));
            });

            it('should be able to make a canvasPath without any problems', function () {
                var point = new engine.Geo.Point(game.worldView, this.x, this.y, this.radius, engine.Colour.red);

                var expectedPath = new Path2D();
                expectedPath.arc(this.x, this.y, this.radius, 0, 2*Math.PI);

                var actualPath = point.makeCanvasPath();

                console.log(actualPath);
                console.log(expectedPath);
                (actualPath).should.be.eql(expectedPath);
            });
        });
    });

});<commit_msg>added test scaffolding<commit_after>// Load the engineine and describe tests.
define(['engine/engine'], function(engine){

    if (!Function.prototype.bind) {
        Function.prototype.bind = function () {
            var fn = this,
                args = Array.prototype.slice.call(arguments),
                context = args.shift();
            return function () {
                fn.apply(context, args);
            };
        };
    }

    describe('Engine API', function () {

        var game = {};
        before(function () {

            /* if (window.__html__) {
                document.body.innerHTML = window.__html__['index.html'];
            }*/

            game.worldView = new engine.worldView('guiLayer', {zIndex:1});
        });

        describe('Geo tests', function () {
            describe('Geo.Point test', function () {
                before(function () {
                   this.x = -50;
                   this.y = 50;
                   this.radius = 2;
                   this.colour = engine.Colour.red;
                });

                it('should throw an error if a non-numeric value is used for x or y', function () {
                    (function(){
                      new engine.Geo.Point(game.worldView, this.x, 'a', this.radius, engine.Colour.red)
                    }).should.throw(Error('x, y of Point must be integers'));

                    (function(){
                      new engine.Geo.Point(game.worldView, 'b', this.y, this.radius, engine.Colour.red)
                    }).should.throw(Error('x, y of Point must be integers'));
                });

                it('should throw an error if a non-numeric value is used for radius', function () {
                    (function(){
                        new engine.Geo.Point(game.worldView, this.x, this.y, 'nt', engine.Colour.red);
                    }).should.throw(Error('radius of Point must be an integer'));
                });

                it('should throw an error if a negative value is used for radius', function () {
                    (function(){
                        new engine.Geo.Point(game.worldView, this.x, this.y, -2, engine.Colour.red);
                    }).should.throw(Error('radius of Point must be greater than 0'));
                });

                it('should throw an error if a non-engine.WorldView value is used for viewPort', function () {
                    (function(){
                        new engine.Geo.Point(null, this.x, this.y, this.radius, engine.Colour.red);
                    }).should.throw(Error('viewPort of Point must be a engine.WorldView type object'));
                });

                it('should be able to make a canvasPath without any problems', function () {
                    var point = new engine.Geo.Point(game.worldView, this.x, this.y, this.radius, engine.Colour.red);

                    var expectedPath = new Path2D();
                    expectedPath.arc(this.x, this.y, this.radius, 0, 2*Math.PI);

                    var actualPath = point.makeCanvasPath();

                    (actualPath).should.be.eql(expectedPath);
                });
            });

            describe('Geo.PathPoint test', function () {
                before(function () {
                   this.x = -50;
                   this.y = 50;
                   this.radius = 2;
                   this.colour = engine.Colour.red;
                });
            });

            describe('Geo.Path test', function () {
                before(function () {
                   this.x = -50;
                   this.y = 50;
                   this.radius = 2;
                   this.colour = engine.Colour.red;
                });
            });

            describe('Geo.PathPoint test', function () {
                before(function () {
                   this.x = -50;
                   this.y = 50;
                   this.radius = 2;
                   this.colour = engine.Colour.red;
                });
            });

            describe('Geo.Vector test', function () {
                before(function () {
                   this.x = -50;
                   this.y = 50;
                   this.radius = 2;
                   this.colour = engine.Colour.red;
                });
            });

            describe('Geo.Line test', function () {
                before(function () {
                   this.x = -50;
                   this.y = 50;
                   this.radius = 2;
                   this.colour = engine.Colour.red;
                });
            });

            describe('Geo.PathLine test', function () {
                before(function () {
                   this.x = -50;
                   this.y = 50;
                   this.radius = 2;
                   this.colour = engine.Colour.red;
                });
            });

            describe('Geo.Combatant test', function () {
                before(function () {
                   this.x = -50;
                   this.y = 50;
                   this.radius = 2;
                   this.colour = engine.Colour.red;
                });
            });

            describe('Geo.Rect test', function () {
                before(function () {
                   this.x = -50;
                   this.y = 50;
                   this.radius = 2;
                   this.colour = engine.Colour.red;
                });
            });

            describe('Geo.Path test', function () {
                before(function () {
                   this.x = -50;
                   this.y = 50;
                   this.radius = 2;
                   this.colour = engine.Colour.red;
                });
            });
        });
    });

});<|endoftext|>


<commit_before>var assert = require('assert');
var regexpTpl = require('../src/index');

describe('regexpTpl', function () {

  it('should be a function', function() {
    assert(regexpTpl instanceof Function);
  });

  it('should fail with a bad objs value', function() {
    assert.throws(function() {
      regexpTpl({}, 'rr');
    });
  });

  it('should fail with a bad regexpTpl value', function() {
    assert.throws(function() {
      regexpTpl([], {});
    });
  });

  it('should return undefined with an unmatched template', function() {
    var tree = [];

    assert.equal(
      typeof regexpTpl(tree, 'a {foo.bar} b'),
      'undefined'
    );
  });

  it('should work with simple property addressing', function() {
    var tree = [{
      foo: {
        bar: 'test'
      },
      bar: {
        bar: 'test2'
      }
    }];

    assert.equal(
      regexpTpl(tree, 'a {foo.bar} b').toString(),
      '/a test b/'
    );
  });

  it('should work with flags', function() {
    var tree = [{
      foo: {
        bar: 'test'
      },
      bar: {
        bar: 'test2'
      }
    }];

    assert.equal(
      regexpTpl(tree, 'a {foo.bar} b', 'img').toString(),
      '/a test b/gim'
    );
  });

  it('should work with any property addressing', function() {
    var tree = [{
      foo: {
        bar: 'test'
      },
      bar: {
        bar: 'test2'
      }
    }];

    assert.equal(
      regexpTpl(tree, '/:@.bar', '', /(.*\/|^):([a-z0-9_\-\.\*\@\#]+)(\/.*|$)/i).toString(),
      '//(test|test2)/'
    );
  });

  it('should work with a custom template regexp', function() {
    var tree = [{
      foo: {
        bar: 'test'
      },
      bar: {
        bar: 'test2'
      }
    }];

    assert.equal(
      regexpTpl(tree, 'a {@.bar} b').toString(),
      '/a (test|test2) b/'
    );
  });

  it('should work with README samples', function() {
    var fruits = [{
      name: 'orange',
      count: 2,
      colors: ['orange']
    }, {
      name: 'banana',
      count: 0,
      colors: ['yellow', 'white']
    }, {
      name: 'kiwi',
      count: 8,
      colors: ['brown', 'green']
    }];

    assert(regexpTpl(fruits, 'My car is {colors.#}!').test('My car is brown!'));
    assert(!regexpTpl(fruits, 'My car is {colors.#}!').test('My car is blue!'));
  });

});
<commit_msg>Fixing tests<commit_after>var assert = require('assert');
var regexpTpl = require('../src/index');

describe('regexpTpl', function () {

  it('should be a function', function() {
    assert(regexpTpl instanceof Function);
  });

  it('should fail with a bad objs value', function() {
    assert.throws(function() {
      regexpTpl({}, 'rr');
    });
  });

  it('should fail with a bad regexpTpl value', function() {
    assert.throws(function() {
      regexpTpl([], {});
    });
  });

  it('should return undefined with an unmatched template', function() {
    var tree = [];

    assert.equal(
      typeof regexpTpl(tree, 'a {foo.bar} b'),
      'undefined'
    );
  });

  it('should work with simple property addressing', function() {
    var tree = [{
      foo: {
        bar: 'test'
      },
      bar: {
        bar: 'test2'
      }
    }];

    assert.equal(
      regexpTpl(tree, 'a {foo.bar} b').toString(),
      '/a test b/'
    );
  });

  it('should work with flags', function() {
    var tree = [{
      foo: {
        bar: 'test'
      },
      bar: {
        bar: 'test2'
      }
    }];

    assert.equal(
      regexpTpl(tree, 'a {foo.bar} b', 'img').toString(),
      '/a test b/gim'
    );
  });

  it('should work with any property addressing', function() {
    var tree = [{
      foo: {
        bar: 'test'
      },
      bar: {
        bar: 'test2'
      }
    }];

    assert.equal(
      regexpTpl(tree, '/:@.bar', '', /(.*\/|^):([a-z0-9_\-\.\*\@\#]+)(\/.*|$)/i).toString(),
      '/\\/(test|test2)/'
    );
  });

  it('should work with a custom template regexp', function() {
    var tree = [{
      foo: {
        bar: 'test'
      },
      bar: {
        bar: 'test2'
      }
    }];

    assert.equal(
      regexpTpl(tree, 'a {@.bar} b').toString(),
      '/a (test|test2) b/'
    );
  });

  it('should work with README samples', function() {
    var fruits = [{
      name: 'orange',
      count: 2,
      colors: ['orange']
    }, {
      name: 'banana',
      count: 0,
      colors: ['yellow', 'white']
    }, {
      name: 'kiwi',
      count: 8,
      colors: ['brown', 'green']
    }];

    assert(regexpTpl(fruits, 'My car is {colors.#}!').test('My car is brown!'));
    assert(!regexpTpl(fruits, 'My car is {colors.#}!').test('My car is blue!'));
  });

});
<|endoftext|>


<commit_before>/* eslint max-nested-callbacks:[1] */

'use strict';

var gulp = require('gulp');
var gutil = require('gulp-util');
var Stream = require('stream');
var fs = require('fs');
var path = require('path');

var assert = require('assert');
var StreamTest = require('streamtest');

var ttf2woff2 = require(path.join(__dirname, '..', 'src', 'index.js'));

describe('gulp-ttf2woff2 conversion', function() {
  var filename = path.join(__dirname, 'fixtures', 'iconsfont');
  var woff = fs.readFileSync(filename + '.woff2');

  // Iterating through versions
  StreamTest.versions.forEach(function(version) {

    describe('for ' + version + ' streams', function() {

      describe('with null contents', function() {

        it('should let null files pass through', function(done) {

            StreamTest[version].fromObjects([new gutil.File({
              path: 'bibabelula.foo',
              contents: null,
            })])
            .pipe(ttf2woff2())
            .pipe(StreamTest[version].toObjects(function(err, objs) {
              if(err) {
                return done(err);
              }
              assert.equal(objs.length, 1);
              assert.equal(objs[0].path, 'bibabelula.foo');
              assert.equal(objs[0].contents, null);
              done();
            }));

          });

      });

      describe('in buffer mode', function() {

        it('should work', function(done) {

          gulp.src(filename + '.ttf', { buffer: true })
            .pipe(ttf2woff2())
            // Uncomment to regenerate the test files if changes in the ttf2woff lib
            // .pipe(gulp.dest(__dirname + '/fixtures/'))
            .pipe(StreamTest[version].toObjects(function(err, objs) {
              if(err) {
                return done(err);
              }
              assert.equal(objs.length, 1);
              assert.equal(objs[0].path, filename + '.woff2');
              assert.equal(objs[0].contents.toString('utf-8'), woff.toString('utf-8'));
              done();
            }));

        });

        it('should work with the clone option', function(done) {

          gulp.src(filename + '.ttf', { buffer: true })
            .pipe(ttf2woff2({ clone: true }))
            .pipe(StreamTest[version].toObjects(function(err, objs) {
              if(err) {
                return done(err);
              }
              assert.equal(objs.length, 2);
              assert.equal(objs[0].path, filename + '.ttf');
              assert.equal(
                objs[0].contents.toString('utf-8'),
                fs.readFileSync(filename + '.ttf', 'utf-8')
              );
              assert.equal(objs[1].path, filename + '.woff2');
              assert.equal(
                objs[1].contents.toString('utf-8'),
                woff.toString('utf-8')
              );
              done();
            }));

        });

        it('should let non-ttf files pass through', function(done) {

          StreamTest[version].fromObjects([new gutil.File({
            path: 'bibabelula.foo',
            contents: new Buffer('ohyeah'),
          })])
          .pipe(ttf2woff2())
          .pipe(StreamTest[version].toObjects(function(err, objs) {
            if(err) {
              return done(err);
            }
            assert.equal(objs.length, 1);
            assert.equal(objs[0].path, 'bibabelula.foo');
            assert.equal(objs[0].contents.toString('utf-8'), 'ohyeah');
            done();
          }));

        });
      });

      describe('in stream mode', function() {
        it('should work', function(done) {

          gulp.src(filename + '.ttf', { buffer: false })
            .pipe(ttf2woff2())
            .pipe(StreamTest[version].toObjects(function(err, objs) {
              if(err) {
                return done(err);
              }
              assert.equal(objs.length, 1);
              assert.equal(objs[0].path, filename + '.woff2');
              objs[0].contents.pipe(StreamTest[version].toText(function(err, text) {
                if(err) {
                  return done(err);
                }
                assert.equal(text, woff.toString('utf-8'));
                done();
              }));
            }));

        });

        it('should work with the clone option', function(done) {

          gulp.src(filename + '.ttf', { buffer: false })
            .pipe(ttf2woff2({ clone: true }))
            .pipe(StreamTest[version].toObjects(function(err, objs) {
              if(err) {
                return done(err);
              }
              assert.equal(objs.length, 2);
              assert.equal(objs[0].path, filename + '.ttf');
              assert.equal(objs[1].path, filename + '.woff2');
              objs[0].contents.pipe(StreamTest[version].toText(function(err2, text) {
                if(err2) {
                  return done(err2);
                }
                assert.equal(text, fs.readFileSync(filename + '.ttf', 'utf-8'));
                objs[1].contents.pipe(StreamTest[version].toText(function(err3, text2) {
                  if(err3) {
                    return done(err3);
                  }
                  assert.equal(text2, woff.toString('utf-8'));
                  done();
                }));
              }));
            }));

        });

        it('should let non-ttf files pass through', function(done) {

          StreamTest[version].fromObjects([new gutil.File({
            path: 'bibabelula.foo',
            contents: new Stream.PassThrough(),
          })])
          .pipe(ttf2woff2())
          .pipe(StreamTest[version].toObjects(function(err, objs) {
            if(err) {
              return done(err);
            }
            assert.equal(objs.length, 1);
            assert.equal(objs[0].path, 'bibabelula.foo');
            assert(objs[0].contents instanceof Stream.PassThrough);
            done();
          }));

        });
      });

    });

  });

});
<commit_msg>Fixing linter issues<commit_after>/* eslint max-nested-callbacks:[1] */

'use strict';

var gulp = require('gulp');
var gutil = require('gulp-util');
var Stream = require('stream');
var fs = require('fs');
var path = require('path');

var assert = require('assert');
var StreamTest = require('streamtest');

var ttf2woff2 = require(path.join(__dirname, '..', 'src', 'index.js'));

describe('gulp-ttf2woff2 conversion', function() {
  var filename = path.join(__dirname, 'fixtures', 'iconsfont');
  var woff = fs.readFileSync(filename + '.woff2');

  // Iterating through versions
  StreamTest.versions.forEach(function(version) {

    describe('for ' + version + ' streams', function() {

      describe('with null contents', function() {

        it('should let null files pass through', function(done) {

          StreamTest[version].fromObjects([new gutil.File({
            path: 'bibabelula.foo',
            contents: null,
          })])
          .pipe(ttf2woff2())
          .pipe(StreamTest[version].toObjects(function(err, objs) {
            if(err) {
              return done(err);
            }
            assert.equal(objs.length, 1);
            assert.equal(objs[0].path, 'bibabelula.foo');
            assert.equal(objs[0].contents, null);
            done();
          }));

        });

      });

      describe('in buffer mode', function() {

        it('should work', function(done) {

          gulp.src(filename + '.ttf', { buffer: true })
            .pipe(ttf2woff2())
            // Uncomment to regenerate the test files if changes in the ttf2woff lib
            // .pipe(gulp.dest(__dirname + '/fixtures/'))
            .pipe(StreamTest[version].toObjects(function(err, objs) {
              if(err) {
                return done(err);
              }
              assert.equal(objs.length, 1);
              assert.equal(objs[0].path, filename + '.woff2');
              assert.equal(objs[0].contents.toString('utf-8'), woff.toString('utf-8'));
              done();
            }));

        });

        it('should work with the clone option', function(done) {

          gulp.src(filename + '.ttf', { buffer: true })
            .pipe(ttf2woff2({ clone: true }))
            .pipe(StreamTest[version].toObjects(function(err, objs) {
              if(err) {
                return done(err);
              }
              assert.equal(objs.length, 2);
              assert.equal(objs[0].path, filename + '.ttf');
              assert.equal(
                objs[0].contents.toString('utf-8'),
                fs.readFileSync(filename + '.ttf', 'utf-8')
              );
              assert.equal(objs[1].path, filename + '.woff2');
              assert.equal(
                objs[1].contents.toString('utf-8'),
                woff.toString('utf-8')
              );
              done();
            }));

        });

        it('should let non-ttf files pass through', function(done) {

          StreamTest[version].fromObjects([new gutil.File({
            path: 'bibabelula.foo',
            contents: new Buffer('ohyeah'),
          })])
          .pipe(ttf2woff2())
          .pipe(StreamTest[version].toObjects(function(err, objs) {
            if(err) {
              return done(err);
            }
            assert.equal(objs.length, 1);
            assert.equal(objs[0].path, 'bibabelula.foo');
            assert.equal(objs[0].contents.toString('utf-8'), 'ohyeah');
            done();
          }));

        });
      });

      describe('in stream mode', function() {
        it('should work', function(done) {

          gulp.src(filename + '.ttf', { buffer: false })
            .pipe(ttf2woff2())
            .pipe(StreamTest[version].toObjects(function(err, objs) {
              if(err) {
                return done(err);
              }
              assert.equal(objs.length, 1);
              assert.equal(objs[0].path, filename + '.woff2');
              objs[0].contents.pipe(StreamTest[version].toText(function(err, text) {
                if(err) {
                  return done(err);
                }
                assert.equal(text, woff.toString('utf-8'));
                done();
              }));
            }));

        });

        it('should work with the clone option', function(done) {

          gulp.src(filename + '.ttf', { buffer: false })
            .pipe(ttf2woff2({ clone: true }))
            .pipe(StreamTest[version].toObjects(function(err, objs) {
              if(err) {
                return done(err);
              }
              assert.equal(objs.length, 2);
              assert.equal(objs[0].path, filename + '.ttf');
              assert.equal(objs[1].path, filename + '.woff2');
              objs[0].contents.pipe(StreamTest[version].toText(function(err2, text) {
                if(err2) {
                  return done(err2);
                }
                assert.equal(text, fs.readFileSync(filename + '.ttf', 'utf-8'));
                objs[1].contents.pipe(StreamTest[version].toText(function(err3, text2) {
                  if(err3) {
                    return done(err3);
                  }
                  assert.equal(text2, woff.toString('utf-8'));
                  done();
                }));
              }));
            }));

        });

        it('should let non-ttf files pass through', function(done) {

          StreamTest[version].fromObjects([new gutil.File({
            path: 'bibabelula.foo',
            contents: new Stream.PassThrough(),
          })])
          .pipe(ttf2woff2())
          .pipe(StreamTest[version].toObjects(function(err, objs) {
            if(err) {
              return done(err);
            }
            assert.equal(objs.length, 1);
            assert.equal(objs[0].path, 'bibabelula.foo');
            assert(objs[0].contents instanceof Stream.PassThrough);
            done();
          }));

        });
      });

    });

  });

});
<|endoftext|>


<commit_before>'use strict';

describe('Server', function() {
  it('Should initialize without error', function() {
    var fork = require('child_process').fork;

    var server = fork('lib/server.js');
    server.kill('SIGKILL');
  });
});
<commit_msg>Updated test<commit_after>'use strict';

describe('Server', function() {
  it('Should initialize without error', function(done) {
    var fork = require('child_process').fork;

    var delegate = {
      handler: function() {
        server.kill('SIGKILL');
        done();
      }
    };

    var server = fork('lib/server.js');
    server.on('message', delegate.handler);
  });
});
<|endoftext|>


<commit_before>'use strict';

var path = require('path');
var assert = require('chai').assert;
var applicationStorage = process.requireAPI('lib/applicationStorage.js');

// i18n.js
describe('i18n', function() {
  var i18n;

  before(function() {
    applicationStorage.setPlugins(
      [
        {
          name: 'example',
          i18nDirectory: path.join(__dirname, 'i18n', 'example')
        },
        {
          name: 'example2',
          i18nDirectory: path.join(__dirname, 'i18n', 'example2')
        }
      ]
      );
    i18n = process.requireAPI('lib/i18n.js');
  });

  // getTranslations method
  describe('getTranslations', function() {

    it('should be able to get translation of a particular language', function(done) {
      i18n.getTranslations('french', 'fr', function(error, translations) {
        assert.isUndefined(error, 'Getting translations failed : ' + (error && error.message));
        assert.equal(translations.EXAMPLE.FRENCH, 'Français');
        done();
      });
    });

    it('should be able to get a translation of a particular language and country', function(done) {
      i18n.getTranslations('canadian', 'en-CA', function(error, translations) {
        assert.equal(translations.EXAMPLE.DOLLAR, 'Loonie');
        done();
      });
    });

    it('should not wrap translations if already wrapped', function(done) {
      i18n.getTranslations('wrapped', 'en', function(error, translations) {
        assert.equal(translations.EXAMPLE.WRAPPED, 'wrapped');
        done();
      });
    });

    it('should return null if no translation found', function(done) {
      i18n.getTranslations('no-translation', 'fr', function(error, translations) {
        assert.isNull(translations);
        done();
      });
    });

    it('should return null if dictionary is not specified', function(done) {
      i18n.getTranslations(null, 'fr', function(error, translations) {
        assert.isNull(translations);
        done();
      });
    });

    it('should return translations in english if no language is not specified', function(done) {
      i18n.getTranslations('english', null, function(error, translations) {
        assert.equal(translations.EXAMPLE.ENGLISH, 'English');
        done();
      });
    });

    it('should be able to get translations for all plugins (merged)', function(done) {
      i18n.getTranslations('common', 'en', function(error, translations) {
        assert.equal(translations.EXAMPLE.COMMON, 'Common');
        assert.equal(translations.EXAMPLE2.COMMON, 'Common');
        done();
      });
    });

  });

});
<commit_msg>Update mochaTest for async update<commit_after>'use strict';

var path = require('path');
var assert = require('chai').assert;
var applicationStorage = process.requireAPI('lib/applicationStorage.js');

// i18n.js
describe('i18n', function() {
  var i18n;

  before(function() {
    applicationStorage.setPlugins(
      [
        {
          name: 'example',
          i18nDirectory: path.join(__dirname, 'i18n', 'example')
        },
        {
          name: 'example2',
          i18nDirectory: path.join(__dirname, 'i18n', 'example2')
        }
      ]
      );
    i18n = process.requireAPI('lib/i18n.js');
  });

  // getTranslations method
  describe('getTranslations', function() {

    it('should be able to get translation of a particular language', function(done) {
      i18n.getTranslations('french', 'fr', function(error, translations) {
        assert.isNull(error, 'Getting translations failed : ' + (error && error.message));
        assert.equal(translations.EXAMPLE.FRENCH, 'Français');
        done();
      });
    });

    it('should be able to get a translation of a particular language and country', function(done) {
      i18n.getTranslations('canadian', 'en-CA', function(error, translations) {
        assert.equal(translations.EXAMPLE.DOLLAR, 'Loonie');
        done();
      });
    });

    it('should not wrap translations if already wrapped', function(done) {
      i18n.getTranslations('wrapped', 'en', function(error, translations) {
        assert.equal(translations.EXAMPLE.WRAPPED, 'wrapped');
        done();
      });
    });

    it('should return null if no translation found', function(done) {
      i18n.getTranslations('no-translation', 'fr', function(error, translations) {
        assert.isNull(translations);
        done();
      });
    });

    it('should return null if dictionary is not specified', function(done) {
      i18n.getTranslations(null, 'fr', function(error, translations) {
        assert.isNull(translations);
        done();
      });
    });

    it('should return translations in english if no language is not specified', function(done) {
      i18n.getTranslations('english', null, function(error, translations) {
        assert.equal(translations.EXAMPLE.ENGLISH, 'English');
        done();
      });
    });

    it('should be able to get translations for all plugins (merged)', function(done) {
      i18n.getTranslations('common', 'en', function(error, translations) {
        assert.equal(translations.EXAMPLE.COMMON, 'Common');
        assert.equal(translations.EXAMPLE2.COMMON, 'Common');
        done();
      });
    });

  });

});
<|endoftext|>


<commit_before>/**
 * @venus-library jasmine
 * @venus-include ../../vendor/Reflection.js/reflection.min.js
 * @venus-include ../../src/functions.js
 * @venus-include ../../src/FactoryInterface.js
 * @venus-include ../../src/RegistryInterface.js
 * @venus-include ../../src/Registry.js
 * @venus-include ../../src/RegistryFactory.js
 * @venus-include ../../src/QueueInterface.js
 * @venus-include ../../src/Queue.js
 * @venus-include ../../src/EntityInterface.js
 * @venus-include ../../src/Entity.js
 * @venus-include ../../src/Lib/Generator/Interface.js
 * @venus-include ../../src/Lib/Generator/UUID.js
 * @venus-include ../../src/Storage/EngineInterface.js
 * @venus-code ../../src/Storage/UnitOfWork.js
 */

describe('storage UnitOfWork', function () {

    var uow = new Sy.Storage.UnitOfWork();

    it('should throw if trying to set invalid queue object', function () {
        expect(function () {
            uow.setQueue({});
        }).toThrow('Invalid queue');
    });

    it('should set the queue', function () {
        var q = new Sy.Queue();
        q.setRegistryFactory(new Sy.RegistryFactory());

        expect(uow.setQueue(q)).toEqual(uow);
    });

    it('should throw if trying to set invalid engine', function () {
        expect(function () {
            uow.setEngine({});
        }).toThrow('Invalid engine');
    });

    it('should set the engine', function () {
        var e = new Sy.Storage.EngineInterface();

        expect(uow.setEngine(e)).toEqual(uow);
    });

    it('should throw if trying to set invalid generator', function () {
        expect(function () {
            uow.setGenerator({});
        }).toThrow('Invalid generator');
    });

    it('should set the generator', function () {
        var gen = new Sy.Lib.Generator.UUID();

        expect(uow.setGenerator(gen)).toEqual(uow);
    });

    it('should set the entity key', function () {
        expect(uow.setEntityKey('uuid')).toEqual(uow);
    });

    it('should schedule an entity for creation', function () {
        var e = new Sy.Entity();

        uow.handle(e);

        expect(uow.isScheduledForCreation(e)).toBe(true);
    });

    it('should schedule an entity for update', function () {
        var e = new Sy.Entity();

        e.set('uuid', 'foo');
        uow.handle(e);

        expect(uow.isScheduledForUpdate(e)).toBe(true);
    });

    it('should schedule an entity for removal', function () {
        var e = new Sy.Entity();

        e.set('uuid', 'removal-scheduled');
        uow.remove(e);

        expect(uow.isScheduledForRemoval(e)).toBe(true);
    });

    it('should cancel an entity creation schedule', function () {
        var e = new Sy.Entity();

        uow.handle(e);

        expect(uow.isScheduledForCreation(e)).toBe(true);

        uow.remove(e);

        expect(uow.isScheduledForCreation(e)).toBe(false);
        expect(uow.isScheduledForRemoval(e)).toBe(false);
    });

    it('should cancel an entity update schedule and schedule it for removal', function () {
        var e = new Sy.Entity();

        e.set('uuid', 'cancel-update');
        uow.handle(e);

        expect(uow.isScheduledForUpdate(e)).toBe(true);

        uow.remove(e);

        expect(uow.isScheduledForUpdate(e)).toBe(false);
        expect(uow.isScheduledForRemoval(e)).toBe(true);
    });

    it('should return the raw representation of the entity', function () {
        var e = new Sy.Entity();

        e.set('foo', 'bar');
        e.getFoo = function () {
            return 'bar';
        };

        expect(uow.getEntityData(e)).toEqual({
            foo: 'bar'
        });
    });

});
<commit_msg>added an ssertion to be sure a UUID is created when the entity is first handled by the unit of work<commit_after>/**
 * @venus-library jasmine
 * @venus-include ../../vendor/Reflection.js/reflection.min.js
 * @venus-include ../../src/functions.js
 * @venus-include ../../src/FactoryInterface.js
 * @venus-include ../../src/RegistryInterface.js
 * @venus-include ../../src/Registry.js
 * @venus-include ../../src/RegistryFactory.js
 * @venus-include ../../src/QueueInterface.js
 * @venus-include ../../src/Queue.js
 * @venus-include ../../src/EntityInterface.js
 * @venus-include ../../src/Entity.js
 * @venus-include ../../src/Lib/Generator/Interface.js
 * @venus-include ../../src/Lib/Generator/UUID.js
 * @venus-include ../../src/Storage/EngineInterface.js
 * @venus-code ../../src/Storage/UnitOfWork.js
 */

describe('storage UnitOfWork', function () {

    var uow = new Sy.Storage.UnitOfWork();

    it('should throw if trying to set invalid queue object', function () {
        expect(function () {
            uow.setQueue({});
        }).toThrow('Invalid queue');
    });

    it('should set the queue', function () {
        var q = new Sy.Queue();
        q.setRegistryFactory(new Sy.RegistryFactory());

        expect(uow.setQueue(q)).toEqual(uow);
    });

    it('should throw if trying to set invalid engine', function () {
        expect(function () {
            uow.setEngine({});
        }).toThrow('Invalid engine');
    });

    it('should set the engine', function () {
        var e = new Sy.Storage.EngineInterface();

        expect(uow.setEngine(e)).toEqual(uow);
    });

    it('should throw if trying to set invalid generator', function () {
        expect(function () {
            uow.setGenerator({});
        }).toThrow('Invalid generator');
    });

    it('should set the generator', function () {
        var gen = new Sy.Lib.Generator.UUID();

        expect(uow.setGenerator(gen)).toEqual(uow);
    });

    it('should set the entity key', function () {
        expect(uow.setEntityKey('uuid')).toEqual(uow);
    });

    it('should schedule an entity for creation', function () {
        var e = new Sy.Entity();

        uow.handle(e);

        expect(uow.isScheduledForCreation(e)).toBe(true);
        expect(!!e.get('uuid')).toBe(true);
    });

    it('should schedule an entity for update', function () {
        var e = new Sy.Entity();

        e.set('uuid', 'foo');
        uow.handle(e);

        expect(uow.isScheduledForUpdate(e)).toBe(true);
    });

    it('should schedule an entity for removal', function () {
        var e = new Sy.Entity();

        e.set('uuid', 'removal-scheduled');
        uow.remove(e);

        expect(uow.isScheduledForRemoval(e)).toBe(true);
    });

    it('should cancel an entity creation schedule', function () {
        var e = new Sy.Entity();

        uow.handle(e);

        expect(uow.isScheduledForCreation(e)).toBe(true);

        uow.remove(e);

        expect(uow.isScheduledForCreation(e)).toBe(false);
        expect(uow.isScheduledForRemoval(e)).toBe(false);
    });

    it('should cancel an entity update schedule and schedule it for removal', function () {
        var e = new Sy.Entity();

        e.set('uuid', 'cancel-update');
        uow.handle(e);

        expect(uow.isScheduledForUpdate(e)).toBe(true);

        uow.remove(e);

        expect(uow.isScheduledForUpdate(e)).toBe(false);
        expect(uow.isScheduledForRemoval(e)).toBe(true);
    });

    it('should return the raw representation of the entity', function () {
        var e = new Sy.Entity();

        e.set('foo', 'bar');
        e.getFoo = function () {
            return 'bar';
        };

        expect(uow.getEntityData(e)).toEqual({
            foo: 'bar'
        });
    });

});
<|endoftext|>


<commit_before>define(function (require) {
  var registerSuite = require('intern!object');
  var assert = require('intern/chai!assert');
  var expect = require('intern/chai!expect');
  require('fauxOS.js');
  const g = {};

  registerSuite({
    name: "Pathname",

    setUp: function() {
      g.path = new Pathname("/hello/././///../waddup//world.tar.gz");
    },

    "Basename": function() {
      assert.deepEqual(g.path.basename(), "world",
        "Extracts a file or directory's basename");
    },
    "Chop path segments": function() {
      assert.deepEqual(g.path.chop(), ["waddup", "world.tar.gz"],
        "Chops a path into segments");
    },
    "Clean / normalize": function() {
      assert.deepEqual(g.path.clean(), "/waddup/world.tar.gz",
        "Cleans up / normalizes a messy path");
    },
    "Extentions array": function() {
      assert.deepEqual(g.path.extentions(), [".tar", ".gz"],
        "Can return an array of the file's extentions");
    },
    "Name": function() {
      assert.deepEqual(g.path.name(), "world.tar.gz",
        "Gets a file or directory name");
    },
    "Parent path": function() {
      assert.deepEqual(g.path.parent(), "/waddup/",
        "Finds the file or directory's parent directory");
    }
  });

  registerSuite({
    name: "Disk",

    setUp: function() {
      g.rootDisk = box.fs.mounts["/"];
      g.rootInode = box.fs.resolve("/");
      g.inode = g.rootDisk.addInode("type", "name", g.rootInode);
      g.rootDisk.mkLink("linkToName", g.rootInode, g.inode);
      g.symLinkID = g.rootDisk.mkSymLink("symLinkToName", g.rootInode, "/./relative/link/../../name");
    },

    "Adds inodes to the table correctly": function() {
      assert.equal(g.rootDisk.addInode("type", "name/with/slashes", 0), -1,
        "Adding an inode with slashes returns -1");
    },
    "Adds inodes to parent directory list": function() {
      assert.equal(g.rootInode.files["name"], g.inode.id,
        "Adds an entry to its parent directory");
    },
    "Linking inodes works": function() {
      assert.equal(g.rootInode.files["linkToName"], g.inode.id,
        "Hard linking works");
      assert.equal(g.rootDisk.inodes[ g.rootDisk.inodes[0].files["symLinkToName"] ].redirect, "/name",
        "Symbolic links are clean and redirect to set path");
    }
  });

  registerSuite({
    name: "VFS",

    "Mount and unmount": function() {
      var someDisk = box.fs.mount(new Disk(), "/blah");

      assert.isTrue(someDisk instanceof Disk,
        "VFS.mount returns the disk");
      assert.equal(box.fs.mounts["/blah"], someDisk,
        "Mounts disk to given mount point");
      assert.isTrue(box.fs.unmount("/blah"),
        "Returns true on unmount");
      assert.isUndefined(box.fs.mounts["/blah"],
        "Unmount properly removes from mounts list");

      var otherDisk = box.fs.mount(new Disk(), "/doop");

      assert.isTrue(box.fs.unmountByUUID( otherDisk.uuid ),
        "can unmount by disk uuid");
      assert.isUndefined(box.fs.mounts["/doop"],
        "Unmounting by a UUID properly removes from mounts list");
    },

    "Resolve a disk from path": function() {
      box.fs.getDisk("/");
    },

    "Resolve paths to inodes": function() {
      box.fs.resolveHard("/");
      box.fs.resolve("/");
    }
  });
});<commit_msg>update Pathname tests<commit_after>define(function (require) {
  var registerSuite = require('intern!object');
  var assert = require('intern/chai!assert');
  var expect = require('intern/chai!expect');
  require('fauxOS.js');
  const g = {};

  registerSuite({
    name: "Pathname",

    setUp: function() {
      g.path = new Pathname("/hello/././///../waddup//path//././world.tar.gz");
    },

    "Basename": function() {
      assert.deepEqual(g.path.basename, "world",
        "Extracts a file or directory's basename");
    },
    "Chop path segments": function() {
      assert.deepEqual(g.path.chop, ["waddup", "path", "world.tar.gz"],
        "Chops a path into segments");
    },
    "Clean / normalize": function() {
      assert.deepEqual(g.path.clean, "/waddup/path/world.tar.gz",
        "Cleans up / normalizes a messy path");
    },
    "Extentions array": function() {
      assert.deepEqual(g.path.extentions, [".tar", ".gz"],
        "Can return an array of the file's extentions");
    },
    "Name": function() {
      assert.deepEqual(g.path.name, "world.tar.gz",
        "Gets a file or directory name");
    },
    "Parent path": function() {
      assert.deepEqual(g.path.parent, "/waddup/path/",
        "Finds the file or directory's parent directory");
    },
    "Path segments": function() {
      assert.deepEqual(g.path.segment, ["/", "/waddup", "/waddup/path", "/waddup/path/world.tar.gz"],
        "Can extract an array of every path from root to the input file/dir");
    }
  });

  registerSuite({
    name: "Disk",

    setUp: function() {
      g.rootDisk = box.fs.mounts["/"];
      g.rootInode = box.fs.resolve("/");
      g.inode = g.rootDisk.addInode("type", "name", g.rootInode);
      g.rootDisk.mkLink("linkToName", g.rootInode, g.inode);
      g.symLinkID = g.rootDisk.mkSymLink("symLinkToName", g.rootInode, "/./relative/link/../../name");
    },

    "Adds inodes to the table correctly": function() {
      assert.equal(g.rootDisk.addInode("type", "name/with/slashes", 0), -1,
        "Adding an inode with slashes returns -1");
    },
    "Adds inodes to parent directory list": function() {
      assert.equal(g.rootInode.files["name"], g.inode.id,
        "Adds an entry to its parent directory");
    },
    "Linking inodes works": function() {
      assert.equal(g.rootInode.files["linkToName"], g.inode.id,
        "Hard linking works");
      assert.equal(g.rootDisk.inodes[ g.rootDisk.inodes[0].files["symLinkToName"] ].redirect, "/name",
        "Symbolic links are clean and redirect to set path");
    }
  });

  registerSuite({
    name: "VFS",

    "Mount and unmount": function() {
      var someDisk = box.fs.mount(new Disk(), "/blah");

      assert.isTrue(someDisk instanceof Disk,
        "VFS.mount returns the disk");
      assert.equal(box.fs.mounts["/blah"], someDisk,
        "Mounts disk to given mount point");
      assert.isTrue(box.fs.unmount("/blah"),
        "Returns true on unmount");
      assert.isUndefined(box.fs.mounts["/blah"],
        "Unmount properly removes from mounts list");

      var otherDisk = box.fs.mount(new Disk(), "/doop");

      assert.isTrue(box.fs.unmountByUUID( otherDisk.uuid ),
        "can unmount by disk uuid");
      assert.isUndefined(box.fs.mounts["/doop"],
        "Unmounting by a UUID properly removes from mounts list");
    },

    "Resolve a disk from path": function() {
      box.fs.getDisk("/");
    },

    "Resolve paths to inodes": function() {
      box.fs.resolveHard("/");
      box.fs.resolve("/");
    }
  });
});
<|endoftext|>


<commit_before>describe("switch-plugin", function() {
    var pattern;

    requireDependencies(["jquery/switch"], function(cls) {
        pattern = cls;
    });

    // Reset the lab before each test
    beforeEach(function() {
        $("#lab *").remove();
    });

    describe("parse", function() {
        it("Shorthand notation", function() {
            var $trigger = $("<button id='trigger' data-switch='#victim; hide; show'>Click</button>");
                options = pattern.parse($trigger);
            expect(options.length).toBe(1);
            expect(options[0]).toEqual({selector: "#victim", remove: "hide", add: "show"});
        });

        it("Multiple changes", function() {
            var $trigger = $("<button id='trigger' data-switch='#victim; hide; show && #victim; hide; red'>Click</button>");
                options = pattern.parse($trigger);
            expect(options.length).toBe(2);
            expect(options[0]).toEqual({selector: "#victim", remove: "hide", add: "show"});
            expect(options[1]).toEqual({selector: "#victim", remove: "hide", add: "red"});
        });
    });

    describe("validateOptions", function() {
        it("Bad options", function() {
            var options = pattern.validateOptions([{}]);
            expect(options).toBeFalsy();
        });

        it("Mix valid and invalid options", function() {
            var options = pattern.validateOptions(
                [{selector: "#victim", add: "purple"}, {}]);
            expect(options.length).toBe(1);
            expect(options[0]).toEqual({selector: "#victim", add: "purple"});
        });

    });

    describe("update", function() {
        it("No targets", function() {
            spyOn(jQuery.fn, "addClass");
            spyOn(jQuery.fn, "removeClass");
            pattern.update(".missing");
            expect(jQuery.fn.addClass).not.toHaveBeenCalled();
            expect(jQuery.fn.removeClass).not.toHaveBeenCalled();
        });

        it("Remove basic class", function() {
            $("#lab").html("
");
            pattern.update("#lab div", "on");
            expect($("#lab div").hasClass("on")).toBe(false);
        });

        it("Remove uses whole words", function() {
            $("#lab").html("
");
            pattern.update("#lab div", "on");
            expect($("#lab div").attr("class")).toBe("cheese-on-bread");
        });

        it("Remove wildcard postfix class", function() {
            $("#lab").html("
");
            pattern.update("#lab div", "icon-*");
            expect($("#lab div").attr("class")).toBeFalsy();
        });

        it("Remove wildcard infix class", function() {
            $("#lab").html("
");
            pattern.update("#lab div", "icon-*-alert");
            expect($("#lab div").attr("class")).toBeFalsy();
        });

        it("Add class", function() {
            $("#lab").html("
");
            pattern.update("#lab div", null, "icon-alert");
            expect($("#lab div").attr("class")).toBe("icon-alert");
        });
    });

    describe("Initialise via jQuery", function() {
        it("Specify defaults via API", function() {
            $("#lab").html("<button>Click me</button>");
            $("#lab button").patternSwitch({selector: "#victim", add: "pink"});
            var $trigger = $("#lab button");
            expect($trigger.data("patternSwitch")).toEqual([{selector: "#victim", add: "pink"}]);
        });

        it("Invalid defaults via API", function() {
            $("#lab").html("<button>Click me</button>");
            $("#lab button").patternSwitch({selector: "#victim"});
            var $trigger = $("#lab button");
            expect($trigger.data("patternSwitch")).toBeFalsy();
        });

        it("Parse defaults from DOM", function() {
            $("#lab").html("<button data-switch='#victim; foo ; bar'>Click me</button>");
            $("#lab button").patternSwitch();
            var $trigger = $("#lab button");
            expect($trigger.data("patternSwitch")).toEqual([{selector: "#victim", remove:"foo", add: "bar"}]);
        });

        it("Setup click event handler", function() {
            $("#lab").html("<button data-switch='#victim; foo'>Click me</button>");
            var $trigger = $("#lab button").patternSwitch(),
                 events = $trigger.data("events");
            expect(events.click).toBeDefined();
            expect(events.click[0].namespace).toBe("patternSwitch");
        });
    });

    it("Execute changes", function() {
        $("#lab")
            .append("<button data-switch='#victim; foo'>Click me</button>")
            .append("
");
        var $trigger = $("#lab button").patternSwitch();
        $trigger.patternSwitch("execute");
        expect($("#victim").hasClass("foo")).toBeFalsy();

    });

    describe("Destroy all hooks", function() {
        it("Setup click event handler", function() {
            $("#lab").html("<button data-switch='#victim; foo'>Click me</button>");
            var $trigger = $("#lab button").patternSwitch(),
                 events = $trigger.data("events");
            expect(events.click).toBeDefined();
            $trigger.patternSwitch("destroy");
            expect(events.click).not.toBeDefined();
            expect($trigger.data("patternSwitch")).toBeFalsy();
        });
    });
});

// jshint indent: 4, browser: true, jquery: true, quotmark: double
// vim: sw=4 expandtab
<commit_msg>Add explicit test that other classes are not removed.<commit_after>describe("switch-plugin", function() {
    var pattern;

    requireDependencies(["jquery/switch"], function(cls) {
        pattern = cls;
    });

    // Reset the lab before each test
    beforeEach(function() {
        $("#lab *").remove();
    });

    describe("parse", function() {
        it("Shorthand notation", function() {
            var $trigger = $("<button id='trigger' data-switch='#victim; hide; show'>Click</button>");
                options = pattern.parse($trigger);
            expect(options.length).toBe(1);
            expect(options[0]).toEqual({selector: "#victim", remove: "hide", add: "show"});
        });

        it("Multiple changes", function() {
            var $trigger = $("<button id='trigger' data-switch='#victim; hide; show && #victim; hide; red'>Click</button>");
                options = pattern.parse($trigger);
            expect(options.length).toBe(2);
            expect(options[0]).toEqual({selector: "#victim", remove: "hide", add: "show"});
            expect(options[1]).toEqual({selector: "#victim", remove: "hide", add: "red"});
        });
    });

    describe("validateOptions", function() {
        it("Bad options", function() {
            var options = pattern.validateOptions([{}]);
            expect(options).toBeFalsy();
        });

        it("Mix valid and invalid options", function() {
            var options = pattern.validateOptions(
                [{selector: "#victim", add: "purple"}, {}]);
            expect(options.length).toBe(1);
            expect(options[0]).toEqual({selector: "#victim", add: "purple"});
        });

    });

    describe("update", function() {
        it("No targets", function() {
            spyOn(jQuery.fn, "addClass");
            spyOn(jQuery.fn, "removeClass");
            pattern.update(".missing");
            expect(jQuery.fn.addClass).not.toHaveBeenCalled();
            expect(jQuery.fn.removeClass).not.toHaveBeenCalled();
        });

        it("Remove basic class", function() {
            $("#lab").html("
");
            pattern.update("#lab div", "on");
            expect($("#lab div").hasClass("on")).toBe(false);
        });

        it("Remove uses whole words", function() {
            $("#lab").html("
");
            pattern.update("#lab div", "on");
            expect($("#lab div").attr("class")).toBe("cheese-on-bread");
        });

        it("Remove wildcard postfix class", function() {
            $("#lab").html("
");
            pattern.update("#lab div", "icon-*");
            expect($("#lab div").attr("class")).toBeFalsy();
        });

        it("Keep other classes", function() {
            $("#lab").html("
");
            pattern.update("#lab div", "one");
            expect($("#lab div").attr("class")).toBe("two");
        });

        it("Remove wildcard infix class", function() {
            $("#lab").html("
");
            pattern.update("#lab div", "icon-*-alert");
            expect($("#lab div").attr("class")).toBeFalsy();
        });

        it("Add class", function() {
            $("#lab").html("
");
            pattern.update("#lab div", null, "icon-alert");
            expect($("#lab div").attr("class")).toBe("icon-alert");
        });
    });

    describe("Initialise via jQuery", function() {
        it("Specify defaults via API", function() {
            $("#lab").html("<button>Click me</button>");
            $("#lab button").patternSwitch({selector: "#victim", add: "pink"});
            var $trigger = $("#lab button");
            expect($trigger.data("patternSwitch")).toEqual([{selector: "#victim", add: "pink"}]);
        });

        it("Invalid defaults via API", function() {
            $("#lab").html("<button>Click me</button>");
            $("#lab button").patternSwitch({selector: "#victim"});
            var $trigger = $("#lab button");
            expect($trigger.data("patternSwitch")).toBeFalsy();
        });

        it("Parse defaults from DOM", function() {
            $("#lab").html("<button data-switch='#victim; foo ; bar'>Click me</button>");
            $("#lab button").patternSwitch();
            var $trigger = $("#lab button");
            expect($trigger.data("patternSwitch")).toEqual([{selector: "#victim", remove:"foo", add: "bar"}]);
        });

        it("Setup click event handler", function() {
            $("#lab").html("<button data-switch='#victim; foo'>Click me</button>");
            var $trigger = $("#lab button").patternSwitch(),
                 events = $trigger.data("events");
            expect(events.click).toBeDefined();
            expect(events.click[0].namespace).toBe("patternSwitch");
        });
    });

    it("Execute changes", function() {
        $("#lab")
            .append("<button data-switch='#victim; foo'>Click me</button>")
            .append("
");
        var $trigger = $("#lab button").patternSwitch();
        $trigger.patternSwitch("execute");
        expect($("#victim").hasClass("foo")).toBeFalsy();

    });

    describe("Destroy all hooks", function() {
        it("Setup click event handler", function() {
            $("#lab").html("<button data-switch='#victim; foo'>Click me</button>");
            var $trigger = $("#lab button").patternSwitch(),
                 events = $trigger.data("events");
            expect(events.click).toBeDefined();
            $trigger.patternSwitch("destroy");
            expect(events.click).not.toBeDefined();
            expect($trigger.data("patternSwitch")).toBeFalsy();
        });
    });
});

// jshint indent: 4, browser: true, jquery: true, quotmark: double
// vim: sw=4 expandtab
<|endoftext|>