<commit_before>/* global Module */

/* MMM-RottenTomatoes.js
 *
 * Magic Mirror
 * Module: MMM-RottenTomatoes
 *
 * Magic Mirror By Michael Teeuw http://michaelteeuw.nl
 * MIT Licensed.
 *
 * Module MMM-RottenTomatoes By Adam Moses http://adammoses.com
 * MIT Licensed.
 */

Module.register("MMM-RottenTomatoes", {
	// setup the default config options
	defaults: {
		// optional
		showHeader: true,
		showOpeningThisWeek: true,
		showBoxOffice: true,
		showComingSoon: true,
		limitOpeningThisWeek: 5,
		limitBoxOffice: 5,
		limitComingSoon: 3,
		boxOfficeAfter: true,
		mergeOpeningAndComingSoon: true,
	},
	// the start function
	start: function() {
		// log starting
		Log.info("Starting module: " + this.name);
		// set refresh rate to 12 hours
		this.config.refreshRate = 12 * 60 * 60 * 1000;
        // set an identier config tag
		this.config.identifier = this.identifier;
		// set loaded, error, and the update to init values
		this.loaded = false;
		this.errorMessage = null;
		// set the header to this place
        if (this.config.showHeader) {
            this.data.header = 'Rotten Tomatoes';
        }
		if (this.config.limitOpeningThisWeek == 0)
			this.config.limitOpeningThisWeek = 100;
		if (this.config.limitBoxOffice == 0)
			this.config.limitBoxOffice = 100;
		if (this.config.limitComingSoon == 0)
			this.config.limitComingSoon = 100;
        // add this config to the helper functions
		this.sendSocketNotification('ROTTEN_TOMATOES_REGISTER_CONFIG', this.config);
	},
	// the socket handler
	socketNotificationReceived: function(notification, payload) {
		// if an update was received
		if (notification === "ROTTEN_TOMATOES_UPDATE") {
			// check this is for this module based on the woeid
			if (payload.identifier === this.identifier)
			{
				// set loaded flag, set the update, and call update dom
				this.rtData = payload.rtData;
                this.loaded = true;
                this.updateDom();
			}
		}
        // if sent error notice
        if (notification === "ROTTEN_TOMATOES_TOO_MANY_ERRORS") {
            this.errorMessage("There was an error.");
            if (this.updateTimer !== null)
                clearTimeout(this.updateTimer);
            this.updateTimer = null;
            this.updateDom();
        }
	},
	//
	cleanScore: function(theScore) {
		if (theScore.indexOf('%') == -1)
			return '--';
		else
			return theScore;
	},
	// the get dom handler
	getDom: function() {
        // if an error, say so
        if (this.errorMessage !== null) {
            var wrapper = document.createElement("div");
			wrapper.className = "small";
			wrapper.innerHTML = this.errorMessage;
			return wrapper;
        }
		// if nothing loaded yet, put in placeholder text
		if (!this.loaded) {
			var wrapper = document.createElement("div");
			wrapper.className = "small";
			wrapper.innerHTML = "Awaiting Update...";
			return wrapper;
		}
		var titleSize = 'small';
		var movieSize = 'xsmall';
		var wrapper = document.createElement("table");
		// do opening this week
		var allOTWandCSRows = [ ];
		if (this.config.showOpeningThisWeek) {
			var otwData = this.rtData.openingThisWeek;
			var otwTitleTR = document.createElement("tr");
			otwTitleTR.className = titleSize;
			var otwTitleTD = document.createElement("td");
			otwTitleTD.innerHTML = "Opening This Week";
			if (this.config.mergeOpeningAndComingSoon)
				otwTitleTD.innerHTML = "Opening / Coming Soon";
			otwTitleTD.colSpan = "3";
			otwTitleTR.appendChild(otwTitleTD);
			allOTWandCSRows.push(otwTitleTR);
			for (var cIndex = 0;
					(cIndex < otwData.length) && (cIndex < this.config.limitOpeningThisWeek);
					cIndex++) {
				var cOTW = otwData[cIndex];
				var otwRowTR = document.createElement("tr");
				otwRowTR.className = movieSize;
				var otwRowMeter = document.createElement("td");
				otwRowMeter.innerHTML = this.cleanScore(cOTW.meter) + "  ";
				otwRowTR.appendChild(otwRowMeter);
				var otwRowTitle = document.createElement("td");
				otwRowTitle.innerHTML = cOTW.title + "  ";
				otwRowTitle.align = 'left';
				otwRowTR.appendChild(otwRowTitle);
				var otwRowDate = document.createElement("td");
				otwRowDate.innerHTML = "  " + cOTW.date;
				otwRowTR.appendChild(otwRowDate);
				allOTWandCSRows.push(otwRowTR);
			}
		}
		// do opening this week
		if (this.config.showOpeningThisWeek) {
			var csData = this.rtData.comingSoon;
			var csTitleTR = document.createElement("tr");
			csTitleTR.className = titleSize;
			var csTitleTD = document.createElement("td");
			csTitleTD.innerHTML = "Coming Soon";
			csTitleTD.colSpan = "3";
			csTitleTR.appendChild(csTitleTD);
			if (!this.config.mergeOpeningAndComingSoon)
				allOTWandCSRows.push(csTitleTR);
			for (var cIndex = 0;
					(cIndex < csData.length) && (cIndex < this.config.limitComingSoon);
					cIndex++) {
				var ccs = csData[cIndex];
				var csRowTR = document.createElement("tr");
				csRowTR.className = movieSize;
				var csRowMeter = document.createElement("td");
				csRowMeter.innerHTML = this.cleanScore(ccs.meter) + "  ";
				csRowTR.appendChild(csRowMeter);
				var csRowTitle = document.createElement("td");
				csRowTitle.innerHTML = ccs.title + "  ";
				csRowTitle.align = 'left';
				csRowTR.appendChild(csRowTitle);
				var csRowDate = document.createElement("td");
				csRowDate.innerHTML = "  " + ccs.date;
				csRowTR.appendChild(csRowDate);
				allOTWandCSRows.push(csRowTR);
			}
		}
		// do box office
		var boRows = [ ];
		if (this.config.showBoxOffice) {
			var boData = this.rtData.boxOffice;
			var boTitleTR = document.createElement("tr");
			boTitleTR.className = titleSize;
			var boTitleTD = document.createElement("td");
			boTitleTD.innerHTML = "Box Office";
			boTitleTD.width = "250px";
			boTitleTD.colSpan = "3";
			boTitleTR.appendChild(boTitleTD);
			boRows.push(boTitleTR);
			for (var cIndex = 0;
					(cIndex < boData.length) && (cIndex < this.config.limitBoxOffice);
					cIndex++) {
				var cbo = boData[cIndex];
				var boRowTR = document.createElement("tr");
				boRowTR.className = movieSize;
				var boRowMeter = document.createElement("td");
				boRowMeter.innerHTML = this.cleanScore(cbo.meter) + "  ";
				boRowTR.appendChild(boRowMeter);
				var boRowTitle = document.createElement("td");
				boRowTitle.innerHTML = cbo.title + "  ";
				boRowTitle.align = 'left';
				boRowTR.appendChild(boRowTitle);
				var boRowGross = document.createElement("td");
				boRowGross.innerHTML = "  " + cbo.gross;
				boRowTR.appendChild(boRowGross);
				boRows.push(boRowTR);
			}
		}
		// build the table
        var allRows = [ ];
        // if set to show box office first, do that
		if (!this.config.boxOfficeAfter)
			allRows = allRows.concat(boRows);
        // add opening this week and coming soon rows
		allRows = allRows.concat(allOTWandCSRows);
        // if set to show box office after, do that
		if (this.config.boxOfficeAfter)
			allRows = allRows.concat(boRows);
        // add all rows to the return table wrapper
		for (var cIndex = 0; cIndex < allRows.length; cIndex++) {
			wrapper.appendChild(allRows[cIndex]);
		}
        // return table wrapper
		return wrapper;
	}
});

// ------------ end -------------
<commit_msg>small style changes<commit_after>/* global Module */

/* MMM-RottenTomatoes.js
 *
 * Magic Mirror
 * Module: MMM-RottenTomatoes
 *
 * Magic Mirror By Michael Teeuw http://michaelteeuw.nl
 * MIT Licensed.
 *
 * Module MMM-RottenTomatoes By Adam Moses http://adammoses.com
 * MIT Licensed.
 */

