<commit_before>// Copyright (c) 2015, Frappe Technologies Pvt. Ltd. and Contributors
// MIT License. See license.txt

// for license information please see license.txt

// constructor: parent, label, method, args
frappe.ui.Tree = Class.extend({
	init: function(args) {
		$.extend(this, args);
		this.nodes = {};
		this.wrapper = $('
').appendTo(this.parent);
		this.rootnode = new frappe.ui.TreeNode({
			tree: this,
			parent: this.wrapper,
			label: this.label,
			parent_label: null,
			expandable: true,
			root: true,
			data: {
				value: this.label,
				parent: this.label,
				expandable: true
			}
		});
		this.rootnode.toggle();
	},
	get_selected_node: function() {
		return this.selected_node;
	},
	toggle: function() {
		this.get_selected_node().toggle();
	}
})

frappe.ui.TreeNode = Class.extend({
	init: function(args) {
		$.extend(this, args);
		this.loaded = false;
		this.expanded = false;
		this.tree.nodes[this.label] = this;
		if(this.parent_label)
			this.parent_node = this.tree.nodes[this.parent_label];

		this.make();
		this.setup_drag_drop();

		if(this.tree.onrender) {
			this.tree.onrender(this);
		}
	},
	make: function() {
		var me = this;
		this.$a = $('')
			.click(function(event) {
				me.tree.selected_node = me;
				me.tree.wrapper.find(".tree-link.active").removeClass("active");
				me.$a.addClass("active");
				if(me.tree.toolbar) {
					me.show_toolbar();
				}
				if(me.toggle_on_click) {
					me.toggle();
				}
				if(me.tree.click)
					me.tree.click(this);
			})
			.data('label', this.label)
			.data('node', this)
			.appendTo(this.parent);

		this.$ul = $('
')
			.toggle(false).appendTo(this.parent);

		this.make_icon();

	},
	make_icon: function() {
		// label with icon
		var me= this;
		var icon_html = '';
		if(this.expandable) {
			icon_html = '';
		}
		$(icon_html + ' ' + this.get_label() + "").
			appendTo(this.$a);

		this.$a.find('i').click(function() {
			setTimeout(function() { me.toolbar.find(".btn-expand").click(); }, 100);
		});
	},
	get_label: function() {
		if(this.tree.get_label) {
			return this.tree.get_label(this);
		}
		return __(this.label);
	},
	toggle: function(callback) {
		if(this.expandable && this.tree.method && !this.loaded) {
			this.load(callback)
		} else {
			this.toggle_node(callback);
		}
	},
	show_toolbar: function() {
		if(this.tree.cur_toolbar)
			$(this.tree.cur_toolbar).toggle(false);

		if(!this.toolbar)
			this.make_toolbar();

		this.tree.cur_toolbar = this.toolbar;
		this.toolbar.toggle(true);
	},
	make_toolbar: function() {
		var me = this;
		this.toolbar = $('').insertAfter(this.$a);

		$.each(this.tree.toolbar, function(i, item) {
			if(item.toggle_btn) {
				item = {
					condition: function() { return me.expandable; },
					get_label: function() { return me.expanded ? __("Collapse") : __("Expand") },
					click:function(node, btn) {
						node.toggle(function() {
							$(btn).html(node.expanded ? __("Collapse") : __("Expand"));
						});
					},
					btnClass: "btn-expand hidden-xs"
				}
			}
			if(item.condition) {
				if(!item.condition(me)) return;
			}
			var label = item.get_label ? item.get_label() : item.label;
			var link = $("<button class='btn btn-default btn-xs'></button>")
				.html(label)
				.appendTo(me.toolbar)
				.click(function() { item.click(me, this); return false; });

			if(item.btnClass) link.addClass(item.btnClass);
		})

	},
	setup_drag_drop: function() {
		// experimental
		var me = this;
		if(this.tree.drop && this.parent_label) {
			this.$ul.droppable({
				hoverClass: "tree-hover",
				greedy: true,
				drop: function(event, ui) {
					event.preventDefault();
					var dragged_node = $(ui.draggable).find(".tree-link:first").data("node");
					var dropped_node = $(this).parent().find(".tree-link:first").data("node");
					me.tree.drop(dragged_node, dropped_node, $(ui.draggable), $(this));
					return false;
				}
			});
		}

	},
	addnode: function(data) {
		var $li = $('
');
		if(this.tree.drop) $li.draggable({revert:true});
		return new frappe.ui.TreeNode({
			tree:this.tree,
			parent: $li.appendTo(this.$ul),
			parent_label: this.label,
			label: data.value,
			expandable: data.expandable,
			data: data
		});
	},
	toggle_node: function(callback) {
		// expand children
		if(this.$ul) {
			if(this.$ul.children().length) {
				this.$ul.toggle(!this.expanded);
			}

			// open close icon
			this.$a.find('i').removeClass();
			if(!this.expanded) {
				this.$a.find('i').addClass('icon-fixed-width icon-folder-open text-muted');
			} else {
				this.$a.find('i').addClass('icon-fixed-width icon-folder-close text-muted');
			}
		}

		// select this link
		this.tree.wrapper.find('.selected')
			.removeClass('selected');
		this.$a.toggleClass('selected');
		this.expanded = !this.expanded;
		if(callback) callback();
	},
	reload: function() {
		this.load();
	},
	reload_parent: function() {
		this.parent_node.load();
	},
	load: function(callback) {
		var node = this;
		args = $.extend(this.tree.args || {}, {
			parent: this.data.value
		});

		return frappe.call({
			method: this.tree.method,
			args: args,
			callback: function(r) {
				node.$ul.empty();
				if (r.message) {
					$.each(r.message, function(i, v) {
						var child_node = node.addnode(v);
						child_node.$a
							.data('node-data', v)
							.data('node', child_node);
					});
				}

				node.expanded = false;
				node.toggle_node(callback);
				node.loaded = true;
			}
		})
	}
})
<commit_msg>[fix] anchor click fix for tree<commit_after>// Copyright (c) 2015, Frappe Technologies Pvt. Ltd. and Contributors
// MIT License. See license.txt

// for license information please see license.txt

// constructor: parent, label, method, args
frappe.ui.Tree = Class.extend({
	init: function(args) {
		$.extend(this, args);
		this.nodes = {};
		this.wrapper = $('
').appendTo(this.parent);
		this.rootnode = new frappe.ui.TreeNode({
			tree: this,
			parent: this.wrapper,
			label: this.label,
			parent_label: null,
			expandable: true,
			root: true,
			data: {
				value: this.label,
				parent: this.label,
				expandable: true
			}
		});
		this.rootnode.toggle();
	},
	get_selected_node: function() {
		return this.selected_node;
	},
	toggle: function() {
		this.get_selected_node().toggle();
	}
})

frappe.ui.TreeNode = Class.extend({
	init: function(args) {
		$.extend(this, args);
		this.loaded = false;
		this.expanded = false;
		this.tree.nodes[this.label] = this;
		if(this.parent_label)
			this.parent_node = this.tree.nodes[this.parent_label];

		this.make();
		this.setup_drag_drop();

		if(this.tree.onrender) {
			this.tree.onrender(this);
		}
	},
	make: function() {
		var me = this;
		this.$a = $('')
			.click(function(event) {
				me.tree.selected_node = me;
				me.tree.wrapper.find(".tree-link.active").removeClass("active");
				me.$a.addClass("active");
				if(me.tree.toolbar) {
					me.show_toolbar();
				}
				if(me.toggle_on_click) {
					me.toggle();
				}
				if(me.tree.click)
					me.tree.click(this);
			})
			.data('label', this.label)
			.data('node', this)
			.appendTo(this.parent);

		this.$ul = $('
')
			.toggle(false).appendTo(this.parent);

		this.make_icon();

	},
	make_icon: function() {
		// label with icon
		var me= this;
		var icon_html = '';
		if(this.expandable) {
			icon_html = '';
		}
		$(icon_html + ' ' + this.get_label() + "").
			appendTo(this.$a);

		this.$a.find('i, a').click(function() {
			setTimeout(function() { me.toolbar.find(".btn-expand").click(); }, 100);
		});
	},
	get_label: function() {
		if(this.tree.get_label) {
			return this.tree.get_label(this);
		}
		return __(this.label);
	},
	toggle: function(callback) {
		if(this.expandable && this.tree.method && !this.loaded) {
			this.load(callback)
		} else {
			this.toggle_node(callback);
		}
	},
	show_toolbar: function() {
		if(this.tree.cur_toolbar)
			$(this.tree.cur_toolbar).toggle(false);

		if(!this.toolbar)
			this.make_toolbar();

		this.tree.cur_toolbar = this.toolbar;
		this.toolbar.toggle(true);
	},
	make_toolbar: function() {
		var me = this;
		this.toolbar = $('').insertAfter(this.$a);

		$.each(this.tree.toolbar, function(i, item) {
			if(item.toggle_btn) {
				item = {
					condition: function() { return me.expandable; },
					get_label: function() { return me.expanded ? __("Collapse") : __("Expand") },
					click:function(node, btn) {
						node.toggle(function() {
							$(btn).html(node.expanded ? __("Collapse") : __("Expand"));
						});
					},
					btnClass: "btn-expand hidden-xs"
				}
			}
			if(item.condition) {
				if(!item.condition(me)) return;
			}
			var label = item.get_label ? item.get_label() : item.label;
			var link = $("<button class='btn btn-default btn-xs'></button>")
				.html(label)
				.appendTo(me.toolbar)
				.click(function() { item.click(me, this); return false; });

			if(item.btnClass) link.addClass(item.btnClass);
		})

	},
	setup_drag_drop: function() {
		// experimental
		var me = this;
		if(this.tree.drop && this.parent_label) {
			this.$ul.droppable({
				hoverClass: "tree-hover",
				greedy: true,
				drop: function(event, ui) {
					event.preventDefault();
					var dragged_node = $(ui.draggable).find(".tree-link:first").data("node");
					var dropped_node = $(this).parent().find(".tree-link:first").data("node");
					me.tree.drop(dragged_node, dropped_node, $(ui.draggable), $(this));
					return false;
				}
			});
		}

	},
	addnode: function(data) {
		var $li = $('
');
		if(this.tree.drop) $li.draggable({revert:true});
		return new frappe.ui.TreeNode({
			tree:this.tree,
			parent: $li.appendTo(this.$ul),
			parent_label: this.label,
			label: data.value,
			expandable: data.expandable,
			data: data
		});
	},
	toggle_node: function(callback) {
		// expand children
		if(this.$ul) {
			if(this.$ul.children().length) {
				this.$ul.toggle(!this.expanded);
			}

			// open close icon
			this.$a.find('i').removeClass();
			if(!this.expanded) {
				this.$a.find('i').addClass('icon-fixed-width icon-folder-open text-muted');
			} else {
				this.$a.find('i').addClass('icon-fixed-width icon-folder-close text-muted');
			}
		}

		// select this link
		this.tree.wrapper.find('.selected')
			.removeClass('selected');
		this.$a.toggleClass('selected');
		this.expanded = !this.expanded;
		if(callback) callback();
	},
	reload: function() {
		this.load();
	},
	reload_parent: function() {
		this.parent_node.load();
	},
	load: function(callback) {
		var node = this;
		args = $.extend(this.tree.args || {}, {
			parent: this.data.value
		});

		return frappe.call({
			method: this.tree.method,
			args: args,
			callback: function(r) {
				node.$ul.empty();
				if (r.message) {
					$.each(r.message, function(i, v) {
						var child_node = node.addnode(v);
						child_node.$a
							.data('node-data', v)
							.data('node', child_node);
					});
				}

				node.expanded = false;
				node.toggle_node(callback);
				node.loaded = true;
			}
		})
	}
})
<|endoftext|>


<commit_before>/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/

const yaserver = require('yaserver');
const http = require('http');
const cp = require('child_process');

const PORT = 8563;

yaserver.createServer({
	rootDir: __dirname
}).then((staticServer) => {
	const server = http.createServer((request, response) => {
		return staticServer.handle(request, response);
	});
	server.listen(PORT, '127.0.0.1', () => {
		runTests().then(() => {
			console.log(`All good`);
			process.exit(0);
		}, (err) => {
			console.error(err);
			process.exit(1);
		})
	});
});

function runTests() {
	return (
		runTest('chromium')
			.then(() => runTest('firefox'))
			.then(() => runTest('webkit'))
	);
}

function runTest(browser) {
	return new Promise((resolve, reject) => {
		const proc = cp.spawn('node', ['../../node_modules/mocha/bin/mocha', 'out/*.test.js', '--headless'], {
			env: { BROWSER: browser, ...process.env },
			stdio: 'inherit'
		});
		proc.on('error', reject);
		proc.on('exit', (code) => {
			if (code === 0) {
				resolve();
			} else {
				reject(code);
			}
		});
	})
}
<commit_msg>Skip webkit<commit_after>/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/

const yaserver = require('yaserver');
const http = require('http');
const cp = require('child_process');

const PORT = 8563;

yaserver.createServer({
	rootDir: __dirname
}).then((staticServer) => {
	const server = http.createServer((request, response) => {
		return staticServer.handle(request, response);
	});
	server.listen(PORT, '127.0.0.1', () => {
		runTests().then(() => {
			console.log(`All good`);
			process.exit(0);
		}, (err) => {
			console.error(err);
			process.exit(1);
		})
	});
});

function runTests() {
	return (
		runTest('chromium')
			.then(() => runTest('firefox'))
			// .then(() => runTest('webkit'))
	);
}

function runTest(browser) {
	return new Promise((resolve, reject) => {
		const proc = cp.spawn('node', ['../../node_modules/mocha/bin/mocha', 'out/*.test.js', '--headless'], {
			env: { BROWSER: browser, ...process.env },
			stdio: 'inherit'
		});
		proc.on('error', reject);
		proc.on('exit', (code) => {
			if (code === 0) {
				resolve();
			} else {
				reject(code);
			}
		});
	})
}
<|endoftext|>


<commit_before>'use strict';

var assert = require('assert');
var fs = require('fs');
require('../fixture/sandbox.js');

describe('html', function() {
  describe('compress', function() {
    it('should simplify doctype', function() {
      var source = fs.readFileSync(__dirname + '/fixture/testSimpleDoctype.html');
      var result = fs.readFileSync(__dirname + '/fixture/testSimpleDoctypeResult.html');
      assert.strictEqual(result.toString(), lfr.html.compress(source.toString()));
    });

    it('should remove comments', function() {
      var source = fs.readFileSync(__dirname + '/fixture/testRemoveComments.html');
      var result = fs.readFileSync(__dirname + '/fixture/testRemoveCommentsResult.html');
      assert.strictEqual(result.toString(), lfr.html.compress(source.toString()));
    });

    it('should remove intertag spaces', function() {
      var source = fs.readFileSync(__dirname + '/fixture/testRemoveIntertagSpaces.html');
      var result = fs.readFileSync(__dirname + '/fixture/testRemoveIntertagSpacesResult.html');
      assert.strictEqual(result.toString(), lfr.html.compress(source.toString()));
    });

    it('should remove multi spaces', function() {
      var source = fs.readFileSync(__dirname + '/fixture/testRemoveMultiSpaces.html');
      var result = fs.readFileSync(__dirname + '/fixture/testRemoveMultiSpacesResult.html');
      assert.strictEqual(result.toString(), lfr.html.compress(source.toString()));
    });

    it('should remove spaces inside tags', function() {
      var source = fs.readFileSync(__dirname + '/fixture/testRemoveSpacesInsideTags.html');
      var result = fs.readFileSync(__dirname + '/fixture/testRemoveSpacesInsideTagsResult.html');
      assert.strictEqual(result.toString(), lfr.html.compress(source.toString()));
    });

    it('should remove surrounding spaces', function() {
      var source = fs.readFileSync(__dirname + '/fixture/testSurroundingSpaces.html');
      var result = fs.readFileSync(__dirname + '/fixture/testSurroundingSpacesResult.html');
      assert.strictEqual(result.toString(), lfr.html.compress(source.toString()));
    });

    it('should compress html', function() {
      var source = fs.readFileSync(__dirname + '/fixture/testCompress.html');
      var result = fs.readFileSync(__dirname + '/fixture/testCompressResult.html');
      assert.strictEqual(result.toString(), lfr.html.compress(source.toString()));
    });
  });
});
<commit_msg>Adds test to compress text contents<commit_after>'use strict';

var assert = require('assert');
var fs = require('fs');
require('../fixture/sandbox.js');

describe('html', function() {
  describe('compress', function() {
    it('should simplify doctype', function() {
      var source = fs.readFileSync(__dirname + '/fixture/testSimpleDoctype.html');
      var result = fs.readFileSync(__dirname + '/fixture/testSimpleDoctypeResult.html');
      assert.strictEqual(result.toString(), lfr.html.compress(source.toString()));
    });

    it('should remove comments', function() {
      var source = fs.readFileSync(__dirname + '/fixture/testRemoveComments.html');
      var result = fs.readFileSync(__dirname + '/fixture/testRemoveCommentsResult.html');
      assert.strictEqual(result.toString(), lfr.html.compress(source.toString()));
    });

    it('should remove intertag spaces', function() {
      var source = fs.readFileSync(__dirname + '/fixture/testRemoveIntertagSpaces.html');
      var result = fs.readFileSync(__dirname + '/fixture/testRemoveIntertagSpacesResult.html');
      assert.strictEqual(result.toString(), lfr.html.compress(source.toString()));
    });

    it('should remove multi spaces', function() {
      var source = fs.readFileSync(__dirname + '/fixture/testRemoveMultiSpaces.html');
      var result = fs.readFileSync(__dirname + '/fixture/testRemoveMultiSpacesResult.html');
      assert.strictEqual(result.toString(), lfr.html.compress(source.toString()));
    });

    it('should remove spaces inside tags', function() {
      var source = fs.readFileSync(__dirname + '/fixture/testRemoveSpacesInsideTags.html');
      var result = fs.readFileSync(__dirname + '/fixture/testRemoveSpacesInsideTagsResult.html');
      assert.strictEqual(result.toString(), lfr.html.compress(source.toString()));
    });

    it('should remove surrounding spaces', function() {
      var source = fs.readFileSync(__dirname + '/fixture/testSurroundingSpaces.html');
      var result = fs.readFileSync(__dirname + '/fixture/testSurroundingSpacesResult.html');
      assert.strictEqual(result.toString(), lfr.html.compress(source.toString()));
    });

    it('should compress html', function() {
      var source = fs.readFileSync(__dirname + '/fixture/testCompress.html');
      var result = fs.readFileSync(__dirname + '/fixture/testCompressResult.html');
      assert.strictEqual(result.toString(), lfr.html.compress(source.toString()));
    });

    it('should compress text content', function() {
      assert.strictEqual('foo', lfr.html.compress('   foo   '));
    });
  });
});
<|endoftext|>


<commit_before>// Copyright 2015 OpenWhere, Inc.
//
// 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.

'use strict';

var Instance = require ('../lib/EC2/Instance.js');
var Nameable = require ('../lib/Nameable.js');
var _ = require('lodash');

exports.NameableTypeTest = function(test){
    var myInstance = new Instance();

    test.expect(2);
    test.ok(myInstance instanceof Nameable);
    test.ok(myInstance.Name)
    test.done();
};

exports.canNameTest = function(test){
    var myInstance = new Instance();
    var name = "testName";
    myInstance.Name(name);

    test.expect(1);
    test.ok( _.isEqual({ 'Key': 'Name', 'Value': name}, myInstance.node.Properties.Tags[0]) );
    test.done();
};
<commit_msg>Fix JSHint herrors in nameable_test<commit_after>// Copyright 2015 OpenWhere, Inc.
//
// 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.

'use strict';

var Instance = require ('../lib/EC2/Instance.js');
var Nameable = require ('../lib/Nameable.js');
var _ = require('lodash');

exports.NameableTypeTest = function(test){
    var myInstance = new Instance();

    test.expect(2);
    test.ok(myInstance instanceof Nameable);
    test.ok(myInstance.Name);
    test.done();
};

exports.canNameTest = function(test){
    var myInstance = new Instance();
    var name = 'testName';
    myInstance.Name(name);

    test.expect(1);
    test.ok( _.isEqual({ 'Key': 'Name', 'Value': name}, myInstance.node.Properties.Tags[0]) );
    test.done();
};
<|endoftext|>


<commit_before>/*global describe it*/

var assert = require('assert');
var request = require('request');
var queue = require('queue-async');

var cfg = require("envigor")();

// since we don't need to worry about latency to localhost,
// use really quick timeouts
var waitDuration = 250;
cfg.pollWait = cfg.afterWait = waitDuration;
var timeoutLength = waitDuration * 3;

cfg.port = cfg.port || 3000;

var app = require('../lib/caress.js')(cfg);

// This should probably be done as somesort of setup/teardown around each
// test case, with the redis DB being cleared in every teardown. But, for now,
// we're just going to declare that noe server is good enough to catch the
// things we're looking for.
var server = require('http').createServer(app);
server.listen(cfg.port);

// Utility functions

function cbwrap(func) {
  var args = Array.prototype.slice.call(arguments,1);
  return function() {
    return func.apply(this,args);
  };
}

var localRoot = 'http://localhost:' + cfg.port;

function localGet(url, cb) {
  return request(localRoot + url, cb);
}

function localPost(url, body, cb) {
  return request({url: localRoot + url,
    method: 'POST', body: body}, cb);
}

function assertStatus(rightStatus, cb) {
  return function (err, res, body) {
    if (err) return cb(err);

    assert(res.statusCode == rightStatus);
    cb && cb(err, res, body);
  };
}

function assertBody(rightBody, cb) {
  return function (err, res, body) {
    if (err) return cb(err);

    assert(body == rightBody);
    cb && cb(err, res, body);
  };
}

describe("Offer-Answer flow", function() {
  describe("missing offers", function() {
    it("should 404", function(done) {
      localGet('/offers/nothing', assertStatus(404,done));
    });
    it("should 404 even when another offer is posted", function(done) {
      localPost('/offers/do','dew',
        cbwrap(localGet,'/offers/do-without',assertStatus(404,done)));
    });
  });
  describe("initial offers", function() {
    it("should post and be readable", function(done) {
      var endpoint = '/offers/telegram';
      var body = 'test body';
      localPost(endpoint,body,assertStatus(201,
        cbwrap(localGet,endpoint,assertStatus(200,assertBody(body,done)))));
    });
  });
  describe("answers to offers", function() {
    it("should free up the offer path", function(done) {
      var endpoint = '/offers/flashpoint';
      var obody = 'offer body';
      var abody = 'answer body';
      localPost(endpoint,obody,assertStatus(201,
        cbwrap(localGet,endpoint,assertStatus(200,answerOffer))));

      function answerOffer(err, res, body) {
        localPost(res.headers.location, abody,
          cbwrap(localGet,endpoint,assertStatus(404,done)));
      }
    });
    it("should be received by the offerer", function(done) {
      var endpoint = '/offers/get-this';
      var obody = 'offer initial body';
      var abody = 'answer initial body';
      localPost(endpoint,obody,listenForAnswer);

      function listenForAnswer(err, res, body) {
        localGet(res.headers.location,assertBody(abody, done));
        localGet(endpoint,answerOffer);
      }

      function answerOffer(err, res, body) {
        localPost(res.headers.location, abody);
      }
    });
    it("should not be received by other offers", function(done) {
      // This function calls a callback that takes a function that sets a
      // callback for a call that was made *earlier*. This makes sense in my
      // head, even though it's totally bananas in code.
      function timeyWimeyBall(endpoint, obody, cb) {
        localPost(endpoint, obody, function(err, res, body) {
          // This will be set a couple callbacks down
          var expectedAnswer, finalCallback;

          localGet(res.headers.location, receiveAnswer);

          cb(err,function answerer(abody, fcb) {
            expectedAnswer = abody; finalCallback = fcb;
            localGet(endpoint,function(err,res,body){
              localPost(res.headers.location, abody);
            });
          });

          function receiveAnswer(err, res, body) {
            assert(body == expectedAnswer);
            finalCallback && finalCallback(err);
          }
        });
      }

      queue()
        .defer(timeyWimeyBall, '/offers/point-a', 'Offer A initial body')
        .defer(timeyWimeyBall, '/offers/point-b', 'Offer B initial body')
        .await(function(err, answererA, answererB){
          queue()
            .defer(answererA,'Answer A initial body')
            .defer(answererB,'Answer B initial body')
            .await(done);
        });
    });
  });
});
<commit_msg>Use more informative assertion<commit_after>/*global describe it*/

var assert = require('assert');
var request = require('request');
var queue = require('queue-async');

var cfg = require("envigor")();

// since we don't need to worry about latency to localhost,
// use really quick timeouts
var waitDuration = 250;
cfg.pollWait = cfg.afterWait = waitDuration;
var timeoutLength = waitDuration * 3;

cfg.port = cfg.port || 3000;

var app = require('../lib/caress.js')(cfg);

// This should probably be done as somesort of setup/teardown around each
// test case, with the redis DB being cleared in every teardown. But, for now,
// we're just going to declare that noe server is good enough to catch the
// things we're looking for.
var server = require('http').createServer(app);
server.listen(cfg.port);

// Utility functions

function cbwrap(func) {
  var args = Array.prototype.slice.call(arguments,1);
  return function() {
    return func.apply(this,args);
  };
}

var localRoot = 'http://localhost:' + cfg.port;

function localGet(url, cb) {
  return request(localRoot + url, cb);
}

function localPost(url, body, cb) {
  return request({url: localRoot + url,
    method: 'POST', body: body}, cb);
}

function assertStatus(rightStatus, cb) {
  return function (err, res, body) {
    if (err) return cb(err);

    assert.equal(res.statusCode, rightStatus);
    cb && cb(err, res, body);
  };
}

function assertBody(rightBody, cb) {
  return function (err, res, body) {
    if (err) return cb(err);

    assert.equal(body, rightBody);
    cb && cb(err, res, body);
  };
}

describe("Offer-Answer flow", function() {
  describe("missing offers", function() {
    it("should 404", function(done) {
      localGet('/offers/nothing', assertStatus(404,done));
    });
    it("should 404 even when another offer is posted", function(done) {
      localPost('/offers/do','dew',
        cbwrap(localGet,'/offers/do-without',assertStatus(404,done)));
    });
  });
  describe("initial offers", function() {
    it("should post and be readable", function(done) {
      var endpoint = '/offers/telegram';
      var body = 'test body';
      localPost(endpoint,body,assertStatus(201,
        cbwrap(localGet,endpoint,assertStatus(200,assertBody(body,done)))));
    });
  });
  describe("answers to offers", function() {
    it("should free up the offer path", function(done) {
      var endpoint = '/offers/flashpoint';
      var obody = 'offer body';
      var abody = 'answer body';
      localPost(endpoint,obody,assertStatus(201,
        cbwrap(localGet,endpoint,assertStatus(200,answerOffer))));

      function answerOffer(err, res, body) {
        localPost(res.headers.location, abody,
          cbwrap(localGet,endpoint,assertStatus(404,done)));
      }
    });
    it("should be received by the offerer", function(done) {
      var endpoint = '/offers/get-this';
      var obody = 'offer initial body';
      var abody = 'answer initial body';
      localPost(endpoint,obody,listenForAnswer);

      function listenForAnswer(err, res, body) {
        localGet(res.headers.location,assertBody(abody, done));
        localGet(endpoint,answerOffer);
      }

      function answerOffer(err, res, body) {
        localPost(res.headers.location, abody);
      }
    });
    it("should not be received by other offers", function(done) {
      // This function calls a callback that takes a function that sets a
      // callback for a call that was made *earlier*. This makes sense in my
      // head, even though it's totally bananas in code.
      function timeyWimeyBall(endpoint, obody, cb) {
        localPost(endpoint, obody, function(err, res, body) {
          // This will be set a couple callbacks down
          var expectedAnswer, finalCallback;

          localGet(res.headers.location, receiveAnswer);

          cb(err,function answerer(abody, fcb) {
            expectedAnswer = abody; finalCallback = fcb;
            localGet(endpoint,function(err,res,body){
              localPost(res.headers.location, abody);
            });
          });

          function receiveAnswer(err, res, body) {
            assert.equal(body, expectedAnswer);
            finalCallback && finalCallback(err);
          }
        });
      }

      queue()
        .defer(timeyWimeyBall, '/offers/point-a', 'Offer A initial body')
        .defer(timeyWimeyBall, '/offers/point-b', 'Offer B initial body')
        .await(function(err, answererA, answererB){
          queue()
            .defer(answererA,'Answer A initial body')
            .defer(answererB,'Answer B initial body')
            .await(done);
        });
    });
  });
});
<|endoftext|>


<commit_before>(function( w, $ ) {
	"use strict";
	var simple;

	function commonSetup(){
		$(document).trigger("enhance");
		simple = $( "#simple" ).data( "NumericInput" );
	}

	module( "Methods", {
		setup: commonSetup
	});

	test("initMaxlength", function(){
		simple.initMaxlength();
		equal(simple.maxLength, Infinity);

		simple.$el.attr("maxlength", 10);
		simple.initMaxlength();
		equal(simple.maxLength, 10);

		simple.$el.removeAttr("maxlength");
		simple.$el.attr("max", 200);
		simple.initMaxlength();
		equal(simple.maxLength, 3);
	});

	test("isNumeric key range", function(){
		// first range from 48 to 57
		ok(!simple.isNumeric(47));
		ok(simple.isNumeric(48));
		ok(simple.isNumeric(57));
		ok(!simple.isNumeric(58));

		// second range from 96 to 105
		ok(!simple.isNumeric(95));
		ok(simple.isNumeric(96));
		ok(simple.isNumeric(105));
		ok(!simple.isNumeric(106));
	});

	test("isMetaKeyAllowed", function(){
		ok(simple.isMetaKeyAllowed(event = {
			keyCode: -1,
			altKey: true
		}));

		ok(simple.isMetaKeyAllowed(event = {
			keyCode: -1,
			ctrlKey: true
		}));

		ok(simple.isMetaKeyAllowed(event = {
			keyCode: -1,
			metaKey: true
		}));

		$.each(window.NumericInput.allowedKeys, function(i, k){
			ok(simple.isMetaKeyAllowed(event = {
				keyCode: k
			}));
		});

		ok(simple.isMetaKeyAllowed(event = {
			keyCode: 38
		}));

		simple.isNavDisabled = true;
		ok(!simple.isMetaKeyAllowed(event = {
			keyCode: 38
		}));
	});

	test("onKeydown prevented", function(){
		expect(4);

		function preventDefault(){
			ok(true, "preventDefault called");
		}

		simple.maxLength = 0;

		simple.onKeydown({
			preventDefault: preventDefault,

			// space
			keyCode: 32
		});

		// prevents extra decimal points
		simple.$el.val( "1." );
		simple.onKeydown({
			preventDefault: preventDefault,

			// `.`
			keyCode: 190
		});

		// prevents extra minus
		simple.$el.val( "-1" );
		simple.onKeydown({
			preventDefault: preventDefault,

			// `.`
			keyCode: 189
		});

		simple.onKeydown({
			preventDefault: preventDefault,

			// `1`
			keyCode: 49,
			shiftKey: true
		});
	});
})(window, shoestring);
<commit_msg>onKeydown not prevented<commit_after>(function( w, $ ) {
	"use strict";
	var simple;

	function commonSetup(){
		$(document).trigger("enhance");
		simple = $( "#simple" ).data( "NumericInput" );
	}

	module( "Methods", {
		setup: commonSetup
	});

	test("initMaxlength", function(){
		simple.initMaxlength();
		equal(simple.maxLength, Infinity);

		simple.$el.attr("maxlength", 10);
		simple.initMaxlength();
		equal(simple.maxLength, 10);

		simple.$el.removeAttr("maxlength");
		simple.$el.attr("max", 200);
		simple.initMaxlength();
		equal(simple.maxLength, 3);
	});

	test("isNumeric key range", function(){
		// first range from 48 to 57
		ok(!simple.isNumeric(47));
		ok(simple.isNumeric(48));
		ok(simple.isNumeric(57));
		ok(!simple.isNumeric(58));

		// second range from 96 to 105
		ok(!simple.isNumeric(95));
		ok(simple.isNumeric(96));
		ok(simple.isNumeric(105));
		ok(!simple.isNumeric(106));
	});

	test("isMetaKeyAllowed", function(){
		ok(simple.isMetaKeyAllowed(event = {
			keyCode: -1,
			altKey: true
		}));

		ok(simple.isMetaKeyAllowed(event = {
			keyCode: -1,
			ctrlKey: true
		}));

		ok(simple.isMetaKeyAllowed(event = {
			keyCode: -1,
			metaKey: true
		}));

		$.each(window.NumericInput.allowedKeys, function(i, k){
			ok(simple.isMetaKeyAllowed(event = {
				keyCode: k
			}));
		});

		ok(simple.isMetaKeyAllowed(event = {
			keyCode: 38
		}));

		simple.isNavDisabled = true;
		ok(!simple.isMetaKeyAllowed(event = {
			keyCode: 38
		}));
	});

	function preventDefault(){
		ok(true, "preventDefault called");
	}

	test("onKeydown prevented", function(){
		expect(5);

		simple.maxLength = 0;

		simple.onKeydown({
			preventDefault: preventDefault,

			// space
			keyCode: 32
		});

		// prevents extra decimal points
		simple.$el.val( "1." );
		simple.onKeydown({
			preventDefault: preventDefault,

			// `.`
			keyCode: 190
		});

		// prevents extra minus
		simple.$el.val( "-1" );
		simple.allowNegative = true;
		simple.onKeydown({
			preventDefault: preventDefault,

			// `-`
			keyCode: 189
		});

		// prevents extra minus
		simple.el.value = "-1";
		simple.allowNegative = true;
		simple.onKeydown({
			preventDefault: preventDefault,

			// `-`
			keyCode: 189
		});

		simple.onKeydown({
			preventDefault: preventDefault,

			// `1`
			keyCode: 49,
			shiftKey: true
		});
	});

	test("onKeydown not prevented", function(){
		expect(0);

		simple.onKeydown({
			preventDefault: preventDefault,
			metaKey: true
		});

		// allows decimals
		simple.allowFloat = true;
		simple.$el.val( "1" );
		simple.onKeydown({
			preventDefault: preventDefault,

			// `.`
			keyCode: 190
		});

		// prevents extra minus
		simple.$el.val( "" );
		simple.allowNegative = true;
		simple.onKeydown({
			preventDefault: preventDefault,

			// `-`
			keyCode: 189
		});

		simple.onKeydown({
			preventDefault: preventDefault,

			// `1`
			keyCode: 49
		});
	});
})(window, shoestring);
<|endoftext|>


<commit_before>
'use strict';

var mockery = require('mockery'),
    when = require('saywhen'),
    buffer = require('buffer');

describe("Petition utilities", function() {
    var httpsMock;

    beforeEach(function() {
        httpsMock = {
            get : jasmine.createSpy('get')
        };

        mockery.enable({
            warnOnReplace : false,
            warnOnUnregistered : false,
            useCleanCache : true
        });
        mockery.registerMock('https', httpsMock);
    });
    afterEach(function() {
        mockery.deregisterAll();
        mockery.disable();
    });

    it('supports HTTPS requests', function() {
        var util = require('../src/petition-util');
        expect(util.getJsonOverHttps).toBeDefined();
    });
    it('fires an event when http requests complete', function(done) {
        var util = require('../src/petition-util');

        var responseListener;
        when(httpsMock.get)
            .isCalledWith(
                jasmine.any(Object),
                jasmine.any(Function))
            .then(function(options, callback) {
                responseListener = callback;
                return {
                    on : jasmine.createSpy('on')
                };
            });

        util.getJsonOverHttps({
            hostname: 'localhost',
            path: '/path'
        })
        .on('data', function(data) {
            expect(data).toBeDefined();
            expect(data.foo).toBeDefined();
            expect(data.foo).toBe('bar');
            done();
        })
        .on('error', function() {
            done.fail('The error event was fired');
        });

        var response = {
            statusCode : 200,
            on : jasmine.createSpy('on')
        };
        var dataListener;
        when(response.on).isCalledWith('data', jasmine.any(Function))
            .then(function(event, listener) {
                dataListener = function(d) {
                    listener(d);
                };
                return response;
            });
        when(response.on).isCalledWith('end', jasmine.any(Function))
            .then(function(event, listener) {
                dataListener(new buffer.Buffer('{"foo":"bar"}'));
                listener();
                return response;
            });
        responseListener(response);
    });
    it('fires an error event when http returns non-200 status code', function(done) {
        var util = require('../src/petition-util');

        var responseListener;
        when(httpsMock.get)
            .isCalledWith(
                jasmine.any(Object),
                jasmine.any(Function))
            .then(function(options, callback) {
                responseListener = callback;
                return {
                    on : jasmine.createSpy('on')
                };
            });

        util.getJsonOverHttps({
            hostname: 'localhost',
            path: '/path'
        })
        .on('data', function(data) {
            done.fail('Data not expected');
        })
        .on('error', function() {
            done();
        });

        var response = {
            statusCode : 404,
            on : jasmine.createSpy('on')
        };
        var dataListener;
        when(response.on).isCalledWith('data', jasmine.any(Function))
            .then(function(event, listener) {
                dataListener = function(d) {
                    listener(d);
                };
                return response;
            });
        when(response.on).isCalledWith('end', jasmine.any(Function))
            .then(function(event, listener) {
                dataListener(new buffer.Buffer('{"foo":"bar"}'));
                listener();
                return response;
            });
        responseListener(response);
    });
    it('supports forwarding errors', function() {
        var util = require('../src/petition-util');
        expect(util.forwardError).toBeDefined();
    });
});
<commit_msg>Improve forwarding error test.<commit_after>
'use strict';

var mockery = require('mockery'),
    when = require('saywhen'),
    buffer = require('buffer'),
    EventEmitter = require('events');

describe("Petition utilities", function() {
    var httpsMock;

    beforeEach(function() {
        httpsMock = {
            get : jasmine.createSpy('get')
        };

        mockery.enable({
            warnOnReplace : false,
            warnOnUnregistered : false,
            useCleanCache : true
        });
        mockery.registerMock('https', httpsMock);
    });
    afterEach(function() {
        mockery.deregisterAll();
        mockery.disable();
    });

    it('supports HTTPS requests', function() {
        var util = require('../src/petition-util');
        expect(util.getJsonOverHttps).toBeDefined();
    });
    it('fires an event when http requests complete', function(done) {
        var util = require('../src/petition-util');

        var responseListener;
        when(httpsMock.get)
            .isCalledWith(
                jasmine.any(Object),
                jasmine.any(Function))
            .then(function(options, callback) {
                responseListener = callback;
                return {
                    on : jasmine.createSpy('on')
                };
            });

        util.getJsonOverHttps({
            hostname: 'localhost',
            path: '/path'
        })
        .on('data', function(data) {
            expect(data).toBeDefined();
            expect(data.foo).toBeDefined();
            expect(data.foo).toBe('bar');
            done();
        })
        .on('error', function() {
            done.fail('The error event was fired');
        });

        var response = {
            statusCode : 200,
            on : jasmine.createSpy('on')
        };
        var dataListener;
        when(response.on).isCalledWith('data', jasmine.any(Function))
            .then(function(event, listener) {
                dataListener = function(d) {
                    listener(d);
                };
                return response;
            });
        when(response.on).isCalledWith('end', jasmine.any(Function))
            .then(function(event, listener) {
                dataListener(new buffer.Buffer('{"foo":"bar"}'));
                listener();
                return response;
            });
        responseListener(response);
    });
    it('fires an error event when http returns non-200 status code', function(done) {
        var util = require('../src/petition-util');

        var responseListener;
        when(httpsMock.get)
            .isCalledWith(
                jasmine.any(Object),
                jasmine.any(Function))
            .then(function(options, callback) {
                responseListener = callback;
                return {
                    on : jasmine.createSpy('on')
                };
            });

        util.getJsonOverHttps({
            hostname: 'localhost',
            path: '/path'
        })
        .on('data', function(data) {
            done.fail('Data not expected');
        })
        .on('error', function() {
            done();
        });

        var response = {
            statusCode : 404,
            on : jasmine.createSpy('on')
        };
        var dataListener;
        when(response.on).isCalledWith('data', jasmine.any(Function))
            .then(function(event, listener) {
                dataListener = function(d) {
                    listener(d);
                };
                return response;
            });
        when(response.on).isCalledWith('end', jasmine.any(Function))
            .then(function(event, listener) {
                dataListener(new buffer.Buffer('{"foo":"bar"}'));
                listener();
                return response;
            });
        responseListener(response);
    });
    it('supports forwarding errors', function(done) {
        var util = require('../src/petition-util');
        expect(util.forwardError).toBeDefined();

        var sourceEmitter = new EventEmitter();
        var forwardingEmitter = new EventEmitter();
        sourceEmitter.on('error', util.forwardError(forwardingEmitter));
        forwardingEmitter.on('error', done);
        sourceEmitter.emit('error', new Error('Test error'));
    });
});
<|endoftext|>


<commit_before>var _ = require('underscore'),
    lib = require('../lib');

describe('scope plugin', function() {
  describe('var scope', function() {
    function testScope(scope, scripts, callback) {
      if (_.isFunction(scripts)) {
        callback = scripts;
        scripts = undefined;
      }

      var module = {
        topLevelName: 'foo',
        scripts: scripts || [
          'js/init.js',
          'js/views/test.js'
        ]
      };
      var config = {
        scope: {
          scope: scope,
          template: 'moduleStart{{yield}}moduleEnd'
        }
      };

      lib.pluginExec('scope', 'scripts', module, [], config, function(resources) {
        resources = _.map(resources, function(resource) {
          return resource.stringValue || resource.src;
        });

        callback(resources);
      });
    }

    it('should scope files', function(done) {
      testScope('file', function(resources) {
        resources.should.eql([
          'var foo;\n',
          'moduleStart',
          'js/init.js',
          'js/views/test.js',
          'moduleEnd'
        ]);
        done();
      });
    });
    it('should scope resources', function(done) {
      testScope('resource', function(resources) {
        resources.should.eql([
          'var foo;\n',
          'moduleStart',
          '(function() {\n',
          'js/init.js',
          '}).call(this);\n',
          '(function() {\n',
          'js/views/test.js',
          '}).call(this);\n',
          'moduleEnd'
        ]);
        done();
      });
    });
    it('should scope nothing', function(done) {
      testScope('none', function(resources) {
        resources.should.eql([
          'js/init.js',
          'js/views/test.js',
        ]);
        done();
      });
    });

    it('should scope globals', function(done) {
      testScope('file', [{src: 'js/init.js', global: true}, 'js/views/test.js'], function(resources) {
        resources.should.eql([
          'var foo;\n',
          'js/init.js',
          'moduleStart',
          'js/views/test.js',
          'moduleEnd'
        ]);
        done();
      });
    });
  });

  describe('modules', function() {
    describe('object', function() {
      it('should expose top level object inside scope', function(done) {
        var module = {
          topLevelName: 'foo',
          scripts: [
            'js/init.js'
          ]
        };
        var config = {
          scope: {
            scope: 'file',
            template: 'moduleStart;{{{internalScope}}}{{yield}}moduleEnd'
          }
        };

        lib.pluginExec('scope', 'scripts', module, [], config, function(resources) {
          resources = _.map(resources, function(resource) {
            return resource.stringValue || resource.src;
          });

          resources.should.eql([
            'var foo;\n',
            'moduleStart;var foo = exports;',
            'js/init.js',
            'moduleEnd'
          ]);
          done();
        });
      });
      it('should map child module alias', function(done) {
        var module = {
          scripts: [
            'js/init.js'
          ]
        };
        var config = {
          modules: {
            module: module
          },
          application: {
            'name': 'Application',
            'module': 'base'
          },
          scope: {
            scope: 'file',
            aliases: {
              'View': 'Application.module',
              'View2': 'Application["module"]',
              'foo': 'foo',
              'Application': 'Application'
            },
            template: 'moduleStart;{{{internalScope}}}{{yield}}moduleEnd'
          }
        };

        lib.pluginExec('scope', 'scripts', module, [], config, function(resources) {
          resources = _.map(resources, function(resource) {
            return resource.stringValue || resource.src;
          });

          resources.should.eql([
            'moduleStart;Application[\'module\'] = exports;var View = exports, View2 = exports;',
            'js/init.js',
            'moduleEnd'
          ]);
          done();
        });
      });
    });
    describe('aliases', function() {
      it('should define aliases as parameters', function(done) {
        var module = {
          topLevelName: 'foo',
          scripts: [
            'js/init.js'
          ]
        };
        var config = {
          scope: {
            scope: 'file',
            aliases: {
              'View': 'Application.View',
              'foo': 'foo',
              'Application': 'Application'
            },
            template: 'moduleStart({{{aliasVars}}}){{yield}}moduleEnd({{{callSpec}}})'
          }
        };

        lib.pluginExec('scope', 'scripts', module, [], config, function(resources) {
          resources = _.map(resources, function(resource) {
            return resource.stringValue || resource.src;
          });

          resources.should.eql([
            'var foo;\n',
            'moduleStart(View, Application)',
            'js/init.js',
            'moduleEnd(this, Application.View, Application)'
          ]);
          done();
        });
      });
      it('should handle no aliases', function(done) {
        var module = {
          topLevelName: 'foo',
          scripts: [
            'js/init.js'
          ]
        };
        var config = {
          scope: {
            scope: 'file',
            template: 'moduleStart({{{aliasVars}}}){{yield}}moduleEnd({{{callSpec}}})'
          }
        };

        lib.pluginExec('scope', 'scripts', module, [], config, function(resources) {
          resources = _.map(resources, function(resource) {
            return resource.stringValue || resource.src;
          });

          resources.should.eql([
            'var foo;\n',
            'moduleStart()',
            'js/init.js',
            'moduleEnd(this)'
          ]);
          done();
        });
      });

      it('should pull aliases from module', function(done) {
        var module = {
          topLevelName: 'foo',
          aliases: {
            'View': 'Application.View',
            'foo': 'foo'
          },
          scripts: [
            'js/init.js'
          ]
        };
        var config = {
          scope: {
            template: 'moduleStart({{{aliasVars}}}){{yield}}moduleEnd({{{callSpec}}})',
            aliases: {
              'View': 'Application.Views',
              'foo': 'food',
              'Application': 'Application'
            }
          }
        };

        lib.pluginExec('scope', 'scripts', module, [], config, function(resources) {
          resources = _.map(resources, function(resource) {
            return resource.stringValue || resource.src;
          });

          resources.should.eql([
            'var foo;\n',
            'moduleStart(View, Application)',
            'js/init.js',
            'moduleEnd(this, Application.View, Application)'
          ]);
          done();
        });
      });

      it('should handle alias overrides', function(done) {
        var module = {
          topLevelName: 'foo',
          scripts: [
            'js/init.js'
          ],
          aliases: {
            'View': 'bar',
            'Application': false
          }
        };
        var config = {
          scope: {
            scope: 'file',
            aliases: {
              'View': 'Application.View',
              'foo': 'foo',
              'Application': 'Application'
            },
            template: 'moduleStart({{{aliasVars}}}){{yield}}moduleEnd({{{callSpec}}})'
          }
        };

        lib.pluginExec('scope', 'scripts', module, [], config, function(resources) {
          resources = _.map(resources, function(resource) {
            return resource.stringValue || resource.src;
          });

          resources.should.eql([
            'var foo;\n',
            'moduleStart(View)',
            'js/init.js',
            'moduleEnd(this, bar)'
          ]);
          done();
        });
      });
    });
  });

  describe('mixin', function() {
    it('should include special values from mixins', function(done) {
      var mixins = [
        {
          root: 'mixin1/',
          scope: {
            scope: 'module',
            template: 'module.handlebars',
            aliases: {
              'foo': 'bar',
              'baz': 'bar'
            }
          }
        },
        {
          scope: 'none'
        }
      ];

      var config = {
        scope: {
          scope: 'resource',
          aliases: {
            'foo': 'bat',
            'bat': 'baz'
          }
        }
      };

      lib.mixinExec({}, mixins, config, function(mixins, context) {
        mixins.load(context, mixins, function() {
          context.config.attributes.scope.should.eql({
            scope: 'resource',
            template: 'mixin1/module.handlebars',
            aliases: {
              'foo': 'bat',
              'baz': 'bar',
              'bat': 'baz'
            }
          });
          done();
        });
      });
    });
    it('should merge with shorthand', function(done) {
      var mixins = [
        {
          root: 'mixin1/',
          scope: {
            scope: 'module',
            template: 'module.handlebars',
            aliases: {
              'foo': 'bar',
              'baz': 'bar'
            }
          }
        },
        {
          scope: 'none'
        }
      ];

      var config = {
        scope: 'resource'
      };

      lib.mixinExec({}, mixins, config, function(mixins, context) {
        mixins.load(context, mixins, function() {
          context.config.attributes.scope.should.eql({
            scope: 'resource',
            template: 'mixin1/module.handlebars',
            aliases: {
              'foo': 'bar',
              'baz': 'bar'
            }
          });
          done();
        });
      });
    });
    it('should create scope config if necessary', function(done) {
      var mixin = {
        scope: {
          scope: 'module',
          template: 'module.handlebars',
          aliases: {
            'foo': 'bar',
            'baz': 'bar'
          }
        }
      };

      lib.mixinExec({}, [], {}, function(mixins, context) {
        mixins.load(context, mixin, function() {
          context.config.attributes.scope.should.eql({
            scope: 'module',
            template: 'module.handlebars',
            aliases: {
              'foo': 'bar',
              'baz': 'bar'
            }
          });
          done();
        });
      });
    });
    it('should mixin module aliases', function(done) {
      var mixins = [
        {
          root: 'mixin1/',
          mixins: {
            mixin1: {
              aliases: {
                'foo': 'bar',
                'baz': 'bar'
              }
            }
          }
        }
      ];

      lib.mixinExec({mixins: ['mixin1'], aliases: {'foo': 'bat'}}, mixins, {}, function(mixins, context) {
        mixins.load(context, mixins, function() {
          context.module.aliases.should.eql({
            'foo': 'bat',
            'baz': 'bar'
          });
          done();
        });
      });
    });
  });
});
<commit_msg>Additional scope alias test<commit_after>var _ = require('underscore'),
    lib = require('../lib');

describe('scope plugin', function() {
  describe('var scope', function() {
    function testScope(scope, scripts, callback) {
      if (_.isFunction(scripts)) {
        callback = scripts;
        scripts = undefined;
      }

      var module = {
        topLevelName: 'foo',
        scripts: scripts || [
          'js/init.js',
          'js/views/test.js'
        ]
      };
      var config = {
        scope: {
          scope: scope,
          template: 'moduleStart{{yield}}moduleEnd'
        }
      };

      lib.pluginExec('scope', 'scripts', module, [], config, function(resources) {
        resources = _.map(resources, function(resource) {
          return resource.stringValue || resource.src;
        });

        callback(resources);
      });
    }

    it('should scope files', function(done) {
      testScope('file', function(resources) {
        resources.should.eql([
          'var foo;\n',
          'moduleStart',
          'js/init.js',
          'js/views/test.js',
          'moduleEnd'
        ]);
        done();
      });
    });
    it('should scope resources', function(done) {
      testScope('resource', function(resources) {
        resources.should.eql([
          'var foo;\n',
          'moduleStart',
          '(function() {\n',
          'js/init.js',
          '}).call(this);\n',
          '(function() {\n',
          'js/views/test.js',
          '}).call(this);\n',
          'moduleEnd'
        ]);
        done();
      });
    });
    it('should scope nothing', function(done) {
      testScope('none', function(resources) {
        resources.should.eql([
          'js/init.js',
          'js/views/test.js',
        ]);
        done();
      });
    });

    it('should scope globals', function(done) {
      testScope('file', [{src: 'js/init.js', global: true}, 'js/views/test.js'], function(resources) {
        resources.should.eql([
          'var foo;\n',
          'js/init.js',
          'moduleStart',
          'js/views/test.js',
          'moduleEnd'
        ]);
        done();
      });
    });
  });

  describe('modules', function() {
    describe('object', function() {
      it('should expose top level object inside scope', function(done) {
        var module = {
          topLevelName: 'foo',
          scripts: [
            'js/init.js'
          ]
        };
        var config = {
          scope: {
            scope: 'file',
            template: 'moduleStart;{{{internalScope}}}{{yield}}moduleEnd'
          }
        };

        lib.pluginExec('scope', 'scripts', module, [], config, function(resources) {
          resources = _.map(resources, function(resource) {
            return resource.stringValue || resource.src;
          });

          resources.should.eql([
            'var foo;\n',
            'moduleStart;var foo = exports;',
            'js/init.js',
            'moduleEnd'
          ]);
          done();
        });
      });
      it('should map child module alias', function(done) {
        var module = {
          scripts: [
            'js/init.js'
          ]
        };
        var config = {
          modules: {
            module: module
          },
          application: {
            'name': 'Application',
            'module': 'base'
          },
          scope: {
            scope: 'file',
            aliases: {
              'View': 'Application.module',
              'View2': 'Application["module"]',
              'foo': 'foo',
              'Application': 'Application'
            },
            template: 'moduleStart;{{{internalScope}}}{{yield}}moduleEnd'
          }
        };

        lib.pluginExec('scope', 'scripts', module, [], config, function(resources) {
          resources = _.map(resources, function(resource) {
            return resource.stringValue || resource.src;
          });

          resources.should.eql([
            'moduleStart;Application[\'module\'] = exports;var View = exports, View2 = exports;',
            'js/init.js',
            'moduleEnd'
          ]);
          done();
        });
      });
    });
    describe('aliases', function() {
      it('should define aliases as parameters', function(done) {
        var module = {
          topLevelName: 'foo',
          scripts: [
            'js/init.js'
          ]
        };
        var config = {
          scope: {
            scope: 'file',
            aliases: {
              'View': 'Application.View',
              'foo': 'foo',
              'Application': 'Application'
            },
            template: 'moduleStart({{{aliasVars}}}){{yield}}moduleEnd({{{callSpec}}})'
          }
        };

        lib.pluginExec('scope', 'scripts', module, [], config, function(resources) {
          resources = _.map(resources, function(resource) {
            return resource.stringValue || resource.src;
          });

          resources.should.eql([
            'var foo;\n',
            'moduleStart(View, Application)',
            'js/init.js',
            'moduleEnd(this, Application.View, Application)'
          ]);
          done();
        });
      });
      it('should handle no aliases', function(done) {
        var module = {
          topLevelName: 'foo',
          scripts: [
            'js/init.js'
          ]
        };
        var config = {
          scope: {
            scope: 'file',
            template: 'moduleStart({{{aliasVars}}}){{yield}}moduleEnd({{{callSpec}}})'
          }
        };

        lib.pluginExec('scope', 'scripts', module, [], config, function(resources) {
          resources = _.map(resources, function(resource) {
            return resource.stringValue || resource.src;
          });

          resources.should.eql([
            'var foo;\n',
            'moduleStart()',
            'js/init.js',
            'moduleEnd(this)'
          ]);
          done();
        });
      });

      it('should pull aliases from module', function(done) {
        var module = {
          topLevelName: 'foo',
          aliases: {
            'View': 'Application.View',
            'foo': 'foo'
          },
          scripts: [
            'js/init.js'
          ]
        };
        var config = {
          scope: {
            template: 'moduleStart({{{aliasVars}}}){{yield}}moduleEnd({{{callSpec}}})',
            aliases: {
              'View': 'Application.Views',
              'foo': 'food',
              'Application': 'Application'
            }
          }
        };

        lib.pluginExec('scope', 'scripts', module, [], config, function(resources) {
          resources = _.map(resources, function(resource) {
            return resource.stringValue || resource.src;
          });

          resources.should.eql([
            'var foo;\n',
            'moduleStart(View, Application)',
            'js/init.js',
            'moduleEnd(this, Application.View, Application)'
          ]);
          done();
        });
      });

      it('should handle alias overrides', function(done) {
        var module = {
          topLevelName: 'foo',
          scripts: [
            'js/init.js'
          ],
          aliases: {
            'View': 'bar',
            'Application': false
          }
        };
        var config = {
          scope: {
            scope: 'file',
            aliases: {
              'View': 'Application.View',
              'foo': 'foo',
              'Application': 'Application'
            },
            template: 'moduleStart({{{aliasVars}}}){{yield}}moduleEnd({{{callSpec}}})'
          }
        };

        lib.pluginExec('scope', 'scripts', module, [], config, function(resources) {
          resources = _.map(resources, function(resource) {
            return resource.stringValue || resource.src;
          });

          resources.should.eql([
            'var foo;\n',
            'moduleStart(View)',
            'js/init.js',
            'moduleEnd(this, bar)'
          ]);
          done();
        });
      });
      it('should handle total alias overrides', function(done) {
        var module = {
          topLevelName: 'foo',
          scripts: [
            'js/init.js'
          ],
          aliases: {
            'View': false,
            'Application': false
          }
        };
        var config = {
          scope: {
            scope: 'file',
            aliases: {
              'View': 'Application.View',
              'foo': 'foo',
              'Application': 'Application'
            },
            template: 'moduleStart({{{aliasVars}}}){{yield}}moduleEnd({{{callSpec}}})'
          }
        };

        lib.pluginExec('scope', 'scripts', module, [], config, function(resources) {
          resources = _.map(resources, function(resource) {
            return resource.stringValue || resource.src;
          });

          resources.should.eql([
            'var foo;\n',
            'moduleStart()',
            'js/init.js',
            'moduleEnd(this)'
          ]);
          done();
        });
      });
    });
  });

  describe('mixin', function() {
    it('should include special values from mixins', function(done) {
      var mixins = [
        {
          root: 'mixin1/',
          scope: {
            scope: 'module',
            template: 'module.handlebars',
            aliases: {
              'foo': 'bar',
              'baz': 'bar'
            }
          }
        },
        {
          scope: 'none'
        }
      ];

      var config = {
        scope: {
          scope: 'resource',
          aliases: {
            'foo': 'bat',
            'bat': 'baz'
          }
        }
      };

      lib.mixinExec({}, mixins, config, function(mixins, context) {
        mixins.load(context, mixins, function() {
          context.config.attributes.scope.should.eql({
            scope: 'resource',
            template: 'mixin1/module.handlebars',
            aliases: {
              'foo': 'bat',
              'baz': 'bar',
              'bat': 'baz'
            }
          });
          done();
        });
      });
    });
    it('should merge with shorthand', function(done) {
      var mixins = [
        {
          root: 'mixin1/',
          scope: {
            scope: 'module',
            template: 'module.handlebars',
            aliases: {
              'foo': 'bar',
              'baz': 'bar'
            }
          }
        },
        {
          scope: 'none'
        }
      ];

      var config = {
        scope: 'resource'
      };

      lib.mixinExec({}, mixins, config, function(mixins, context) {
        mixins.load(context, mixins, function() {
          context.config.attributes.scope.should.eql({
            scope: 'resource',
            template: 'mixin1/module.handlebars',
            aliases: {
              'foo': 'bar',
              'baz': 'bar'
            }
          });
          done();
        });
      });
    });
    it('should create scope config if necessary', function(done) {
      var mixin = {
        scope: {
          scope: 'module',
          template: 'module.handlebars',
          aliases: {
            'foo': 'bar',
            'baz': 'bar'
          }
        }
      };

      lib.mixinExec({}, [], {}, function(mixins, context) {
        mixins.load(context, mixin, function() {
          context.config.attributes.scope.should.eql({
            scope: 'module',
            template: 'module.handlebars',
            aliases: {
              'foo': 'bar',
              'baz': 'bar'
            }
          });
          done();
        });
      });
    });
    it('should mixin module aliases', function(done) {
      var mixins = [
        {
          root: 'mixin1/',
          mixins: {
            mixin1: {
              aliases: {
                'foo': 'bar',
                'baz': 'bar'
              }
            }
          }
        }
      ];

      lib.mixinExec({mixins: ['mixin1'], aliases: {'foo': 'bat'}}, mixins, {}, function(mixins, context) {
        mixins.load(context, mixins, function() {
          context.module.aliases.should.eql({
            'foo': 'bat',
            'baz': 'bar'
          });
          done();
        });
      });
    });
  });
});
<|endoftext|>


<commit_before>// Copyright 2016 Lohith Royal Pinto <royalpinto@gmail.com>
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE

var cares = require('../lib/cares.js');
var net = require('net');

var SERVERS = ['127.0.0.1'];
var PORT = 49160;
var dnsentries = require('./setup/dnsentries.js');

module.exports = {

    setUp: function (callback) {
        this.resolver = new cares.Resolver({
            servers: SERVERS,
            udp_port: PORT,
        });
        callback();
    },
    tearDown: function (callback) {
        callback();
    },

    resolve: function (test) {
        this.resolver.resolve('www.something.com', function (err, response) {
            test.ifError(err);
            test.notStrictEqual(response, null, err);
            test.ok(response instanceof Array, "Invalid response returned.");
            test.ok(response.length > 0, "Invalid response returned.");
            response.forEach(function (ip) {
                test.ok(net.isIP(ip), "Invalid IP address.");
                test.ok(net.isIPv4(ip), "Invalid IP address.");
            });

            var expected = (dnsentries[1][1]['www.something.com']['answer'])
            .filter( function (answer) {
                return answer['type'] === 1;
            })
            .map( function (answer) {
                return answer['address'];
            });

            test.strictEqual(
                expected.length,
                response.length,
                "Number of records expected and recived are not same."
            );

            response.forEach(function (answer, index) {
                test.strictEqual(
                    answer,
                    expected[index],
                    "Expected and recieved record is not same."
                );
            });

            test.done();
        });
    },

    resolve4: function (test) {
        this.resolver.resolve4('www.something.com', function (err, response) {
            test.ifError(err);
            test.notStrictEqual(response, null, err);
            test.ok(response instanceof Array, "Invalid response returned.");
            test.ok(response.length > 0, "Invalid response returned.");
            response.forEach(function (ip) {
                test.ok(net.isIP(ip), "Invalid IP address.");
                test.ok(net.isIPv4(ip), "Invalid IP address.");
            });

            var expected = (dnsentries[1][1]['www.something.com']['answer'])
            .filter( function (answer) {
                return answer['type'] === 1;
            })
            .map( function (answer) {
                return answer['address'];
            });

            test.strictEqual(
                expected.length,
                response.length,
                "Number of records expected and recived are not same."
            );

            response.forEach(function (answer, index) {
                test.strictEqual(
                    answer,
                    expected[index],
                    "Expected and recieved record is not same."
                );
            });

            test.done();
        });
    },

    resolve6: function (test) {
        this.resolver.resolve6('www.something.com', function (err, response) {
            test.ifError(err);
            test.notStrictEqual(response, null, err);
            test.ok(response instanceof Array, "Invalid response returned.");
            test.ok(response.length > 0, "Invalid response returned.");
            response.forEach(function (ip) {
                test.ok(net.isIP(ip), "Invalid IP address.");
                test.ok(net.isIPv6(ip), "Invalid IP address.");
            });
            test.done();
        });
    },

};
<commit_msg>Added more assertions for resolver.resolve6 test method to check actual records with expected.<commit_after>// Copyright 2016 Lohith Royal Pinto <royalpinto@gmail.com>
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE

var cares = require('../lib/cares.js');
var net = require('net');

var SERVERS = ['127.0.0.1'];
var PORT = 49160;
var dnsentries = require('./setup/dnsentries.js');

module.exports = {

    setUp: function (callback) {
        this.resolver = new cares.Resolver({
            servers: SERVERS,
            udp_port: PORT,
        });
        callback();
    },
    tearDown: function (callback) {
        callback();
    },

    resolve: function (test) {
        this.resolver.resolve('www.something.com', function (err, response) {
            test.ifError(err);
            test.notStrictEqual(response, null, err);
            test.ok(response instanceof Array, "Invalid response returned.");
            test.ok(response.length > 0, "Invalid response returned.");
            response.forEach(function (ip) {
                test.ok(net.isIP(ip), "Invalid IP address.");
                test.ok(net.isIPv4(ip), "Invalid IP address.");
            });

            var expected = (dnsentries[1][1]['www.something.com']['answer'])
            .filter( function (answer) {
                return answer['type'] === 1;
            })
            .map( function (answer) {
                return answer['address'];
            });

            test.strictEqual(
                expected.length,
                response.length,
                "Number of records expected and recived are not same."
            );

            response.forEach(function (answer, index) {
                test.strictEqual(
                    answer,
                    expected[index],
                    "Expected and recieved record is not same."
                );
            });

            test.done();
        });
    },

    resolve4: function (test) {
        this.resolver.resolve4('www.something.com', function (err, response) {
            test.ifError(err);
            test.notStrictEqual(response, null, err);
            test.ok(response instanceof Array, "Invalid response returned.");
            test.ok(response.length > 0, "Invalid response returned.");
            response.forEach(function (ip) {
                test.ok(net.isIP(ip), "Invalid IP address.");
                test.ok(net.isIPv4(ip), "Invalid IP address.");
            });

            var expected = (dnsentries[1][1]['www.something.com']['answer'])
            .filter( function (answer) {
                return answer['type'] === 1;
            })
            .map( function (answer) {
                return answer['address'];
            });

            test.strictEqual(
                expected.length,
                response.length,
                "Number of records expected and recived are not same."
            );

            response.forEach(function (answer, index) {
                test.strictEqual(
                    answer,
                    expected[index],
                    "Expected and recieved record is not same."
                );
            });

            test.done();
        });
    },

    resolve6: function (test) {
        this.resolver.resolve6('www.something.com', function (err, response) {
            test.ifError(err);
            test.notStrictEqual(response, null, err);
            test.ok(response instanceof Array, "Invalid response returned.");
            test.ok(response.length > 0, "Invalid response returned.");
            response.forEach(function (ip) {
                test.ok(net.isIP(ip), "Invalid IP address.");
                test.ok(net.isIPv6(ip), "Invalid IP address.");
            });

            var expected = (dnsentries[1][28]['www.something.com']['answer'])
            .filter( function (answer) {
                return answer['type'] === 28;
            })
            .map( function (answer) {
                return answer['address'];
            });

            test.strictEqual(
                expected.length,
                response.length,
                "Number of records expected and recived are not same."
            );

            response.forEach(function (answer, index) {
                test.strictEqual(
                    answer,
                    expected[index],
                    "Expected and recieved record is not same."
                );
            });

            test.done();
        });
    },

};
<|endoftext|>


<commit_before>var test = require('tape')

var response = require('../lib/responses')

test('verify json response', verify_json_response)

function verify_json_response(assert) {
  var res = {}

  res.writeHead = function(status, headers) {
    assert.strictEqual(status, 200)
    assert.deepEqual(headers, {'Content-Type': 'application/json'})
  }

  res.write = function(data) {
    assert.strictEqual(data, '{"arbitrary": "data"}')
  }

  res.end = function() {
    assert.end()
  }

  response.json(null, res, 200, '{"arbitrary": "data"}')
}

test('verify unauthorized', verify_error_response)

function verify_error_response(assert) {
  var res = {}

  res.writeHead = function(status, headers) {
    assert.strictEqual(status, 401)
    assert.deepEqual(headers, {'Content-Type': 'application/json'})
  }

  res.write = function(data) {
    assert.strictEqual(data, JSON.stringify({
        error: 'unauthorized'
      , reason: 'Name or password is incorrect.'
    }))
  }

  res.end = function() {
    assert.end()
  }

  response.unauthorized(null, res)
}

test('verify not found', function(assert) {
  var res = {}

  res.writeHead = function(status, headers) {
    assert.strictEqual(status, 404)
    assert.deepEqual(headers, {'Content-Type': 'application/json'})
  }

  res.write = function(data) {
    assert.strictEqual(data, JSON.stringify({
        error: 'not_found'
      , reason: 'Document not found.'
    }))
  }

  res.end = function() {
    assert.end()
  }

  response.not_found(null, res)
})

test('verify conflict', verify_conflict)

function verify_conflict(assert) {
  var res = {}

  res.writeHead = function(status, headers) {
    assert.strictEqual(status, 409)
    assert.deepEqual(headers, {'Content-Type': 'application/json'})
  }

  res.write = function(data) {
    assert.strictEqual(data, JSON.stringify({
        error: 'conflict'
      , reason: 'Document update conflict.'
    }))
  }

  res.end = function() {
    assert.end()
  }

  response.conflict(null, res)
})

test('verify 500', verify_500)

function verify_500(assert) {
  var res = {}

  res.writeHead = function(status) {
    assert.equal(status, 500)
  }

  res.write = function(data) {
    assert.strictEqual('Something went wrong.', data)
  }

  res.end = function() {
    assert.end()
  }

  response.on_error(null, res)
})
<commit_msg>fixing typos<commit_after>var test = require('tape')

var response = require('../lib/responses')

test('verify json response', verify_json_response)

function verify_json_response(assert) {
  var res = {}

  res.writeHead = function(status, headers) {
    assert.strictEqual(status, 200)
    assert.deepEqual(headers, {'Content-Type': 'application/json'})
  }

  res.write = function(data) {
    assert.strictEqual(data, '{"arbitrary": "data"}')
  }

  res.end = function() {
    assert.end()
  }

  response.json(null, res, 200, '{"arbitrary": "data"}')
}

test('verify unauthorized', verify_error_response)

function verify_error_response(assert) {
  var res = {}

  res.writeHead = function(status, headers) {
    assert.strictEqual(status, 401)
    assert.deepEqual(headers, {'Content-Type': 'application/json'})
  }

  res.write = function(data) {
    assert.strictEqual(data, JSON.stringify({
        error: 'unauthorized'
      , reason: 'Name or password is incorrect.'
    }))
  }

  res.end = function() {
    assert.end()
  }

  response.unauthorized(null, res)
}

test('verify not found', verify_not_found)

function verify_not_found(assert) {
  var res = {}

  res.writeHead = function(status, headers) {
    assert.strictEqual(status, 404)
    assert.deepEqual(headers, {'Content-Type': 'application/json'})
  }

  res.write = function(data) {
    assert.strictEqual(data, JSON.stringify({
        error: 'not_found'
      , reason: 'Document not found.'
    }))
  }

  res.end = function() {
    assert.end()
  }

  response.not_found(null, res)
}

test('verify conflict', verify_conflict)

function verify_conflict(assert) {
  var res = {}

  res.writeHead = function(status, headers) {
    assert.strictEqual(status, 409)
    assert.deepEqual(headers, {'Content-Type': 'application/json'})
  }

  res.write = function(data) {
    assert.strictEqual(data, JSON.stringify({
        error: 'conflict'
      , reason: 'Document update conflict.'
    }))
  }

  res.end = function() {
    assert.end()
  }

  response.conflict(null, res)
}

test('verify 500', verify_500)

function verify_500(assert) {
  var res = {}

  res.writeHead = function(status) {
    assert.equal(status, 500)
  }

  res.write = function(data) {
    assert.strictEqual('Something went wrong.', data)
  }

  res.end = function() {
    assert.end()
  }

  response.on_error(null, res)
}
<|endoftext|>


<commit_before>// verify that just loading tap doesn't cause it to
// print out some TAP stuff, unless an actual thing happens.
var t = require('tap')
var spawn = require('child_process').spawn

switch (process.argv[2]) {
  case 'child-plan':
    childPlan()
    break

  case 'child-pragma':
    childPragma()
    break

  case 'child-pipe':
    childPipe()
    break

  case 'child-bail':
    childBail()
    break

  case 'child-assert':
    childAssert()
    break

  case 'child-nothing':
    childNothing()
    break

  case undefined:
    parent()
    break

  default:
    throw new Error('oops')
}

function parent () {
  t.test('non-zero plan has output', runTest('child-plan', true))
  t.test('bailout has output', runTest('child-bail', true))
  t.test('explicit pipe has output', runTest('child-pipe', true))
  t.test('pragma has output', runTest('child-pragma', true))
  t.test('assert has output', runTest('child-assert', true))
  t.test('loading tap has no output', runTest('child-nothing', false))
}

function childPragma () {
  t.pragma({ fine: true, ok: false })
}

function childPipe () {
  t.pipe(process.stdout)
}

function childAssert () {
  t.pass('this is fine')
}

function childBail () {
  t.bailout('bo')
}

function childPlan () {
  t.plan(2)
}

function childNothing () {
  // nothing to see here
}

function runTest (arg, expectOutput) { return function (t) {
  var node = process.execPath
  var args = [__filename, arg]
  var child = spawn(node, args)
  var output = ''

  child.stdout.on('data', function (c) {
    output += c
  })

  child.on('close', function () {
    if (expectOutput) {
      t.notEqual(output.trim(), '')
    } else {
      t.equal(output, '')
    }
    t.end()
  })
}}
<commit_msg>test: don't require('tap'), require('../')<commit_after>// verify that just loading tap doesn't cause it to
// print out some TAP stuff, unless an actual thing happens.
var t = require('../')
var spawn = require('child_process').spawn

switch (process.argv[2]) {
  case 'child-plan':
    childPlan()
    break

  case 'child-pragma':
    childPragma()
    break

  case 'child-pipe':
    childPipe()
    break

  case 'child-bail':
    childBail()
    break

  case 'child-assert':
    childAssert()
    break

  case 'child-nothing':
    childNothing()
    break

  case undefined:
    parent()
    break

  default:
    throw new Error('oops')
}

function parent () {
  t.test('non-zero plan has output', runTest('child-plan', true))
  t.test('bailout has output', runTest('child-bail', true))
  t.test('explicit pipe has output', runTest('child-pipe', true))
  t.test('pragma has output', runTest('child-pragma', true))
  t.test('assert has output', runTest('child-assert', true))
  t.test('loading tap has no output', runTest('child-nothing', false))
}

function childPragma () {
  t.pragma({ fine: true, ok: false })
}

function childPipe () {
  t.pipe(process.stdout)
}

function childAssert () {
  t.pass('this is fine')
}

function childBail () {
  t.bailout('bo')
}

function childPlan () {
  t.plan(2)
}

function childNothing () {
  // nothing to see here
}

function runTest (arg, expectOutput) { return function (t) {
  var node = process.execPath
  var args = [__filename, arg]
  var child = spawn(node, args)
  var output = ''

  child.stdout.on('data', function (c) {
    output += c
  })

  child.on('close', function () {
    if (expectOutput) {
      t.notEqual(output.trim(), '')
    } else {
      t.equal(output, '')
    }
    t.end()
  })
}}
<|endoftext|>