<commit_before>/*
 * Wegas
 * http://wegas.albasim.ch
 *
 * Copyright (c) 2013-2018  School of Business and Engineering Vaud, Comem, MEI
 * Licensed under the MIT License
 */
/**
 * @fileoverview
 * @author maxence
 */
YUI.add("wegas-prettyprinter", function(Y) {
    "use strict";

    var AbstractPrettyPrinter;

    AbstractPrettyPrinter = Y.Base.create("wegas-prettyprinter-abstract", Y.Widget, [Y.WidgetChild, Y.Wegas.Widget, Y.Wegas.Editable], {
        bindUI: function() {
            this.get("contentBox").delegate("click", this.toPdf, ".print-icon", this);
        },
        renderUI: function() {
            var mode = this.get("displayMode"),
                cb = this.get("contentBox");
            this.html = this.generateHTML();
            this.title = this.generateTitle();

            if (mode === "plain" || mode === "both") {
                cb.append("
" + this.html + "
");
            }

            if (mode === "icon" || mode === "both") {
                cb.append("

");
            }

        },
        go: function(theVar, level) {
            var output, i, items, l;

            l = level || 0;

            if (theVar.get("@class") === this.constructor.PRETTYPRINT) {
                return this.generateOutput(theVar);
            } else if (theVar.isAugmentedBy && theVar.isAugmentedBy(Y.Wegas.persistence.VariableContainer)) {
                output = this.newFolderStart(theVar, l);
                items = theVar.get("items");
                for (i in items) {
                    output += this.go(items[i], l + 1);
                }
                output += this.newFolderEnd(theVar, l);
                return output;
            } else {
                return this.generateOutput(theVar);
            }
        },
        newFolderStart: function(theVar, level) {
            return "" + I18n.t(theVar.get("label")) + "";
        },
        newFolderEnd: function(theVar, level) {
            return "
";
        },
        generateHTML: function() {
            return this.go(this.get("variable.evaluated"));
        },
        generateTitle: function() {
            return Y.Wegas.Facade.Game.cache.getCurrentGame().get("name") + " / " + Y.Wegas.Facade.Game.cache.getCurrentTeam().get("name");
        },
        generateOutput: function(theVar) {
            return "
Not yet implemented (\"" + I18n.t(theVar.get("label")) + "\")
";
        },
        toPdf: function() {
            var pdfLink = Y.Wegas.app.get("base") + "print.html";
            this.post(pdfLink, {"title": this.toEntities(this.title || "A Pdf Generated by Wegas"), "body": this.toEntities(this.html), "outputType": this.get("outputType")});
        },
        /*
         ** Opens a new tab where the given data is posted:
         */
        post: function(url, postData) {
            var tabWindowId = window.open('about:blank', '_blank');
            tabWindowId.document.title = postData.title;
            var form = tabWindowId.document.createElement("form");
            form.setAttribute("method", "post");
            form.setAttribute("action", url);

            for (var key in postData) {
                if (postData.hasOwnProperty(key)) {
                    var hiddenField = tabWindowId.document.createElement("input");
                    hiddenField.setAttribute("type", "hidden");
                    hiddenField.setAttribute("name", key);
                    hiddenField.setAttribute("value", postData[key]);
                    form.appendChild(hiddenField);
                }
            }
            // var btn = tabWindowId.document.createElement("button"); btn.appendChild(tabWindowId.document.createTextNode("SUBMIT")); form.appendChild(btn);
            tabWindowId.document.body.appendChild(form);
            form.submit();
        },
        // Convert characters to HTML entities to protect against encoding issues:
        toEntities: function(text) {
            return text.replace(/[\u00A0-\u2666]/g, function(c) {
                return '&#' + c.charCodeAt(0) + ';';
            });
        }
    }, {
        EDITORNAME: "Abstract PrettyPrinter",
        ATTRS: {
            displayMode: {
                type: "string",
                value: "icon", // icon, plain, or both
                view: {
                    type: "select",
                    choices: ["icon", "plain", "both"],
                    label: "Display "
                }
            },
            outputType: {
                type: "string",
                value: "pdf",
                view: {
                    type: "select",
                    choices: ["pdf", "html"],
                    label: "Format "
                }
            },
            variable: {
                getter: Y.Wegas.Widget.VARIABLEDESCRIPTORGETTER,
                view: {
                    type: "variableselect",
                    label: "Variable"
                }
            }
        }
    });
    Y.Wegas.AbstractPrettyPrinter = AbstractPrettyPrinter;

    var TextPrettyPrinter = Y.Base.create("wegas-prettyprinter-text", Y.Wegas.AbstractPrettyPrinter, [], {
        newFolderStart: function(theVar, level) {
            return "
";
        },
        newFolderEnd: function(theVar, level) {
            return "
";
        },
        _getValue: function(attr) {
            if (this.get(attr)) {
                var v = this.get(attr + ".evaluated");
                if (v instanceof Y.Wegas.persistence.ListDescriptor) {
                    return v.getLabel();
                } else {
                    return v.getInstance().get("value");
                }
            }
            return null;
        },
        generateTitle: function() {
            var title = this._getValue("title");
            if (!title) {
                title = this._getValue("variable");
            }
            if (!title) {
                title = "Untitled PDF Generated By Wegas";
            }
            return title;
        },
        generateHTML: function() {
            var css = "";
            return css + this.go(this.get("variable.evaluated"));
        },
        generateOutput: function(theVar) {
            var output = "", instance;

            instance = theVar.getInstance();

            output = "
";

            // @hack injector: Place both href and src so it works for a and img tags
            output += instance.get("value").replace(
                new RegExp('data-file="([^"]*)"', 'gi'),
                "src=\"" + Y.Wegas.Facade.File.getPath() + "$1\""
                + " href=\"" + Y.Wegas.Facade.File.getPath() + "$1\"");

            output += "
";

            return output;
        }
    }, {
        EDITORNAME: "Text PrettyPrinter",
        PRETTYPRINT: "TextDescriptor",
        ATTRS: {
            title: {
                getter: Y.Wegas.Widget.VARIABLEDESCRIPTORGETTER,
                type: "object",
                view: {
                    type: "variableselect",
                    label: "Title",
                    classFilter: ["TextDescriptor", "StringDescriptor", "ListDescriptor"]
                }
            },
            variable: {
                getter: Y.Wegas.Widget.VARIABLEDESCRIPTORGETTER,
                type: "object",
                view: {
                    type: "variableselect",
                    label: "Variable",
                    classFilter: ["TextDescriptor", "ListDescriptor"]
                }
            },
            css: {
                type: "string",
                value: "",
                view: {
                    type: "textarea",
                    label: "CUSTOM CSS"
                }
            }
        }
    });
    Y.Wegas.TextPrettyPrinter = TextPrettyPrinter;
});
<commit_msg>Pretty Printed enhancement<commit_after>/*
 * Wegas
 * http://wegas.albasim.ch
 *
 * Copyright (c) 2013-2018  School of Business and Engineering Vaud, Comem, MEI
 * Licensed under the MIT License
 */
/**
 * @fileoverview
 * @author maxence
 */
YUI.add("wegas-prettyprinter", function(Y) {
    "use strict";

    var AbstractPrettyPrinter;

    AbstractPrettyPrinter = Y.Base.create("wegas-prettyprinter-abstract", Y.Widget, [Y.WidgetChild, Y.Wegas.Widget, Y.Wegas.Editable], {
        bindUI: function() {
            this.get("contentBox").delegate("click", this.toPdf, ".print-icon", this);
        },
        renderUI: function() {
            var mode = this.get("displayMode"),
                cb = this.get("contentBox");

            if (mode === "plain" || mode === "both") {
                this.html = this.generateHTML();
                this.title = this.generateTitle();
                cb.append("
" + this.html + "
");
            }

            if (mode === "icon" || mode === "both") {
                cb.append("

");
            }

        },
        go: function(theVar, level) {
            var output, i, items, l;

            l = level || 0;

            if (theVar.get("@class") === this.constructor.PRETTYPRINT) {
                return this.generateOutput(theVar);
            } else if (theVar.isAugmentedBy && theVar.isAugmentedBy(Y.Wegas.persistence.VariableContainer)) {
                output = this.newFolderStart(theVar, l);
                items = theVar.get("items");
                for (i in items) {
                    output += this.go(items[i], l + 1);
                }
                output += this.newFolderEnd(theVar, l);
                return output;
            } else {
                return this.generateOutput(theVar);
            }
        },
        newFolderStart: function(theVar, level) {
            return "" + I18n.t(theVar.get("label")) + "";
        },
        newFolderEnd: function(theVar, level) {
            return "
";
        },
        generateHTML: function() {
            return this.go(this.get("variable.evaluated"));
        },
        generateTitle: function() {
            return Y.Wegas.Facade.Game.cache.getCurrentGame().get("name") + " / " + Y.Wegas.Facade.Game.cache.getCurrentTeam().get("name");
        },
        generateOutput: function(theVar) {
            return "
Not yet implemented (\"" + I18n.t(theVar.get("label")) + "\")
";
        },
        toPdf: function() {
            this.html = this.generateHTML();
            this.title = this.generateTitle();

            var pdfLink = Y.Wegas.app.get("base") + "print.html";
            this.post(pdfLink, {"title": this.toEntities(this.title || "A Pdf Generated by Wegas"), "body": this.toEntities(this.html), "outputType": this.get("outputType")});
        },
        /*
         ** Opens a new tab where the given data is posted:
         */
        post: function(url, postData) {
            var tabWindowId = window.open('about:blank', '_blank');
            tabWindowId.document.title = postData.title;
            var form = tabWindowId.document.createElement("form");
            form.setAttribute("method", "post");
            form.setAttribute("action", url);

            for (var key in postData) {
                if (postData.hasOwnProperty(key)) {
                    var hiddenField = tabWindowId.document.createElement("input");
                    hiddenField.setAttribute("type", "hidden");
                    hiddenField.setAttribute("name", key);
                    hiddenField.setAttribute("value", postData[key]);
                    form.appendChild(hiddenField);
                }
            }
            // var btn = tabWindowId.document.createElement("button"); btn.appendChild(tabWindowId.document.createTextNode("SUBMIT")); form.appendChild(btn);
            tabWindowId.document.body.appendChild(form);
            form.submit();
        },
        // Convert characters to HTML entities to protect against encoding issues:
        toEntities: function(text) {
            return text.replace(/[\u00A0-\u2666]/g, function(c) {
                return '&#' + c.charCodeAt(0) + ';';
            });
        }
    }, {
        EDITORNAME: "Abstract PrettyPrinter",
        ATTRS: {
            displayMode: {
                type: "string",
                value: "icon", // icon, plain, or both
                view: {
                    type: "select",
                    choices: ["icon", "plain", "both"],
                    label: "Display "
                }
            },
            outputType: {
                type: "string",
                value: "pdf",
                view: {
                    type: "select",
                    choices: ["pdf", "html"],
                    label: "Format "
                }
            },
            variable: {
                getter: Y.Wegas.Widget.VARIABLEDESCRIPTORGETTER,
                view: {
                    type: "variableselect",
                    label: "Variable"
                }
            }
        }
    });
    Y.Wegas.AbstractPrettyPrinter = AbstractPrettyPrinter;

    var TextPrettyPrinter = Y.Base.create("wegas-prettyprinter-text", Y.Wegas.AbstractPrettyPrinter, [], {
        newFolderStart: function(theVar, level) {
            return "
";
        },
        newFolderEnd: function(theVar, level) {
            return "
";
        },
        _getValue: function(attr) {
            if (this.get(attr)) {
                var v = this.get(attr + ".evaluated");
                if (v instanceof Y.Wegas.persistence.ListDescriptor) {
                    return v.getLabel();
                } else {
                    return v.getInstance().get("value");
                }
            }
            return null;
        },
        generateTitle: function() {
            var title = this._getValue("title");
            if (!title) {
                title = this._getValue("variable");
            }
            if (!title) {
                title = "Untitled PDF Generated By Wegas";
            }
            return title;
        },
        generateHTML: function() {
            var css = "";
            return css + this.go(this.get("variable.evaluated"));
        },
        generateOutput: function(theVar) {
            var output = "", instance;

            instance = theVar.getInstance();

            output = "
";

            // @hack injector: Place both href and src so it works for a and img tags
            output += instance.get("value").replace(
                new RegExp('data-file="([^"]*)"', 'gi'),
                "src=\"" + Y.Wegas.Facade.File.getPath() + "$1\""
                + " href=\"" + Y.Wegas.Facade.File.getPath() + "$1\"");

            output += "
";

            return output;
        }
    }, {
        EDITORNAME: "Text PrettyPrinter",
        PRETTYPRINT: "TextDescriptor",
        ATTRS: {
            title: {
                getter: Y.Wegas.Widget.VARIABLEDESCRIPTORGETTER,
                type: "object",
                view: {
                    type: "variableselect",
                    label: "Title",
                    classFilter: ["TextDescriptor", "StringDescriptor", "ListDescriptor"]
                }
            },
            variable: {
                getter: Y.Wegas.Widget.VARIABLEDESCRIPTORGETTER,
                type: "object",
                view: {
                    type: "variableselect",
                    label: "Variable",
                    classFilter: ["TextDescriptor", "ListDescriptor"]
                }
            },
            css: {
                type: "string",
                value: "",
                view: {
                    type: "textarea",
                    label: "CUSTOM CSS"
                }
            }
        }
    });
    Y.Wegas.TextPrettyPrinter = TextPrettyPrinter;
});
<|endoftext|>


<commit_before>'use strict';
const execa = require('execa');
const inquirer = require('inquirer');
const readPkgUp = require('read-pkg-up');
const chalk = require('chalk');
const version = require('./version');

module.exports = options => {
	const pkg = readPkgUp.sync().pkg;
	const oldVersion = pkg.version;

	console.log(`\nPublish a new version of ${chalk.bold.magenta(pkg.name)} ${chalk.dim(`(${oldVersion})`)}\n`);

	const prompts = [
		{
			type: 'list',
			name: 'version',
			message: 'Select semver increment or specify new version',
			choices: version.SEMVER_INCREMENTS
				.map(inc => ({
					name: `${inc} ${chalk.gray.dim(`(${version.getNewVersion(oldVersion, inc)})`)}`,
					value: inc
				}))
				.concat([
					new inquirer.Separator(),
					{
						name: 'Other (specify)',
						value: null
					}
				]),
			filter: input => version.isValidVersionInput(input) ? version.getNewVersion(oldVersion, input) : input
		},
		{
			type: 'input',
			name: 'version',
			message: 'Version',
			when: answers => !answers.version,
			filter: input => version.isValidVersionInput(input) ? version.getNewVersion(pkg.version, input) : input,
			validate: input => {
				if (!version.isValidVersionInput(input)) {
					return 'Please specify a valid semver, for example, `1.2.3`. See http://semver.org';
				} else if (!version.isVersionGreater(oldVersion, input)) {
					return `Version must be greater than ${oldVersion}`;
				}

				return true;
			}
		},
		{
			type: 'list',
			name: 'tag',
			message: 'How should this pre-release version be tagged in npm?',
			when: answers => !pkg.private && version.isPrereleaseVersion(answers.version) && !options.tag,
			choices: () => execa.stdout('npm', ['dist-tag', 'ls'])
				.then(stdout => {
					const existingPrereleaseTags = stdout.split('\n')
						.map(line => line.split(':')[0].replace(/^\s|\s$/, ''))
						.filter(line => line.toLowerCase() !== 'latest');

					if (existingPrereleaseTags.length === 0) {
						existingPrereleaseTags.push('next');
					}

					return existingPrereleaseTags
						.concat([
							new inquirer.Separator(),
							{
								name: 'Other (specify)',
								value: null
							}
						]);
				})
		},
		{
			type: 'input',
			name: 'tag',
			message: 'Tag',
			when: answers => !pkg.private && version.isPrereleaseVersion(answers.version) && !options.tag && !answers.tag,
			validate: input => {
				if (input.length === 0) {
					return 'Please specify a tag, for example, `next`.';
				} else if (input.toLowerCase() === 'latest') {
					return 'It\'s not possible to publish pre-releases under the `latest` tag. Please specify something else, for example, `next`.';
				}
				return true;
			}
		},
		{
			type: 'confirm',
			name: 'confirm',
			message: answers => {
				const tag = answers.tag || options.tag;
				const tagPart = tag ? ` and tag this release in npm as ${tag}` : '';

				return `Will bump from ${chalk.cyan(oldVersion)} to ${chalk.cyan(answers.version + tagPart)}. Continue?`;
			}
		}
	];

	return inquirer
		.prompt(prompts)
		.then(answers => Object.assign({}, options, answers));
};
<commit_msg>Use npm view instead of dist-tag (#101)<commit_after>'use strict';
const execa = require('execa');
const inquirer = require('inquirer');
const readPkgUp = require('read-pkg-up');
const chalk = require('chalk');
const version = require('./version');

module.exports = options => {
	const pkg = readPkgUp.sync().pkg;
	const oldVersion = pkg.version;

	console.log(`\nPublish a new version of ${chalk.bold.magenta(pkg.name)} ${chalk.dim(`(${oldVersion})`)}\n`);

	const prompts = [
		{
			type: 'list',
			name: 'version',
			message: 'Select semver increment or specify new version',
			choices: version.SEMVER_INCREMENTS
				.map(inc => ({
					name: `${inc} ${chalk.gray.dim(`(${version.getNewVersion(oldVersion, inc)})`)}`,
					value: inc
				}))
				.concat([
					new inquirer.Separator(),
					{
						name: 'Other (specify)',
						value: null
					}
				]),
			filter: input => version.isValidVersionInput(input) ? version.getNewVersion(oldVersion, input) : input
		},
		{
			type: 'input',
			name: 'version',
			message: 'Version',
			when: answers => !answers.version,
			filter: input => version.isValidVersionInput(input) ? version.getNewVersion(pkg.version, input) : input,
			validate: input => {
				if (!version.isValidVersionInput(input)) {
					return 'Please specify a valid semver, for example, `1.2.3`. See http://semver.org';
				} else if (!version.isVersionGreater(oldVersion, input)) {
					return `Version must be greater than ${oldVersion}`;
				}

				return true;
			}
		},
		{
			type: 'list',
			name: 'tag',
			message: 'How should this pre-release version be tagged in npm?',
			when: answers => !pkg.private && version.isPrereleaseVersion(answers.version) && !options.tag,
			choices: () => execa.stdout('npm', ['view', '--json', pkg.name, 'dist-tags'])
				.then(stdout => {
					const existingPrereleaseTags = Object.keys(JSON.parse(stdout))
						.filter(tag => tag !== 'latest');

					if (existingPrereleaseTags.length === 0) {
						existingPrereleaseTags.push('next');
					}

					return existingPrereleaseTags
						.concat([
							new inquirer.Separator(),
							{
								name: 'Other (specify)',
								value: null
							}
						]);
				})
		},
		{
			type: 'input',
			name: 'tag',
			message: 'Tag',
			when: answers => !pkg.private && version.isPrereleaseVersion(answers.version) && !options.tag && !answers.tag,
			validate: input => {
				if (input.length === 0) {
					return 'Please specify a tag, for example, `next`.';
				} else if (input.toLowerCase() === 'latest') {
					return 'It\'s not possible to publish pre-releases under the `latest` tag. Please specify something else, for example, `next`.';
				}
				return true;
			}
		},
		{
			type: 'confirm',
			name: 'confirm',
			message: answers => {
				const tag = answers.tag || options.tag;
				const tagPart = tag ? ` and tag this release in npm as ${tag}` : '';

				return `Will bump from ${chalk.cyan(oldVersion)} to ${chalk.cyan(answers.version + tagPart)}. Continue?`;
			}
		}
	];

	return inquirer
		.prompt(prompts)
		.then(answers => Object.assign({}, options, answers));
};
<|endoftext|>


<commit_before>/***
|''Name''|TiddlySpaceToolbar|
|''Description''|augments tiddler toolbar commands with SVG icons|
|''Author''|Osmosoft|
|''Version''|0.6.1|
|''Status''|@@beta@@|
|''Source''|http://github.com/TiddlySpace/tiddlyspace/raw/master/src/plugins/TiddlySpaceToolbar.js|
|''CodeRepository''|http://github.com/TiddlySpace/tiddlyspace|
|''License''|[[BSD|http://www.opensource.org/licenses/bsd-license.php]]|
|''CoreVersion''|2.5.0|
|''Requires''|ImageMacroPlugin|
|''Keywords''|toolbar icons SVG|
!Description
replaces tiddler toolbar commands with SVG icons if available
!Notes
requires [[ImageMacroPlugin|http://svn.tiddlywiki.org/Trunk/contributors/JonRobson/plugins/ImageMacroPlugin/plugins/ImageMacroPlugin.tid]]

SVG icons are drawn from tiddlers titled {{{<command>.svg}}}
!TODO
* rename (IconToolbarPlugin?)
!Code
***/
//{{{
(function($) {

if(!config.macros.image) {
	throw "Missing dependency: ImageMacroPlugin";
}

var macro = config.macros.toolbar;

macro.icons = {
	cloneTiddler: "editTiddler"
};

var _handler = macro.handler;
macro.handler = function(place, macroName, params, wikifier,
		paramString, tiddler) {
	var toolbar = $(place);
	toolbar.attr({
		refresh: "macro",
		macroName: macroName
	}).data("args", arguments);
	var status = _handler.apply(this, arguments);
	if(tiddler.isReadOnly()) {
		toolbar.addClass("toolbarReadOnly");
	} else {
		toolbar.removeClass("toolbarReadOnly");
	}
	var parsedParams = paramString.parseParams("name")[0];
	if(parsedParams.icons && parsedParams.icons == "yes") {
		this.augmentCommandButtons(place);
	}
	if(parsedParams.more && parsedParams.more == "popup") {
		// note we must override the onclick event like in createTiddlyButton
		// otherwise the click event is the popup AND the slider
		$(".moreCommand", place)[0].onclick = macro.onClickMorePopUp;
	}
	return status;
};

macro.refresh = function(place, params) {
	var args = $(place).empty().data("args");
	this.handler.apply(this, args);
};

var imageMacro = config.macros.image;
macro.augmentCommandButtons = function(toolbar) {
	$(".button", toolbar).each(function(i, el) {
		var cmd = $(el).attr("commandname");
		cmd = cmd ? cmd : "moreCommand"; // XXX: special-casing of moreCommand due to ticket #1234
		var icon = store.tiddlerExists(cmd) ? cmd : macro.icons[cmd];
		var text = $(el).text();
		if(store.tiddlerExists(icon)) {
			$(el).empty();
			imageMacro.renderImage(el, icon, { alt: text });
		}
	});
};

// provide onClickMore to provide extra commands in a popup
macro.onClickMorePopUp = function(ev) {
	ev = ev || window.event;
	var sibling = this.nextSibling;
	var commands = sibling.childNodes;
	var popup = Popup.create(this);
	addClass(popup ,"taggedTiddlerList");
	for(var i = 0; i < commands.length; i++) {
		var li = createTiddlyElement(popup, "li", null);
		var oldCommand = commands[i];
		var command = oldCommand.cloneNode(true);
		command.onclick = oldCommand.onclick;
		li.appendChild(command);
	}
	Popup.show();
	ev.cancelBubble = true;
	if(ev.stopPropagation) {
		ev.stopPropagation();
	}
	return false;
};

})(jQuery);
//}}}
<commit_msg>increment version number<commit_after>/***
|''Name''|TiddlySpaceToolbar|
|''Description''|augments tiddler toolbar commands with SVG icons|
|''Author''|Osmosoft|
|''Version''|0.6.2|
|''Status''|@@beta@@|
|''Source''|http://github.com/TiddlySpace/tiddlyspace/raw/master/src/plugins/TiddlySpaceToolbar.js|
|''CodeRepository''|http://github.com/TiddlySpace/tiddlyspace|
|''License''|[[BSD|http://www.opensource.org/licenses/bsd-license.php]]|
|''CoreVersion''|2.5.0|
|''Requires''|ImageMacroPlugin|
|''Keywords''|toolbar icons SVG|
!Description
replaces tiddler toolbar commands with SVG icons if available
!Notes
requires [[ImageMacroPlugin|http://svn.tiddlywiki.org/Trunk/contributors/JonRobson/plugins/ImageMacroPlugin/plugins/ImageMacroPlugin.tid]]

SVG icons are drawn from tiddlers titled {{{<command>.svg}}}
!TODO
* rename (IconToolbarPlugin?)
!Code
***/
//{{{
(function($) {

if(!config.macros.image) {
	throw "Missing dependency: ImageMacroPlugin";
}

var macro = config.macros.toolbar;

macro.icons = {
	cloneTiddler: "editTiddler"
};

var _handler = macro.handler;
macro.handler = function(place, macroName, params, wikifier,
		paramString, tiddler) {
	var toolbar = $(place);
	toolbar.attr({
		refresh: "macro",
		macroName: macroName
	}).data("args", arguments);
	var status = _handler.apply(this, arguments);
	if(tiddler.isReadOnly()) {
		toolbar.addClass("toolbarReadOnly");
	} else {
		toolbar.removeClass("toolbarReadOnly");
	}
	var parsedParams = paramString.parseParams("name")[0];
	if(parsedParams.icons && parsedParams.icons == "yes") {
		this.augmentCommandButtons(place);
	}
	if(parsedParams.more && parsedParams.more == "popup") {
		// note we must override the onclick event like in createTiddlyButton
		// otherwise the click event is the popup AND the slider
		$(".moreCommand", place)[0].onclick = macro.onClickMorePopUp;
	}
	return status;
};

macro.refresh = function(place, params) {
	var args = $(place).empty().data("args");
	this.handler.apply(this, args);
};

var imageMacro = config.macros.image;
macro.augmentCommandButtons = function(toolbar) {
	$(".button", toolbar).each(function(i, el) {
		var cmd = $(el).attr("commandname");
		cmd = cmd ? cmd : "moreCommand"; // XXX: special-casing of moreCommand due to ticket #1234
		var icon = store.tiddlerExists(cmd) ? cmd : macro.icons[cmd];
		var text = $(el).text();
		if(store.tiddlerExists(icon)) {
			$(el).empty();
			imageMacro.renderImage(el, icon, { alt: text });
		}
	});
};

// provide onClickMore to provide extra commands in a popup
macro.onClickMorePopUp = function(ev) {
	ev = ev || window.event;
	var sibling = this.nextSibling;
	var commands = sibling.childNodes;
	var popup = Popup.create(this);
	addClass(popup ,"taggedTiddlerList");
	for(var i = 0; i < commands.length; i++) {
		var li = createTiddlyElement(popup, "li", null);
		var oldCommand = commands[i];
		var command = oldCommand.cloneNode(true);
		command.onclick = oldCommand.onclick;
		li.appendChild(command);
	}
	Popup.show();
	ev.cancelBubble = true;
	if(ev.stopPropagation) {
		ev.stopPropagation();
	}
	return false;
};

})(jQuery);
//}}}
<|endoftext|>


<commit_before>var Runner = require('integra').Runner;

module.exports = function(configurations) {
  //
  //  SSL tests
  //
  //

  // NOTE NOTE NOTE NOTE NOTE NOTE NOTE NOTE NOTE NOTE NOTE NOTE
  // NOTE NOTE NOTE NOTE NOTE NOTE NOTE NOTE NOTE NOTE NOTE NOTE
  // NOTE NOTE NOTE NOTE NOTE NOTE NOTE NOTE NOTE NOTE NOTE NOTE
  // Add the following line to /etc/hosts
  //    127.0.0.1 server

  // Configure a Run of tests
  var ssl_server_runner = Runner
    // Add configurations to the test runner
    .configurations(configurations)
    .exeuteSerially(true)
    // First parameter is test suite name
    // Second parameter is the configuration used
    // Third parameter is the list of files to execute
    .add("ssl_tests",
      [
          '/test/tests/ssl/mongoclient_tests.js'
        , '/test/tests/ssl/ssl_validation_tests.js'
        , '/test/tests/ssl/x509_validation_tests.js'
      ]
    );

   // Export runners
  return {
    runner: ssl_server_runner
  }
}<commit_msg>Added fips tests to runner<commit_after>var Runner = require('integra').Runner;

module.exports = function(configurations) {
  //
  //  SSL tests
  //
  //

  // NOTE NOTE NOTE NOTE NOTE NOTE NOTE NOTE NOTE NOTE NOTE NOTE
  // NOTE NOTE NOTE NOTE NOTE NOTE NOTE NOTE NOTE NOTE NOTE NOTE
  // NOTE NOTE NOTE NOTE NOTE NOTE NOTE NOTE NOTE NOTE NOTE NOTE
  // Add the following line to /etc/hosts
  //    127.0.0.1 server

  // Configure a Run of tests
  var ssl_server_runner = Runner
    // Add configurations to the test runner
    .configurations(configurations)
    .exeuteSerially(true)
    // First parameter is test suite name
    // Second parameter is the configuration used
    // Third parameter is the list of files to execute
    .add("ssl_tests",
      [
          '/test/tests/ssl/mongoclient_tests.js'
        , '/test/tests/ssl/ssl_validation_tests.js'
        , '/test/tests/ssl/ssl_fips_validation_tests.js'
        , '/test/tests/ssl/x509_validation_tests.js'
      ]
    );

   // Export runners
  return {
    runner: ssl_server_runner
  }
}<|endoftext|>


<commit_before>// we will re-enable the broken browsers once saucelabs will fix all the timeout issues
module.exports = {
  browsers: {
/*
    slIphone6: {
      base: 'SauceLabs',
      device: 'iPhone 6',
      os: 'ios',
      os_version: '9.1'
    },
    slIphone5: {
      base: 'SauceLabs',
      browserName: 'iphone',
      platform: 'OS X 10.10',
      version: '8.1'
    },
    slIpad: {
      base: 'SauceLabs',
      browserName: 'ipad',
      platform: 'iOS',
      deviceName: 'iPad 2',
      version: '9.1'
    },
*/
/*    slSafari9: {
      base: 'SauceLabs',
      browserName: 'safari',
      platform: 'OS X 10.11'
    },
    slSafari8: {
      base: 'SauceLabs',
      browserName: 'safari',
      platform: 'OS X 10.10'
    },*/
    slSafari7: {
      base: 'SauceLabs',
      browserName: 'safari',
      platform: 'OS X 10.9'
    },
    slIE9: {
      base: 'SauceLabs',
      browserName: 'internet explorer',
      platform: 'Windows 7',
      version: '9'
    },
    slIE10: {
      base: 'SauceLabs',
      browserName: 'internet explorer',
      platform: 'Windows 8',
      version: '10'
    },
    slIE11: {
      base: 'SauceLabs',
      browserName: 'internet explorer',
      platform: 'Windows 8.1',
      version: '11'
    },
/*    slEdge: {
      base: 'SauceLabs',
      browserName: 'microsoftedge',
      platform: 'Windows 10',
      version: '20.10240'
    },*/
    slAndroid5: {
      base: 'SauceLabs',
      browserName: 'android',
      version: '5.1'
    },
    slChrome: {
      base: 'SauceLabs',
      browserName: 'chrome'
    },
    slFirefox: {
      base: 'SauceLabs',
      browserName: 'firefox'
    },
    slAndroid4: {
      base: 'SauceLabs',
      browserName: 'android',
      version: '4.0'
    }
  }
}
<commit_msg>SourceLabs browsers<commit_after>// we will re-enable the broken browsers once saucelabs will fix all the timeout issues
module.exports = {
  browsers: {
    slIphone5: {
      base: 'SauceLabs',
      browserName: 'iphone',
      platform: 'OS X 10.10',
      version: '8.1'
    },
    slIphone6: {
      base: 'SauceLabs',
      device: 'iPhone 6',
      os: 'ios',
      version: '9.1'
    },
    slIpad: {
      base: 'SauceLabs',
      browserName: 'ipad',
      platform: 'iOS',
      deviceName: 'iPad 2',
      version: '9.1'
    },
    slSafari7: {
      base: 'SauceLabs',
      browserName: 'safari',
      platform: 'OS X 10.9'
    },
    slSafari8: {
      base: 'SauceLabs',
      browserName: 'safari',
      platform: 'OS X 10.10'
    },
    slSafari9: {
      base: 'SauceLabs',
      browserName: 'safari',
      platform: 'OS X 10.11'
    },
    slIE9: {
      base: 'SauceLabs',
      browserName: 'internet explorer',
      platform: 'Windows 7',
      version: '9'
    },
    slIE10: {
      base: 'SauceLabs',
      browserName: 'internet explorer',
      platform: 'Windows 8',
      version: '10'
    },
    slIE11: {
      base: 'SauceLabs',
      browserName: 'internet explorer',
      platform: 'Windows 8.1',
      version: '11'
    },
    slEdge: {
      base: 'SauceLabs',
      browserName: 'microsoftedge',
      platform: 'Windows 10',
      version: '20.10240'
    },
    slChrome: {
      base: 'SauceLabs',
      browserName: 'chrome'
    },
    slFirefox: {
      base: 'SauceLabs',
      browserName: 'firefox'
    },
    slAndroid4: {
      base: 'SauceLabs',
      browserName: 'android',
      version: '4.0'
    },
    slAndroid5: {
      base: 'SauceLabs',
      browserName: 'android',
      version: '5.1'
    }
  }
}
<|endoftext|>


<commit_before>/*
    Copyright 2015 Leafbird

  Licensed under the Apache License, Version 2.0 (the "License");
  you may not use this file except in compliance with the License.
  You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

  Unless required by applicable law or agreed to in writing, software
  distributed under the License is distributed on an "AS IS" BASIS,
  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  See the License for the specific language governing permissions and
  limitations under the License.
*/

describe('configure', function() {

  it('verify if a leafbird global object has defined', function() {
    expect(leafbird).toBeDefined();
  });

  it('verify if leafbird global variable has a Leafbird object instance',
    function() {
      if(!(leafbird instanceof Leafbird)) {
        fail('leafbird global variable is not a Leafbird instance.');
      }
    }
  );

  it('verify if Leafbird has a configure method', function() {
    if(typeof leafbird.configure !== 'function') {
      fail('The Leafbird object has not a configure method');
    }
  });

  it('verify if configure method make configuration on the leafbird object',
    function() {
      leafbird.configure({});
      expect(leafbird.config).toEqual(undefined);
    }
  );
});
<commit_msg>Change test of configure() to validate if configure sets de parameters on the Leafbird config<commit_after>/*
    Copyright 2015 Leafbird

  Licensed under the Apache License, Version 2.0 (the "License");
  you may not use this file except in compliance with the License.
  You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

  Unless required by applicable law or agreed to in writing, software
  distributed under the License is distributed on an "AS IS" BASIS,
  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  See the License for the specific language governing permissions and
  limitations under the License.
*/

describe('configure', function() {

  it('verify if a leafbird global object has defined', function() {
    expect(leafbird).toBeDefined();
  });

  it('verify if leafbird global variable has a Leafbird object instance',
    function() {
      if(!(leafbird instanceof Leafbird)) {
        fail('leafbird global variable is not a Leafbird instance.');
      }
    }
  );

  it('verify if Leafbird has a configure method', function() {
    if(typeof leafbird.configure !== 'function') {
      fail('The Leafbird object has not a configure method');
    }
  });

  it('verify if configure method make configuration on the leafbird object',
    function() {
      var configObject = {
        "someConfig": "someValue"
      };

      leafbird.configure(configObject);
      expect(leafbird.config).toEqual(configObject);
    }
  );

});
<|endoftext|>


<commit_before>/*global describe, it, chai, Hyperagent, beforeEach, fixtures */
'use strict';
(function () {
  describe('Resource', function () {
    it('should initialize', function () {
      var agent = new Hyperagent.Resource('http://example.com/');
      assert(agent.fetch);
    });

    it('should accept options hash', function () {
      var agent = new Hyperagent.Resource({
        url: 'http://example.com/'
      });
      assert(agent.fetch);
    });

    it('should return its url', function () {
      var agent = new Hyperagent.Resource('http://example.com/');
      assert(agent.url(), 'http://example.com/');
    });

    it('should return its url from an options hash', function () {
      var agent = new Hyperagent.Resource({ url: 'http://example.com/' });
      assert(agent.url(), 'http://example.com/');
    });

    it('should not be loaded by default', function () {
      var agent = new Hyperagent.Resource({ url: 'http://example.com/' });
      assert.isFalse(agent.loaded);
    });

    describe('Resource.props', function () {
      beforeEach(function () {
        this.agent = new Hyperagent.Resource({ url: 'http://example.com/' });
      });

      it('should propagate properties via _parse', function () {
        this.agent._parse(JSON.stringify({ title: 'Hello World' }));
        assert(this.agent.props.title, 'Hello World');
      });

      it('should be iterable', function () {
        this.agent._load({prop1: 1, prop2: 2, prop3: 3});
        var pairs = _.pairs(this.agent.props);
        assert.deepEqual(pairs, [['prop1', 1], ['prop2', 2], ['prop3', 3]]);
      });
    });

    describe('Resource.embedded', function () {
      beforeEach(function () {
        this.agent = new Hyperagent.Resource({ url: 'http://example.com/' });
      });

      it('should expose embedded after parsing', function () {
        this.agent._parse(JSON.stringify(fixtures.embeddedOrders));
        assert.equal(this.agent.embedded.single.props.title, 'yours truly');
        assert.equal(this.agent.embedded.orders.length, 2);
        assert.equal(this.agent.embedded.orders[0].props.status, 'shipped');
      });

      it('should support recursively embedded resources', function () {
        this.agent._load(fixtures.recursiveEmbed);

        assert.equal(this.agent.embedded.single.embedded.user.props.title,
          'passy');
      });

      it('should have loaded embeds', function () {
        this.agent._parse(JSON.stringify(fixtures.embeddedOrders));

        assert(this.agent.embedded.single.loaded,
          'single should be marked as loaded');
        assert(this.agent.embedded.orders[0].loaded,
          'first order be marked as loaded');
      });

      it('should have the self url of the embedded resource', function () {
        this.agent._parse(JSON.stringify(fixtures.embeddedOrders));

        assert.equal(this.agent.embedded.single.url(), '/self/');
      });

      it('should be iterable', function () {
        this.agent._parse(JSON.stringify(fixtures.embeddedOrders));

        var keys = Object.keys(this.agent.embedded);
        assert.deepEqual(keys, ['orders', 'single']);
      });
    });

    describe('Resource.links', function () {
      beforeEach(function () {
        this.agent = new Hyperagent.Resource({ url: 'http://example.com/' });
      });

      it('should expose their props', function () {
        this.agent._load({ _links: { self: { href: 'http://example.com/self' } } });
        assert.equal(this.agent.links.self.props.href, 'http://example.com/self');
      });

      it('should expose self link without fetching', function () {
        this.agent._load({ _links: { self: { href: 'http://example.com/self' } } });
        assert.equal(this.agent.links.self.url(), 'http://example.com/self');
      });

      it('should have its self href as url', function () {
        this.agent._load(fixtures.simpleLink);

        assert.equal(this.agent.links.orders.url(),
          'https://example.com/orders/');
      });

      it('should be iterable', function () {
        this.agent._load(fixtures.simpleLink);

        var keys = Object.keys(this.agent.links);
        assert.deepEqual(keys, ['self', 'orders']);
      })
    });
  });
}());
<commit_msg>Added tests for resource URL normalization<commit_after>/*global describe, it, Hyperagent, beforeEach, fixtures, assert, _ */
'use strict';
(function () {
  describe('Resource', function () {
    it('should initialize', function () {
      var agent = new Hyperagent.Resource('http://example.com/');
      assert(agent.fetch);
    });

    it('should accept options hash', function () {
      var agent = new Hyperagent.Resource({
        url: 'http://example.com/'
      });
      assert(agent.fetch);
    });

    it('should return its url', function () {
      var agent = new Hyperagent.Resource('http://example.com/');
      assert(agent.url(), 'http://example.com/');
    });

    it('should return its url from an options hash', function () {
      var agent = new Hyperagent.Resource({ url: 'http://example.com/' });
      assert(agent.url(), 'http://example.com/');
    });

    it('should not be loaded by default', function () {
      var agent = new Hyperagent.Resource({ url: 'http://example.com/' });
      assert.isFalse(agent.loaded);
    });

    it('should normalize relative paths', function () {
      var agent = new Hyperagent.Resource({
        url: 'http://example.com/subresource'
      });
      agent._load({ _links: { order: { href: '../orders' } } });
      assert.equal(agent.links.order.url(), 'http://example.com/orders');
    });

    it('should absolutize paths', function () {
      var agent = new Hyperagent.Resource({
        url: 'http://example.com/subresource/nested'
      });
      agent._load({ _links: { order: { href: '/orders' } } });
      assert.equal(agent.links.order.url(), 'http://example.com/orders');
    });

    describe('Resource.props', function () {
      beforeEach(function () {
        this.agent = new Hyperagent.Resource({ url: 'http://example.com/' });
      });

      it('should propagate properties via _parse', function () {
        this.agent._parse(JSON.stringify({ title: 'Hello World' }));
        assert(this.agent.props.title, 'Hello World');
      });

      it('should be iterable', function () {
        this.agent._load({prop1: 1, prop2: 2, prop3: 3});
        var pairs = _.pairs(this.agent.props);
        assert.deepEqual(pairs, [['prop1', 1], ['prop2', 2], ['prop3', 3]]);
      });
    });

    describe('Resource.embedded', function () {
      beforeEach(function () {
        this.agent = new Hyperagent.Resource({ url: 'http://example.com/' });
      });

      it('should expose embedded after parsing', function () {
        this.agent._parse(JSON.stringify(fixtures.embeddedOrders));
        assert.equal(this.agent.embedded.single.props.title, 'yours truly');
        assert.equal(this.agent.embedded.orders.length, 2);
        assert.equal(this.agent.embedded.orders[0].props.status, 'shipped');
      });

      it('should support recursively embedded resources', function () {
        this.agent._load(fixtures.recursiveEmbed);

        assert.equal(this.agent.embedded.single.embedded.user.props.title,
          'passy');
      });

      it('should have loaded embeds', function () {
        this.agent._parse(JSON.stringify(fixtures.embeddedOrders));

        assert(this.agent.embedded.single.loaded,
          'single should be marked as loaded');
        assert(this.agent.embedded.orders[0].loaded,
          'first order be marked as loaded');
      });

      it('should have the self url of the embedded resource', function () {
        this.agent._parse(JSON.stringify(fixtures.embeddedOrders));

        assert.equal(this.agent.embedded.single.url(), '/self/');
      });

      it('should be iterable', function () {
        this.agent._parse(JSON.stringify(fixtures.embeddedOrders));

        var keys = Object.keys(this.agent.embedded);
        assert.deepEqual(keys, ['orders', 'single']);
      });
    });

    describe('Resource.links', function () {
      beforeEach(function () {
        this.agent = new Hyperagent.Resource({ url: 'http://example.com/' });
      });

      it('should expose their props', function () {
        this.agent._load({ _links: { self: { href: 'http://example.com/self' } } });
        assert.equal(this.agent.links.self.props.href, 'http://example.com/self');
      });

      it('should expose self link without fetching', function () {
        this.agent._load({ _links: { self: { href: 'http://example.com/self' } } });
        assert.equal(this.agent.links.self.url(), 'http://example.com/self');
      });

      it('should have its self href as url', function () {
        this.agent._load(fixtures.simpleLink);

        assert.equal(this.agent.links.orders.url(),
          'https://example.com/orders/');
      });

      it('should be iterable', function () {
        this.agent._load(fixtures.simpleLink);

        var keys = Object.keys(this.agent.links);
        assert.deepEqual(keys, ['self', 'orders']);
      });
    });
  });
}());
<|endoftext|>


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

  beforeEach(function (done) {
    window.sessionStorage.clear();
    done();
  });

  it('to set the namespace property', function() {
    var store = new SessionStore('sessionstore');

    expect(store).to.have.property('ns');
    expect(store.ns).to.equal('sessionstore');
  });

  it('to set data property', function () {
    var store = new SessionStore('sessionstore', { version: '1.0.0' });

    expect(store.data).to.be.a('object');
    expect(store.data).to.eql({ version: '1.0.0' })
  });

  it('to store data passed in as argument, in sessionStorage', function () {
    var store = new SessionStore('sessionstore', { version: '2.0.0' });

    expect(JSON.parse(sessionStorage.getItem('sessionstore'))).to.eql({ version: '2.0.0' });
  });

  it('to store data set as value in sessionStorage', function () {
    var store = new SessionStore('sessionstore');

    store.data = { test: '1234' };

    expect(JSON.parse(sessionStorage.getItem('sessionstore'))).to.eql({ test: '1234' });
  });

  it('to not overwrite data in sessionStorage', function () {
    window.sessionStorage.setItem('sessionstore', '{ "test": 123 }');
    var store = new SessionStore('sessionstore');

    expect(JSON.parse(sessionStorage.getItem('sessionstore'))).to.eql({ test: 123 });
  });
});
<commit_msg>added more specs<commit_after>describe('SessionStore', function () {

  beforeEach(function (done) {
    window.sessionStorage.clear();
    done();
  });

  it('to set the namespace property', function() {
    var store = new SessionStore('sessionstore');

    expect(store).to.have.property('ns');
    expect(store.ns).to.equal('sessionstore');
  });

  it('to set data property', function () {
    var store = new SessionStore('sessionstore', { version: '1.0.0' });

    expect(store.data).to.be.a('object');
    expect(store.data).to.eql({ version: '1.0.0' })
  });

  it('to store data passed in as argument, in sessionStorage', function () {
    var store = new SessionStore('sessionstore', { version: '2.0.0' });

    expect(JSON.parse(sessionStorage.getItem('sessionstore'))).to.eql({ version: '2.0.0' });
  });

  it('to store data set as value in sessionStorage', function () {
    var store = new SessionStore('sessionstore');

    store.data = { test: '1234' };

    expect(JSON.parse(sessionStorage.getItem('sessionstore'))).to.eql({ test: '1234' });
  });

  it('to not overwrite data in sessionStorage', function () {
    window.sessionStorage.setItem('sessionstore', '{ "test": 123 }');
    var store = new SessionStore('sessionstore');

    expect(JSON.parse(sessionStorage.getItem('sessionstore'))).to.eql({ test: 123 });
  });

  it('retrives the individual property from data', function () {
    var store = new SessionStore('testing', { storage: ['session', 'local'] });

    expect(store.getItem('storage')).to.eql(['session', 'local']);
  });

  it('sets the individual property to data', function () {
    var store = new SessionStore('testing', { storage: ['session', 'local'] });

    store.setItem('storage', 'IndexedDB');

    expect(store.getItem('storage')).to.eql('IndexedDB');
  });

  it('data should be unique among instances', function () {
    var store1 =  new SessionStore('sessionstore', { version: '1.0.0' });
    var store2 =  new SessionStore('sessionstore', { version: '2.0.0' });

    expect(store1.data).to.not.eql(store2.data);
  })
});
<|endoftext|>


<commit_before>import {expect} from 'chai';
import {generateSitemaps, config, CsvSource} from '../../src/main';
import libxmljs from 'libxmljs';
import zlib from 'zlib';
import concat from 'concat-stream';
import fs from 'fs';
import util from 'util';

describe('sitemap generator', function() {
  this.timeout(5000);
  this.logOutput = null;
  it('exists', () => {
    expect(generateSitemaps).to_exist;
  });

  it('works with the test configuration', (done) => {
    generateSitemaps((err, results) => {
      expect(err).to.be_null
      expect(results.length).to.equal(1);
      expect(results[0].sitemaps.length).to.equal(2);

      let sitemap1Files = results[0].sitemaps[0].allFiles();
      expect(sitemap1Files.length).to.equal(1);
      expect(sitemap1Files[0].fileName).to.match(/channel10/);
      expect(sitemap1Files[0].urlCount).to.equal(4);
      let sitemap2Files = results[0].sitemaps[1].allFiles();
      expect(sitemap2Files.length).to.equal(1);
      expect(sitemap2Files[0].fileName).to.match(/channel20/);
      expect(sitemap2Files[0].urlCount).to.equal(4);

      // Check that sitemaps are well formed xml
      let parseXml = (xmlData) => {
        return () => {
          return new libxmljs.parseXml(xmlData);
        }
      };

      expect(results[0].indexFileName).to.match(/testSitemap\.xml/);
      expect(parseXml(fs.readFileSync(results[0].indexFileName))).to.not.throw(Error);

      let gzipOut = concat((xmlData) => {
        expect(parseXml(xmlData)).to.not.throw(Error);
        let againGzipOut = concat((xmlData) => {
          expect(parseXml(xmlData)).to.not.throw(Error);
          done();
        });
        fs.createReadStream(sitemap1Files[0].fileName).pipe(zlib.createGunzip()).pipe(againGzipOut);
      });
      fs.createReadStream(sitemap2Files[0].fileName).pipe(zlib.createGunzip()).pipe(gzipOut);
    });
  });

  describe('with a source with error', () => {
    before( () => {
      this.sourceOptions = {
        type: CsvSource,
        options: {
          input: { noValidKeys: ""},
          options: {},
          siteMap: {}
        }
      };
      config.sources.errorSource = (sitemapConfig) => {
        return this.sourceOptions;
      };
    });
    describe('with default config', () => {
      it('fails', (done) => {
        generateSitemaps((err, results) => {
          expect(err).to.not.be_null;
          done();
        });
      });
    });

    describe('with config to ignore errors', () => {
      before(() => {
        this.sourceOptions.options.ignoreErrors = true;
      });
      it('works', (done) => {
        generateSitemaps((err, results) => {
          expect(err).to.be_null;
          expect(results.length).to.equal(1);
          // The errored source does not result in a sitemap, hence only 2 sitemaps
          expect(results[0].sitemaps.length).to.equal(2);
          done();
        });
      });
    });
  });
});
<commit_msg>test: Add schema validation check to generator test<commit_after>import {expect} from 'chai';
import request from 'request';
import {generateSitemaps, config, CsvSource} from '../../src/main';
import libxmljs from 'libxmljs';
import zlib from 'zlib';
import concat from 'concat-stream';
import fs from 'fs';
import util from 'util';

describe('sitemap generator', function() {
  this.timeout(5000);
  this.logOutput = null;
  before((done) => {
    let xsd = request("http://www.sitemaps.org/schemas/sitemap/0.9/sitemap.xsd", (error, response, body) => {
      this.xsdSchema = libxmljs.parseXml(body);
      done();
    });
  });
  it('exists', () => {
    expect(generateSitemaps).to_exist;
  });

  it('works with the test configuration', (done) => {
    generateSitemaps((err, results) => {
      expect(err).to.be_null
      expect(results.length).to.equal(1);
      expect(results[0].sitemaps.length).to.equal(2);

      let sitemap1Files = results[0].sitemaps[0].allFiles();
      expect(sitemap1Files.length).to.equal(1);
      expect(sitemap1Files[0].fileName).to.match(/channel10/);
      expect(sitemap1Files[0].urlCount).to.equal(4);
      let sitemap2Files = results[0].sitemaps[1].allFiles();
      expect(sitemap2Files.length).to.equal(1);
      expect(sitemap2Files[0].fileName).to.match(/channel20/);
      expect(sitemap2Files[0].urlCount).to.equal(4);

      // Check that sitemaps are well formed xml
      let parseXml = (xmlData) => {
        return () => {
          return new libxmljs.parseXml(xmlData);
        }
      };

      expect(results[0].indexFileName).to.match(/testSitemap\.xml/);
      expect(parseXml(fs.readFileSync(results[0].indexFileName))).to.not.throw(Error);

      let gzipOut = concat((xmlData) => {
        expect(parseXml(xmlData)).to.not.throw(Error);
        let doc = parseXml(xmlData)();
        expect(doc.validate(this.xsdSchema)).to.be_true;
        let againGzipOut = concat((xmlData) => {
          expect(parseXml(xmlData)).to.not.throw(Error);
          let doc = parseXml(xmlData)();
          expect(doc.validate(this.xsdSchema)).to.be_true;
          done();
        });
        fs.createReadStream(sitemap1Files[0].fileName).pipe(zlib.createGunzip()).pipe(againGzipOut);
      });
      fs.createReadStream(sitemap2Files[0].fileName).pipe(zlib.createGunzip()).pipe(gzipOut);
    });
  });

  describe('with a source with error', () => {
    before( () => {
      this.sourceOptions = {
        type: CsvSource,
        options: {
          input: { noValidKeys: ""},
          options: {},
          siteMap: {}
        }
      };
      config.sources.errorSource = (sitemapConfig) => {
        return this.sourceOptions;
      };
    });
    describe('with default config', () => {
      it('fails', (done) => {
        generateSitemaps((err, results) => {
          expect(err).to.not.be_null;
          done();
        });
      });
    });

    describe('with config to ignore errors', () => {
      before(() => {
        this.sourceOptions.options.ignoreErrors = true;
      });
      it('works', (done) => {
        generateSitemaps((err, results) => {
          expect(err).to.be_null;
          expect(results.length).to.equal(1);
          // The errored source does not result in a sitemap, hence only 2 sitemaps
          expect(results[0].sitemaps.length).to.equal(2);
          done();
        });
      });
    });
  });
});
<|endoftext|>


<commit_before>
var parser = require('../scripts/parser.js');
var fs = require('fs-extra');
var assert = require('better-assert');
var tab = fs.readFileSync('test/stairway-to-heaven.txt', 'utf-8');

describe('tab parser', function () {
  var intro = [ // TODO: Test entire tab txt file
    'e ------5--7-----7--8------8--2-----2-0--------0---------------',
    'B ----5------5--------5---------3--------1---1---1----0-1-1----',
    'G --5----------5--------5---------2--------2-------2--0-2-2----',
    'D 7--------6--------5---------4-------3------------------------',
    'A ----------------------------------------------------2-0-0-0--',
    'E -------------------------------------------------------------'
  ].join('\r\n');
  var moments = parser(intro);

  it('should build an array of "moments"', function () {
    assert(Array.isArray(moments));
  });

  it('should parse out useless characters at the beginning of each "string"', function () {
    var itAintMe = ['e', 'b', 'g', 'd', 'a'];
    moments.forEach(function (moment) {
      for (key in moment) {
        if (moment.hasOwnProperty(key)) {
          assert(itAintMe.indexOf(moment[key].toLowerCase()) === -1);
        }
      }
    });
  });
  it('should handle hammers and pull offs');
  it('should handle slides');

  describe('each moment', function () {
    it('should be an object consisting of exactly 6 values', function () {
      moments.forEach(function (moment) {
        var momentLength = 0;
        for (key in moment) {
          if (moment.hasOwnProperty(key)) {
            momentLength++;
            assert(moment[key].length === 1);
          }
        }

        assert(momentLength === 6);
      });
    });
  });
});

<commit_msg>Zipsssssssssssss<commit_after>
var parser = require('../scripts/parser.js');
var fs = require('fs-extra');
var assert = require('better-assert');
var tab = fs.readFileSync('test/tabs/stairway-to-heaven.txt', 'utf-8');

describe('tab parser', function () {
  var intro = [ // TODO: Test entire tab txt file
    'e ------5--7-----7--8------8--2-----2-0--------0---------------',
    'B ----5------5--------5---------3--------1---1---1----0-1-1----',
    'G --5----------5--------5---------2--------2-------2--0-2-2----',
    'D 7--------6--------5---------4-------3------------------------',
    'A ----------------------------------------------------2-0-0-0--',
    'E -------------------------------------------------------------'
  ].join('\r\n');
  var moments = parser(intro);

  it('should build an array of "moments"', function () {
    assert(Array.isArray(moments));
  });

  it('should parse out useless characters at the beginning of each "string"', function () {
    var itAintMe = ['e', 'b', 'g', 'd', 'a'];
    moments.forEach(function (moment) {
      for (key in moment) {
        if (moment.hasOwnProperty(key)) {
          assert(itAintMe.indexOf(moment[key].toLowerCase()) === -1);
        }
      }
    });
  });
  it('should handle hammers and pull offs');
  it('should handle slides');

  describe('each moment', function () {
    it('should be an object consisting of exactly 6 values', function () {
      moments.forEach(function (moment) {
        var momentLength = 0;
        for (key in moment) {
          if (moment.hasOwnProperty(key)) {
            momentLength++;
            assert(moment[key].length === 1);
          }
        }

        assert(momentLength === 6);
      });
    });
  });
});

<|endoftext|>


<commit_before>(function(context) {

  // The global context
  var globalContext = typeof global !== 'undefined' && global.Object ? global : context;
  var nativeState;

  var NATIVES = ['Number','String','Array','Date','RegExp','Function', 'Object'];

  function restoreNative(methodName, target, storedMethod) {
    if (target[methodName] !== storedMethod) {
      if (!storedMethod) {
        delete target[methodName];
      } else {
        target[methodName] = storedMethod;
      }
    }
  }

  function assertNamespaces(namespaces, assert, checkStatic, checkInstance) {
    for (var i = 0; i < namespaces.length; i++) {
      assertNamespace(namespaces[i], assert, checkStatic, checkInstance);
    }
  }

  function assertNamespace(namespace, assert, checkStatic, checkInstance) {
    var sugarNamespace = Sugar[namespace],
        nativeClass = globalContext[namespace],
        count = 0, mappedCount = 0;

    function methodIsMapped(method, name) {
      return (method.instance && method.instance === nativeClass.prototype[name]) || method === nativeClass[name];
    }

    function checkMethod() {
      return (!!method.instance && checkInstance) || (method.static && checkStatic);
    }

    testIterateOverObject(sugarNamespace, function(name, method) {
      if (!checkMethod(method)) {
        return;
      }
      count++;
      if (methodIsMapped(method, name)) {
        mappedCount++;
      }
    });
    if (assert === false) {
      equal(mappedCount, 0, namespace + ' methods not mapped.');
    } else {
      equal(mappedCount, count, 'All methods mapped to ' + namespace + '.');
    }
  }

  function isSugarMethod(method) {
    return typeof method === 'function' && (method.static || !!method.instance);
  }

  assertAllMethodsMappedToNative = function(namespaces) {
    assertNamespaces(namespaces, true, true, true);
  }

  assertNoMethodsMappedToNative = function(namespaces) {
    assertNamespaces(namespaces, false, true, true);
  }

  assertStaticMethodsMappedToNative = function(namespaces) {
    assertNamespaces(namespaces, true, true, false);
  }

  assertStaticMethodsNotMappedToNative = function(namespaces) {
    assertNamespaces(namespaces, false, true, false);
  }

  assertInstanceMethodsMappedToNative = function(namespaces) {
    assertNamespaces(namespaces, true, false, true);
  }

  assertInstanceMethodsNotMappedToNative = function(namespaces) {
    assertNamespaces(namespaces, false, false, true);
  }

  storeNativeState = function() {
    nativeState = {};
    testIterateOverObject(Sugar, function(name, ns) {
      var state = nativeState[name] = {};
      nativeState[name + 'Active'] = ns.active;
      var nativeClass = globalContext[name];
      testIterateOverObject(ns, function(methodName, method) {
        if (!isSugarMethod(method)) {
          // Only store Sugar defined methods.
          return;
        }
        // Store both static and instance methods as both
        // are possible, such as in the case of Object.keys.
        state[methodName] = {
          static: nativeClass[methodName],
          instance: nativeClass.prototype[methodName]
        }
      });
    });
  }

  restoreNativeState = function() {
    // "objectPrototype" preserves state for future
    // method definitions, so reset that flag here.
    Sugar.Object.extend({
      methods: [],
      objectPrototype: false
    });
    for (var i = 0; i < NATIVES.length; i++) {

      var name        = NATIVES[i];
      var ns          = Sugar[name];
      var nativeClass = globalContext[name];

      ns.active = nativeState[name + 'Active'];
      testIterateOverObject(ns, function(methodName, method) {
        if (!isSugarMethod(method)) {
          // Only restore Sugar defined methods.
          return;
        }
        var state = nativeState[name][methodName];
        if (!state) {
          // If there is no stored state for this method, then
          // it's safe to assume that it was not there previously
          // and remove it completely. Do this by setting it's
          // state as undefined.
          state = {};
        }
        restoreNative(methodName, nativeClass, state.static);
        restoreNative(methodName, nativeClass.prototype, state.instance);
      });
    }
  }

})(this);
<commit_msg>need to possibly handle multiple stored native states<commit_after>(function(context) {

  // The global context
  var globalContext = typeof global !== 'undefined' && global.Object ? global : context;
  var nativeStates = [];

  var NATIVES = ['Number','String','Array','Date','RegExp','Function', 'Object'];

  function restoreNative(methodName, target, storedMethod) {
    if (target[methodName] !== storedMethod) {
      if (!storedMethod) {
        delete target[methodName];
      } else {
        target[methodName] = storedMethod;
      }
    }
  }

  function assertNamespaces(namespaces, assert, checkStatic, checkInstance) {
    for (var i = 0; i < namespaces.length; i++) {
      assertNamespace(namespaces[i], assert, checkStatic, checkInstance);
    }
  }

  function assertNamespace(namespace, assert, checkStatic, checkInstance) {
    var sugarNamespace = Sugar[namespace],
        nativeClass = globalContext[namespace],
        count = 0, mappedCount = 0;

    function methodIsMapped(method, name) {
      return (method.instance && method.instance === nativeClass.prototype[name]) || method === nativeClass[name];
    }

    function checkMethod() {
      return (!!method.instance && checkInstance) || (method.static && checkStatic);
    }

    testIterateOverObject(sugarNamespace, function(name, method) {
      if (!checkMethod(method)) {
        return;
      }
      count++;
      if (methodIsMapped(method, name)) {
        mappedCount++;
      }
    });
    if (assert === false) {
      equal(mappedCount, 0, namespace + ' methods not mapped.');
    } else {
      equal(mappedCount, count, 'All methods mapped to ' + namespace + '.');
    }
  }

  function isSugarMethod(method) {
    return typeof method === 'function' && (method.static || !!method.instance);
  }

  assertAllMethodsMappedToNative = function(namespaces) {
    assertNamespaces(namespaces, true, true, true);
  }

  assertNoMethodsMappedToNative = function(namespaces) {
    assertNamespaces(namespaces, false, true, true);
  }

  assertStaticMethodsMappedToNative = function(namespaces) {
    assertNamespaces(namespaces, true, true, false);
  }

  assertStaticMethodsNotMappedToNative = function(namespaces) {
    assertNamespaces(namespaces, false, true, false);
  }

  assertInstanceMethodsMappedToNative = function(namespaces) {
    assertNamespaces(namespaces, true, false, true);
  }

  assertInstanceMethodsNotMappedToNative = function(namespaces) {
    assertNamespaces(namespaces, false, false, true);
  }

  storeNativeState = function() {
    var nativeState = {};
    testIterateOverObject(Sugar, function(name, ns) {
      var state = nativeState[name] = {};
      nativeState[name + 'Active'] = ns.active;
      var nativeClass = globalContext[name];
      testIterateOverObject(ns, function(methodName, method) {
        if (!isSugarMethod(method)) {
          // Only store Sugar defined methods.
          return;
        }
        // Store both static and instance methods as both
        // are possible, such as in the case of Object.keys.
        state[methodName] = {
          static: nativeClass[methodName],
          instance: nativeClass.prototype[methodName]
        }
      });
    });
    nativeStates.push(nativeState);
  }

  restoreNativeState = function() {
    // "objectPrototype" preserves state for future
    // method definitions, so reset that flag here.
    Sugar.Object.extend({
      methods: [],
      objectPrototype: false
    });

    var nativeState = nativeStates.pop();

    for (var i = 0; i < NATIVES.length; i++) {

      var name        = NATIVES[i];
      var ns          = Sugar[name];
      var nativeClass = globalContext[name];

      ns.active = nativeState[name + 'Active'];
      testIterateOverObject(ns, function(methodName, method) {
        if (!isSugarMethod(method)) {
          // Only restore Sugar defined methods.
          return;
        }
        var methodState = nativeState[name][methodName];
        if (!methodState) {
          // If there is no stored state for this method, then
          // it's safe to assume that it was not there previously
          // and remove it completely. Do this by setting it's
          // state as undefined.
          methodState = {};
        }
        restoreNative(methodName, nativeClass, methodState.static);
        restoreNative(methodName, nativeClass.prototype, methodState.instance);
      });
    }
  }

})(this);
<|endoftext|>


<commit_before>'use strict';

var path = require('path');
var helpers = require('yeoman-generator').test;

describe('H5BP Server Configs generator', function () {

	beforeEach(function (cb) {
		var deps = ['../../app'];

		helpers.testDirectory(path.join(__dirname, 'temp'), function (err) {
			if (err) {
				return cb(err);
			}

			this.generator = helpers.createGenerator('server-configs:app', deps);
			cb();
		}.bind(this));
	});

	it('`apache` option generates expected files', function (cb) {
		var expected = [ '.htaccess' ];

		this.generator.run(['apache'], function () {
			helpers.assertFiles(expected);
			cb();
		});
	});

	it('`gae` option generates expected files', function (cb) {
		var expected = [ 'app.yaml', 'gae.py' ];

		this.generator.run(['gae'], function () {
			helpers.assertFiles(expected);
			cb();
		});
	});

	it('`iis` option generates expected files', function (cb) {
		var expected = [ 'dotnet 3', 'dotnet 4' ];

		this.generator.run(['iis'], function () {
			helpers.assertFiles(expected);
			cb();
		});
	});

	it('`lighttpd` option generates expected files', function (cb) {
		var expected = [ 'lighttpd.conf' ];

		this.generator.run(['lighttpd'], function () {
			helpers.assertFiles(expected);
			cb();
		});
	});

	it('`nginx` option generates expected files', function (cb) {
		var expected = [ 'conf', 'mime.types', 'nginx.conf', 'sites-available', 'sites-enabled' ];

		this.generator.run(['nginx'], function () {
			helpers.assertFiles(expected);
			cb();
		});
	});

	it('`node` option generates expected files', function (cb) {
		var expected = [ 'lib', 'package.json' ];

		this.generator.run(['node'], function () {
			helpers.assertFiles(expected);
			cb();
		});
	});

});
<commit_msg>Update Nginx test<commit_after>'use strict';

var path = require('path');
var helpers = require('yeoman-generator').test;

describe('H5BP Server Configs generator', function () {

	beforeEach(function (cb) {
		var deps = ['../../app'];

		helpers.testDirectory(path.join(__dirname, 'temp'), function (err) {
			if (err) {
				return cb(err);
			}

			this.generator = helpers.createGenerator('server-configs:app', deps);
			cb();
		}.bind(this));
	});

	it('`apache` option generates expected files', function (cb) {
		var expected = [ '.htaccess' ];

		this.generator.run(['apache'], function () {
			helpers.assertFiles(expected);
			cb();
		});
	});

	it('`gae` option generates expected files', function (cb) {
		var expected = [ 'app.yaml', 'gae.py' ];

		this.generator.run(['gae'], function () {
			helpers.assertFiles(expected);
			cb();
		});
	});

	it('`iis` option generates expected files', function (cb) {
		var expected = [ 'dotnet 3', 'dotnet 4' ];

		this.generator.run(['iis'], function () {
			helpers.assertFiles(expected);
			cb();
		});
	});

	it('`lighttpd` option generates expected files', function (cb) {
		var expected = [ 'lighttpd.conf' ];

		this.generator.run(['lighttpd'], function () {
			helpers.assertFiles(expected);
			cb();
		});
	});

	it('`nginx` option generates expected files', function (cb) {
		var expected = [ 'h5bp', 'mime.types', 'nginx.conf', 'sites-available', 'sites-enabled' ];

		this.generator.run(['nginx'], function () {
			helpers.assertFiles(expected);
			cb();
		});
	});

	it('`node` option generates expected files', function (cb) {
		var expected = [ 'lib', 'package.json' ];

		this.generator.run(['node'], function () {
			helpers.assertFiles(expected);
			cb();
		});
	});

});
<|endoftext|>


<commit_before>var assert = require('assert');

var constraints = {
    maxMessageLength: 268435455
};

function encodeRemainingLength(value) {

    if (value > constraints.maxMessageLength) {
        throw new Error('max message length exceeded');
    }
    var buffer = new Buffer(0);
    do {
        var digit = value % 128;
        value = parseInt(value / 128);
        if (value > 0) {
            digit = digit | 0xFF;
        }
        var next = new Buffer(1);
        next.writeUInt8(digit, 0);
        buffer = Buffer.concat([buffer, next])
    }
    while (value > 0);
    return buffer;
}

function decodeRemainingLength(buffer) {
    var multiplier = 1;
    var value = 0;
    var index = 0;
    var digit;
    do {
        if (index === buffer.length)
            throw Error('malformed remaining length')
        digit = buffer.readUInt8(index++);
        value += (digit & 127) * multiplier;
        multiplier *= 128;
    }
    while ((digit & 128) !== 0);
    return value;
}

describe('MQTT Special Functions', function() {

    describe('Encoding remaining length', function() {

        function expectEncoding(value, expectedValues) {
            var result = encodeRemainingLength(value);
            assert.equal(result.length, expectedValues.length);
            for (var i = 0; i < expectedValues.length; i++) {
                assert.equal(result.readUInt8(i), expectedValues[i]);
            }
        }

        it('encoding 127 returns a 1 byte Buffer', function() {
            expectEncoding(127, [0x7F]);
        });

        it('encoding 128 x 127 returns a 2 byte Buffer', function() {
            expectEncoding(128 * 127, [0xFF, 0x7F]);
        });

        it('encoding 128 x 128 x 127 returns a 3 byte Buffer', function() {
            expectEncoding(128 * 128 * 127, [0xFF, 0xFF, 0x7F]);
        });

        it('encoding 128 x 128 x 128 x 127 returns a 4 byte Buffer', function() {
            expectEncoding(128 * 128 * 128 * 127, [0xFF, 0xFF, 0xFF, 0x7F]);
        });

        it('encoding a number greater than 128x128x128x127 throws an error', function() {
            assert.throws(function() {
                encodeRemainingLength(128 * 128 * 128 * 128);
            }, /max message length exceeded/);
        });
    });

    describe('Decoding remaining length', function() {

        function expectDecoding(value, expectedValue) {
            var buffer = new Buffer(value.length);
            for (var i = 0; i < value.length; i++) {
                buffer.writeUInt8(value[i], i);
            }
            var result = decodeRemainingLength(buffer);
            assert.equal(result, expectedValue);
        }

        it('decodes 0x7F as one byte upper limit', function() {
            var oneByteUpperLimit = 128 - 1;
            expectDecoding([0x7F], oneByteUpperLimit);
        });

        it('decodes 0xFF 0x7F as two byte upper limit', function() {
            var twoByteUpperLimit = 128 * 128 - 1;
            expectDecoding([0xFF, 0x7F], twoByteUpperLimit);
        });

        it('decodes 0xFF 0xFF 0x7F as three byte upper limit', function() {
            var threeByteUpperLimit = 128 * 128 * 128 - 1;
            expectDecoding([0xFF, 0xFF, 0x7F], threeByteUpperLimit);
        });

        it('decodes 0xFF 0xFF 0xFF 0x7F as four byte upper limit', function(){
            var fourByteUpperLimit = 128*128*128*128-1;
            expectDecoding([0xFF,0xFF,0xFF,0x7F], fourByteUpperLimit);
        });

        it('decoding a buffer greater than the four byte upper limit throws an error', function(){
            assert.throws(function(){
               decodeRemainingLength(new Buffer([0xFF, 0xFF, 0xFF, 0xFF]))
            }, /malformed remaining length/);
        });
    });

});
<commit_msg>moving to a more functional style<commit_after>var assert = require('assert');

function validateRemainingLength(value) {
    var maxMessageLength = 268435455;
    if (value > maxMessageLength) {
        return Error('max message length exceeded');
    }
    return undefined;
}

function existy(value) {
    return value !== null && value !== undefined;
}

function dispatch() {
    var funcs = arguments;

    return function(target) {
        for (var funcIndex in funcs) {
            var func = funcs[funcIndex];
            var ret = func.apply(null, [target]);
            if (existy(ret)) {
                return ret;
            }
        }
        return undefined;
    }
}

function encodeRemainingLength(value) {

    var dispatcher = dispatch(validateRemainingLength, encode);

    return dispatcher(value);

    function encode(value) {
        var buffer = new Buffer(0);
        do {
            var digit = value % 128;
            value = parseInt(value / 128);
            if (value > 0) {
                digit = digit | 0xFF;
            }
            var next = new Buffer(1);
            next.writeUInt8(digit, 0);
            buffer = Buffer.concat([buffer, next])
        }
        while (value > 0);
        return buffer;
    }
}

function decodeRemainingLength(buffer) {
    var multiplier = 1;
    var value = 0;
    var index = 0;
    var digit;
    do {
        if (index === buffer.length)
            throw Error('malformed remaining length')
        digit = buffer.readUInt8(index++);
        value += (digit & 127) * multiplier;
        multiplier *= 128;
    }
    while ((digit & 128) !== 0);
    return value;
}

function remainingLengthByteCount(value) {
    var dispatcher = dispatch(validateRemainingLength, count);
    return dispatcher(value);

    function count(value){
        return Math.ceil(Math.log(value) / Math.log(128));
    }
}

describe('MQTT Special Functions', function() {

    describe('Encoding remaining length', function() {

        function expectEncoding(value, expectedValues) {
            var result = encodeRemainingLength(value);
            assert.equal(result.length, expectedValues.length);
            for (var i = 0; i < expectedValues.length; i++) {
                assert.equal(result.readUInt8(i), expectedValues[i]);
            }
        }

        it('encoding 127 returns a 1 byte Buffer', function() {
            expectEncoding(127, [0x7F]);
        });

        it('encoding 128 x 127 returns a 2 byte Buffer', function() {
            expectEncoding(128 * 127, [0xFF, 0x7F]);
        });

        it('encoding 128 x 128 x 127 returns a 3 byte Buffer', function() {
            expectEncoding(128 * 128 * 127, [0xFF, 0xFF, 0x7F]);
        });

        it('encoding 128 x 128 x 128 x 127 returns a 4 byte Buffer', function() {
            expectEncoding(128 * 128 * 128 * 127, [0xFF, 0xFF, 0xFF, 0x7F]);
        });

        it('encoding a number greater than 128x128x128x127 throws an error', function() {
            var error = encodeRemainingLength(128 * 128 * 128 * 128);
            assert.equal(error.message,'max message length exceeded');
        });
    });

    describe('Decoding remaining length', function() {

        var oneByteUpperLimit = 128 - 1;
        var twoByteUpperLimit = 128 * 128 - 1;
        var threeByteUpperLimit = 128 * 128 * 128 - 1;
        var fourByteUpperLimit = 128 * 128 * 128 * 128 - 1;

        function expectDecoding(value, expectedValue) {
            var buffer = new Buffer(value.length);
            for (var i = 0; i < value.length; i++) {
                buffer.writeUInt8(value[i], i);
            }
            var result = decodeRemainingLength(buffer);
            assert.equal(result, expectedValue);
        }

        it('decodes 0x7F as one byte upper limit', function() {
            expectDecoding([0x7F], oneByteUpperLimit);
        });

        it('decodes 0xFF 0x7F as two byte upper limit', function() {
            expectDecoding([0xFF, 0x7F], twoByteUpperLimit);
        });

        it('decodes 0xFF 0xFF 0x7F as three byte upper limit', function() {
            expectDecoding([0xFF, 0xFF, 0x7F], threeByteUpperLimit);
        });

        it('decodes 0xFF 0xFF 0xFF 0x7F as four byte upper limit', function() {
            expectDecoding([0xFF, 0xFF, 0xFF, 0x7F], fourByteUpperLimit);
        });

        it('decoding a buffer greater than the four byte upper limit throws an error', function() {
            assert.throws(function() {
                decodeRemainingLength(new Buffer([0xFF, 0xFF, 0xFF, 0xFF]))
            }, /malformed remaining length/);
        });

        it('remainingLengthByteCount returns 1', function() {
            assert.equal(1, remainingLengthByteCount(oneByteUpperLimit));
        });

        it('remainLengthByteCount returns 2', function() {
            assert.equal(2, remainingLengthByteCount(twoByteUpperLimit));
        });

        it('remainingLengthByteCount returns 2', function() {
            assert.equal(3, remainingLengthByteCount(threeByteUpperLimit));
        });

        it('remainingLengthByteCount returns 4', function() {
            assert.equal(4, remainingLengthByteCount(fourByteUpperLimit));
        });

        it('remainingLengthByteCount returns error when number is greater than fourByteUpperLimit', function() {
            assert.ok(remainingLengthByteCount(fourByteUpperLimit + 1) instanceof Error);
        });
    });

});
<|endoftext|>