Module.register("MMM-RottenTomatoes", {
	// setup the default config options
	defaults: {
		// optional
		showHeader: true,
		showOpeningThisWeek: true,
		showBoxOffice: true,
		showComingSoon: true,
		limitOpeningThisWeek: 4,
		limitBoxOffice: 3,
		limitComingSoon: 3,
		boxOfficeAfter: true,
		mergeOpeningAndComingSoon: true,
	},
	// the start function
	start: function() {
		// log starting
		Log.info("Starting module: " + this.name);
		// set refresh rate to 12 hours
		this.config.refreshRate = 12 * 60 * 60 * 1000;
        // set an identier config tag
		this.config.identifier = this.identifier;
		// set loaded, error, and the update to init values
		this.loaded = false;
		this.errorMessage = null;
		// set the header to this place
        if (this.config.showHeader) {
            this.data.header = 'Rotten Tomatoes';
        }
		if (this.config.limitOpeningThisWeek == 0)
			this.config.limitOpeningThisWeek = 100;
		if (this.config.limitBoxOffice == 0)
			this.config.limitBoxOffice = 100;
		if (this.config.limitComingSoon == 0)
			this.config.limitComingSoon = 100;
        // add this config to the helper functions
		this.sendSocketNotification('ROTTEN_TOMATOES_REGISTER_CONFIG', this.config);
	},
	// the socket handler
	socketNotificationReceived: function(notification, payload) {
		// if an update was received
		if (notification === "ROTTEN_TOMATOES_UPDATE") {
			// check this is for this module based on the woeid
			if (payload.identifier === this.identifier)
			{
				// set loaded flag, set the update, and call update dom
				this.rtData = payload.rtData;
                this.loaded = true;
                this.updateDom();
			}
		}
        // if sent error notice
        if (notification === "ROTTEN_TOMATOES_TOO_MANY_ERRORS") {
            this.errorMessage("There was an error.");
            if (this.updateTimer !== null)
                clearTimeout(this.updateTimer);
            this.updateTimer = null;
            this.updateDom();
        }
	},
	//
	cleanScore: function(theScore) {
		if (theScore.indexOf('%') == -1)
			return '--';
		else
			return theScore;
	},
	// the get dom handler
	getDom: function() {
        // if an error, say so
        if (this.errorMessage !== null) {
            var wrapper = document.createElement("div");
			wrapper.className = "small";
			wrapper.innerHTML = this.errorMessage;
			return wrapper;
        }
		// if nothing loaded yet, put in placeholder text
		if (!this.loaded) {
			var wrapper = document.createElement("div");
			wrapper.className = "small";
			wrapper.innerHTML = "Awaiting Update...";
			return wrapper;
		}
		var titleSize = 'xsmall';
		var movieSize = 'xsmall';
		var wrapper = document.createElement("table");
		// do opening this week
		var allOTWandCSRows = [ ];
		if (this.config.showOpeningThisWeek) {
			var otwData = this.rtData.openingThisWeek;
			var otwTitleTR = document.createElement("tr");
			otwTitleTR.className = titleSize;
			var otwTitleTD = document.createElement("td");
			otwTitleTD.innerHTML = "Opening This Week";
			if (this.config.mergeOpeningAndComingSoon)
				otwTitleTD.innerHTML = "Opening / Coming Soon";
			otwTitleTD.colSpan = "3";
			otwTitleTR.appendChild(otwTitleTD);
			allOTWandCSRows.push(otwTitleTR);
			for (var cIndex = 0;
					(cIndex < otwData.length) && (cIndex < this.config.limitOpeningThisWeek);
					cIndex++) {
				var cOTW = otwData[cIndex];
				var otwRowTR = document.createElement("tr");
				otwRowTR.className = movieSize;
				var otwRowMeter = document.createElement("td");
				otwRowMeter.innerHTML = this.cleanScore(cOTW.meter) + "  ";
				otwRowTR.appendChild(otwRowMeter);
				var otwRowTitle = document.createElement("td");
				otwRowTitle.innerHTML = cOTW.title + "  ";
				otwRowTitle.align = 'left';
				otwRowTR.appendChild(otwRowTitle);
				var otwRowDate = document.createElement("td");
				otwRowDate.innerHTML = "  " + cOTW.date;
				otwRowTR.appendChild(otwRowDate);
				allOTWandCSRows.push(otwRowTR);
			}
		}
		// do opening this week
		if (this.config.showOpeningThisWeek) {
			var csData = this.rtData.comingSoon;
			var csTitleTR = document.createElement("tr");
			csTitleTR.className = titleSize;
			var csTitleTD = document.createElement("td");
			csTitleTD.innerHTML = "Coming Soon";
			csTitleTD.colSpan = "3";
			csTitleTR.appendChild(csTitleTD);
			if (!this.config.mergeOpeningAndComingSoon)
				allOTWandCSRows.push(csTitleTR);
			for (var cIndex = 0;
					(cIndex < csData.length) && (cIndex < this.config.limitComingSoon);
					cIndex++) {
				var ccs = csData[cIndex];
				var csRowTR = document.createElement("tr");
				csRowTR.className = movieSize;
				var csRowMeter = document.createElement("td");
				csRowMeter.innerHTML = this.cleanScore(ccs.meter) + "  ";
				csRowTR.appendChild(csRowMeter);
				var csRowTitle = document.createElement("td");
				csRowTitle.innerHTML = ccs.title + "  ";
				csRowTitle.align = 'left';
				csRowTR.appendChild(csRowTitle);
				var csRowDate = document.createElement("td");
				csRowDate.innerHTML = "  " + ccs.date;
				csRowTR.appendChild(csRowDate);
				allOTWandCSRows.push(csRowTR);
			}
		}
		// do box office
		var boRows = [ ];
		if (this.config.showBoxOffice) {
			var boData = this.rtData.boxOffice;
			var boTitleTR = document.createElement("tr");
			boTitleTR.className = titleSize;
			var boTitleTD = document.createElement("td");
			boTitleTD.innerHTML = "Box Office";
			boTitleTD.width = "250px";
			boTitleTD.colSpan = "3";
			boTitleTR.appendChild(boTitleTD);
			boRows.push(boTitleTR);
			for (var cIndex = 0;
					(cIndex < boData.length) && (cIndex < this.config.limitBoxOffice);
					cIndex++) {
				var cbo = boData[cIndex];
				var boRowTR = document.createElement("tr");
				boRowTR.className = movieSize;
				var boRowMeter = document.createElement("td");
				boRowMeter.innerHTML = this.cleanScore(cbo.meter) + "  ";
				boRowTR.appendChild(boRowMeter);
				var boRowTitle = document.createElement("td");
				boRowTitle.innerHTML = cbo.title + "  ";
				boRowTitle.align = 'left';
				boRowTR.appendChild(boRowTitle);
				var boRowGross = document.createElement("td");
				boRowGross.innerHTML = "  " + cbo.gross;
				boRowTR.appendChild(boRowGross);
				boRows.push(boRowTR);
			}
		}
		// build the table
        var allRows = [ ];
        // if set to show box office first, do that
		if (!this.config.boxOfficeAfter)
			allRows = allRows.concat(boRows);
        // add opening this week and coming soon rows
		allRows = allRows.concat(allOTWandCSRows);
        // if set to show box office after, do that
		if (this.config.boxOfficeAfter)
			allRows = allRows.concat(boRows);
        // add all rows to the return table wrapper
		for (var cIndex = 0; cIndex < allRows.length; cIndex++) {
			wrapper.appendChild(allRows[cIndex]);
		}
        // return table wrapper
		return wrapper;
	}
});

// ------------ end -------------
<|endoftext|>


<commit_before>define("dijit/form/_TextBoxMixin", ["dojo", "dijit"], function(dojo, dijit) {

dojo.declare( "dijit.form._TextBoxMixin", null, {
	// summary:
	//		A mixin for textbox form input widgets

	// trim: Boolean
	//		Removes leading and trailing whitespace if true.  Default is false.
	trim: false,

	// uppercase: Boolean
	//		Converts all characters to uppercase if true.  Default is false.
	uppercase: false,

	// lowercase: Boolean
	//		Converts all characters to lowercase if true.  Default is false.
	lowercase: false,

	// propercase: Boolean
	//		Converts the first character of each word to uppercase if true.
	propercase: false,

	// maxLength: String
	//		HTML INPUT tag maxLength declaration.
	maxLength: "",

	// selectOnClick: [const] Boolean
	//		If true, all text will be selected when focused with mouse
	selectOnClick: false,

	// placeHolder: String
	//		Defines a hint to help users fill out the input field (as defined in HTML 5).
	//		This should only contain plain text (no html markup).
	placeHolder: "",

	_getValueAttr: function(){
		// summary:
		//		Hook so get('value') works as we like.
		// description:
		//		For `dijit.form.TextBox` this basically returns the value of the <input>.
		//
		//		For `dijit.form.MappedTextBox` subclasses, which have both
		//		a "displayed value" and a separate "submit value",
		//		This treats the "displayed value" as the master value, computing the
		//		submit value from it via this.parse().
		return this.parse(this.get('displayedValue'), this.constraints);
	},

	_setValueAttr: function(value, /*Boolean?*/ priorityChange, /*String?*/ formattedValue){
		// summary:
		//		Hook so set('value', ...) works.
		//
		// description:
		//		Sets the value of the widget to "value" which can be of
		//		any type as determined by the widget.
		//
		// value:
		//		The visual element value is also set to a corresponding,
		//		but not necessarily the same, value.
		//
		// formattedValue:
		//		If specified, used to set the visual element value,
		//		otherwise a computed visual value is used.
		//
		// priorityChange:
		//		If true, an onChange event is fired immediately instead of
		//		waiting for the next blur event.

		var filteredValue;
		if(value !== undefined){
			// TODO: this is calling filter() on both the display value and the actual value.
			// I added a comment to the filter() definition about this, but it should be changed.
			filteredValue = this.filter(value);
			if(typeof formattedValue != "string"){
				if(filteredValue !== null && ((typeof filteredValue != "number") || !isNaN(filteredValue))){
					formattedValue = this.filter(this.format(filteredValue, this.constraints));
				}else{ formattedValue = ''; }
			}
		}
		if(formattedValue != null && formattedValue != undefined && ((typeof formattedValue) != "number" || !isNaN(formattedValue)) && this.textbox.value != formattedValue){
			this.textbox.value = formattedValue;
			this._set("displayedValue", this.get("displayedValue"));
		}

		if(this.textDir == "auto"){
			this.applyTextDir(this.focusNode, formattedValue);
		}

		this.inherited(arguments, [filteredValue, priorityChange]);
	},

	// displayedValue: String
	//		For subclasses like ComboBox where the displayed value
	//		(ex: Kentucky) and the serialized value (ex: KY) are different,
	//		this represents the displayed value.
	//
	//		Setting 'displayedValue' through set('displayedValue', ...)
	//		updates 'value', and vice-versa.  Otherwise 'value' is updated
	//		from 'displayedValue' periodically, like onBlur etc.
	//
	//		TODO: move declaration to MappedTextBox?
	//		Problem is that ComboBox references displayedValue,
	//		for benefit of FilteringSelect.
	displayedValue: "",

	_getDisplayedValueAttr: function(){
		// summary:
		//		Hook so get('displayedValue') works.
		// description:
		//		Returns the displayed value (what the user sees on the screen),
		// 		after filtering (ie, trimming spaces etc.).
		//
		//		For some subclasses of TextBox (like ComboBox), the displayed value
		//		is different from the serialized value that's actually
		//		sent to the server (see dijit.form.ValidationTextBox.serialize)

		// TODO: maybe we should update this.displayedValue on every keystroke so that we don't need
		// this method
		// TODO: this isn't really the displayed value when the user is typing
		return this.filter(this.textbox.value);
	},

	_setDisplayedValueAttr: function(/*String*/ value){
		// summary:
		//		Hook so set('displayedValue', ...) works.
		// description:
		//		Sets the value of the visual element to the string "value".
		//		The widget value is also set to a corresponding,
		//		but not necessarily the same, value.

		if(value === null || value === undefined){ value = '' }
		else if(typeof value != "string"){ value = String(value) }

		this.textbox.value = value;

		// sets the serialized value to something corresponding to specified displayedValue
		// (if possible), and also updates the textbox.value, for example converting "123"
		// to "123.00"
		this._setValueAttr(this.get('value'), undefined);

		this._set("displayedValue", this.get('displayedValue'));

		// textDir support
		if(this.textDir == "auto"){
			this.applyTextDir(this.focusNode, value);
		}
	},

	format: function(/*String*/ value, /*Object*/ constraints){
		// summary:
		//		Replacable function to convert a value to a properly formatted string.
		// tags:
		//		protected extension
		return ((value == null || value == undefined) ? "" : (value.toString ? value.toString() : value));
	},

	parse: function(/*String*/ value, /*Object*/ constraints){
		// summary:
		//		Replacable function to convert a formatted string to a value
		// tags:
		//		protected extension

		return value;	// String
	},

	_refreshState: function(){
		// summary:
		//		After the user types some characters, etc., this method is
		//		called to check the field for validity etc.  The base method
		//		in `dijit.form.TextBox` does nothing, but subclasses override.
		// tags:
		//		protected
	},

	/*=====
	onInput: function(event){
		// summary:
		//		Connect to this function to receive notifications of various user data-input events.
		//		Return false to cancel the event and prevent it from being processed.
		// event:
		//		keydown | keypress | cut | paste | input
		// tags:
		//		callback
	},
	=====*/
	onInput: function(){},

	__skipInputEvent: false,
	_onInput: function(e){
		// summary:
		//		Called AFTER the input event has happened
		// set text direction according to textDir that was defined in creation
		if(this.textDir == "auto"){
			this.applyTextDir(this.focusNode, this.focusNode.value);
		}

		this._refreshState();

		// In case someone is watch()'ing for changes to displayedValue
		this._set("displayedValue", this.get("displayedValue"));
	},

	postCreate: function(){
		// setting the value here is needed since value="" in the template causes "undefined"
		// and setting in the DOM (instead of the JS object) helps with form reset actions
		this.textbox.setAttribute("value", this.textbox.value); // DOM and JS values should be the same

		this.inherited(arguments);

		// normalize input events to reduce spurious event processing
		//	onkeydown: do not forward modifier keys
		//	           set charOrCode to numeric keycode
		//	onkeypress: do not forward numeric charOrCode keys (already sent thru onkeydown)
		//	onpaste & oncut: set charOrCode to 229 (IME)
		//	oninput: if primary event not already processed, set charOrCode to 229 (IME), else do not forward
		var handleEvent = function(e){
			var charCode = e.charOrCode || e.keyCode || 229;
			if(e.type == "keydown"){
				switch(charCode){ // ignore "state" keys
					case dojo.keys.SHIFT:
					case dojo.keys.ALT:
					case dojo.keys.CTRL:
					case dojo.keys.META:
					case dojo.keys.CAPSLOCK:
						return;
					default:
						if(charCode >= 65 && charCode <= 90){ return; } // keydown for A-Z can be processed with keypress
				}
			}
			if(e.type == "keypress" && typeof charCode != "string"){ return; }
			if(e.type == "input"){
				if(this.__skipInputEvent){ // duplicate event
					this.__skipInputEvent = false;
					return;
				}
			}else{
				this.__skipInputEvent = true;
			}
			// create fake event to set charOrCode and to know if preventDefault() was called
			var faux = dojo.mixin({}, e, {
				charOrCode: charCode,
				wasConsumed: false,
				preventDefault: function(){
					faux.wasConsumed = true;
					e.preventDefault();
				},
				stopPropagation: function(){ e.stopPropagation(); }
			});
			// give web page author a chance to consume the event
			if(this.onInput(faux) === false){
				dojo.stopEvent(faux); // return false means stop
			}
			if(faux.wasConsumed){ return; } // if preventDefault was called
			setTimeout(dojo.hitch(this, "_onInput", faux), 0); // widget notification after key has posted
		};
		dojo.forEach([ "onkeydown", "onkeypress", "onpaste", "oncut", "oninput" ], function(event){
			this.connect(this.textbox, event, handleEvent);
		}, this);
	},

	_blankValue: '', // if the textbox is blank, what value should be reported
	filter: function(val){
		// summary:
		//		Auto-corrections (such as trimming) that are applied to textbox
		//		value on blur or form submit.
		// description:
		//		For MappedTextBox subclasses, this is called twice
		// 			- once with the display value
		//			- once the value as set/returned by set('value', ...)
		//		and get('value'), ex: a Number for NumberTextBox.
		//
		//		In the latter case it does corrections like converting null to NaN.  In
		//		the former case the NumberTextBox.filter() method calls this.inherited()
		//		to execute standard trimming code in TextBox.filter().
		//
		//		TODO: break this into two methods in 2.0
		//
		// tags:
		//		protected extension
		if(val === null){ return this._blankValue; }
		if(typeof val != "string"){ return val; }
		if(this.trim){
			val = dojo.trim(val);
		}
		if(this.uppercase){
			val = val.toUpperCase();
		}
		if(this.lowercase){
			val = val.toLowerCase();
		}
		if(this.propercase){
			val = val.replace(/[^\s]+/g, function(word){
				return word.substring(0,1).toUpperCase() + word.substring(1);
			});
		}
		return val;
	},

	_setBlurValue: function(){
		this._setValueAttr(this.get('value'), true);
	},

	_onBlur: function(e){
		if(this.disabled){ return; }
		this._setBlurValue();
		this.inherited(arguments);

		if(this._selectOnClickHandle){
			this.disconnect(this._selectOnClickHandle);
		}
	},

	_isTextSelected: function(){
		return this.textbox.selectionStart == this.textbox.selectionEnd;
	},

	_onFocus: function(/*String*/ by){
		if(this.disabled || this.readOnly){ return; }

		// Select all text on focus via click if nothing already selected.
		// Since mouse-up will clear the selection need to defer selection until after mouse-up.
		// Don't do anything on focus by tabbing into the widget since there's no associated mouse-up event.
		if(this.selectOnClick && by == "mouse"){
			this._selectOnClickHandle = this.connect(this.domNode, "onmouseup", function(){
				// Only select all text on first click; otherwise users would have no way to clear
				// the selection.
				this.disconnect(this._selectOnClickHandle);

				// Check if the user selected some text manually (mouse-down, mouse-move, mouse-up)
				// and if not, then select all the text
				if(this._isTextSelected()){
					dijit.selectInputText(this.textbox);
				}
			});
		}
		// call this.inherited() before refreshState(), since this.inherited() will possibly scroll the viewport
		// (to scroll the TextBox into view), which will affect how _refreshState() positions the tooltip
		this.inherited(arguments);

		this._refreshState();
	},

	reset: function(){
		// Overrides dijit._FormWidget.reset().
		// Additionally resets the displayed textbox value to ''
		this.textbox.value = '';
		this.inherited(arguments);
	},
	_setTextDirAttr: function(/*String*/ textDir){
		// summary:
		//		Setter for textDir.
		// description:
		//		Users shouldn't call this function; they should be calling
		//		set('textDir', value)
		// tags:
		//		private

		// only if new textDir is different from the old one
		// and on widgets creation.
		if(!this._created
			|| this.textDir != textDir){
				this._set("textDir", textDir);
				// so the change of the textDir will take place immediately.
				this.applyTextDir(this.focusNode, this.focusNode.value);
		}
	}
});

dijit._setSelectionRange = function(/*DomNode*/ element, /*Number?*/ start, /*Number?*/ stop){
	if(element.setSelectionRange){
		element.setSelectionRange(start, stop);
	}
};

dijit.selectInputText = function(/*DomNode*/ element, /*Number?*/ start, /*Number?*/ stop){
	// summary:
	//		Select text in the input element argument, from start (default 0), to stop (default end).

	// TODO: use functions in _editor/selection.js?
	var _window = dojo.global;
	var _document = dojo.doc;
	element = dojo.byId(element);
	if(isNaN(start)){ start = 0; }
	if(isNaN(stop)){ stop = element.value ? element.value.length : 0; }
	element.focus();
	dijit._setSelectionRange(element, start, stop);
};

return dijit.form._TextBoxMixin;
});
<commit_msg>Refs #12368.  Handle random exception on IE when element focus fails.<commit_after>define("dijit/form/_TextBoxMixin", ["dojo", "dijit"], function(dojo, dijit) {

