<commit_before>/**
 * Allow Kendo Window to be accessed from states with ui-router
 */

(function () {
    'use strict';

    angular.module("kendo.stateWindow", ["ui.router"])

    /**
     * stateWindowConfigProvider
     *
     * Allow state window default configuration options to be changed globally.
     */
        .provider("stateWindowConfig", function () {
            this.options = {
                modal: true
            };

            this.$get = function () {
                var options = this.options;
                return {
                    getOptions: function () {
                        return options;
                    }
                }
            };

            this.setOptions = function (options) {
                this.options = options;
            };
        })

        /**
         * stateProvider
         *
         * Evaluate window parameter on state definition and generate
         * template to include state-window directive ie:
         *
         * .state('window1', {
         *  window: {
         *   name: 'window1',
         *   options: {
         *    title: 'Example Window'
         *   }
         *  }
         * }
         *
         * Window name is required, and used to reference the kendo window.
         * @see http://docs.telerik.com/kendo-ui/AngularJS/introduction#widget-references
         *
         * Window options can be provided, as documented in Kendo Window configuration
         * @see http://docs.telerik.com/kendo-ui/api/javascript/ui/window#configuration
         */
        .config(["$stateProvider", function ($stateProvider) {
            var stateProviderState = $stateProvider.state;
            $stateProvider["state"] = state;

            function state(name, config) {
                var stateName, windowName, closeState, options = {};

                if (angular.isObject(name)) {
                    options = name;
                    stateName = options.name;
                } else {
                    options = config;
                    stateName = name;
                }

                if (options.data && options.data.window) {
                    options.window = options.data.window;
                }

                //options.cache = false;

                if (options.window) {

                    if (!options.window.name) {
                        options.window.name = stateName.replace(".", "_");
                    }

                    if (angular.isDefined(options.template)) {
                        throw new Error('Template content is not supported.')
                    }

                    options.template = '<div state-window="' + options.window.name + '"';

                    if (options.window.closeState) {
                        closeState = options.window.closeState;
                        options.template += ' close-state="' + closeState + '"';
                    }

                    if (options.templateUrl) {
                        options.template += ' template-url="' + options.templateUrl + '"';
                    }

                    if (options.window.append) {
                        options.template += ' append="' + options.window.append + '"';
                    }

                    if (options.window.options) {
                        options.template += " options='" + JSON.stringify(options.window.options) + "'";
                    }

                    options.template += '>
';
                }

                return stateProviderState.call($stateProvider, stateName, options);
            }
        }])

        /**
         * stateWindow
         *
         * Directive to configure and open Kendo Window widget
         */
        .directive('stateWindow', ['$state', 'stateWindowConfig', '$timeout', '$compile', '$window', 'stateWindowMap', function ($state, stateWindowConfig, $timeout, $compile, $window, stateWindowMap) {

            var openWindow = function (window, url) {

                // Preload window content using refresh
                if (angular.isDefined(url)) {
                    window.content("Loading...");
                    window.refresh(url);
                }

                if (angular.isDefined(window.options.center)) {
                    if (angular.isObject(window.options.center)) {
                        centerAlignment(window, window.options.center);
                        return window.open();
                    }

                    if (window.options.center === false) {
                        return window.open();
                    }
                }

                window.center();
                window.open();
            }

            /**
             * Center Alignment
             *
             * Allow fixed position adjustments to top and left while centering window
             *
             * @param window
             * @returns {*}
             */
            var centerAlignment = function (window) {
                var position = window.options.position, wrapper = window.wrapper,
                    documentWindow = angular.element($window), scrollTop = 0, scrollLeft = 0, newTop, newLeft;
                if (window.options.isMaximized) {
                    return window;
                }
                if (!window.options.pinned) {
                    scrollTop = documentWindow.scrollTop();
                    scrollLeft = documentWindow.scrollLeft();
                }

                var alignment = alignment || {};

                newLeft = (scrollLeft + Math.max(0, (documentWindow.width() - wrapper.width()) / 2));
                newTop = scrollTop + Math.max(0, (documentWindow.height() - wrapper.height() - parseInt(wrapper.css("paddingTop"), 10)) / 2);

                if (window.options.center.top) {
                    newTop = scrollTop + window.options.center.top;
                }

                if (window.options.center.left) {
                    newLeft = scrollLeft + window.options.center.left;
                }

                wrapper.css({
                    left: newLeft,
                    top: newTop
                });
                position.top = newTop;
                position.left = newLeft;
                return window;
            }

            return {
                restrict: 'AE',
                template: '
<ui-view />
',
                replace: false,
                controller: function ($scope, $element, $attrs) {
                    var windowName = $attrs.stateWindow,
                        options = {};

                    $scope.windowName = windowName;

                    if ($attrs.options) {
                        options = JSON.parse($attrs.options);
                    }

                    $timeout(function () {

                        var window = $scope[windowName];

                        if (angular.isUndefined(window)) {
                            throw new Error('Cannot find reference to window ' + windowName);
                        }

                        window.bind("close", function (e) {
                            stateWindowMap.remove(windowName);
                        });

                        if (window && (false === stateWindowMap.has(windowName))) {
                            stateWindowMap.add(windowName, window);
                            openWindow(window, $attrs.templateUrl);
                            console.debug('Opened Window:' + windowName);
                        } else {
                            console.debug('Could not open window', windowName);
                        }
                    });

                    if ($attrs.append && options.appendTo) {
                        var appendTo = options.appendTo.replace("#", "");
                        $element.append(angular.element('

'));
                    }

                    $scope.stateWindowOptions = angular.extend(angular.copy(stateWindowConfig.getOptions()), options);

                    if ($attrs.closeState) {
                        $scope.stateWindowOptions.close = function () {
                            $timeout(function () {
                                $scope[windowName].close();
                                $state.go($attrs.closeState);
                            });
                        }
                    }
                }
            }
        }])

        /**
         * Map open state windows by name, and kendo window instance
         */
        .factory('stateWindowMap', ['$q', '$rootScope', function ($q, $rootScope) {
            var map = [];

            var factory = {};

            factory.add = function (key, value) {
                if (false === factory.has(key)) {
                    map.push({
                        key: key,
                        value: value
                    });
                    $rootScope.$broadcast(key+'_created');
                }
            };

            factory.get = function (key) {
                for (var i = 0; i < map.length; i++) {
                    if (key === map[i].key) {
                        return map[i];
                    }
                }
            };

            factory.getWindow = function(key){
                var deferred = $q.defer();
                var deregister = $rootScope.$on(key+'_created', function(){
                    var found = false;
                    for (var i = 0; i < map.length; i++) {
                        if (key === map[i].key) {
                            found = true;
                            deferred.resolve(map[i].value);
                        }
                    }
                    if(!found){
                        deferred.reject();
                    }
                    deregister();
                })
                return deferred.promise;
            }

            factory.has = function (key) {
                if (angular.isDefined(factory.get(key))) {
                    return true;
                }
                return false;
            };

            factory.keys = function () {
                var keys = [];
                for (var i = 0; i < map.length; i++) {
                    keys.push(map[i].key);
                }
                return keys;
            };

            factory.remove = function (key) {
                for (var i = 0; i < map.length; i++) {
                    if (key === map[i].key) {
                        return map.splice(i, 1);
                    }
                }
            };

            factory.length = function () {
                return map.length;
            };

            return factory;
        }]);
})();<commit_msg>Created additional service for onCreate - converted AngularJS promises into old style javascript callbacks.<commit_after>/**
 * Allow Kendo Window to be accessed from states with ui-router
 */

(function () {
    'use strict';

    angular.module("kendo.stateWindow", ["ui.router"])

    /**
     * stateWindowConfigProvider
     *
     * Allow state window default configuration options to be changed globally.
     */
        .provider("stateWindowConfig", function () {
            this.options = {
                modal: true
            };

            this.$get = function () {
                var options = this.options;
                return {
                    getOptions: function () {
                        return options;
                    }
                }
            };

            this.setOptions = function (options) {
                this.options = options;
            };
        })

        /**
         * stateProvider
         *
         * Evaluate window parameter on state definition and generate
         * template to include state-window directive ie:
         *
         * .state('window1', {
         *  window: {
         *   name: 'window1',
         *   options: {
         *    title: 'Example Window'
         *   }
         *  }
         * }
         *
         * Window name is required, and used to reference the kendo window.
         * @see http://docs.telerik.com/kendo-ui/AngularJS/introduction#widget-references
         *
         * Window options can be provided, as documented in Kendo Window configuration
         * @see http://docs.telerik.com/kendo-ui/api/javascript/ui/window#configuration
         */
        .config(["$stateProvider", function ($stateProvider) {
            var stateProviderState = $stateProvider.state;
            $stateProvider["state"] = state;

            function state(name, config) {
                var stateName, windowName, closeState, options = {};

                if (angular.isObject(name)) {
                    options = name;
                    stateName = options.name;
                } else {
                    options = config;
                    stateName = name;
                }

                if (options.data && options.data.window) {
                    options.window = options.data.window;
                }

                //options.cache = false;

                if (options.window) {

                    if (!options.window.name) {
                        options.window.name = stateName.replace(".", "_");
                    }

                    if (angular.isDefined(options.template)) {
                        throw new Error('Template content is not supported.')
                    }

                    options.template = '<div state-window="' + options.window.name + '"';

                    if (options.window.closeState) {
                        closeState = options.window.closeState;
                        options.template += ' close-state="' + closeState + '"';
                    }

                    if (options.templateUrl) {
                        options.template += ' template-url="' + options.templateUrl + '"';
                    }

                    if (options.window.append) {
                        options.template += ' append="' + options.window.append + '"';
                    }

                    if (options.window.options) {
                        options.template += " options='" + JSON.stringify(options.window.options) + "'";
                    }

                    options.template += '>
';
                }

                return stateProviderState.call($stateProvider, stateName, options);
            }
        }])

        /**
         * stateWindow
         *
         * Directive to configure and open Kendo Window widget
         */
        .directive('stateWindow', ['$state', 'stateWindowConfig', '$timeout', '$compile', '$window', 'stateWindowMap', '$rootScope', function ($state, stateWindowConfig, $timeout, $compile, $window, stateWindowMap, $rootScope) {

            var openWindow = function (window, url) {

                // Preload window content using refresh
                if (angular.isDefined(url)) {
                    window.content("Loading...");
                    window.refresh(url);
                }

                if (angular.isDefined(window.options.center)) {
                    if (angular.isObject(window.options.center)) {
                        centerAlignment(window, window.options.center);
                        return window.open();
                    }

                    if (window.options.center === false) {
                        return window.open();
                    }
                }

                window.center();
                window.open();
            }

            /**
             * Center Alignment
             *
             * Allow fixed position adjustments to top and left while centering window
             *
             * @param window
             * @returns {*}
             */
            var centerAlignment = function (window) {
                var position = window.options.position, wrapper = window.wrapper,
                    documentWindow = angular.element($window), scrollTop = 0, scrollLeft = 0, newTop, newLeft;
                if (window.options.isMaximized) {
                    return window;
                }
                if (!window.options.pinned) {
                    scrollTop = documentWindow.scrollTop();
                    scrollLeft = documentWindow.scrollLeft();
                }

                var alignment = alignment || {};

                newLeft = (scrollLeft + Math.max(0, (documentWindow.width() - wrapper.width()) / 2));
                newTop = scrollTop + Math.max(0, (documentWindow.height() - wrapper.height() - parseInt(wrapper.css("paddingTop"), 10)) / 2);

                if (window.options.center.top) {
                    newTop = scrollTop + window.options.center.top;
                }

                if (window.options.center.left) {
                    newLeft = scrollLeft + window.options.center.left;
                }

                wrapper.css({
                    left: newLeft,
                    top: newTop
                });
                position.top = newTop;
                position.left = newLeft;
                return window;
            }

            return {
                restrict: 'AE',
                template: '
<ui-view />
',
                replace: false,
                controller: function ($scope, $element, $attrs) {
                    var windowName = $attrs.stateWindow,
                        options = {};

                    $scope.windowName = windowName;

                    if ($attrs.options) {
                        options = JSON.parse($attrs.options);
                    }

                    $timeout(function () {

                        var window = $scope[windowName];

                        if (angular.isUndefined(window)) {
                            throw new Error('Cannot find reference to window ' + windowName);
                        }

                        window.bind("close", function (e) {
                            stateWindowMap.remove(windowName);
                        });

                        if (window && (false === stateWindowMap.has(windowName))) {
                            stateWindowMap.add(windowName, window);
                            $rootScope.$broadcast('stateWindowCreated', {name: windowName, window: window});
                            openWindow(window, $attrs.templateUrl);
                            console.debug('Opened Window:' + windowName);
                        } else {
                            console.debug('Could not open window', windowName);
                        }
                    });

                    if ($attrs.append && options.appendTo) {
                        var appendTo = options.appendTo.replace("#", "");
                        $element.append(angular.element('

'));
                    }

                    $scope.stateWindowOptions = angular.extend(angular.copy(stateWindowConfig.getOptions()), options);

                    if ($attrs.closeState) {
                        $scope.stateWindowOptions.close = function () {
                            $timeout(function () {
                                $scope[windowName].close();
                                $state.go($attrs.closeState);
                            });
                        }
                    }
                }
            }
        }])

        .service('StateWindowService', ['$rootScope', 'stateWindowMap', function($rootScope, stateWindowMap){
            return {
                onCreated: function(window, callback){
                    if(stateWindowMap.get(window)){
                        callback(stateWindowMap.get(window).value);
                    }
                    else{
                        var deregister = $rootScope.$on('stateWindowCreated', function(event, windowData){
                            if(windowData.name === window){
                                var Window = stateWindowMap.get(window);
                                callback(Window.value);
                                deregister();
                            }
                        })
                    }
                }
            }
        }])

        /**
         * Map open state windows by name, and kendo window instance
         */
        .factory('stateWindowMap', [function () {
            var map = [];

            var factory = {};

            factory.add = function (key, value) {
                if (false === factory.has(key)) {
                    map.push({
                        key: key,
                        value: value
                    });

                }
            };

            factory.get = function (key) {
                for (var i = 0; i < map.length; i++) {
                    if (key === map[i].key) {
                        return map[i];
                    }
                }
            };

            factory.has = function (key) {
                if (angular.isDefined(factory.get(key))) {
                    return true;
                }
                return false;
            };

            factory.keys = function () {
                var keys = [];
                for (var i = 0; i < map.length; i++) {
                    keys.push(map[i].key);
                }
                return keys;
            };

            factory.remove = function (key) {
                for (var i = 0; i < map.length; i++) {
                    if (key === map[i].key) {
                        return map.splice(i, 1);
                    }
                }
            };

            factory.length = function () {
                return map.length;
            };

            return factory;
        }]);
})();<|endoftext|>


<commit_before>'use strict';

describe('Controller: GridsterCtrl', function() {

	// load the controller's module
	beforeEach(module('gridster'));

	var gridster,
		scope,
		item1x1,
		item2x1,
		item1x2,
		item2x2;

	// Initialize the controller and a mock scope
	beforeEach(inject(function($controller, $rootScope) {
		scope = $rootScope.$new();
		gridster = $controller('GridsterCtrl', {
			$scope: scope
		});
		item1x1 = { sizeX: 1, sizeY: 1, id: '1x1' };
		item2x1 = { sizeX: 2, sizeY: 1, id: '2x1' };
		item2x2 = { sizeX: 2, sizeY: 2, id: '2x2' };
		item1x2 = { sizeX: 1, sizeY: 2, id: '1x2' };
	}));

	it('should have a grid Array', function() {
		expect(gridster.grid.constructor).toBe(Array);
	});

	describe('setOpts', function(){
		it('should set properties', function() {
			gridster.setOpts({
				width: 1200,
				colWidth: 120,
				rowHeight: 120,
				columns: 7,
				margins: [15, 15],
				maxRows: 500
			});

			expect(gridster.width).toBe(1200);
			expect(gridster.colWidth).toBe(120);
			expect(gridster.rowHeight).toBe(120);
			expect(gridster.columns).toBe(7);
			expect(gridster.margins).toEqual([15, 15]);
			expect(gridster.maxRows).toBe(500);
		});
	});

	describe('setRowHeight', function(){
		it('should set the value if valid integer or "match"', function() {
			var oldColWidth = gridster.rowHeight;
			gridster.setRowHeight('abc');
			expect(gridster.rowHeight).toBe(oldColWidth);

			gridster.setColumns(6);
			gridster.setMargins([0, 0]);
			gridster.setWidth(1200);
			gridster.setColWidth('auto');

			gridster.setRowHeight('match');
			expect(gridster.rowHeight).toBe(200);

			gridster.setRowHeight(100);
			expect(gridster.rowHeight).toBe(100);
		});

		it('should only set the value if not falsey', function() {
			var oldColWidth = gridster.rowHeight;
			gridster.setRowHeight(0);
			expect(gridster.rowHeight).toBe(oldColWidth);
		});
	});

	describe('setColWidth', function(){
		it('should set the value if valid integer or "auto"', function() {
			var oldColWidth = gridster.colWidth;
			gridster.setColWidth('abc');
			expect(gridster.colWidth).toBe(oldColWidth);

			gridster.setColumns(6);
			gridster.setMargins([0, 0]);
			gridster.setWidth(1200);
			gridster.setColWidth('auto');
			expect(gridster.colWidth).toBe(200);

			gridster.setColWidth(100);
			expect(gridster.colWidth).toBe(100);
		});

		it('should only set the value if not falsey', function() {
			var oldColWidth = gridster.colWidth;
			gridster.setColWidth(0);
			expect(gridster.colWidth).toBe(oldColWidth);
		});
	});

	describe('setMaxRows', function(){
		it('should only set the value if valid integer', function() {
			var oldMaxRows = gridster.maxRows;
			gridster.setMaxRows('abc');
			expect(gridster.maxRows).toBe(oldMaxRows);

			gridster.setMaxRows(123);
			expect(gridster.maxRows).not.toBe(oldMaxRows);
			expect(gridster.maxRows).toBe(123);
		});

		it('should only set the value if not falsey', function() {
			var oldMaxRows = gridster.maxRows;
			gridster.setMaxRows(0);
			expect(gridster.maxRows).toBe(oldMaxRows);
		});
	});

	describe('putItem', function(){
		it('should be place an item', function() {
			gridster.putItem(item1x1, 0, 0);
			expect(gridster.getItem(0, 0)).toBe(item1x1);
		});

		it('should place an item without a position', function() {
			gridster.putItem(item1x1);
			expect(gridster.getItem(0, 0)).toBe(item1x1);
		});

		it('should not allow items to be placed with negative indices', function() {
			gridster.putItem(item1x1, -1, -1);
			expect(gridster.getItem(0, 0)).toBe(item1x1);
			expect(item1x1.row).toBe(0);
			expect(item1x1.col).toBe(0);
		});

		it('should not float items until told to', function() {
			gridster.putItem(item1x1, 3, 0);
			expect(gridster.getItem(0, 0)).toBe(null);
			expect(gridster.getItem(3, 0)).toBe(item1x1);
		});

		it('should not create two references to the same item', function() {
			gridster.putItem(item1x1, 0, 0);
			expect(gridster.getItem(0, 0)).toBe(item1x1);
			gridster.putItem(item1x1, 0, 4);
			expect(gridster.getItem(0, 4)).toBe(item1x1);
			expect(gridster.getItem(0, 0)).toBe(null);
		});
	});

	describe('getItem', function(){
		it('should match any column of a multi-column item', function(){
			gridster.putItem(item2x2, 0, 2);

			// all 4 corners should return the same item
			expect(gridster.getItem(0, 2)).toBe(item2x2);
			expect(gridster.getItem(1, 2)).toBe(item2x2);
			expect(gridster.getItem(0, 3)).toBe(item2x2);
			expect(gridster.getItem(1, 3)).toBe(item2x2);
		});
	});

	describe('getItems', function(){
		it('should get items within an area', function(){
			gridster.putItem(item2x2, 0, 1);
			gridster.putItem(item2x1, 2, 0);

			// verify they are still where we put them
			expect(gridster.getItem(0, 1)).toBe(item2x2);
			expect(gridster.getItem(2, 0)).toBe(item2x1);

			var items = gridster.getItems(1, 0, 2, 1);
			expect(items.length).toBe(1);
			expect(items[0]).toBe(item2x2);
		});
	});

	describe('floatItemsUp', function(){
		it('should float an item up', function() {
			gridster.putItem(item1x1, 3, 0);
			gridster.floatItemsUp();
			expect(gridster.getItem(0, 0)).toBe(item1x1);
		});

		it('should stack items when they float up', function() {
			gridster.putItem(item1x1, 3, 0);
			gridster.floatItemsUp();
			expect(gridster.getItem(0, 0)).toBe(item1x1);

			gridster.putItem(item2x1, 3, 0);
			gridster.floatItemsUp();
			expect(gridster.getItem(1, 0)).toBe(item2x1);

			gridster.putItem(item1x1, 3, 1);
			gridster.floatItemsUp();
			expect(gridster.getItem(1, 1)).toBe(item1x1);
		});

		it('should correctly stack multi-column items when their primary coordinates do not stack', function(){
			gridster.putItem(item2x2, 0, 2);
			gridster.putItem(item2x1, 2, 1);

			// verify they are still where we put them
			expect(gridster.getItem(0, 2)).toBe(item2x2);
			expect(gridster.getItem(2, 1)).toBe(item2x1);

			// allow them to float up
			gridster.floatItemsUp();

			// verify they are still where we put them
			expect(gridster.getItem(0, 2)).toBe(item2x2);
			expect(gridster.getItem(2, 1)).toBe(item2x1);
		});
	});

	describe('moveOverlappingItems', function(){
		it('should correctly stack items on resize when their primary coordinates do not stack', function(){
			gridster.putItem(item1x1, 0, 0);
			gridster.putItem(item2x2, 0, 2);
			gridster.putItem(item2x1, 1, 0);

			// verify they are still where we put them
			expect(gridster.getItem(0, 0)).toBe(item1x1);
			expect(gridster.getItem(0, 2)).toBe(item2x2);
			expect(gridster.getItem(1, 0)).toBe(item2x1);

			item2x1.sizeX = 3;
			gridster.moveOverlappingItems(item2x1);
			expect(gridster.getItem(1, 2)).toBe(item2x1);

			expect(item2x2.row).toBe(2);
		});

		it('should correctly push items down', function(){
			gridster.putItem(item2x2, 0, 0);
			gridster.putItem(item1x1, 2, 0);
			gridster.putItem(item1x2, 1, 1);
			gridster.floatItemsUp();

			// verify they are still where we put them
			expect(gridster.getItem(2, 0)).toBe(item2x2);
			expect(gridster.getItem(0, 0)).toBe(item1x1);
			expect(gridster.getItem(0, 1)).toBe(item1x2);
		});
	});
});<commit_msg>cover all options in test<commit_after>'use strict';

describe('Controller: GridsterCtrl', function() {

	// load the controller's module
	beforeEach(module('gridster'));

	var gridster,
		scope,
		item1x1,
		item2x1,
		item1x2,
		item2x2;

	// Initialize the controller and a mock scope
	beforeEach(inject(function($controller, $rootScope) {
		scope = $rootScope.$new();
		gridster = $controller('GridsterCtrl', {
			$scope: scope
		});
		item1x1 = { sizeX: 1, sizeY: 1, id: '1x1' };
		item2x1 = { sizeX: 2, sizeY: 1, id: '2x1' };
		item2x2 = { sizeX: 2, sizeY: 2, id: '2x2' };
		item1x2 = { sizeX: 1, sizeY: 2, id: '1x2' };
	}));

	it('should have a grid Array', function() {
		expect(gridster.grid.constructor).toBe(Array);
	});

	describe('setOpts', function(){
		it('should set properties', function() {
			gridster.setOpts({
				width: 1200,
				colWidth: 120,
				rowHeight: 120,
        maxGridRows: 500,
				columns: 7,
				minColumns: 3,
				maxColumns: 3,
				margins: [15, 15],
				minRows: 1,
				maxRows: 500
			});

			expect(gridster.width).toBe(1200);
			expect(gridster.colWidth).toBe(120);
			expect(gridster.rowHeight).toBe(120);
			expect(gridster.maxGridRows).toBe(500);
			expect(gridster.columns).toBe(7);
			expect(gridster.minColumns).toEqual(3);
			expect(gridster.maxColumns).toEqual(3);
			expect(gridster.margins).toEqual([15, 15]);
      expect(gridster.minRows).toBe(1);
			expect(gridster.maxRows).toBe(500);
		});
	});

	describe('setRowHeight', function(){
		it('should set the value if valid integer or "match"', function() {
			var oldColWidth = gridster.rowHeight;
			gridster.setRowHeight('abc');
			expect(gridster.rowHeight).toBe(oldColWidth);

			gridster.setColumns(6);
			gridster.setMargins([0, 0]);
			gridster.setWidth(1200);
			gridster.setColWidth('auto');

			gridster.setRowHeight('match');
			expect(gridster.rowHeight).toBe(200);

			gridster.setRowHeight(100);
			expect(gridster.rowHeight).toBe(100);
		});

		it('should only set the value if not falsey', function() {
			var oldColWidth = gridster.rowHeight;
			gridster.setRowHeight(0);
			expect(gridster.rowHeight).toBe(oldColWidth);
		});
	});

	describe('setColWidth', function(){
		it('should set the value if valid integer or "auto"', function() {
			var oldColWidth = gridster.colWidth;
			gridster.setColWidth('abc');
			expect(gridster.colWidth).toBe(oldColWidth);

			gridster.setColumns(6);
			gridster.setMargins([0, 0]);
			gridster.setWidth(1200);
			gridster.setColWidth('auto');
			expect(gridster.colWidth).toBe(200);

			gridster.setColWidth(100);
			expect(gridster.colWidth).toBe(100);
		});

		it('should only set the value if not falsey', function() {
			var oldColWidth = gridster.colWidth;
			gridster.setColWidth(0);
			expect(gridster.colWidth).toBe(oldColWidth);
		});
	});

	describe('setMaxRows', function(){
		it('should only set the value if valid integer', function() {
			var oldMaxRows = gridster.maxRows;
			gridster.setMaxRows('abc');
			expect(gridster.maxRows).toBe(oldMaxRows);

			gridster.setMaxRows(123);
			expect(gridster.maxRows).not.toBe(oldMaxRows);
			expect(gridster.maxRows).toBe(123);
		});

		it('should only set the value if not falsey', function() {
			var oldMaxRows = gridster.maxRows;
			gridster.setMaxRows(0);
			expect(gridster.maxRows).toBe(oldMaxRows);
		});
	});

	describe('putItem', function(){
		it('should be place an item', function() {
			gridster.putItem(item1x1, 0, 0);
			expect(gridster.getItem(0, 0)).toBe(item1x1);
		});

		it('should place an item without a position', function() {
			gridster.putItem(item1x1);
			expect(gridster.getItem(0, 0)).toBe(item1x1);
		});

		it('should not allow items to be placed with negative indices', function() {
			gridster.putItem(item1x1, -1, -1);
			expect(gridster.getItem(0, 0)).toBe(item1x1);
			expect(item1x1.row).toBe(0);
			expect(item1x1.col).toBe(0);
		});

		it('should not float items until told to', function() {
			gridster.putItem(item1x1, 3, 0);
			expect(gridster.getItem(0, 0)).toBe(null);
			expect(gridster.getItem(3, 0)).toBe(item1x1);
		});

		it('should not create two references to the same item', function() {
			gridster.putItem(item1x1, 0, 0);
			expect(gridster.getItem(0, 0)).toBe(item1x1);
			gridster.putItem(item1x1, 0, 4);
			expect(gridster.getItem(0, 4)).toBe(item1x1);
			expect(gridster.getItem(0, 0)).toBe(null);
		});
	});

	describe('getItem', function(){
		it('should match any column of a multi-column item', function(){
			gridster.putItem(item2x2, 0, 2);

			// all 4 corners should return the same item
			expect(gridster.getItem(0, 2)).toBe(item2x2);
			expect(gridster.getItem(1, 2)).toBe(item2x2);
			expect(gridster.getItem(0, 3)).toBe(item2x2);
			expect(gridster.getItem(1, 3)).toBe(item2x2);
		});
	});

	describe('getItems', function(){
		it('should get items within an area', function(){
			gridster.putItem(item2x2, 0, 1);
			gridster.putItem(item2x1, 2, 0);

			// verify they are still where we put them
			expect(gridster.getItem(0, 1)).toBe(item2x2);
			expect(gridster.getItem(2, 0)).toBe(item2x1);

			var items = gridster.getItems(1, 0, 2, 1);
			expect(items.length).toBe(1);
			expect(items[0]).toBe(item2x2);
		});
	});

	describe('floatItemsUp', function(){
		it('should float an item up', function() {
			gridster.putItem(item1x1, 3, 0);
			gridster.floatItemsUp();
			expect(gridster.getItem(0, 0)).toBe(item1x1);
		});

		it('should stack items when they float up', function() {
			gridster.putItem(item1x1, 3, 0);
			gridster.floatItemsUp();
			expect(gridster.getItem(0, 0)).toBe(item1x1);

			gridster.putItem(item2x1, 3, 0);
			gridster.floatItemsUp();
			expect(gridster.getItem(1, 0)).toBe(item2x1);

			gridster.putItem(item1x1, 3, 1);
			gridster.floatItemsUp();
			expect(gridster.getItem(1, 1)).toBe(item1x1);
		});

		it('should correctly stack multi-column items when their primary coordinates do not stack', function(){
			gridster.putItem(item2x2, 0, 2);
			gridster.putItem(item2x1, 2, 1);

			// verify they are still where we put them
			expect(gridster.getItem(0, 2)).toBe(item2x2);
			expect(gridster.getItem(2, 1)).toBe(item2x1);

			// allow them to float up
			gridster.floatItemsUp();

			// verify they are still where we put them
			expect(gridster.getItem(0, 2)).toBe(item2x2);
			expect(gridster.getItem(2, 1)).toBe(item2x1);
		});
	});

	describe('moveOverlappingItems', function(){
		it('should correctly stack items on resize when their primary coordinates do not stack', function(){
			gridster.putItem(item1x1, 0, 0);
			gridster.putItem(item2x2, 0, 2);
			gridster.putItem(item2x1, 1, 0);

			// verify they are still where we put them
			expect(gridster.getItem(0, 0)).toBe(item1x1);
			expect(gridster.getItem(0, 2)).toBe(item2x2);
			expect(gridster.getItem(1, 0)).toBe(item2x1);

			item2x1.sizeX = 3;
			gridster.moveOverlappingItems(item2x1);
			expect(gridster.getItem(1, 2)).toBe(item2x1);

			expect(item2x2.row).toBe(2);
		});

		it('should correctly push items down', function(){
			gridster.putItem(item2x2, 0, 0);
			gridster.putItem(item1x1, 2, 0);
			gridster.putItem(item1x2, 1, 1);
			gridster.floatItemsUp();

			// verify they are still where we put them
			expect(gridster.getItem(2, 0)).toBe(item2x2);
			expect(gridster.getItem(0, 0)).toBe(item1x1);
			expect(gridster.getItem(0, 1)).toBe(item1x2);
		});
	});
});
<|endoftext|>


<commit_before>var fs = require('fs'),
	path = require('path'),
	os = require('os'),
	wrench = require('wrench'),
	colors = require('colors'),
	TU = require('../lib/testUtils'),
	CONST = require('../../Alloy/common/constants'),
	_ = require('../../Alloy/lib/alloy/underscore')._,
	platforms = require('../../platforms/index');

var TIMEOUT_COMPILE = 10000;
var GEN_FOLDER = '_generated';

var alloyRoot = path.join(__dirname,'..','..'),
	paths = {
		apps: path.join(alloyRoot,'test','apps'),
		harness: path.join(alloyRoot,'test','projects','Harness')
	},
	compilerDirectives = (function() {
		var cds = [];
		_.each(_.keys(platforms), function(p) {
			cds.push('OS_' + p.toUpperCase());
		});
		cds.concat(_.pluck(CONST.DEPLOY_TYPES,'key'));
		return cds;
	})(),
	cdRegex = new RegExp('(?:' + compilerDirectives.join('|') + ')');

// The alloy command test suite
describe('alloy compile', function() {
	TU.addMatchers();

	// Iterate through each test app and make sure it compiles for all platforms
	_.each(wrench.readdirSyncRecursive(paths.apps), function(file) {
		// are we testing only a specific app?
		if (process.env.app && file !== process.env.app) { return; }

		// TODO: Stop skipping the ui/navwindow test when TiSDK 3.1.3 is in the HarnessTemplate
		//       tiapp.xml. We skip it now because it purposely fails compilation on any SDK below
		//       TiSDK 3.1.3, where Ti.UI.iOS.NavigationWindow was introduced.
		if (file === 'ui/navwindow' || file === 'testing/ALOY-818') { return; }

		describe(file.yellow, function() {
			var indexJs = path.join(paths.apps,file,'controllers','index.js');
			if (!path.existsSync(indexJs) || indexJs.indexOf(GEN_FOLDER) !== -1) { return; }

			it('preparing test app', function() {
				TU.asyncExecTest('jake app:setup dir=' + file + ' quiet=1', { timeout: 10000 });
			});

			_.each(platforms, function(platform,k) {
				describe(('[' + platform.platform + ']').cyan, function () {
						it('compiles without critical error',
						function() {
							TU.asyncExecTest(
								'alloy compile ' + paths.harness + ' --config platform=' + platform.platform, {
								test: function() {
									// Make sure there were no compile errors
									if (file === 'testing/ALOY-887') {
										// this test specifically tests a compiler error
										expect(this.output.error).toBeTruthy();
									} else {
										expect(this.output.error).toBeFalsy();
									}
								},
								timeout: TIMEOUT_COMPILE
							}
						);
					});

					it('leaves no compiler directives in generated code', function() {
						var hrDir = path.join(paths.harness,'Resources');
						var cPaths = [
							path.join(hrDir,'alloy'),
							path.join(hrDir,platform.titaniumFolder,'alloy')
						];

						_.each(cPaths, function(cPath) {
							if (file === 'testing/ALOY-887') {
								// skip this test since this app forces a compile error
								return;
							}
							if (!fs.existsSync(cPath)) { return; }
							var files = wrench.readdirSyncRecursive(cPath);
							_.each(files, function(file) {
								var fullpath = path.join(cPath,file);
								if (!fs.statSync(fullpath).isFile() ||
									!/\.js$/.test(fullpath)) {
									return;
								}
								var content = fs.readFileSync(fullpath, 'utf8');
								expect(cdRegex.test(content)).toBeFalsy();
							});
						});
					});

					it('has no undefined style entries', function() {
						// skip this test, since it specifically tests undefined values in TSS
						if (file === 'testing/ALOY-822') {
							return;
						}

						var hrDir = path.join(paths.harness,'Resources');
						var cPaths = [
							path.join(hrDir,'alloy','styles'),
							path.join(hrDir,platform.titaniumFolder,'alloy','styles')
						];

						_.each(cPaths, function(cPath) {
							if (!fs.existsSync(cPath)) { return; }
							var files = wrench.readdirSyncRecursive(cPath);
							_.each(files, function(file) {
								var fullpath = path.join(cPath,file);
								if (!fs.statSync(fullpath).isFile() ||
									!/\.js$/.test(fullpath)) {
									return;
								}

								// TODO: Can no longer require() the styles since they
								//       are preprocessed for runtime now. Find a better
								//       way than this lazy text check to verify that
								//       there's no undefined keys in the styles.
								expect(fs.readFileSync(fullpath,'utf8').indexOf('undefined')).toEqual(-1);
								// var json = require(fullpath);
								// expect(json).toHaveNoUndefinedStyles();
							});
						});
					});

					var genFolder = path.join(paths.apps,file,GEN_FOLDER,platform.platform);
					if (!fs.existsSync(genFolder)) { return; }
					var hrFolder = path.join(paths.harness, 'Resources', platform.titaniumFolder);
					var files = wrench.readdirSyncRecursive(genFolder);

					os.platform() === 'darwin' && _.each(files, function(gFile) {
						var goodFile = path.join(genFolder,gFile);
						if (!fs.statSync(goodFile).isFile()) { return; }
						var newFile = path.join(hrFolder,gFile);

						it ('generated a ' + gFile.yellow + ' file', function() {
							expect(fs.existsSync(newFile)).toBeTruthy();
						});

						it('matches known good generated code for ' + gFile.yellow, function () {
							var goodFileContents = fs.readFileSync(goodFile, 'utf8');
							var newFileContents = fs.readFileSync(newFile, 'utf8');
							expect(goodFileContents === newFileContents).toBeTruthy();
						});
					});
				});
			});
		});
	});
});
<commit_msg>skip purposely failing test<commit_after>var fs = require('fs'),
	path = require('path'),
	os = require('os'),
	wrench = require('wrench'),
	colors = require('colors'),
	TU = require('../lib/testUtils'),
	CONST = require('../../Alloy/common/constants'),
	_ = require('../../Alloy/lib/alloy/underscore')._,
	platforms = require('../../platforms/index');

var TIMEOUT_COMPILE = 10000;
var GEN_FOLDER = '_generated';

var alloyRoot = path.join(__dirname,'..','..'),
	paths = {
		apps: path.join(alloyRoot,'test','apps'),
		harness: path.join(alloyRoot,'test','projects','Harness')
	},
	compilerDirectives = (function() {
		var cds = [];
		_.each(_.keys(platforms), function(p) {
			cds.push('OS_' + p.toUpperCase());
		});
		cds.concat(_.pluck(CONST.DEPLOY_TYPES,'key'));
		return cds;
	})(),
	cdRegex = new RegExp('(?:' + compilerDirectives.join('|') + ')');

// The alloy command test suite
describe('alloy compile', function() {
	TU.addMatchers();

	// Iterate through each test app and make sure it compiles for all platforms
	_.each(wrench.readdirSyncRecursive(paths.apps), function(file) {
		// are we testing only a specific app?
		if (process.env.app && file !== process.env.app) { return; }

		// TODO: Stop skipping the ui/navwindow test when TiSDK 3.1.3 is in the HarnessTemplate
		//       tiapp.xml. We skip it now because it purposely fails compilation on any SDK below
		//       TiSDK 3.1.3, where Ti.UI.iOS.NavigationWindow was introduced.
		if (file === 'ui/navwindow' || file === 'testing/ALOY-818' || file === 'testing/ALOY-840') { return; }

		describe(file.yellow, function() {
			var indexJs = path.join(paths.apps,file,'controllers','index.js');
			if (!path.existsSync(indexJs) || indexJs.indexOf(GEN_FOLDER) !== -1) { return; }

			it('preparing test app', function() {
				TU.asyncExecTest('jake app:setup dir=' + file + ' quiet=1', { timeout: 10000 });
			});

			_.each(platforms, function(platform,k) {
				describe(('[' + platform.platform + ']').cyan, function () {
						it('compiles without critical error',
						function() {
							TU.asyncExecTest(
								'alloy compile ' + paths.harness + ' --config platform=' + platform.platform, {
								test: function() {
									// Make sure there were no compile errors
									if (file === 'testing/ALOY-887') {
										// this test specifically tests a compiler error
										expect(this.output.error).toBeTruthy();
									} else {
										expect(this.output.error).toBeFalsy();
									}
								},
								timeout: TIMEOUT_COMPILE
							}
						);
					});

					it('leaves no compiler directives in generated code', function() {
						var hrDir = path.join(paths.harness,'Resources');
						var cPaths = [
							path.join(hrDir,'alloy'),
							path.join(hrDir,platform.titaniumFolder,'alloy')
						];

						_.each(cPaths, function(cPath) {
							if (file === 'testing/ALOY-887') {
								// skip this test since this app forces a compile error
								return;
							}
							if (!fs.existsSync(cPath)) { return; }
							var files = wrench.readdirSyncRecursive(cPath);
							_.each(files, function(file) {
								var fullpath = path.join(cPath,file);
								if (!fs.statSync(fullpath).isFile() ||
									!/\.js$/.test(fullpath)) {
									return;
								}
								var content = fs.readFileSync(fullpath, 'utf8');
								expect(cdRegex.test(content)).toBeFalsy();
							});
						});
					});

					it('has no undefined style entries', function() {
						// skip this test, since it specifically tests undefined values in TSS
						if (file === 'testing/ALOY-822') {
							return;
						}

						var hrDir = path.join(paths.harness,'Resources');
						var cPaths = [
							path.join(hrDir,'alloy','styles'),
							path.join(hrDir,platform.titaniumFolder,'alloy','styles')
						];

						_.each(cPaths, function(cPath) {
							if (!fs.existsSync(cPath)) { return; }
							var files = wrench.readdirSyncRecursive(cPath);
							_.each(files, function(file) {
								var fullpath = path.join(cPath,file);
								if (!fs.statSync(fullpath).isFile() ||
									!/\.js$/.test(fullpath)) {
									return;
								}

								// TODO: Can no longer require() the styles since they
								//       are preprocessed for runtime now. Find a better
								//       way than this lazy text check to verify that
								//       there's no undefined keys in the styles.
								expect(fs.readFileSync(fullpath,'utf8').indexOf('undefined')).toEqual(-1);
								// var json = require(fullpath);
								// expect(json).toHaveNoUndefinedStyles();
							});
						});
					});

					var genFolder = path.join(paths.apps,file,GEN_FOLDER,platform.platform);
					if (!fs.existsSync(genFolder)) { return; }
					var hrFolder = path.join(paths.harness, 'Resources', platform.titaniumFolder);
					var files = wrench.readdirSyncRecursive(genFolder);

					os.platform() === 'darwin' && _.each(files, function(gFile) {
						var goodFile = path.join(genFolder,gFile);
						if (!fs.statSync(goodFile).isFile()) { return; }
						var newFile = path.join(hrFolder,gFile);

						it ('generated a ' + gFile.yellow + ' file', function() {
							expect(fs.existsSync(newFile)).toBeTruthy();
						});

						it('matches known good generated code for ' + gFile.yellow, function () {
							var goodFileContents = fs.readFileSync(goodFile, 'utf8');
							var newFileContents = fs.readFileSync(newFile, 'utf8');
							expect(goodFileContents === newFileContents).toBeTruthy();
						});
					});
				});
			});
		});
	});
});
<|endoftext|>


<commit_before>var fs = require('fs'),
	walkSync = require('walk-sync'),
	path = require('path'),
	os = require('os'),
	colors = require('colors'),
	exec = require('child_process').exec,
	TU = require('../lib/testUtils'),
	CONST = require('../../Alloy/common/constants'),
	_ = require('../../Alloy/lib/alloy/underscore')._,
	tiapp = require('../../Alloy/tiapp'),
	platforms = require('../../platforms/index'),
	sep = process.platform !== 'win32' ? '/' : '\\';

var TIMEOUT_COMPILE = process.platform !== 'win32' ? 10000 : 20000;
var TIMEOUT_PREP = process.platform !== 'win32' ? 10000 : 30000;
var GEN_FOLDER = '_generated';
var TEST_FOLDER = 'testing';
var EXCLUDE_FOLDERS = [
	'ui'+sep+'navwindow',
	TEST_FOLDER+sep+'ALOY-818',
	TEST_FOLDER+sep+'ALOY-840',
	TEST_FOLDER+sep+'ALOY-1080',
	TEST_FOLDER+sep+'ALOY-932',
	TEST_FOLDER+sep+'ALOY-961'
];

/*
// async, so it doesn't complete by the time the tests begin.
// once ALOY-1230 is resolved, rewrite using beforeAll()

// Skip the test that depends on version of SDKs
exec('ti sdk list --output json', function(error, stdout, stderr){
    if (error === null) {
        var sdkInfo = JSON.parse(stdout);

        if (tiapp.version.lt(sdkInfo.activeSDK, '3.6.0') || !sdkInfo) {
        	// Skip ALOY-961 / AttributedString when using pre-3.6.0 SDKs
            EXCLUDE_FOLDERS.push(TEST_FOLDER+sep+'ALOY-961');
        }
    }
});
*/

var alloyRoot = path.join(__dirname,'..','..'),
	paths = {
		apps: path.join(alloyRoot,'test','apps'),
		harness: path.join(alloyRoot,'test','projects','Harness')
	},
	compilerDirectives = (function() {
		var cds = [];
		_.each(_.keys(platforms), function(p) {
			cds.push('OS_' + p.toUpperCase());
		});
		cds.concat(_.pluck(CONST.DEPLOY_TYPES,'key'));
		return cds;
	})(),
	cdRegex = new RegExp('(?:' + compilerDirectives.join('|') + ')');

// The alloy command test suite
describe('alloy compile', function() {
	TU.addMatchers();

	// Iterate through each test app and make sure it compiles for all platforms
	_.each(walkSync(paths.apps), function(file) {
		// are we testing only a specific app?
		if (process.env.app && file !== process.env.app) { return; }

		// TODO: Stop skipping the ui/navwindow test when TiSDK 3.1.3 is in the HarnessTemplate
		//       tiapp.xml. We skip it now because it purposely fails compilation on any SDK below
		//       TiSDK 3.1.3, where Ti.UI.iOS.NavigationWindow was introduced.
		if (_.contains(EXCLUDE_FOLDERS, file)) { return; }

		describe(file.yellow, function() {
			var indexJs = path.join(paths.apps,file,'controllers','index.js');
			if (!path.existsSync(indexJs) || indexJs.indexOf(GEN_FOLDER) !== -1) { return; }

			it('preparing test app', function() {
				TU.asyncExecTest('jake app:setup dir=' + file + ' quiet=1', { timeout: TIMEOUT_PREP });
			});

			_.each(platforms, function(platform,k) {
				if (process.platform !== 'win32' && platform.platform === 'blackberry') {
					return;
				}
				if(process.platform !== 'win32' && platform.platform === 'windows') {
					// skip windows tests on non-Windows computers
					return;
				}

				describe(('[' + platform.platform + ']').cyan, function () {
						it('compiles without critical error',
						function() {
							TU.asyncExecTest(
								'alloy compile ' + paths.harness + ' --config platform=' + platform.platform, {
								test: function() {
									// Make sure there were no compile errors
									if (file === 'testing'+sep+'ALOY-887') {
										// this test specifically tests a compiler error
										expect(this.output.error).toBeTruthy();
									} else {
										// Spit out stderr/stdout, so we can see *why* it failed
										if (this.output.error) {
											console.error(this.output.stderr);
											console.log(this.output.stdout);
										}
										expect(this.output.error).toBeFalsy();
									}
								},
								timeout: TIMEOUT_COMPILE
							}
						);
					});

					it('leaves no compiler directives in generated code', function() {
						var hrDir = path.join(paths.harness,'Resources');
						var cPaths = [
							path.join(hrDir,'alloy'),
							path.join(hrDir,platform.titaniumFolder,'alloy')
						];

						_.each(cPaths, function(cPath) {
							if (file === 'testing'+sep+'ALOY-887') {
								// skip this test since this app forces a compile error
								return;
							}
							if (!fs.existsSync(cPath)) { return; }
							var files = walkSync(cPath);
							_.each(files, function(file) {
								var fullpath = path.join(cPath,file);
								if (!fs.statSync(fullpath).isFile() ||
									!/\.js$/.test(fullpath)) {
									return;
								}
								var content = fs.readFileSync(fullpath, 'utf8');
								expect(cdRegex.test(content)).toBeFalsy();
							});
						});
					});

					it('has no undefined style entries', function() {
						// skip this test, since it specifically tests undefined values in TSS
						if (file === 'testing'+sep+'ALOY-822') {
							return;
						}

						var hrDir = path.join(paths.harness,'Resources');
						var cPaths = [
							path.join(hrDir,'alloy','styles'),
							path.join(hrDir,platform.titaniumFolder,'alloy','styles')
						];

						_.each(cPaths, function(cPath) {
							if (!fs.existsSync(cPath)) { return; }
							var files = walkSync(cPath);
							_.each(files, function(file) {
								var fullpath = path.join(cPath,file);
								if (!fs.statSync(fullpath).isFile() ||
									!/\.js$/.test(fullpath)) {
									return;
								}

								// TODO: Can no longer require() the styles since they
								//       are preprocessed for runtime now. Find a better
								//       way than this lazy text check to verify that
								//       there's no undefined keys in the styles.
								expect(fs.readFileSync(fullpath,'utf8').indexOf('undefined')).toEqual(-1);
								// var json = require(fullpath);
								// expect(json).toHaveNoUndefinedStyles();
							});
						});
					});

					var genFolder = path.join(paths.apps,file,GEN_FOLDER,platform.platform);
					if (!fs.existsSync(genFolder)) { return; }
					var hrFolder = path.join(paths.harness, 'Resources', platform.titaniumFolder);
					var files = walkSync(genFolder);

					// FIXME: Run these comparisons on *every* OS? I assume this was due to windows newline difference?
					/*os.platform() === 'darwin'*/ false && _.each(files, function(gFile) {
						var goodFile = path.join(genFolder,gFile);
						if (!fs.statSync(goodFile).isFile()) { return; }
						var newFile = path.join(hrFolder,gFile);

						it ('generated a ' + gFile.yellow + ' file', function() {
							expect(fs.existsSync(newFile)).toBeTruthy();
						});

						it('matches known good generated code for ' + gFile.yellow, function () {
							var goodFileContents = fs.readFileSync(goodFile, 'utf8');
							var newFileContents = fs.readFileSync(newFile, 'utf8');
/*
							if(goodFileContents !== newFileContents) {
								// Cheat way to re-generate known-good files
								// uncomment this block, run jake test:spec[compile.js]
								// then re-comment this block. jake test:all should now be happy
								console.log('>>>> writing a new goodFile');
								fs.createReadStream(newFile).pipe(fs.createWriteStream(goodFile));
								goodFileContents = fs.readFileSync(goodFile, 'utf8');
							}
*/
							expect(newFileContents).toNotDiff(goodFileContents, gFile);
						});
					});
				});
			});
		});
	});
});
<commit_msg>trailing slash<commit_after>var fs = require('fs'),
	walkSync = require('walk-sync'),
	path = require('path'),
	os = require('os'),
	colors = require('colors'),
	exec = require('child_process').exec,
	TU = require('../lib/testUtils'),
	CONST = require('../../Alloy/common/constants'),
	_ = require('../../Alloy/lib/alloy/underscore')._,
	tiapp = require('../../Alloy/tiapp'),
	platforms = require('../../platforms/index'),
	sep = process.platform !== 'win32' ? '/' : '\\';

var TIMEOUT_COMPILE = process.platform !== 'win32' ? 10000 : 20000;
var TIMEOUT_PREP = process.platform !== 'win32' ? 10000 : 30000;
var GEN_FOLDER = '_generated';
var TEST_FOLDER = 'testing';
var EXCLUDE_FOLDERS = [
	'ui'+sep+'navwindow/',
	TEST_FOLDER+sep+'ALOY-818/',
	TEST_FOLDER+sep+'ALOY-840/',
	TEST_FOLDER+sep+'ALOY-1080/',
	TEST_FOLDER+sep+'ALOY-932/',
	TEST_FOLDER+sep+'ALOY-961/'
];

/*
// async, so it doesn't complete by the time the tests begin.
// once ALOY-1230 is resolved, rewrite using beforeAll()

// Skip the test that depends on version of SDKs
exec('ti sdk list --output json', function(error, stdout, stderr){
    if (error === null) {
        var sdkInfo = JSON.parse(stdout);

        if (tiapp.version.lt(sdkInfo.activeSDK, '3.6.0') || !sdkInfo) {
        	// Skip ALOY-961 / AttributedString when using pre-3.6.0 SDKs
            EXCLUDE_FOLDERS.push(TEST_FOLDER+sep+'ALOY-961');
        }
    }
});
*/

var alloyRoot = path.join(__dirname,'..','..'),
	paths = {
		apps: path.join(alloyRoot,'test','apps'),
		harness: path.join(alloyRoot,'test','projects','Harness')
	},
	compilerDirectives = (function() {
		var cds = [];
		_.each(_.keys(platforms), function(p) {
			cds.push('OS_' + p.toUpperCase());
		});
		cds.concat(_.pluck(CONST.DEPLOY_TYPES,'key'));
		return cds;
	})(),
	cdRegex = new RegExp('(?:' + compilerDirectives.join('|') + ')');

// The alloy command test suite
describe('alloy compile', function() {
	TU.addMatchers();

	// Iterate through each test app and make sure it compiles for all platforms
	_.each(walkSync(paths.apps), function(file) {
		// are we testing only a specific app?
		if (process.env.app && file !== process.env.app) { return; }

		// TODO: Stop skipping the ui/navwindow test when TiSDK 3.1.3 is in the HarnessTemplate
		//       tiapp.xml. We skip it now because it purposely fails compilation on any SDK below
		//       TiSDK 3.1.3, where Ti.UI.iOS.NavigationWindow was introduced.
		if (_.contains(EXCLUDE_FOLDERS, file)) { return; }

		describe(file.yellow, function() {
			var indexJs = path.join(paths.apps,file,'controllers','index.js');
			if (!path.existsSync(indexJs) || indexJs.indexOf(GEN_FOLDER) !== -1) { return; }

			it('preparing test app', function() {
				TU.asyncExecTest('jake app:setup dir=' + file + ' quiet=1', { timeout: TIMEOUT_PREP });
			});

			_.each(platforms, function(platform,k) {
				if (process.platform !== 'win32' && platform.platform === 'blackberry') {
					return;
				}
				if(process.platform !== 'win32' && platform.platform === 'windows') {
					// skip windows tests on non-Windows computers
					return;
				}

				describe(('[' + platform.platform + ']').cyan, function () {
						it('compiles without critical error',
						function() {
							TU.asyncExecTest(
								'alloy compile ' + paths.harness + ' --config platform=' + platform.platform, {
								test: function() {
									// Make sure there were no compile errors
									if (file === 'testing'+sep+'ALOY-887') {
										// this test specifically tests a compiler error
										expect(this.output.error).toBeTruthy();
									} else {
										// Spit out stderr/stdout, so we can see *why* it failed
										if (this.output.error) {
											console.error(this.output.stderr);
											console.log(this.output.stdout);
										}
										expect(this.output.error).toBeFalsy();
									}
								},
								timeout: TIMEOUT_COMPILE
							}
						);
					});

					it('leaves no compiler directives in generated code', function() {
						var hrDir = path.join(paths.harness,'Resources');
						var cPaths = [
							path.join(hrDir,'alloy'),
							path.join(hrDir,platform.titaniumFolder,'alloy')
						];

						_.each(cPaths, function(cPath) {
							if (file === 'testing'+sep+'ALOY-887') {
								// skip this test since this app forces a compile error
								return;
							}
							if (!fs.existsSync(cPath)) { return; }
							var files = walkSync(cPath);
							_.each(files, function(file) {
								var fullpath = path.join(cPath,file);
								if (!fs.statSync(fullpath).isFile() ||
									!/\.js$/.test(fullpath)) {
									return;
								}
								var content = fs.readFileSync(fullpath, 'utf8');
								expect(cdRegex.test(content)).toBeFalsy();
							});
						});
					});

					it('has no undefined style entries', function() {
						// skip this test, since it specifically tests undefined values in TSS
						if (file === 'testing'+sep+'ALOY-822') {
							return;
						}

						var hrDir = path.join(paths.harness,'Resources');
						var cPaths = [
							path.join(hrDir,'alloy','styles'),
							path.join(hrDir,platform.titaniumFolder,'alloy','styles')
						];

						_.each(cPaths, function(cPath) {
							if (!fs.existsSync(cPath)) { return; }
							var files = walkSync(cPath);
							_.each(files, function(file) {
								var fullpath = path.join(cPath,file);
								if (!fs.statSync(fullpath).isFile() ||
									!/\.js$/.test(fullpath)) {
									return;
								}

								// TODO: Can no longer require() the styles since they
								//       are preprocessed for runtime now. Find a better
								//       way than this lazy text check to verify that
								//       there's no undefined keys in the styles.
								expect(fs.readFileSync(fullpath,'utf8').indexOf('undefined')).toEqual(-1);
								// var json = require(fullpath);
								// expect(json).toHaveNoUndefinedStyles();
							});
						});
					});

					var genFolder = path.join(paths.apps,file,GEN_FOLDER,platform.platform);
					if (!fs.existsSync(genFolder)) { return; }
					var hrFolder = path.join(paths.harness, 'Resources', platform.titaniumFolder);
					var files = walkSync(genFolder);

					// FIXME: Run these comparisons on *every* OS? I assume this was due to windows newline difference?
					/*os.platform() === 'darwin'*/ false && _.each(files, function(gFile) {
						var goodFile = path.join(genFolder,gFile);
						if (!fs.statSync(goodFile).isFile()) { return; }
						var newFile = path.join(hrFolder,gFile);

						it ('generated a ' + gFile.yellow + ' file', function() {
							expect(fs.existsSync(newFile)).toBeTruthy();
						});

						it('matches known good generated code for ' + gFile.yellow, function () {
							var goodFileContents = fs.readFileSync(goodFile, 'utf8');
							var newFileContents = fs.readFileSync(newFile, 'utf8');
/*
							if(goodFileContents !== newFileContents) {
								// Cheat way to re-generate known-good files
								// uncomment this block, run jake test:spec[compile.js]
								// then re-comment this block. jake test:all should now be happy
								console.log('>>>> writing a new goodFile');
								fs.createReadStream(newFile).pipe(fs.createWriteStream(goodFile));
								goodFileContents = fs.readFileSync(goodFile, 'utf8');
							}
*/
							expect(newFileContents).toNotDiff(goodFileContents, gFile);
						});
					});
				});
			});
		});
	});
});
<|endoftext|>


<commit_before>/* global $:false */

// Run this once the window is ready
window.onload = function () {

  'use strict';

  // Setup ////////////////////////////////////////////////////////////////////////////////////////
  // Specify the debug mode and your API's base URL (for your own convenience)
  Bridge.setDebug( true );
  var apiUrl = 'https://192.168.2.34/peir/api/1.0';
  /////////////////////////////////////////////////////////////////////////////////////////////////

  // Just a convenience to dump text to the DOM for this demo:
  function timestamp ( message ) {
    return '
' + new Date().toLocaleTimeString() + ': ' + message + '
';
  }

  // You can listen for each request:
  Bridge.onRequestCalled = function ( method, resource, payload ) {
    $( '#notify' ).prepend( timestamp( 'Request >> ' + method + ' resource ' + resource +
      ' = ' + JSON.stringify( payload ) ) );
  };

  $( '#register' ).click( function ( event ) {

    // Read in the input fields
    var email = $( '#register-email' ).val();
    var password = $( '#register-password' ).val();
    var firstName = $( '#register-first-name' ).val();
    var lastName = $( '#register-last-name' ).val();
    var appData = JSON.parse( $( '#register-app-data' ).val() );

    // Send a register request using Bridge.
    Bridge.register( apiUrl, email, password, firstName, lastName, appData )
      .then( function ( data ) {
        $( '#notify' ).prepend( timestamp( 'Registration successful!' ) );
      } )
      .fail( function ( error ) {
        $( '#notify' ).prepend( timestamp( 'Bridge.register() error!  ' +
          JSON.stringify( Bridge.getErrors().getExplanation( error.errorCode ) ) ) );
        $( '#notify' ).prepend( timestamp( 'Register request failed...' ) );
      } );

  } );

  $( '#verify-email' ).click( function ( event ) {

    // Read in the input fields
    var email = $( '#verify-email-email' ).val();
    var hash = $( '#verify-email-hash' ).val();

    // Send a verify email request using Bridge.
    Bridge.verifyEmail( apiUrl, hash )
      .then( function ( data ) {
        $( '#notify' ).prepend( timestamp( 'Email account verified successfully!' ) );
      } )
      .fail( function ( error ) {
        $( '#notify' ).prepend( timestamp( 'Bridge.verifyEmail() error!  ' +
          JSON.stringify( Bridge.getErrors().getExplanation( error.errorCode ) ) ) );
        $( '#notify' ).prepend( timestamp( 'Verify Email request failed...' ) );
      } );

  } );

  $( '#authenticate' ).click( function ( event ) {

    // Read in the input fields
    var email = $( '#authenticate-email' ).val();
    var password = $( '#authenticate-password' ).val();
    var rememberMe = $( '#authenticate-remember-me' ).prop( 'checked' );

    // Send an authenticate request using Bridge.
    Bridge.authenticate( apiUrl, email, password, rememberMe )
      .then( function ( data ) {
        $( '#notify' ).prepend( timestamp( 'Authentication successful!' ) );
        $( '#notify' ).prepend( timestamp( 'Bridge.getIsAuthenticated() result: ' + Bridge.getIsAuthenticated() ) );
      } )
      .fail( function ( error ) {
        $( '#notify' ).prepend( timestamp( 'Bridge.authenticate() error!  ' +
          JSON.stringify( Bridge.getErrors().getExplanation( error.errorCode ) ) ) );
        $( '#notify' ).prepend( timestamp( 'Authenticate request failed...' ) );
      } );

  } );

  $( '#login' ).click( function ( event ) {

    // Read in the input fields
    var email = $( '#login-email' ).val();
    var password = $( '#login-password' ).val();
    var rememberMe = $( '#login-remember-me' ).prop( 'checked' );

    // Login by authenticating, then getting the user's profile (login() does both itself).
    Bridge.login( apiUrl, email, password, rememberMe )
      .then( function ( data ) {
        $( '#notify' ).prepend( timestamp( 'Login successful!' ) );
        $( '#notify' ).prepend( timestamp( 'Bridge.getIsAuthenticated() result: ' + Bridge.getIsAuthenticated() ) );
        $( '#notify' ).prepend( timestamp( 'Bridge.getIsUserLoggedIn() result: ' + Bridge.getIsUserLoggedIn() ) );
        $( '#notify' ).prepend( timestamp( 'Bridge.getIsUserModified() result: ' + Bridge.getIsUserModified() ) );
      } )
      .fail( function ( error ) {
        $( '#notify' ).prepend( timestamp( 'Bridge.login() error!  ' +
          JSON.stringify( Bridge.getErrors().getExplanation( error.errorCode ) ) ) );
        $( '#notify' ).prepend( timestamp( 'Login request failed...' ) );
      } );

  } );

  $( '#save-user' ).click( function ( event ) {

    // Read in the input fields
    var email = $( '#save-user-email' ).val();
    var currentPassword = $( '#save-user-old-password' ).val();
    var newPassword = $( '#save-user-new-password' ).val();
    var firstName = $( '#save-user-first-name' ).val();
    var lastName = $( '#save-user-last-name' ).val();
    var appData = JSON.parse( $( '#save-user-app-data' ).val() );

    // Send a change password request using Bridge.
    Bridge.saveUser( apiUrl, currentPassword, newPassword )
      .then( function ( data ) {
        $( '#notify' ).prepend( timestamp( 'User Profile Update successful!' ) );
      } )
      .fail( function ( error ) {
        $( '#notify' ).prepend( timestamp( 'Bridge.updateUserProfile() error!  ' +
          JSON.stringify( Bridge.getErrors().getExplanation( error.errorCode ) ) ) );
        $( '#notify' ).prepend( timestamp( 'User Profile Update request failed...' ) );
      } );

  } );

  $( '#forgot-password' ).click( function ( event ) {

    // Read in the input fields
    var email = $( '#forgot-password-email' ).val();

    // Send a recover password request using Bridge.
    Bridge.forgotPassword( apiUrl, email )
      .then( function ( data ) {
        $( '#notify' ).prepend( timestamp( 'Forgot Password successful!' ) );
        $( '#notify' ).prepend( timestamp( 'Password recovery email sent!' ) );
      } )
      .fail( function ( error ) {
        $( '#notify' ).prepend( timestamp( 'Bridge.forgotPassword() error!  ' +
          JSON.stringify( Bridge.getErrors().getExplanation( error.errorCode ) ) ) );
        $( '#notify' ).prepend( timestamp( 'Forgot Password request failed...' ) );
      } );

  } );

  $( '#recover-password' ).click( function ( event ) {

    // Read in the input fields
    var newPassword = $( '#recover-password-new-password' ).val();
    var hash = $( '#recover-password-hash' ).val();

    // Send a recover password request using Bridge.
    Bridge.recoverPassword( apiUrl, newPassword, hash )
      .then( function ( data ) {
        $( '#notify' ).prepend( timestamp( 'Recover Password successful!' ) );
      } )
      .fail( function ( error ) {
        $( '#notify' ).prepend( timestamp( 'Bridge.forgotPassword() error!  ' +
          JSON.stringify( Bridge.getErrors().getExplanation( error.errorCode ) ) ) );
        $( '#notify' ).prepend( timestamp( 'Recover Password failed...' ) );
      } );

  } );

  $( 'load-user' ).click( function ( event ) {

    // Send a recover password request using Bridge.
    Bridge.loadUser( apiUrl )
      .then( function ( data ) {
        $( '#notify' ).prepend( timestamp( 'User Profile Fetch successful!' ) );
        $( '#notify' ).prepend( timestamp( 'Bridge.user: ' + JSON.stringify( Bridge.getUser() ) ) );

      } )
      .fail( function ( error ) {
        $( '#notify' ).prepend( timestamp( 'Bridge.getUserProfile() error!  ' +
          JSON.stringify( Bridge.getErrors().getExplanation( error.errorCode ) ) ) );
        $( '#notify' ).prepend( timestamp( 'User Profile Fetch failed...' ) );
      } );

  } );

  $( '#logout' ).click( function ( event ) {

    Bridge.logout( apiUrl )
      .then( function ( data ) {
        $( '#notify' ).prepend( timestamp( 'Logout successful!' ) );
        $( '#notify' ).prepend( timestamp( 'Bridge.getUser(): ' + JSON.stringify( Bridge.getUser() ) ) );
        $( '#notify' ).prepend( timestamp( 'Bridge.getIsAuthenticated() result: ' + Bridge.getIsAuthenticated() ) );
        $( '#notify' ).prepend( timestamp( 'Bridge.getIsUserLoggedIn() result: ' + Bridge.getIsUserLoggedIn() ) );
        $( '#notify' ).prepend( timestamp( 'Bridge.getIsUserModified() result: ' + Bridge.getIsUserModified() ) );

      } )
      .fail( function ( error ) {
        $( '#notify' ).prepend( timestamp( 'Bridge.logout() error!  ' +
          JSON.stringify( Bridge.getErrors().getExplanation( error.errorCode ) ) ) );
        $( '#notify' ).prepend( timestamp( 'Logout failed...' ) );
      } );
  } );

};
<commit_msg>Nope. didn't fix it. This should, though.<commit_after>/* global $:false */

// Run this once the window is ready
window.onload = function () {

  'use strict';

  // Setup ////////////////////////////////////////////////////////////////////////////////////////
  // Specify the debug mode and your API's base URL (for your own convenience)
  Bridge.setDebug( true );
  var apiUrl = 'https://192.168.2.34/peir/api/1.0';
  /////////////////////////////////////////////////////////////////////////////////////////////////

  // Just a convenience to dump text to the DOM for this demo:
  function timestamp ( message ) {
    return '
' + new Date().toLocaleTimeString() + ': ' + message + '
';
  }

  // You can listen for each request:
  Bridge.onRequestCalled = function ( method, resource, payload ) {
    $( '#notify' ).prepend( timestamp( 'Request >> ' + method + ' resource ' + resource +
      ' = ' + JSON.stringify( payload ) ) );
  };

  $( '#register' ).click( function ( event ) {

    // Read in the input fields
    var email = $( '#register-email' ).val();
    var password = $( '#register-password' ).val();
    var firstName = $( '#register-first-name' ).val();
    var lastName = $( '#register-last-name' ).val();
    var appData = JSON.parse( $( '#register-app-data' ).val() );

    // Send a register request using Bridge.
    Bridge.register( apiUrl, email, password, firstName, lastName, appData )
      .then( function ( data ) {
        $( '#notify' ).prepend( timestamp( 'Registration successful!' ) );
      } )
      .fail( function ( error ) {
        $( '#notify' ).prepend( timestamp( 'Bridge.register() error!  ' +
          JSON.stringify( Bridge.getErrors().getExplanation( error.errorCode ) ) ) );
        $( '#notify' ).prepend( timestamp( 'Register request failed...' ) );
      } );

  } );

  $( '#verify-email' ).click( function ( event ) {

    // Read in the input fields
    var email = $( '#verify-email-email' ).val();
    var hash = $( '#verify-email-hash' ).val();

    // Send a verify email request using Bridge.
    Bridge.verifyEmail( apiUrl, hash )
      .then( function ( data ) {
        $( '#notify' ).prepend( timestamp( 'Email account verified successfully!' ) );
      } )
      .fail( function ( error ) {
        $( '#notify' ).prepend( timestamp( 'Bridge.verifyEmail() error!  ' +
          JSON.stringify( Bridge.getErrors().getExplanation( error.errorCode ) ) ) );
        $( '#notify' ).prepend( timestamp( 'Verify Email request failed...' ) );
      } );

  } );

  $( '#authenticate' ).click( function ( event ) {

    // Read in the input fields
    var email = $( '#authenticate-email' ).val();
    var password = $( '#authenticate-password' ).val();
    var rememberMe = $( '#authenticate-remember-me' ).prop( 'checked' );

    // Send an authenticate request using Bridge.
    Bridge.authenticate( apiUrl, email, password, rememberMe )
      .then( function ( data ) {
        $( '#notify' ).prepend( timestamp( 'Authentication successful!' ) );
        $( '#notify' ).prepend( timestamp( 'Bridge.getIsAuthenticated() result: ' + Bridge.getIsAuthenticated() ) );
      } )
      .fail( function ( error ) {
        $( '#notify' ).prepend( timestamp( 'Bridge.authenticate() error!  ' +
          JSON.stringify( Bridge.getErrors().getExplanation( error.errorCode ) ) ) );
        $( '#notify' ).prepend( timestamp( 'Authenticate request failed...' ) );
      } );

  } );

  $( '#login' ).click( function ( event ) {

    // Read in the input fields
    var email = $( '#login-email' ).val();
    var password = $( '#login-password' ).val();
    var rememberMe = $( '#login-remember-me' ).prop( 'checked' );

    // Login by authenticating, then getting the user's profile (login() does both itself).
    Bridge.login( apiUrl, email, password, rememberMe )
      .then( function ( data ) {
        $( '#notify' ).prepend( timestamp( 'Login successful!' ) );
        $( '#notify' ).prepend( timestamp( 'Bridge.getIsAuthenticated() result: ' + Bridge.getIsAuthenticated() ) );
        $( '#notify' ).prepend( timestamp( 'Bridge.getIsUserLoggedIn() result: ' + Bridge.getIsUserLoggedIn() ) );
        $( '#notify' ).prepend( timestamp( 'Bridge.getIsUserModified() result: ' + Bridge.getIsUserModified() ) );
      } )
      .fail( function ( error ) {
        $( '#notify' ).prepend( timestamp( 'Bridge.login() error!  ' +
          JSON.stringify( Bridge.getErrors().getExplanation( error.errorCode ) ) ) );
        $( '#notify' ).prepend( timestamp( 'Login request failed...' ) );
      } );

  } );

  $( '#save-user' ).click( function ( event ) {

    // Read in the input fields
    var email = $( '#save-user-email' ).val();
    var currentPassword = $( '#save-user-old-password' ).val();
    var newPassword = $( '#save-user-new-password' ).val();
    var firstName = $( '#save-user-first-name' ).val();
    var lastName = $( '#save-user-last-name' ).val();
    var appData = JSON.parse( $( '#save-user-app-data' ).val() );

    // Send a change password request using Bridge.
    Bridge.saveUser( apiUrl, currentPassword, newPassword )
      .then( function ( data ) {
        $( '#notify' ).prepend( timestamp( 'User Profile Update successful!' ) );
      } )
      .fail( function ( error ) {
        $( '#notify' ).prepend( timestamp( 'Bridge.updateUserProfile() error!  ' +
          JSON.stringify( Bridge.getErrors().getExplanation( error.errorCode ) ) ) );
        $( '#notify' ).prepend( timestamp( 'User Profile Update request failed...' ) );
      } );

  } );

  $( '#forgot-password' ).click( function ( event ) {

    // Read in the input fields
    var email = $( '#forgot-password-email' ).val();

    // Send a recover password request using Bridge.
    Bridge.forgotPassword( apiUrl, email )
      .then( function ( data ) {
        $( '#notify' ).prepend( timestamp( 'Forgot Password successful!' ) );
        $( '#notify' ).prepend( timestamp( 'Password recovery email sent!' ) );
      } )
      .fail( function ( error ) {
        $( '#notify' ).prepend( timestamp( 'Bridge.forgotPassword() error!  ' +
          JSON.stringify( Bridge.getErrors().getExplanation( error.errorCode ) ) ) );
        $( '#notify' ).prepend( timestamp( 'Forgot Password request failed...' ) );
      } );

  } );

  $( '#recover-password' ).click( function ( event ) {

    // Read in the input fields
    var newPassword = $( '#recover-password-new-password' ).val();
    var hash = $( '#recover-password-hash' ).val();

    // Send a recover password request using Bridge.
    Bridge.recoverPassword( apiUrl, newPassword, hash )
      .then( function ( data ) {
        $( '#notify' ).prepend( timestamp( 'Recover Password successful!' ) );
      } )
      .fail( function ( error ) {
        $( '#notify' ).prepend( timestamp( 'Bridge.forgotPassword() error!  ' +
          JSON.stringify( Bridge.getErrors().getExplanation( error.errorCode ) ) ) );
        $( '#notify' ).prepend( timestamp( 'Recover Password failed...' ) );
      } );

  } );

  $( '#load-user' ).click( function ( event ) {

    // Send a recover password request using Bridge.
    Bridge.loadUser( apiUrl )
      .then( function ( data ) {
        $( '#notify' ).prepend( timestamp( 'User Profile Fetch successful!' ) );
        $( '#notify' ).prepend( timestamp( 'Bridge.user: ' + JSON.stringify( Bridge.getUser() ) ) );

      } )
      .fail( function ( error ) {
        $( '#notify' ).prepend( timestamp( 'Bridge.getUserProfile() error!  ' +
          JSON.stringify( Bridge.getErrors().getExplanation( error.errorCode ) ) ) );
        $( '#notify' ).prepend( timestamp( 'User Profile Fetch failed...' ) );
      } );

  } );

  $( '#logout' ).click( function ( event ) {

    Bridge.logout( apiUrl )
      .then( function ( data ) {
        $( '#notify' ).prepend( timestamp( 'Logout successful!' ) );
        $( '#notify' ).prepend( timestamp( 'Bridge.getUser(): ' + JSON.stringify( Bridge.getUser() ) ) );
        $( '#notify' ).prepend( timestamp( 'Bridge.getIsAuthenticated() result: ' + Bridge.getIsAuthenticated() ) );
        $( '#notify' ).prepend( timestamp( 'Bridge.getIsUserLoggedIn() result: ' + Bridge.getIsUserLoggedIn() ) );
        $( '#notify' ).prepend( timestamp( 'Bridge.getIsUserModified() result: ' + Bridge.getIsUserModified() ) );

      } )
      .fail( function ( error ) {
        $( '#notify' ).prepend( timestamp( 'Bridge.logout() error!  ' +
          JSON.stringify( Bridge.getErrors().getExplanation( error.errorCode ) ) ) );
        $( '#notify' ).prepend( timestamp( 'Logout failed...' ) );
      } );
  } );

};
<|endoftext|>


<commit_before>var vows = require('vows');
var assert = require('assert');
var util = require('util');
var WindowsLiveStrategy = require('passport-windowslive/strategy');

vows.describe('WindowsLiveStrategy').addBatch({

  'strategy': {
    topic: function() {
      return new WindowsLiveStrategy({
        clientID: 'ABC123',
        clientSecret: 'secret'
      },
      function() {});
    },

    'should be named windowslive': function (strategy) {
      assert.equal(strategy.name, 'windowslive');
    },
  },

  'strategy when loading user profile': {
    topic: function() {
      var strategy = new WindowsLiveStrategy({
        clientID: 'ABC123',
        clientSecret: 'secret'
      },
      function() {});

      // mock
      strategy._oauth2.get = function(url, accessToken, callback) {
        var body = '{ \
           "id": "8c8ce076ca27823f", \
           "name": "Roberto Tamburello", \
           "first_name": "Roberto", \
           "last_name": "Tamburello", \
           "link": "http://cid-8c8ce076ca27823f.profile.live.com/", \
           "birth_day": 20, \
           "birth_month": 4, \
           "birth_year": 2010, \
           "work": [ \
              { \
                 "employer": { \
                    "name": "Microsoft Corporation" \
                 }, \
                 "position": { \
                    "name": "Software Development Engineer" \
                 } \
              } \
           ], \
           "gender": "male", \
           "emails": { \
              "preferred": "Roberto@contoso.com", \
              "account": "Roberto@contoso.com", \
              "personal": "Roberto@fabrikam.com", \
              "business": "Robert@adatum.com", \
              "other": "Roberto@adventure-works.com" \
           }, \
           "addresses": { \
              "personal": { \
                 "street": "123 Main St.", \
                 "street_2": "Apt. A", \
                 "city": "Redmond", \
                 "state": "WA", \
                 "postal_code": "12990", \
                 "region": "United States" \
              }, \
              "business": { \
                 "street": "456 Anywhere St.", \
                 "street_2": "Suite 1", \
                 "city": "Redmond", \
                 "state": "WA", \
                 "postal_code": "12399", \
                 "region": "United States" \
              } \
           }, \
           "phones": { \
              "personal": "(555) 555-1212", \
              "business": "(555) 111-1212", \
              "mobile": null \
           }, \
           "locale": "en_US", \
           "updated_time": "2011-04-21T23:55:34+0000" \
        }';

        callback(null, body, undefined);
      }

      return strategy;
    },

    'when told to load user profile': {
      topic: function(strategy) {
        var self = this;
        function done(err, profile) {
          self.callback(err, profile);
        }

        process.nextTick(function () {
          strategy.userProfile('access-token', done);
        });
      },

      'should not error' : function(err, req) {
        assert.isNull(err);
      },
      'should load profile' : function(err, profile) {
        assert.equal(profile.provider, 'windowslive');
        assert.equal(profile.id, '8c8ce076ca27823f');
        assert.equal(profile.displayName, 'Roberto Tamburello');
        assert.equal(profile.name.familyName, 'Tamburello');
        assert.equal(profile.name.givenName, 'Roberto');
      },
      'should set raw property' : function(err, profile) {
        assert.isString(profile._raw);
      },
      'should set json property' : function(err, profile) {
        assert.isObject(profile._json);
      },
    },
  },

  'strategy when loading user profile and encountering an error': {
    topic: function() {
      var strategy = new WindowsLiveStrategy({
        clientID: 'ABC123',
        clientSecret: 'secret'
      },
      function() {});

      // mock
      strategy._oauth2.get = function(url, accessToken, callback) {
        callback(new Error('something-went-wrong'));
      }

      return strategy;
    },

    'when told to load user profile': {
      topic: function(strategy) {
        var self = this;
        function done(err, profile) {
          self.callback(err, profile);
        }

        process.nextTick(function () {
          strategy.userProfile('access-token', done);
        });
      },

      'should error' : function(err, req) {
        assert.isNotNull(err);
      },
      'should wrap error in InternalOAuthError' : function(err, req) {
        assert.equal(err.constructor.name, 'InternalOAuthError');
      },
      'should not load profile' : function(err, profile) {
        assert.isUndefined(profile);
      },
    },
  },

}).export(module);
<commit_msg>Add test case for profile photo.<commit_after>var vows = require('vows');
var assert = require('assert');
var util = require('util');
var WindowsLiveStrategy = require('passport-windowslive/strategy');

vows.describe('WindowsLiveStrategy').addBatch({

  'strategy': {
    topic: function() {
      return new WindowsLiveStrategy({
        clientID: 'ABC123',
        clientSecret: 'secret'
      },
      function() {});
    },

    'should be named windowslive': function (strategy) {
      assert.equal(strategy.name, 'windowslive');
    },
  },

  'strategy when loading user profile': {
    topic: function() {
      var strategy = new WindowsLiveStrategy({
        clientID: 'ABC123',
        clientSecret: 'secret'
      },
      function() {});

      // mock
      strategy._oauth2.get = function(url, accessToken, callback) {
        var body = '{ \
           "id": "8c8ce076ca27823f", \
           "name": "Roberto Tamburello", \
           "first_name": "Roberto", \
           "last_name": "Tamburello", \
           "link": "http://cid-8c8ce076ca27823f.profile.live.com/", \
           "birth_day": 20, \
           "birth_month": 4, \
           "birth_year": 2010, \
           "work": [ \
              { \
                 "employer": { \
                    "name": "Microsoft Corporation" \
                 }, \
                 "position": { \
                    "name": "Software Development Engineer" \
                 } \
              } \
           ], \
           "gender": "male", \
           "emails": { \
              "preferred": "Roberto@contoso.com", \
              "account": "Roberto@contoso.com", \
              "personal": "Roberto@fabrikam.com", \
              "business": "Robert@adatum.com", \
              "other": "Roberto@adventure-works.com" \
           }, \
           "addresses": { \
              "personal": { \
                 "street": "123 Main St.", \
                 "street_2": "Apt. A", \
                 "city": "Redmond", \
                 "state": "WA", \
                 "postal_code": "12990", \
                 "region": "United States" \
              }, \
              "business": { \
                 "street": "456 Anywhere St.", \
                 "street_2": "Suite 1", \
                 "city": "Redmond", \
                 "state": "WA", \
                 "postal_code": "12399", \
                 "region": "United States" \
              } \
           }, \
           "phones": { \
              "personal": "(555) 555-1212", \
              "business": "(555) 111-1212", \
              "mobile": null \
           }, \
           "locale": "en_US", \
           "updated_time": "2011-04-21T23:55:34+0000" \
        }';

        callback(null, body, undefined);
      }

      return strategy;
    },

    'when told to load user profile': {
      topic: function(strategy) {
        var self = this;
        function done(err, profile) {
          self.callback(err, profile);
        }

        process.nextTick(function () {
          strategy.userProfile('access-token', done);
        });
      },

      'should not error' : function(err, req) {
        assert.isNull(err);
      },
      'should load profile' : function(err, profile) {
        assert.equal(profile.provider, 'windowslive');
        assert.equal(profile.id, '8c8ce076ca27823f');
        assert.equal(profile.displayName, 'Roberto Tamburello');
        assert.equal(profile.name.familyName, 'Tamburello');
        assert.equal(profile.name.givenName, 'Roberto');
        assert.lengthOf(profile.photos, 1);
        assert.equal(profile.photos[0].value, 'https://apis.live.net/v5.0/8c8ce076ca27823f/picture');
      },
      'should set raw property' : function(err, profile) {
        assert.isString(profile._raw);
      },
      'should set json property' : function(err, profile) {
        assert.isObject(profile._json);
      },
    },
  },

  'strategy when loading user profile and encountering an error': {
    topic: function() {
      var strategy = new WindowsLiveStrategy({
        clientID: 'ABC123',
        clientSecret: 'secret'
      },
      function() {});

      // mock
      strategy._oauth2.get = function(url, accessToken, callback) {
        callback(new Error('something-went-wrong'));
      }

      return strategy;
    },

    'when told to load user profile': {
      topic: function(strategy) {
        var self = this;
        function done(err, profile) {
          self.callback(err, profile);
        }

        process.nextTick(function () {
          strategy.userProfile('access-token', done);
        });
      },

      'should error' : function(err, req) {
        assert.isNotNull(err);
      },
      'should wrap error in InternalOAuthError' : function(err, req) {
        assert.equal(err.constructor.name, 'InternalOAuthError');
      },
      'should not load profile' : function(err, profile) {
        assert.isUndefined(profile);
      },
    },
  },

}).export(module);
<|endoftext|>


<commit_before>// Dependencies
var Lien = require("../lib/index");

// Init lien server
var server = new Lien({
    host: "localhost"
  , port: 9000
});

// Add page
server.page.add("/", function (lien) {
    lien.file("/index.html");
});
<commit_msg>Updated the example<commit_after>// Dependencies
var Lien = require("../lib/index");

// Init lien server
var server = new Lien({
    host: "localhost"
  , port: 9000
});

// Listen for load
server.on("load", function (err) {
    console.log(err || "Server started on port 9000.");
    err && process.exit(1);
});

// Add page
server.page.add("/", function (lien) {
    lien.file("/index.html");
});
<|endoftext|>


<commit_before>'use strict';
const extend = require('gextend');
const Server = require('..').init;

let context = {
    getLogger: ()=> console,
    resolve: ()=> Promise.resolve(),
    hook: (e, configurator)=>{
        context['_server.pre'](configurator);
        return Promise.resolve();
    },
    on: (e, c)=>{
        console.log('context.on', e);
        context['_' + e] = c;
    },
    emit: (e, p)=>{
        console.log('context.emit', e);
    }
};

const MyApp = require('..').initializeSubapp('root');

let _data = {
    _i: 1,
    1: {
        id: 1,
        email: 'hello@goliatone.com'
    }
};

MyApp(context, {
    moduleid: 'myapp',
    basedir: './myapp',
    mount: '/',
    routes: {
        path: ['./myapp/routes']
    },
    locals: {
        title: 'MyApp Test'
    },
    passport: {
        findUserById: function(id){
            return Promise.resolve(_data[id]);
        },
        findUserBy: function(prop, val){
            return Promise.resolve(_data[2]);
        },
        createUser: function(user){
            console.log('createUser', JSON.stringify(user, null, 4));

            const cryptoUtils = require('./myapp/middleware/core.io-auth/cryptoUtils');
            ++_data._i;
            let i = _data._i;
            user.id = i;
            _data[i] = user;

            return cryptoUtils.hash(user).then((user)=>{
                console.log('Added user:', user);
                console.log(Object.keys(_data));
                return user;
            });
        },
        cleanUser: function(user){
            let clone = extend({}, user);
            delete clone.password;
            return clone;
        }
    },
    policies: {
        'GET /hello': [
            require('./myapp/middleware/isAuthenticated')
        ],
    },
    middleware: {
        passport: require('./myapp/middleware/core.io-auth'),
        /*
         * This actually indicates which middleware
         * to use.
         */
        use: [
            'poweredBy',
            'compression',
            'viewEngine',
            'logger',
            'favicon',
            'bodyParser',
            'cookieParser',
            'session',
            // 'isAuthenticated',
            'passport',
            'flash',
            'expressStatic',
            'expressLayouts',
            'appVariables',
            'routes',
            'locals'
        ]
    }
});

Server(context, {});
<commit_msg>fix order of middleware<commit_after>'use strict';
const extend = require('gextend');
const Server = require('..').init;

let context = {
    getLogger: ()=> console,
    resolve: ()=> Promise.resolve(),
    hook: (e, configurator)=>{
        context['_server.pre'](configurator);
        return Promise.resolve();
    },
    on: (e, c)=>{
        console.log('context.on', e);
        context['_' + e] = c;
    },
    emit: (e, p)=>{
        console.log('context.emit', e);
    }
};

const MyApp = require('..').initializeSubapp('root');

let _data = {
    _i: 1,
    1: {
        id: 1,
        email: 'hello@goliatone.com'
    }
};

MyApp(context, {
    moduleid: 'myapp',
    basedir: './myapp',
    mount: '/',
    routes: {
        path: ['./myapp/routes']
    },
    locals: {
        title: 'MyApp Test'
    },
    passport: {
        findUserById: function(id){
            return Promise.resolve(_data[id]);
        },
        findUserBy: function(prop, val){
            return Promise.resolve(_data[2]);
        },
        createUser: function(user){
            console.log('createUser', JSON.stringify(user, null, 4));

            const cryptoUtils = require('./myapp/middleware/core.io-auth/cryptoUtils');
            ++_data._i;
            let i = _data._i;
            user.id = i;
            _data[i] = user;

            return cryptoUtils.hash(user).then((user)=>{
                console.log('Added user:', user);
                console.log(Object.keys(_data));
                return user;
            });
        },
        cleanUser: function(user){
            let clone = extend({}, user);
            delete clone.password;
            return clone;
        }
    },
    policies: {
        'GET /hello': [
            require('./myapp/middleware/isAuthenticated')
        ],
    },
    middleware: {
        passport: require('./myapp/middleware/core.io-auth'),
        /*
         * This actually indicates which middleware
         * to use.
         */
        use: [
            'poweredBy',
            'compression',
            'viewEngine',
            'logger',
            'favicon',
            'bodyParser',
            'cookieParser',
            'session',
            // 'isAuthenticated',
            'flash',
            'passport',
            'expressStatic',
            'expressLayouts',
            'appVariables',
            'routes',
            'locals'
        ]
    }
});

Server(context, {});
<|endoftext|>