dojo.declare( "dijit.form._TextBoxMixin", null, {
	// summary:
	//		A mixin for textbox form input widgets

	// trim: Boolean
	//		Removes leading and trailing whitespace if true.  Default is false.
	trim: false,

	// uppercase: Boolean
	//		Converts all characters to uppercase if true.  Default is false.
	uppercase: false,

	// lowercase: Boolean
	//		Converts all characters to lowercase if true.  Default is false.
	lowercase: false,

	// propercase: Boolean
	//		Converts the first character of each word to uppercase if true.
	propercase: false,

	// maxLength: String
	//		HTML INPUT tag maxLength declaration.
	maxLength: "",

	// selectOnClick: [const] Boolean
	//		If true, all text will be selected when focused with mouse
	selectOnClick: false,

	// placeHolder: String
	//		Defines a hint to help users fill out the input field (as defined in HTML 5).
	//		This should only contain plain text (no html markup).
	placeHolder: "",

	_getValueAttr: function(){
		// summary:
		//		Hook so get('value') works as we like.
		// description:
		//		For `dijit.form.TextBox` this basically returns the value of the <input>.
		//
		//		For `dijit.form.MappedTextBox` subclasses, which have both
		//		a "displayed value" and a separate "submit value",
		//		This treats the "displayed value" as the master value, computing the
		//		submit value from it via this.parse().
		return this.parse(this.get('displayedValue'), this.constraints);
	},

	_setValueAttr: function(value, /*Boolean?*/ priorityChange, /*String?*/ formattedValue){
		// summary:
		//		Hook so set('value', ...) works.
		//
		// description:
		//		Sets the value of the widget to "value" which can be of
		//		any type as determined by the widget.
		//
		// value:
		//		The visual element value is also set to a corresponding,
		//		but not necessarily the same, value.
		//
		// formattedValue:
		//		If specified, used to set the visual element value,
		//		otherwise a computed visual value is used.
		//
		// priorityChange:
		//		If true, an onChange event is fired immediately instead of
		//		waiting for the next blur event.

		var filteredValue;
		if(value !== undefined){
			// TODO: this is calling filter() on both the display value and the actual value.
			// I added a comment to the filter() definition about this, but it should be changed.
			filteredValue = this.filter(value);
			if(typeof formattedValue != "string"){
				if(filteredValue !== null && ((typeof filteredValue != "number") || !isNaN(filteredValue))){
					formattedValue = this.filter(this.format(filteredValue, this.constraints));
				}else{ formattedValue = ''; }
			}
		}
		if(formattedValue != null && formattedValue != undefined && ((typeof formattedValue) != "number" || !isNaN(formattedValue)) && this.textbox.value != formattedValue){
			this.textbox.value = formattedValue;
			this._set("displayedValue", this.get("displayedValue"));
		}

		if(this.textDir == "auto"){
			this.applyTextDir(this.focusNode, formattedValue);
		}

		this.inherited(arguments, [filteredValue, priorityChange]);
	},

	// displayedValue: String
	//		For subclasses like ComboBox where the displayed value
	//		(ex: Kentucky) and the serialized value (ex: KY) are different,
	//		this represents the displayed value.
	//
	//		Setting 'displayedValue' through set('displayedValue', ...)
	//		updates 'value', and vice-versa.  Otherwise 'value' is updated
	//		from 'displayedValue' periodically, like onBlur etc.
	//
	//		TODO: move declaration to MappedTextBox?
	//		Problem is that ComboBox references displayedValue,
	//		for benefit of FilteringSelect.
	displayedValue: "",

	_getDisplayedValueAttr: function(){
		// summary:
		//		Hook so get('displayedValue') works.
		// description:
		//		Returns the displayed value (what the user sees on the screen),
		// 		after filtering (ie, trimming spaces etc.).
		//
		//		For some subclasses of TextBox (like ComboBox), the displayed value
		//		is different from the serialized value that's actually
		//		sent to the server (see dijit.form.ValidationTextBox.serialize)

		// TODO: maybe we should update this.displayedValue on every keystroke so that we don't need
		// this method
		// TODO: this isn't really the displayed value when the user is typing
		return this.filter(this.textbox.value);
	},

	_setDisplayedValueAttr: function(/*String*/ value){
		// summary:
		//		Hook so set('displayedValue', ...) works.
		// description:
		//		Sets the value of the visual element to the string "value".
		//		The widget value is also set to a corresponding,
		//		but not necessarily the same, value.

		if(value === null || value === undefined){ value = '' }
		else if(typeof value != "string"){ value = String(value) }

		this.textbox.value = value;

		// sets the serialized value to something corresponding to specified displayedValue
		// (if possible), and also updates the textbox.value, for example converting "123"
		// to "123.00"
		this._setValueAttr(this.get('value'), undefined);

		this._set("displayedValue", this.get('displayedValue'));

		// textDir support
		if(this.textDir == "auto"){
			this.applyTextDir(this.focusNode, value);
		}
	},

	format: function(/*String*/ value, /*Object*/ constraints){
		// summary:
		//		Replacable function to convert a value to a properly formatted string.
		// tags:
		//		protected extension
		return ((value == null || value == undefined) ? "" : (value.toString ? value.toString() : value));
	},

	parse: function(/*String*/ value, /*Object*/ constraints){
		// summary:
		//		Replacable function to convert a formatted string to a value
		// tags:
		//		protected extension

		return value;	// String
	},

	_refreshState: function(){
		// summary:
		//		After the user types some characters, etc., this method is
		//		called to check the field for validity etc.  The base method
		//		in `dijit.form.TextBox` does nothing, but subclasses override.
		// tags:
		//		protected
	},

	/*=====
	onInput: function(event){
		// summary:
		//		Connect to this function to receive notifications of various user data-input events.
		//		Return false to cancel the event and prevent it from being processed.
		// event:
		//		keydown | keypress | cut | paste | input
		// tags:
		//		callback
	},
	=====*/
	onInput: function(){},

	__skipInputEvent: false,
	_onInput: function(e){
		// summary:
		//		Called AFTER the input event has happened
		// set text direction according to textDir that was defined in creation
		if(this.textDir == "auto"){
			this.applyTextDir(this.focusNode, this.focusNode.value);
		}

		this._refreshState();

		// In case someone is watch()'ing for changes to displayedValue
		this._set("displayedValue", this.get("displayedValue"));
	},

	postCreate: function(){
		// setting the value here is needed since value="" in the template causes "undefined"
		// and setting in the DOM (instead of the JS object) helps with form reset actions
		this.textbox.setAttribute("value", this.textbox.value); // DOM and JS values should be the same

		this.inherited(arguments);

		// normalize input events to reduce spurious event processing
		//	onkeydown: do not forward modifier keys
		//	           set charOrCode to numeric keycode
		//	onkeypress: do not forward numeric charOrCode keys (already sent thru onkeydown)
		//	onpaste & oncut: set charOrCode to 229 (IME)
		//	oninput: if primary event not already processed, set charOrCode to 229 (IME), else do not forward
		var handleEvent = function(e){
			var charCode = e.charOrCode || e.keyCode || 229;
			if(e.type == "keydown"){
				switch(charCode){ // ignore "state" keys
					case dojo.keys.SHIFT:
					case dojo.keys.ALT:
					case dojo.keys.CTRL:
					case dojo.keys.META:
					case dojo.keys.CAPSLOCK:
						return;
					default:
						if(charCode >= 65 && charCode <= 90){ return; } // keydown for A-Z can be processed with keypress
				}
			}
			if(e.type == "keypress" && typeof charCode != "string"){ return; }
			if(e.type == "input"){
				if(this.__skipInputEvent){ // duplicate event
					this.__skipInputEvent = false;
					return;
				}
			}else{
				this.__skipInputEvent = true;
			}
			// create fake event to set charOrCode and to know if preventDefault() was called
			var faux = dojo.mixin({}, e, {
				charOrCode: charCode,
				wasConsumed: false,
				preventDefault: function(){
					faux.wasConsumed = true;
					e.preventDefault();
				},
				stopPropagation: function(){ e.stopPropagation(); }
			});
			// give web page author a chance to consume the event
			if(this.onInput(faux) === false){
				dojo.stopEvent(faux); // return false means stop
			}
			if(faux.wasConsumed){ return; } // if preventDefault was called
			setTimeout(dojo.hitch(this, "_onInput", faux), 0); // widget notification after key has posted
		};
		dojo.forEach([ "onkeydown", "onkeypress", "onpaste", "oncut", "oninput" ], function(event){
			this.connect(this.textbox, event, handleEvent);
		}, this);
	},

	_blankValue: '', // if the textbox is blank, what value should be reported
	filter: function(val){
		// summary:
		//		Auto-corrections (such as trimming) that are applied to textbox
		//		value on blur or form submit.
		// description:
		//		For MappedTextBox subclasses, this is called twice
		// 			- once with the display value
		//			- once the value as set/returned by set('value', ...)
		//		and get('value'), ex: a Number for NumberTextBox.
		//
		//		In the latter case it does corrections like converting null to NaN.  In
		//		the former case the NumberTextBox.filter() method calls this.inherited()
		//		to execute standard trimming code in TextBox.filter().
		//
		//		TODO: break this into two methods in 2.0
		//
		// tags:
		//		protected extension
		if(val === null){ return this._blankValue; }
		if(typeof val != "string"){ return val; }
		if(this.trim){
			val = dojo.trim(val);
		}
		if(this.uppercase){
			val = val.toUpperCase();
		}
		if(this.lowercase){
			val = val.toLowerCase();
		}
		if(this.propercase){
			val = val.replace(/[^\s]+/g, function(word){
				return word.substring(0,1).toUpperCase() + word.substring(1);
			});
		}
		return val;
	},

	_setBlurValue: function(){
		this._setValueAttr(this.get('value'), true);
	},

	_onBlur: function(e){
		if(this.disabled){ return; }
		this._setBlurValue();
		this.inherited(arguments);

		if(this._selectOnClickHandle){
			this.disconnect(this._selectOnClickHandle);
		}
	},

	_isTextSelected: function(){
		return this.textbox.selectionStart == this.textbox.selectionEnd;
	},

	_onFocus: function(/*String*/ by){
		if(this.disabled || this.readOnly){ return; }

		// Select all text on focus via click if nothing already selected.
		// Since mouse-up will clear the selection need to defer selection until after mouse-up.
		// Don't do anything on focus by tabbing into the widget since there's no associated mouse-up event.
		if(this.selectOnClick && by == "mouse"){
			this._selectOnClickHandle = this.connect(this.domNode, "onmouseup", function(){
				// Only select all text on first click; otherwise users would have no way to clear
				// the selection.
				this.disconnect(this._selectOnClickHandle);

				// Check if the user selected some text manually (mouse-down, mouse-move, mouse-up)
				// and if not, then select all the text
				if(this._isTextSelected()){
					dijit.selectInputText(this.textbox);
				}
			});
		}
		// call this.inherited() before refreshState(), since this.inherited() will possibly scroll the viewport
		// (to scroll the TextBox into view), which will affect how _refreshState() positions the tooltip
		this.inherited(arguments);

		this._refreshState();
	},

	reset: function(){
		// Overrides dijit._FormWidget.reset().
		// Additionally resets the displayed textbox value to ''
		this.textbox.value = '';
		this.inherited(arguments);
	},
	_setTextDirAttr: function(/*String*/ textDir){
		// summary:
		//		Setter for textDir.
		// description:
		//		Users shouldn't call this function; they should be calling
		//		set('textDir', value)
		// tags:
		//		private

		// only if new textDir is different from the old one
		// and on widgets creation.
		if(!this._created
			|| this.textDir != textDir){
				this._set("textDir", textDir);
				// so the change of the textDir will take place immediately.
				this.applyTextDir(this.focusNode, this.focusNode.value);
		}
	}
});

dijit._setSelectionRange = function(/*DomNode*/ element, /*Number?*/ start, /*Number?*/ stop){
	if(element.setSelectionRange){
		element.setSelectionRange(start, stop);
	}
};

dijit.selectInputText = function(/*DomNode*/ element, /*Number?*/ start, /*Number?*/ stop){
	// summary:
	//		Select text in the input element argument, from start (default 0), to stop (default end).

	// TODO: use functions in _editor/selection.js?
	var _window = dojo.global;
	var _document = dojo.doc;
	element = dojo.byId(element);
	if(isNaN(start)){ start = 0; }
	if(isNaN(stop)){ stop = element.value ? element.value.length : 0; }
	try{
		element.focus();
		dijit._setSelectionRange(element, start, stop);
	}catch(e){ /* squelch random errors (esp. on IE) from unexpected focus changes or DOM nodes being hidden */ }
};

return dijit.form._TextBoxMixin;
});
<|endoftext|>


<commit_before>const axios = require('axios');
const expect = require('chai').expect;

describe('Bad response', () => {
  // Server accepts traffic but never sends back data
  it('should handle no response gracefully', (done) => {
    axios.get('http://localhost:5501', { timeout: 30000 })
      .catch((err) => {
        expect(err.code).to.equal('ECONNABORTED');
        done();
      });
  }).timeout(35000);

  // Server sends back an empty string immediately upon connection
  it('should handle empty response gracefully (GET)', (done) => {
    axios.get('http://localhost:5502', { timeout: 30000 })
      .catch((err) => {
        expect(err.code).to.equal('ECONNRESET');
        done();
      });
  });

  // Server sends back an empty string after client sends data
  it('should handle empty response gracefully (POST)', (done) => {
    axios.post('http://localhost:5503', 'foo bar', { timeout: 30000 })
      .catch((err) => {
        expect(err.code).to.equal('ECONNRESET');
        done();
      });
  });

  // Server sends back a malformed response ("foo bar") immediately upon connection
  it('should handle malformed response gracefully (GET)', (done) => {
    axios.get('http://localhost:5504', 'foo bar', { timeout: 30000 })
      .catch((err) => {
        expect(err.code).to.equal('HPE_INVALID_CONSTANT');
        done();
      });
  });

  // Server sends back a malformed response ("foo bar") after the client sends data
  it('should handle malformed response gracefully (POST)', (done) => {
    axios.post('http://localhost:5505', 'foo bar', { timeout: 30000 })
      .catch((err) => {
        expect(err.code).to.equal('HPE_INVALID_CONSTANT');
        done();
      });
  });
});
<commit_msg>Add long running response test cases<commit_after>const axios = require('axios');
const expect = require('chai').expect;

describe('Bad response', () => {
  // Server accepts traffic but never sends back data
  it('should handle no response gracefully', (done) => {
    axios.get('http://localhost:5501', { timeout: 30000 })
      .catch((err) => {
        expect(err.code).to.equal('ECONNABORTED');
        done();
      });
  }).timeout(35000);

  // Server sends back an empty string immediately upon connection
  it('should handle empty response gracefully (GET)', (done) => {
    axios.get('http://localhost:5502', { timeout: 30000 })
      .catch((err) => {
        expect(err.code).to.equal('ECONNRESET');
        done();
      });
  });

  // Server sends back an empty string after client sends data
  it('should handle empty response gracefully (POST)', (done) => {
    axios.post('http://localhost:5503', 'foo bar', { timeout: 30000 })
      .catch((err) => {
        expect(err.code).to.equal('ECONNRESET');
        done();
      });
  });

  // Server sends back a malformed response ("foo bar") immediately upon connection
  it('should handle malformed response gracefully (GET)', (done) => {
    axios.get('http://localhost:5504', 'foo bar', { timeout: 30000 })
      .catch((err) => {
        expect(err.code).to.equal('HPE_INVALID_CONSTANT');
        done();
      });
  });

  // Server sends back a malformed response ("foo bar") after the client sends data
  it('should handle malformed response gracefully (POST)', (done) => {
    axios.post('http://localhost:5505', 'foo bar', { timeout: 30000 })
      .catch((err) => {
        expect(err.code).to.equal('HPE_INVALID_CONSTANT');
        done();
      });
  });

  // Server accepts the request and sends back one byte every 5 seconds
  it('should handle long running response gracefully (1)', (done) => {
    const source = axios.CancelToken.source();

    axios.get('http://localhost:5506', {
      cancelToken: source.token,
      timeout: 30000,
    }).catch((err) => {
      expect(err.message).to.equal('Request canceled by the user.');
      done();
    });

    setTimeout(() => {
      source.cancel('Request canceled by the user.');
    }, 30000);
  }).timeout(35000);

  // Server accepts the request and sends back one byte every 30 seconds
  it('should handle long running response gracefully (2)', (done) => {
    const source = axios.CancelToken.source();

    axios.get('http://localhost:5507', {
      cancelToken: source.token,
      timeout: 30000,
    }).catch((err) => {
      expect(err.message).to.equal('Request canceled by the user.');
      done();
    });

    setTimeout(() => {
      source.cancel('Request canceled by the user.');
    }, 30000);
  }).timeout(35000);
});
<|endoftext|>


<commit_before><commit_msg>fix exports for MarkdownEditor<commit_after><|endoftext|>


<commit_before>/**
 * @fileOverview middlewarify tests
 */
var sinon  = require('sinon');
var assert = require('chai').assert;
var Promise = require('bluebird');

var midd = require('../');

var noop = function(){};

suite('6. Before / After middleware', function() {

  setup(function() {});

  teardown(function() {});

  // The numbering (e.g. 1.1.1) has nothing to do with order
  // The purpose is to provide a unique string so specific tests are
  // run by using the mocha --grep "1.1.1" option.

  test('6.1 Types Test', function() {
    var obj = Object.create(null);
    midd.make(obj, 'create', {
      beforeAfter: true,
    });
    assert.isFunction(obj.create, 'obj.create should be a function');
    assert.isFunction(obj.create.before, 'obj.create.before should be a function');
    assert.isFunction(obj.create.after, 'obj.create.after should be a function');
    assert.notProperty(obj.create, 'use', 'obj.create should NOT have a use fn');
    assert.isFunction(obj.create().then, 'obj.create().then should be a Function');
    assert.ok(Promise.is(obj.create()), 'obj.create() is a Promise');
  });
});

suite('6.2. middleware before/after Sequence of invocation', function() {
  var obj, midd1, midd2, midd3, midd4, midd5, midd6, fnPayload;

  setup(function() {
    obj = Object.create(null);
    midd1 = sinon.spy();
    midd2 = sinon.spy();
    midd3 = sinon.spy();
    midd4 = sinon.spy();
    midd5 = sinon.spy();
    midd6 = sinon.spy();
    fnPayload = sinon.spy();
    midd.make(obj, 'create', fnPayload, {beforeAfter: true});
  });

  teardown(function(done) {
    obj.create().then(function() {
      assert.ok(midd1.calledOnce, 'midd1 called only once, called: ' + midd1.callCount);
      assert.ok(midd2.calledOnce, 'midd2 called only once, called: ' + midd2.callCount);
      assert.ok(midd3.calledOnce, 'midd3 called only once, called: ' + midd3.callCount);
      assert.ok(midd4.calledOnce, 'midd4 called only once, called: ' + midd4.callCount);
      assert.ok(midd5.calledOnce, 'midd5 called only once, called: ' + midd5.callCount);
      assert.ok(midd6.calledOnce, 'midd6 called only once, called: ' + midd6.callCount);
      assert.ok(fnPayload.calledOnce, 'fnPayload called only once');

      assert.ok(midd1.calledBefore(midd2), '"midd1" called before "midd2"');
      assert.ok(midd2.calledBefore(midd3), '"midd2" called before "midd3"');
      assert.ok(midd3.calledBefore(fnPayload), '"midd3" called before "fnPayload"');
      assert.ok(fnPayload.calledBefore(midd4), '"fnPayload" called before "midd4"');
      assert.ok(midd4.calledBefore(midd5), '"midd4" called before "midd5"');
      assert.ok(midd5.calledBefore(midd6), '"midd5" called before "midd6"');
    }).then(done, done);
  });

  test('6.2.1 Multiple arguments', function() {
    obj.create.before(midd1, midd2, midd3);
    obj.create.after(midd4, midd5, midd6);
  });
  test('6.2.2 Multiple calls', function() {
    obj.create.before(midd1);
    obj.create.before(midd2);
    obj.create.before(midd3);
    obj.create.after(midd4);
    obj.create.after(midd5);
    obj.create.after(midd6);
  });
  test('6.2.3 An array', function() {
    obj.create.before([midd1, midd2, midd3]);
    obj.create.after([midd4, midd5, midd6]);
  });
  test('6.2.4 Array mixed with arg', function() {
    obj.create.before([midd1, midd2], midd3);
    obj.create.after([midd4, midd5], midd6);
  });
});

suite('6.3. middleware() argument piping', function() {
  var obj, mainMidd, firstMidd, secondMidd, thirdMidd;
  setup(function() {
  });

  teardown(function(){
  });

  test('6.3.1 Three arguments', function(done) {
    obj = Object.create(null);
    mainMidd = sinon.spy();
    firstMidd = sinon.spy();
    secondMidd = sinon.spy();
    thirdMidd = sinon.spy();
    midd.make(obj, 'create', mainMidd, {beforeAfter: true});
    obj.create.before(firstMidd, secondMidd);
    obj.create.after(thirdMidd);

    var foo = {a: 1};
    var bar = {b: 2};
    obj.create(1, foo, bar).then(function(err){
      assert.notOk(err, 'error should not be truthy');
      assert.ok(firstMidd.alwaysCalledWith(1, foo, bar), 'firstMidd should be invoked with these arguments');
      assert.ok(secondMidd.alwaysCalledWith(1, foo, bar), 'secondMidd should be invoked with these arguments');
      assert.ok(thirdMidd.alwaysCalledWith(1, foo, bar), 'thirdMidd should be invoked with these arguments');
      assert.ok(mainMidd.alwaysCalledWith(1, foo, bar), 'mainMidd should be invoked with these arguments');
      done();
    }, done).then(null, done);
  });
  suite('6.3.2 Main Callback arguments pipes to final promise', function() {
    function invoke(returnValue) {
      obj = Object.create(null);
      mainMidd = function() {
        return returnValue;
      };
      firstMidd = sinon.spy();
      secondMidd = sinon.spy();
      thirdMidd = sinon.spy();
      midd.make(obj, 'create', mainMidd, {beforeAfter: true});
      obj.create.before(firstMidd, secondMidd);
      obj.create.after(thirdMidd);
    }
    test('6.3.2.1 Using a promise', function(done) {
      var prom = new Promise(function(resolve){
        resolve('value');
      });
      invoke(prom);

      obj.create().then(function(val) {
        assert.equal(val, 'value');
      }).then(done, done);
    });
    test('6.3.2.2 Using a string', function(done) {
      invoke('value');
      obj.create().then(function(val) {
        assert.equal(val, 'value');
      }).then(done, done);
    });
    test('6.3.2.3 Using a number', function(done) {
      invoke(9);
      obj.create().then(function(val) {
        assert.equal(val, 9);
      }).then(done, done);
    });
  });
});

suite('6.5. Failing middleware cases', function(){
  var obj;
  setup(function(){
    obj = Object.create(null);
    midd.make(obj, 'create', {beforeAfter: true});
  });
  test('6.5.1.1 Before middleware throws an error', function(done){
    obj.create.before(function() {
      throw new Error('an error');
    });

    obj.create().then(null, function(err) {
      assert.instanceOf(err, Error);
      assert.equal(err.message, 'an error');
      done();
    }).then(null, done);
  });

  test('6.5.1.1.2 After middleware throws an error', function(done){
    obj.create.after(function() {
      throw new Error('an error');
    });

    obj.create().then(null, function(err) {
      assert.instanceOf(err, Error);
      assert.equal(err.message, 'an error');
      done();
    }).then(null, done);
  });

  test('6.5.1.2 Main callback throws an error', function(done){
    var custObj = Object.create(null);
    midd.make(custObj, 'create', function() {
      throw new Error('an error');
    }, {beforeAfter: true});

    custObj.create().then(noop, function(err){
      assert.instanceOf(err, Error, '"err" should be instanceOf Error');
      assert.equal(err.message, 'an error', 'Error message should match');
      done();
    }, done).then(null, done);
  });
  test('6.5.1.3 Main callback throws an error async', function(done){
    function promiseAsyncReject() {
      return new Promise(function(resolve, reject) {
        setTimeout(function(){
          reject(new Error('an error'));
        });
      });
    }

    var custObj = Object.create(null);
    midd.make(custObj, 'create', function() {
      return promiseAsyncReject()
        .catch(function(err) {
          console.log('err:', err);
          throw err;
        });
    }, {beforeAfter: true});

    custObj.create().then(noop, function(err){
      assert.instanceOf(err, Error, '"err" should be instanceOf Error');
      assert.equal(err.message, 'an error', 'Error message should match');
      done();
    }, done).then(null, done);
  });
});
suite('6.6. Resolving Value propagation to After middl', function(){
  var obj;
  setup(function(){
    obj = Object.create(null);
  });
  test('6.6.1 resolving value gets passed as an extra argument by promise', function(done) {
    midd.make(obj, 'create', function() {
      return new Promise(function(resolve) {
        setTimeout(function(){
          resolve('abc');
        });
      });
    },{beforeAfter: true});

    obj.create.after(function(arg1, arg2, resolveValue) {
      assert.equal(resolveValue, 'abc');
    });
    obj.create(1, 2).then(done.bind(null, null), done);
  });
  test('6.6.2 resolving value gets passed as an extra argument by returning', function(done) {
    midd.make(obj, 'create', function() {
      return 'abc';
    }, {beforeAfter: true});

    obj.create.after(function(arg1, arg2, resolveValue) {
      assert.equal(resolveValue, 'abc');
    });
    obj.create(1, 2).then(done.bind(null, null), done);
  });
});
<commit_msg>ensure thrown errors do not cause unhandler errors on Bluebird<commit_after>/**
 * @fileOverview middlewarify tests
 */
var sinon  = require('sinon');
var assert = require('chai').assert;
var Promise = require('bluebird');

var midd = require('../');

var noop = function(){};

suite('6. Before / After middleware', function() {

  setup(function() {});

  teardown(function() {});

  // The numbering (e.g. 1.1.1) has nothing to do with order
  // The purpose is to provide a unique string so specific tests are
  // run by using the mocha --grep "1.1.1" option.

  test('6.1 Types Test', function() {
    var obj = Object.create(null);
    midd.make(obj, 'create', {
      beforeAfter: true,
    });
    assert.isFunction(obj.create, 'obj.create should be a function');
    assert.isFunction(obj.create.before, 'obj.create.before should be a function');
    assert.isFunction(obj.create.after, 'obj.create.after should be a function');
    assert.notProperty(obj.create, 'use', 'obj.create should NOT have a use fn');
    assert.isFunction(obj.create().then, 'obj.create().then should be a Function');
    assert.ok(Promise.is(obj.create()), 'obj.create() is a Promise');
  });
});

suite('6.2. middleware before/after Sequence of invocation', function() {
  var obj, midd1, midd2, midd3, midd4, midd5, midd6, fnPayload;

  setup(function() {
    obj = Object.create(null);
    midd1 = sinon.spy();
    midd2 = sinon.spy();
    midd3 = sinon.spy();
    midd4 = sinon.spy();
    midd5 = sinon.spy();
    midd6 = sinon.spy();
    fnPayload = sinon.spy();
    midd.make(obj, 'create', fnPayload, {beforeAfter: true});
  });

  teardown(function(done) {
    obj.create().then(function() {
      assert.ok(midd1.calledOnce, 'midd1 called only once, called: ' + midd1.callCount);
      assert.ok(midd2.calledOnce, 'midd2 called only once, called: ' + midd2.callCount);
      assert.ok(midd3.calledOnce, 'midd3 called only once, called: ' + midd3.callCount);
      assert.ok(midd4.calledOnce, 'midd4 called only once, called: ' + midd4.callCount);
      assert.ok(midd5.calledOnce, 'midd5 called only once, called: ' + midd5.callCount);
      assert.ok(midd6.calledOnce, 'midd6 called only once, called: ' + midd6.callCount);
      assert.ok(fnPayload.calledOnce, 'fnPayload called only once');

      assert.ok(midd1.calledBefore(midd2), '"midd1" called before "midd2"');
      assert.ok(midd2.calledBefore(midd3), '"midd2" called before "midd3"');
      assert.ok(midd3.calledBefore(fnPayload), '"midd3" called before "fnPayload"');
      assert.ok(fnPayload.calledBefore(midd4), '"fnPayload" called before "midd4"');
      assert.ok(midd4.calledBefore(midd5), '"midd4" called before "midd5"');
      assert.ok(midd5.calledBefore(midd6), '"midd5" called before "midd6"');
    }).then(done, done);
  });

  test('6.2.1 Multiple arguments', function() {
    obj.create.before(midd1, midd2, midd3);
    obj.create.after(midd4, midd5, midd6);
  });
  test('6.2.2 Multiple calls', function() {
    obj.create.before(midd1);
    obj.create.before(midd2);
    obj.create.before(midd3);
    obj.create.after(midd4);
    obj.create.after(midd5);
    obj.create.after(midd6);
  });
  test('6.2.3 An array', function() {
    obj.create.before([midd1, midd2, midd3]);
    obj.create.after([midd4, midd5, midd6]);
  });
  test('6.2.4 Array mixed with arg', function() {
    obj.create.before([midd1, midd2], midd3);
    obj.create.after([midd4, midd5], midd6);
  });
});

suite('6.3. middleware() argument piping', function() {
  var obj, mainMidd, firstMidd, secondMidd, thirdMidd;
  setup(function() {
  });

  teardown(function(){
  });

  test('6.3.1 Three arguments', function(done) {
    obj = Object.create(null);
    mainMidd = sinon.spy();
    firstMidd = sinon.spy();
    secondMidd = sinon.spy();
    thirdMidd = sinon.spy();
    midd.make(obj, 'create', mainMidd, {beforeAfter: true});
    obj.create.before(firstMidd, secondMidd);
    obj.create.after(thirdMidd);

    var foo = {a: 1};
    var bar = {b: 2};
    obj.create(1, foo, bar).then(function(err){
      assert.notOk(err, 'error should not be truthy');
      assert.ok(firstMidd.alwaysCalledWith(1, foo, bar), 'firstMidd should be invoked with these arguments');
      assert.ok(secondMidd.alwaysCalledWith(1, foo, bar), 'secondMidd should be invoked with these arguments');
      assert.ok(thirdMidd.alwaysCalledWith(1, foo, bar), 'thirdMidd should be invoked with these arguments');
      assert.ok(mainMidd.alwaysCalledWith(1, foo, bar), 'mainMidd should be invoked with these arguments');
      done();
    }, done).then(null, done);
  });
  suite('6.3.2 Main Callback arguments pipes to final promise', function() {
    function invoke(returnValue) {
      obj = Object.create(null);
      mainMidd = function() {
        return returnValue;
      };
      firstMidd = sinon.spy();
      secondMidd = sinon.spy();
      thirdMidd = sinon.spy();
      midd.make(obj, 'create', mainMidd, {beforeAfter: true});
      obj.create.before(firstMidd, secondMidd);
      obj.create.after(thirdMidd);
    }
    test('6.3.2.1 Using a promise', function(done) {
      var prom = new Promise(function(resolve){
        resolve('value');
      });
      invoke(prom);

      obj.create().then(function(val) {
        assert.equal(val, 'value');
      }).then(done, done);
    });
    test('6.3.2.2 Using a string', function(done) {
      invoke('value');
      obj.create().then(function(val) {
        assert.equal(val, 'value');
      }).then(done, done);
    });
    test('6.3.2.3 Using a number', function(done) {
      invoke(9);
      obj.create().then(function(val) {
        assert.equal(val, 9);
      }).then(done, done);
    });
  });
});

suite('6.5. Failing middleware cases', function(){
  var obj;
  setup(function(){
    obj = Object.create(null);
    midd.make(obj, 'create', {beforeAfter: true});
  });
  test('6.5.1.1 Before middleware throws an error', function(done){
    obj.create.before(function() {
      throw new Error('an error');
    });

    obj.create().then(null, function(err) {
      assert.instanceOf(err, Error);
      assert.equal(err.message, 'an error');
      done();
    }).then(null, done);
  });

  test('6.5.1.1.2 After middleware throws an error', function(done){
    obj.create.after(function() {
      throw new Error('an error');
    });

    obj.create().then(null, function(err) {
      assert.instanceOf(err, Error);
      assert.equal(err.message, 'an error');
      done();
    }).then(null, done);
  });

  test('6.5.1.2 Main callback throws an error', function(done){
    var custObj = Object.create(null);
    midd.make(custObj, 'create', function() {
      throw new Error('an error');
    }, {beforeAfter: true});

    custObj.create().then(noop, function(err){
      assert.instanceOf(err, Error, '"err" should be instanceOf Error');
      assert.equal(err.message, 'an error', 'Error message should match');
      done();
    }, done).then(null, done);
  });
  test('6.5.1.3 Main callback throws an error async', function(done){
    function promiseAsyncReject() {
      return new Promise(function(resolve, reject) {
        setTimeout(function(){
          reject(new Error('an error'));
        });
      });
    }

    var custObj = Object.create(null);
    midd.make(custObj, 'create', function() {
      return promiseAsyncReject()
        .catch(function(err) {
          console.log('err:', err);
          throw err;
        });
    }, {beforeAfter: true});

    custObj.create().then(noop, function(err){
      assert.instanceOf(err, Error, '"err" should be instanceOf Error');
      assert.equal(err.message, 'an error', 'Error message should match');
      done();
    }, done).then(null, done);
  });
});
suite('6.6. Resolving Value propagation to After middl', function(){
  var obj;
  setup(function(){
    obj = Object.create(null);
  });
  test('6.6.1 resolving value gets passed as an extra argument by promise', function(done) {
    midd.make(obj, 'create', function() {
      return new Promise(function(resolve) {
        setTimeout(function(){
          resolve('abc');
        });
      });
    },{beforeAfter: true});

    obj.create.after(function(arg1, arg2, resolveValue) {
      assert.equal(resolveValue, 'abc');
    });
    obj.create(1, 2).then(done.bind(null, null), done);
  });
  test('6.6.2 resolving value gets passed as an extra argument by returning', function(done) {
    midd.make(obj, 'create', function() {
      return 'abc';
    }, {beforeAfter: true});

    obj.create.after(function(arg1, arg2, resolveValue) {
      assert.equal(resolveValue, 'abc');
    });
    obj.create(1, 2).then(done.bind(null, null), done);
  });
});

suite('6.7 Unhandled errors', function() {
  var obj;
  setup(function(){
    obj = Object.create(null);
  });
  test('6.7.1 Throwing errors does not cause Unhandled exceptions', function(done) {
    Promise.onPossiblyUnhandledRejection(done);
    midd.make(obj, 'create', Promise.method(function() {
      throw new Error('Boo');
    }), {beforeAfter: true});

    obj.create().catch(function(err) {
      assert.equal(err.message, 'Boo');
      assert.instanceOf(err, Error);
    }).then(done, done);
  });
  test('6.7.2 Throwing errors does not cause Unhandled exceptions', function(done) {
    Promise.onPossiblyUnhandledRejection(done);

    function prom() {
      return new Promise(function(resolve) {
        setTimeout(resolve, 1000);
      });
    }

    midd.make(obj, 'create', Promise.method(function() {
      return prom().then(function() {
        throw new Error('Boo');
      });
    }), {beforeAfter: true});

    obj.create().catch(function(err) {
      assert.equal(err.message, 'Boo');
      assert.instanceOf(err, Error);
    }).then(done, done);
  });

});
<|endoftext|>


<commit_before>'use strict'
var util = require('./util')
var BN = require('ethereumjs-util').BN

function DynamicByteArray () {
  this.storageSlots = 1
  this.storageBytes = 32
  this.typeName = 'bytes'
}

DynamicByteArray.prototype.decodeFromStorage = function (location, storageContent) {
  var value = util.extractHexValue(location, storageContent, this.storageBytes)
  var bn = new BN(value, 16)
  if (bn.testn(0)) {
    var length = bn.div(new BN(2))
    var dataPos = new BN(util.sha3(location.slot).replace('0x', ''), 16)
    var ret = ''
    var currentSlot = util.readFromStorage(dataPos, storageContent)
    while (length.gt(ret.length) && ret.length < 32000) {
      currentSlot = currentSlot.replace('0x', '')
      ret += currentSlot
      dataPos = dataPos.add(new BN(1))
      currentSlot = util.readFromStorage(dataPos, storageContent)
    }
    return {
      value: '0x' + ret.replace(/(00)+$/, ''),
      length: '0x' + length.toString(16)
    }
  } else {
    var size = parseInt(value.substr(value.length - 2, 2), 16) / 2
    return {
      value: '0x' + value.substr(0, size * 2),
      length: '0x' + size.toString(16)
    }
  }
}

DynamicByteArray.prototype.decodeLocals = function (stackHeight, stack, memory) {
  if (stack.length - 1 < stackHeight) {
    return {
      value: '0x',
      length: '0x'
    }
  } else {
    var offset = stack[stack.length - 1 - stackHeight]
    offset = 2 * parseInt(offset, 16)
    var length = memory.substr(offset, 64)
    length = parseInt(length, 16)
    return {
      length: 2 * length,
      value: '0x' + memory.substr(offset + 64, 2 * length)
    }
  }
}

module.exports = DynamicByteArray
<commit_msg>decodeFromMemory DynamicByteArray<commit_after>'use strict'
var util = require('./util')
var BN = require('ethereumjs-util').BN

function DynamicByteArray () {
  this.storageSlots = 1
  this.storageBytes = 32
  this.typeName = 'bytes'
}

DynamicByteArray.prototype.decodeFromStorage = function (location, storageContent) {
  var value = util.extractHexValue(location, storageContent, this.storageBytes)
  var bn = new BN(value, 16)
  if (bn.testn(0)) {
    var length = bn.div(new BN(2))
    var dataPos = new BN(util.sha3(location.slot).replace('0x', ''), 16)
    var ret = ''
    var currentSlot = util.readFromStorage(dataPos, storageContent)
    while (length.gt(ret.length) && ret.length < 32000) {
      currentSlot = currentSlot.replace('0x', '')
      ret += currentSlot
      dataPos = dataPos.add(new BN(1))
      currentSlot = util.readFromStorage(dataPos, storageContent)
    }
    return {
      value: '0x' + ret.replace(/(00)+$/, ''),
      length: '0x' + length.toString(16)
    }
  } else {
    var size = parseInt(value.substr(value.length - 2, 2), 16) / 2
    return {
      value: '0x' + value.substr(0, size * 2),
      length: '0x' + size.toString(16)
    }
  }
}

DynamicByteArray.prototype.decodeLocals = function (stackHeight, stack, memory) {
  if (stack.length - 1 < stackHeight) {
    return {
      value: '0x',
      length: '0x0'
    }
  } else {
    var offset = stack[stack.length - 1 - stackHeight]
    offset = 2 * parseInt(offset, 16)
    return this.decodeFromMemory(offset, memory)
  }
}

DynamicByteArray.prototype.decodeFromMemory = function (offset, memory) {
  var length = memory.substr(offset, 64)
  length = 2 * parseInt(length, 16)
  return {
    length: '0x' + length.toString(16),
    value: '0x' + memory.substr(offset + 64, length)
  }
}

module.exports = DynamicByteArray
<|endoftext|>


<commit_before>$(document).ready(function() {

  module("underscore.collections.walk");

  var getSimpleTestTree = function() {
    return {
      val: 0,
      l: { val: 1, l: { val: 2 }, r: { val: 3 } },
      r: { val: 4, l: { val: 5 }, r: { val: 6 } }
    };
  };

  var getMixedTestTree = function() {
    return {
      current:
        { city: 'Munich', aliases: ['Muenchen'], population: 1378000 },
      previous: [
        { city: 'San Francisco', aliases: ['SF', 'San Fran'], population: 812826 },
        { city: 'Toronto', aliases: ['TO', 'T-dot'], population: 2615000 }
      ]
    };
  };

  test("basic", function() {
    // Updates the value of `node` to be the sum of the values of its subtrees.
    // Ignores leaf nodes.
    var visitor = function(node) {
      if (node.l && node.r)
        node.val = node.l.val + node.r.val;
    };

    var tree = getSimpleTestTree();
    _.walk.postorder(tree, visitor);
    equal(tree.val, 16, 'should visit subtrees first');

    tree = getSimpleTestTree();
    _.walk.preorder(tree, visitor);
    equal(tree.val, 5, 'should visit subtrees after the node itself');
  });

  test("circularRefs", function() {
    var tree = getSimpleTestTree();
    tree.l.l.r = tree;
    throws(function() { _.walk.preorder(tree, _.identity); }, TypeError, 'preorder throws an exception');
    throws(function() { _.walk.postrder(tree, _.identity); }, TypeError, 'postorder throws an exception');

    tree = getSimpleTestTree();
    tree.r.l = tree.r;
    throws(function() { _.walk.preorder(tree, _.identity); }, TypeError, 'exception for a self-referencing node');
  });

  test("simpleMap", function() {
    var visitor = function(node, key, parent) {
      if (_.has(node, 'val')) return node.val;
      if (key !== 'val') throw Error('Leaf node with incorrect key');
      return this.leafChar || '-';
    };
    var visited = _.walk.map(getSimpleTestTree(), _.walk.preorder, visitor).join('');
    equal(visited, '0-1-2-3-4-5-6-', 'pre-order map');

    visited = _.walk.map(getSimpleTestTree(), _.walk.postorder, visitor).join('');
    equal(visited, '---2-31--5-640', 'post-order map');

    var context = { leafChar: '*' };
    visited = _.walk.map(getSimpleTestTree(), _.walk.preorder, visitor, context).join('');
    equal(visited, '0*1*2*3*4*5*6*', 'pre-order with context');

    visited = _.walk.map(getSimpleTestTree(), _.walk.postorder, visitor, context).join('');
    equal(visited, '***2*31**5*640', 'post-order with context');

    if (document.querySelector) {
      var root = document.querySelector('#map-test');
      var ids = _.walk.map(root, _.walk.preorder, function(el) { return el.id; });
      deepEqual(ids, ['map-test', 'id1', 'id2'], 'preorder map with DOM elements');

      ids = _.walk.map(root, _.walk.postorder, function(el) { return el.id; });
      deepEqual(ids, ['id1', 'id2', 'map-test'], 'postorder map with DOM elements');
    }
  });

  test("mixedMap", function() {
    var visitor = function(node, key, parent) {
      return _.isString(node) ? node.toLowerCase() : null;
    };

    var tree = getMixedTestTree();
    var preorderResult = _.walk.map(tree, _.walk.preorder, visitor);
    equal(preorderResult.length, 19, 'all nodes are visited');
    deepEqual(_.reject(preorderResult, _.isNull),
        ['munich', 'muenchen', 'san francisco', 'sf', 'san fran', 'toronto', 'to', 't-dot'],
        'pre-order map on a mixed tree');

    var postorderResult = _.walk.map(tree, _.walk.postorder, visitor);
    deepEqual(preorderResult.sort(), postorderResult.sort(), 'post-order map on a mixed tree');

    tree = [['foo'], tree];
    var result = _.walk.map(tree, _.walk.postorder, visitor);
    deepEqual(_.difference(result, postorderResult), ['foo'], 'map on list of trees');
  });

  test("pluck", function() {
    var tree = getSimpleTestTree();
    tree.val = { val: 'z' };

    var plucked = _.walk.pluckRec(tree, 'val');
    equal(plucked.shift(), tree.val);
    equal(plucked.join(''), 'z123456', 'pluckRec is recursive');

    plucked = _.walk.pluck(tree, 'val');
    equal(plucked.shift(), tree.val);
    equal(plucked.join(''), '123456', 'regular pluck is not recursive');

    tree.l.r.foo = 42;
    equal(_.walk.pluck(tree, 'foo'), 42, 'pluck a value from deep in the tree');

    tree = getMixedTestTree();
    deepEqual(_.walk.pluck(tree, 'city'), ['Munich', 'San Francisco', 'Toronto'], 'pluck from a mixed tree');
    tree = [tree, { city: 'Loserville', population: 'you' }];
    deepEqual(_.walk.pluck(tree, 'population'), [1378000, 812826, 2615000, 'you'], 'pluck from a list of trees');
  });

  test("reduce", function() {
    var add = function(a, b) { return a + b; };
    var leafMemo = [];
    var sum = function(memo, node) {
      if (_.isObject(node))
        return _.reduce(memo, add, 0);

      strictEqual(memo, leafMemo);
      return node;
    };
    var tree = getSimpleTestTree();
    equal(_.walk.reduce(tree, sum, leafMemo), 21);

    // A more useful example: transforming a tree.

    // Returns a new node where the left and right subtrees are swapped.
    var mirror = function(memo, node) {
      if (!_.has(node, 'r')) return node;
      return _.extend(_.clone(node), { l: memo.r, r: memo.l });
    };
    // Returns the '-' for internal nodes, and the value itself for leaves.
    var toString =  function(node) { return _.has(node, 'val') ? '-' : node; };

    tree = _.walk.reduce(getSimpleTestTree(), mirror);
    equal(_.walk.reduce(tree, sum, leafMemo), 21);
    equal(_.walk.map(tree, _.walk.preorder, toString).join(''), '-0-4-6-5-1-3-2', 'pre-order map');
  });

  test("find", function() {
    var tree = getSimpleTestTree();

    // Returns a visitor function that will succeed when a node with the given
    // value is found, and then raise an exception the next time it's called.
    var findValue = function(value) {
      var found = false;
      return function(node) {
        if (found) throw 'already found!';
        found = (node.val === value);
        return found;
      };
    };

    equal(_.walk.find(tree, findValue(0)).val, 0);
    equal(_.walk.find(tree, findValue(6)).val, 6);
    deepEqual(_.walk.find(tree, findValue(99)), undefined);
  });

  test("filter", function() {
    var tree = getSimpleTestTree();
    tree.r.val = '.oOo.';  // Remove one of the numbers.
    var isEvenNumber = function(x) {
      return _.isNumber(x) && x % 2 === 0;
    };

    equal(_.walk.filter(tree, _.walk.preorder, _.isObject).length, 7, 'filter objects');
    equal(_.walk.filter(tree, _.walk.preorder, _.isNumber).length, 6, 'filter numbers');
    equal(_.walk.filter(tree, _.walk.postorder, _.isNumber).length, 6, 'postorder filter numbers');
    equal(_.walk.filter(tree, _.walk.preorder, isEvenNumber).length, 3, 'filter even numbers');

    // With the identity function, only the value '0' should be omitted.
    equal(_.walk.filter(tree, _.walk.preorder, _.identity).length, 13, 'filter on identity function');
  });

  test("reject", function() {
    var tree = getSimpleTestTree();
    tree.r.val = '.oOo.';  // Remove one of the numbers.

    equal(_.walk.reject(tree, _.walk.preorder, _.isObject).length, 7, 'reject objects');
    equal(_.walk.reject(tree, _.walk.preorder, _.isNumber).length, 8, 'reject numbers');
    equal(_.walk.reject(tree, _.walk.postorder, _.isNumber).length, 8, 'postorder reject numbers');

    // With the identity function, only the value '0' should be kept.
    equal(_.walk.reject(tree, _.walk.preorder, _.identity).length, 1, 'reject with identity function');
  });

  test("customTraversal", function() {
    var tree = getSimpleTestTree();

    // Set up a walker that will not traverse the 'val' properties.
    var walker = _.walk(function(node) {
      return _.omit(node, 'val');
    });
    var visitor = function(node) {
      if (!_.isObject(node)) throw Error("Leaf value visited when it shouldn't be");
    };
    equal(walker.pluck(tree, 'val').length, 7, 'pluck with custom traversal');
    equal(walker.pluckRec(tree, 'val').length, 7, 'pluckRec with custom traversal');

    equal(walker.map(tree, _.walk.postorder, _.identity).length, 7, 'traversal strategy is dynamically scoped');

    // Check that the default walker is unaffected.
    equal(_.walk.map(tree, _.walk.postorder, _.identity).length, 14, 'default map still works');
    equal(_.walk.pluckRec(tree, 'val').join(''), '0123456', 'default pluckRec still works');
  });
});
<commit_msg>Add missing 'new'<commit_after>$(document).ready(function() {

  module("underscore.collections.walk");

  var getSimpleTestTree = function() {
    return {
      val: 0,
      l: { val: 1, l: { val: 2 }, r: { val: 3 } },
      r: { val: 4, l: { val: 5 }, r: { val: 6 } }
    };
  };

  var getMixedTestTree = function() {
    return {
      current:
        { city: 'Munich', aliases: ['Muenchen'], population: 1378000 },
      previous: [
        { city: 'San Francisco', aliases: ['SF', 'San Fran'], population: 812826 },
        { city: 'Toronto', aliases: ['TO', 'T-dot'], population: 2615000 }
      ]
    };
  };

  test("basic", function() {
    // Updates the value of `node` to be the sum of the values of its subtrees.
    // Ignores leaf nodes.
    var visitor = function(node) {
      if (node.l && node.r)
        node.val = node.l.val + node.r.val;
    };

    var tree = getSimpleTestTree();
    _.walk.postorder(tree, visitor);
    equal(tree.val, 16, 'should visit subtrees first');

    tree = getSimpleTestTree();
    _.walk.preorder(tree, visitor);
    equal(tree.val, 5, 'should visit subtrees after the node itself');
  });

  test("circularRefs", function() {
    var tree = getSimpleTestTree();
    tree.l.l.r = tree;
    throws(function() { _.walk.preorder(tree, _.identity); }, TypeError, 'preorder throws an exception');
    throws(function() { _.walk.postrder(tree, _.identity); }, TypeError, 'postorder throws an exception');

    tree = getSimpleTestTree();
    tree.r.l = tree.r;
    throws(function() { _.walk.preorder(tree, _.identity); }, TypeError, 'exception for a self-referencing node');
  });

  test("simpleMap", function() {
    var visitor = function(node, key, parent) {
      if (_.has(node, 'val')) return node.val;
      if (key !== 'val') throw new Error('Leaf node with incorrect key');
      return this.leafChar || '-';
    };
    var visited = _.walk.map(getSimpleTestTree(), _.walk.preorder, visitor).join('');
    equal(visited, '0-1-2-3-4-5-6-', 'pre-order map');

    visited = _.walk.map(getSimpleTestTree(), _.walk.postorder, visitor).join('');
    equal(visited, '---2-31--5-640', 'post-order map');

    var context = { leafChar: '*' };
    visited = _.walk.map(getSimpleTestTree(), _.walk.preorder, visitor, context).join('');
    equal(visited, '0*1*2*3*4*5*6*', 'pre-order with context');

    visited = _.walk.map(getSimpleTestTree(), _.walk.postorder, visitor, context).join('');
    equal(visited, '***2*31**5*640', 'post-order with context');

    if (document.querySelector) {
      var root = document.querySelector('#map-test');
      var ids = _.walk.map(root, _.walk.preorder, function(el) { return el.id; });
      deepEqual(ids, ['map-test', 'id1', 'id2'], 'preorder map with DOM elements');

      ids = _.walk.map(root, _.walk.postorder, function(el) { return el.id; });
      deepEqual(ids, ['id1', 'id2', 'map-test'], 'postorder map with DOM elements');
    }
  });

  test("mixedMap", function() {
    var visitor = function(node, key, parent) {
      return _.isString(node) ? node.toLowerCase() : null;
    };

    var tree = getMixedTestTree();
    var preorderResult = _.walk.map(tree, _.walk.preorder, visitor);
    equal(preorderResult.length, 19, 'all nodes are visited');
    deepEqual(_.reject(preorderResult, _.isNull),
        ['munich', 'muenchen', 'san francisco', 'sf', 'san fran', 'toronto', 'to', 't-dot'],
        'pre-order map on a mixed tree');

    var postorderResult = _.walk.map(tree, _.walk.postorder, visitor);
    deepEqual(preorderResult.sort(), postorderResult.sort(), 'post-order map on a mixed tree');

    tree = [['foo'], tree];
    var result = _.walk.map(tree, _.walk.postorder, visitor);
    deepEqual(_.difference(result, postorderResult), ['foo'], 'map on list of trees');
  });

  test("pluck", function() {
    var tree = getSimpleTestTree();
    tree.val = { val: 'z' };

    var plucked = _.walk.pluckRec(tree, 'val');
    equal(plucked.shift(), tree.val);
    equal(plucked.join(''), 'z123456', 'pluckRec is recursive');

    plucked = _.walk.pluck(tree, 'val');
    equal(plucked.shift(), tree.val);
    equal(plucked.join(''), '123456', 'regular pluck is not recursive');

    tree.l.r.foo = 42;
    equal(_.walk.pluck(tree, 'foo'), 42, 'pluck a value from deep in the tree');

    tree = getMixedTestTree();
    deepEqual(_.walk.pluck(tree, 'city'), ['Munich', 'San Francisco', 'Toronto'], 'pluck from a mixed tree');
    tree = [tree, { city: 'Loserville', population: 'you' }];
    deepEqual(_.walk.pluck(tree, 'population'), [1378000, 812826, 2615000, 'you'], 'pluck from a list of trees');
  });

  test("reduce", function() {
    var add = function(a, b) { return a + b; };
    var leafMemo = [];
    var sum = function(memo, node) {
      if (_.isObject(node))
        return _.reduce(memo, add, 0);

      strictEqual(memo, leafMemo);
      return node;
    };
    var tree = getSimpleTestTree();
    equal(_.walk.reduce(tree, sum, leafMemo), 21);

    // A more useful example: transforming a tree.

    // Returns a new node where the left and right subtrees are swapped.
    var mirror = function(memo, node) {
      if (!_.has(node, 'r')) return node;
      return _.extend(_.clone(node), { l: memo.r, r: memo.l });
    };
    // Returns the '-' for internal nodes, and the value itself for leaves.
    var toString =  function(node) { return _.has(node, 'val') ? '-' : node; };

    tree = _.walk.reduce(getSimpleTestTree(), mirror);
    equal(_.walk.reduce(tree, sum, leafMemo), 21);
    equal(_.walk.map(tree, _.walk.preorder, toString).join(''), '-0-4-6-5-1-3-2', 'pre-order map');
  });

  test("find", function() {
    var tree = getSimpleTestTree();

    // Returns a visitor function that will succeed when a node with the given
    // value is found, and then raise an exception the next time it's called.
    var findValue = function(value) {
      var found = false;
      return function(node) {
        if (found) throw 'already found!';
        found = (node.val === value);
        return found;
      };
    };

    equal(_.walk.find(tree, findValue(0)).val, 0);
    equal(_.walk.find(tree, findValue(6)).val, 6);
    deepEqual(_.walk.find(tree, findValue(99)), undefined);
  });

  test("filter", function() {
    var tree = getSimpleTestTree();
    tree.r.val = '.oOo.';  // Remove one of the numbers.
    var isEvenNumber = function(x) {
      return _.isNumber(x) && x % 2 === 0;
    };

    equal(_.walk.filter(tree, _.walk.preorder, _.isObject).length, 7, 'filter objects');
    equal(_.walk.filter(tree, _.walk.preorder, _.isNumber).length, 6, 'filter numbers');
    equal(_.walk.filter(tree, _.walk.postorder, _.isNumber).length, 6, 'postorder filter numbers');
    equal(_.walk.filter(tree, _.walk.preorder, isEvenNumber).length, 3, 'filter even numbers');

    // With the identity function, only the value '0' should be omitted.
    equal(_.walk.filter(tree, _.walk.preorder, _.identity).length, 13, 'filter on identity function');
  });

  test("reject", function() {
    var tree = getSimpleTestTree();
    tree.r.val = '.oOo.';  // Remove one of the numbers.

    equal(_.walk.reject(tree, _.walk.preorder, _.isObject).length, 7, 'reject objects');
    equal(_.walk.reject(tree, _.walk.preorder, _.isNumber).length, 8, 'reject numbers');
    equal(_.walk.reject(tree, _.walk.postorder, _.isNumber).length, 8, 'postorder reject numbers');

    // With the identity function, only the value '0' should be kept.
    equal(_.walk.reject(tree, _.walk.preorder, _.identity).length, 1, 'reject with identity function');
  });

  test("customTraversal", function() {
    var tree = getSimpleTestTree();

    // Set up a walker that will not traverse the 'val' properties.
    var walker = _.walk(function(node) {
      return _.omit(node, 'val');
    });
    var visitor = function(node) {
      if (!_.isObject(node)) throw new Error("Leaf value visited when it shouldn't be");
    };
    equal(walker.pluck(tree, 'val').length, 7, 'pluck with custom traversal');
    equal(walker.pluckRec(tree, 'val').length, 7, 'pluckRec with custom traversal');

    equal(walker.map(tree, _.walk.postorder, _.identity).length, 7, 'traversal strategy is dynamically scoped');

    // Check that the default walker is unaffected.
    equal(_.walk.map(tree, _.walk.postorder, _.identity).length, 14, 'default map still works');
    equal(_.walk.pluckRec(tree, 'val').join(''), '0123456', 'default pluckRec still works');
  });
});
<|endoftext|>


<commit_before>/* global chai */
/* global sinon */
/* global describe */
/* global it */

import { isFSA } from 'flux-standard-action';
import configureStore from 'redux-mock-store';
import thunk from 'redux-thunk';

import actions from '../../../../app/redux/actions/index';

import initialState from '../../../../app/redux/reducers/initialState';

describe('Actions', () => {
  const mockStore = configureStore([thunk]);

  describe('Asyncronous Actions', () => {
    describe('signup', (done) => {
      it('for a successful request, it should trigger SIGNUP_SUCESS and it should call signup and get once', () => {
        let user = { id: 27 };
        let api = {
          user: {
            signup: sinon.stub().callsArgWith(1, null, 'success!'),
            get: sinon.stub().callsArgWith(0, null, user)
          }
        };

        let expectedActions = [
          { type: 'SIGNUP_REQUEST' },
          { type: 'SIGNUP_SUCCESS', payload: { user: { id: 27 } } }
        ];
        let store = mockStore(initialState, expectedActions, done);

        store.dispatch(actions.async.signup(api, {foo: 'bar'}));

        expect(api.user.signup.callCount).to.equal(1);
        expect(api.user.get.callCount).to.equal(1);
      });
    });
  });

  describe('Syncronous Actions', () => {

  });
});<commit_msg>Add pending tests for actionCreators and implement isFSA checks for sync actionCreators<commit_after>/* global chai */
/* global sinon */
/* global describe */
/* global it */

import { isFSA } from 'flux-standard-action';
import configureStore from 'redux-mock-store';
import thunk from 'redux-thunk';

import actions from '../../../../app/redux/actions/index';

import initialState from '../../../../app/redux/reducers/initialState';

describe('Actions', () => {
  const mockStore = configureStore([thunk]);

  describe('Asyncronous Actions', () => {
    describe('signup', (done) => {
      it('should trigger SIGNUP_SUCCESS and it should call signup and get once for a successful request', () => {
        let user = { id: 27 };
        let api = {
          user: {
            signup: sinon.stub().callsArgWith(1, null, 'success!'),
            get: sinon.stub().callsArgWith(0, null, user)
          }
        };

        let expectedActions = [
          { type: 'SIGNUP_REQUEST' },
          { type: 'SIGNUP_SUCCESS', payload: { user: { id: 27 } } }
        ];
        let store = mockStore(initialState, expectedActions, done);

        store.dispatch(actions.async.signup(api, {foo: 'bar'}));

        expect(api.user.signup.callCount).to.equal(1);
        expect(api.user.get.callCount).to.equal(1);
      });

      it('should trigger SIGNUP_FAILURE and it should call signup once and get zero times for a failed signup request', () => {
        let user = { id: 27 };
        let api = {
          user: {
            signup: sinon.stub().callsArgWith(1, 'fail!', null),
            get: sinon.stub()
          }
        };

        let expectedActions = [
          { type: 'SIGNUP_REQUEST' },
          { type: 'SIGNUP_FAILURE', error: 'fail!' }
        ];
        let store = mockStore(initialState, expectedActions, done);

        store.dispatch(actions.async.signup(api, {foo: 'bar'}));

        expect(api.user.signup.callCount).to.equal(1);
        expect(api.user.get.callCount).to.equal(0);
      });

      it('should trigger SIGNUP_FAILURE and it should call signup and get once for a failed user retrieval', () => {
        let user = { id: 27 };
        let api = {
          user: {
            signup: sinon.stub().callsArgWith(1, null, 'success!'),
            get: sinon.stub().callsArgWith(0, 'failed user retrieval!', null)
          }
        };

        let expectedActions = [
          { type: 'SIGNUP_REQUEST' },
          { type: 'SIGNUP_FAILURE', error: 'failed user retrieval!' }
        ];
        let store = mockStore(initialState, expectedActions, done);

        store.dispatch(actions.async.signup(api, {foo: 'bar'}));

        expect(api.user.signup.callCount).to.equal(1);
        expect(api.user.get.callCount).to.equal(1);
      });
    });

    describe('confirmSignup', () => {
      it('should trigger CONFIRM_SIGNUP_SUCCESS and it should call confirmSignup once for a successful request');

      it('should trigger CONFIRM_SIGNUP_FAILURE and it should call confirmSignup once for a failed request');
    });

    describe('login', () => {
      it('should trigger LOGIN_SUCCESS and it should call login and user.get once for a successful request');

      it('should trigger LOGIN_FAILURE and it should call login once and user.get zero times for a failed login request');

      it('should trigger LOGIN_FAILURE and it should call login and user.get once for a failed user.get request');
    });

    describe('logout', () => {
      it('should trigger LOGOUT_SUCCESS and it should call logout once for a successful request');

      it('should trigger LOGOUT_FAILURE and it should call logout once for a failed request');
    });

    describe('logApiError', () => {
      it('should trigger LOG_ERROR_SUCCESS and it should call error once for a successful request');

      it('should trigger LOG_ERROR_FAILURE and it should call error once for a failed request');
    });
  });

  describe('Syncronous Actions', () => {
    describe('showWelcomeMessage', () => {
      it('should be a FSA', () => {
        let action = actions.sync.showWelcomeMessage();

        expect(isFSA(action)).to.be.true;
      });

      it('type should equal SHOW_WELCOME_MESSAGE');
    });

    describe('hideWelcomeMessage', () => {
      it('should be a FSA', () => {
        let action = actions.sync.hideWelcomeMessage();

        expect(isFSA(action)).to.be.true;
      });

      it('type should equal HIDE_WELCOME_MESSAGE');
    });

    describe('showNotification', () => {
      it('should be a FSA', () => {
        let action = actions.sync.showNotification('Fake notification');

        expect(isFSA(action)).to.be.true;
      });

      it('type should equal SHOW_NOTIFICATION');
    });

    describe('closeNotification', () => {
      it('should be a FSA', () => {
        let action = actions.sync.closeNotification();

        expect(isFSA(action)).to.be.true;
      });

      it('type should equal CLOSE_NOTIFICATION');
    });

    describe('loginRequest', () => {
      it('should be a FSA', () => {
        let action = actions.sync.loginRequest();

        expect(isFSA(action)).to.be.true;
      });

      it('type should equal LOGIN_REQUEST');
    });

    describe('loginSuccess', () => {
      it('should be a FSA', () => {
        let user = { id: 27, name: 'Frankie' };
        let action = actions.sync.loginSuccess(user);

        expect(isFSA(action)).to.be.true;
      });

      it('type should equal LOGIN_SUCCESS and payload should contain user');
    });

    describe('loginFailure', () => {
      it('should be a FSA', () => {
        let error = 'Error';
        let action = actions.sync.loginFailure(error);

        expect(isFSA(action)).to.be.true;
      });

      it('type should equal LOGIN_FAILURE and error should equal passed error');
    });

    describe('logoutRequest', () => {
      it('should be a FSA', () => {
        let action = actions.sync.logoutRequest();

        expect(isFSA(action)).to.be.true;
      });

      it('type should equal LOGOUT_REQUEST');
    });

    describe('logoutSuccess', () => {
      it('should be a FSA', () => {
        let user = { id: 27, name: 'Frankie' };
        let action = actions.sync.logoutSuccess(user);

        expect(isFSA(action)).to.be.true;
      });

      it('type should equal LOGOUT_SUCCESS');
    });

    describe('logoutFailure', () => {
      it('should be a FSA', () => {
        let error = 'Error';
        let action = actions.sync.logoutFailure(error);

        expect(isFSA(action)).to.be.true;
      });

      it('type should equal LOGOUT_FAILURE and error should equal passed error');
    });

    describe('signupRequest', () => {
      it('should be a FSA', () => {
        let action = actions.sync.signupRequest();

        expect(isFSA(action)).to.be.true;
      });

      it('type should equal SIGNUP_REQUEST');
    });

    describe('signupSuccess', () => {
      it('should be a FSA', () => {
        let user = { id: 27, name: 'Frankie' };
        let action = actions.sync.signupSuccess(user);

        expect(isFSA(action)).to.be.true;
      });

      it('type should equal SIGNUP_SUCCESS and payload should contain user');
    });

    describe('signupFailure', () => {
      it('should be a FSA', () => {
        let error = 'Error';
        let action = actions.sync.signupFailure(error);

        expect(isFSA(action)).to.be.true;
      });

      it('type should equal SIGNUP_FAILURE and error should equal passed error');
    });

    describe('confirmSignupRequest', () => {
      it('should be a FSA', () => {
        let action = actions.sync.confirmSignupRequest();

        expect(isFSA(action)).to.be.true;
      });

      it('type should equal CONFIRM_SIGNUP_REQUEST');
    });

    describe('confirmSignupSuccess', () => {
      it('should be a FSA', () => {
        let user = { id: 27, name: 'Frankie' };
        let action = actions.sync.confirmSignupSuccess(user);

        expect(isFSA(action)).to.be.true;
      });

      it('type should equal CONFIRM_SIGNUP_SUCCESS');
    });

    describe('confirmSignupFailure', () => {
      it('should be a FSA', () => {
        let error = 'Error';
        let action = actions.sync.confirmSignupFailure(error);

        expect(isFSA(action)).to.be.true;
      });

      it('type should equal CONFIRM_SIGNUP_FAILURE and error should equal passed error');
    });

    describe('logErrorRequest', () => {
      it('should be a FSA', () => {
        let action = actions.sync.logErrorRequest();

        expect(isFSA(action)).to.be.true;
      });

      it('type should equal LOG_ERROR_REQUEST');
    });

    describe('logErrorSuccess', () => {
      it('should be a FSA', () => {
        let action = actions.sync.logErrorSuccess();

        expect(isFSA(action)).to.be.true;
      });

      it('type should equal LOG_ERROR_SUCCESS');
    });

    describe('logErrorFailure', () => {
      it('should be a FSA', () => {
        let error = 'Error';
        let action = actions.sync.logErrorFailure(error);

        expect(isFSA(action)).to.be.true;
      });

      it('type should equal LOG_ERROR_FAILURE and error should equal passed error');
    });
  });
});<|endoftext|>