<commit_before>'use strict'

const { before } = require('sdk/test/utils')
const { prefs } = require('sdk/simple-prefs')

const backup = new Map()

for (let key in prefs) {
  backup.set(key, prefs[key])
}

function restorePrefs () {
  // console.log('Restoring simple-prefs')
  for (let [key, data] of backup) {
    prefs[key] = data
  }
}

exports.restorePrefs = restorePrefs

exports.isolateTestCases = (testCases) => {
  before(testCases, (name, assert) => {
    restorePrefs()
  })
}
<commit_msg>Use fake ports so that local gw is not used by tests<commit_after>'use strict'

const { before } = require('sdk/test/utils')
const { prefs } = require('sdk/simple-prefs')

const backup = new Map()

for (let key in prefs) {
  backup.set(key, prefs[key])
}

// set fake ports so that local gw
// does not slow down test suite
backup.set('customApiPort', 55001)
backup.set('customGatewayPort', 58080)

function restorePrefs () {
  // console.log('Restoring simple-prefs')
  for (let [key, data] of backup) {
    prefs[key] = data
  }
}

exports.restorePrefs = restorePrefs

exports.isolateTestCases = (testCases) => {
  before(testCases, (name, assert) => {
    restorePrefs()
  })
}
<|endoftext|>


<commit_before>// Primitive operations on inline content

import * as style from "./style"
import Node from "./node"
import Pos from "./pos"
import {stitchTextNodes} from "./join"
import Transform from "./transform"

function addInline(node, child) {
  node.push(child)
  stitchTextNodes(node, node.content.length - 1)
}

function copyStructure(node, from, to, f, depth = 0) {
  if (node.type.contains == "inline") {
    return f(node, from, to)
  } else {
    let copy = node.copy()
    let start = from ? from.path[depth] : 0
    let end = to ? to.path[depth] : node.content.length - 1
    copy.pushFrom(node, 0, start)
    if (start == end) {
      copy.push(copyStructure(node.content[start], from, to, f, depth + 1))
    } else {
      copy.push(copyStructure(node.content[start], from, null, f, depth + 1))
      for (let i = start + 1; i < end; i++)
        copy.push(copyStructure(node.content[i], null, null, f, depth + 1))
      copy.push(copyStructure(node.content[end], null, to, f, depth + 1))
    }
    copy.pushFrom(node, end + 1)
    return copy
  }
}

function copyInline(node, from, to, f) {
  let copy = node.copy()
  let start = from ? from.offset : 0
  let end = to ? to.offset : node.size
  for (let ch = 0, i = 0; i < node.content.length; i++) {
    let child = node.content[i], size = child.size
    if (ch < start) {
      if (ch + size <= start) {
        copy.push(child)
      } else {
        copy.push(child.slice(0, start - ch))
        if (ch + size <= end) {
          addInline(copy, f(child.slice(start - ch)))
        } else {
          addInline(copy, f(child.slice(start - ch, end - ch)))
          addInline(copy, child.slice(end - ch))
        }
      }
    } else if (ch < end) {
      if (ch + size <= end) {
        addInline(copy, f(child))
      } else {
        addInline(copy, f(child.slice(0, end - ch)))
        addInline(copy, child.slice(end - ch))
      }
    } else {
      addInline(copy, child)
    }
    ch += size
  }
  return copy
}

export function addStyle(doc, from, to, add) {
  return copyStructure(doc, from, to, (node, from, to) => {
    return copyInline(node, from, to, node => {
      return new Node.Inline(node.type, style.add(node.styles, add),
                             node.text, node.attrs)
    })
  })
}

export function removeStyle(doc, from, to, rm) {
  return copyStructure(doc, from, to, (node, from, to) => {
    return copyInline(node, from, to, node => {
      return new Node.Inline(node.type, style.remove(node.styles, rm),
                             node.text, node.attrs)
    })
  })
}

function inlineNodeAtOrBefore(parent, offset) {
  for (let i = 0;; i++) {
    let child = parent.content[i]
    offset -= child.size
    if (offset <= 0)
      return {node: child, offset: i, innerOffset: offset + child.size}
  }
}

export function hasStyle(doc, pos, st) {
  let {node} = inlineNodeAtOrBefore(doc.path(pos.path), pos.offset)
  return style.contains(node.styles, st)
}

export function insertText(doc, pos, text) {
  if (!text) return Transform.identity(doc)

  let parentSize
  let copy = copyStructure(doc, pos, pos, node => {
    let copy = node.copy(node.content.slice())
    let {node, offset, innerOffset} = inlineNodeAtOrBefore(copy, pos.offset)
    if (node.type == Node.types.text) {
      let newText = node.text.slice(0, innerOffset) + text + node.text.slice(innerOffset)
      copy.content[offset] = new Node.Inline(node.type, node.styles, newText, node.attrs)
    } else {
      let newNode = new Node.Inline(Node.types.text, node.styles, text)
      if (innerOffset == 0) {
        copy.content.unshift(newNode)
      } else {
        copy.content.splice(offset + 1, 0, newNode)
        stitchTextNodes(copy, offset + 2)
      }
    }
    parentSize = copy.size
    return copy
  })
  let transform = new Transform(doc, copy, pos)
  let end = new Pos(pos.path, parentSize)
  transform.chunk(end, pos => new Pos(pos.path, pos.offset + text.length))
  transform.chunk(null, pos => pos)
  return transform
}
<commit_msg>Move insertText to slice.around<commit_after>// Primitive operations on inline content

import * as style from "./style"
import Node from "./node"
import Pos from "./pos"
import {stitchTextNodes} from "./join"
import Transform from "./transform"
import * as slice from "./slice"

function addInline(node, child) {
  node.push(child)
  stitchTextNodes(node, node.content.length - 1)
}

function copyStructure(node, from, to, f, depth = 0) {
  if (node.type.contains == "inline") {
    return f(node, from, to)
  } else {
    let copy = node.copy()
    let start = from ? from.path[depth] : 0
    let end = to ? to.path[depth] : node.content.length - 1
    copy.pushFrom(node, 0, start)
    if (start == end) {
      copy.push(copyStructure(node.content[start], from, to, f, depth + 1))
    } else {
      copy.push(copyStructure(node.content[start], from, null, f, depth + 1))
      for (let i = start + 1; i < end; i++)
        copy.push(copyStructure(node.content[i], null, null, f, depth + 1))
      copy.push(copyStructure(node.content[end], null, to, f, depth + 1))
    }
    copy.pushFrom(node, end + 1)
    return copy
  }
}

function copyInline(node, from, to, f) {
  let copy = node.copy()
  let start = from ? from.offset : 0
  let end = to ? to.offset : node.size
  for (let ch = 0, i = 0; i < node.content.length; i++) {
    let child = node.content[i], size = child.size
    if (ch < start) {
      if (ch + size <= start) {
        copy.push(child)
      } else {
        copy.push(child.slice(0, start - ch))
        if (ch + size <= end) {
          addInline(copy, f(child.slice(start - ch)))
        } else {
          addInline(copy, f(child.slice(start - ch, end - ch)))
          addInline(copy, child.slice(end - ch))
        }
      }
    } else if (ch < end) {
      if (ch + size <= end) {
        addInline(copy, f(child))
      } else {
        addInline(copy, f(child.slice(0, end - ch)))
        addInline(copy, child.slice(end - ch))
      }
    } else {
      addInline(copy, child)
    }
    ch += size
  }
  return copy
}

export function addStyle(doc, from, to, add) {
  return copyStructure(doc, from, to, (node, from, to) => {
    return copyInline(node, from, to, node => {
      return new Node.Inline(node.type, style.add(node.styles, add),
                             node.text, node.attrs)
    })
  })
}

export function removeStyle(doc, from, to, rm) {
  return copyStructure(doc, from, to, (node, from, to) => {
    return copyInline(node, from, to, node => {
      return new Node.Inline(node.type, style.remove(node.styles, rm),
                             node.text, node.attrs)
    })
  })
}

function inlineNodeAtOrBefore(parent, offset) {
  for (let i = 0;; i++) {
    let child = parent.content[i]
    offset -= child.size
    if (offset <= 0)
      return {node: child, offset: i, innerOffset: offset + child.size}
  }
}

export function hasStyle(doc, pos, st) {
  let {node} = inlineNodeAtOrBefore(doc.path(pos.path), pos.offset)
  return style.contains(node.styles, st)
}

export function insertText(doc, pos, text) {
  if (!text) return Transform.identity(doc)

  let copy = slice.around(doc, pos)
  let parent = copy.path(pos.path)
  let {node, offset, innerOffset} = inlineNodeAtOrBefore(parent, pos.offset)
  if (node.type == Node.types.text) {
    let newText = node.text.slice(0, innerOffset) + text + node.text.slice(innerOffset)
    parent.content[offset] = new Node.Inline(node.type, node.styles, newText, node.attrs)
  } else {
    let newNode = new Node.Inline(Node.types.text, node.styles, text)
    if (innerOffset == 0) {
      parent.content.unshift(newNode)
    } else {
      parent.content.splice(offset + 1, 0, newNode)
      stitchTextNodes(parent, offset + 2)
    }
  }
  let parentSize = copy.size

  let transform = new Transform(doc, copy, pos)
  let end = new Pos(pos.path, parentSize)
  transform.chunk(end, pos => new Pos(pos.path, pos.offset + text.length))
  transform.chunk(null, pos => pos)
  return transform
}
<|endoftext|>


<commit_before><commit_msg>Zone test has been added and tested.<commit_after><|endoftext|>


<commit_before>describe("TweenJS", function () {
	beforeEach(function () {
		jasmine.DEFAULT_TIMEOUT_INTERVAL = 2000;
	});

	afterEach(function () {
		createjs.Tween.removeAllTweens();
	});

	it("should animate x to 50", function (done) {
		var obj = {x: 0};
		createjs.Tween.get(obj)
				.to({x: 50}, 25)
				.call(function () {
						  expect(obj.x).toBe(50);
						  done();
					  });
	});

	it("should animate in a specifc amount of time.", function (done) {
		var obj = {x: 0};
		var startTime = Date.now();
		createjs.Tween.get(obj)
				.to({x: 50}, 25)
				.call(function () {
						  expect(Date.now() - startTime).toBeInRange(48, 52);
						  done();
					  });
	});

	it("hasActiveTweens should return a boolean", function () {
		var obj = {x: 0};
		expect(createjs.Tween.hasActiveTweens(obj)).toBe(false);
		createjs.Tween.get(obj).to({x: 50}, 500);
		expect(createjs.Tween.hasActiveTweens(obj)).toBe(true);
	});

	it("tweens should fire change events", function (done) {
		var obj = {x: 0};
		var tween = createjs.Tween.get(obj);

		tween.on("change", function () {
			expect(true).toBe(true);
			done();
		});
		tween.to({x: 50});
	});

	it("setPaused() should work", function (done) {
		var obj = {x: 0};
		var tween = createjs.Tween.get(obj);
		var changeCount = 0;

		tween.on("change", function () {
			changeCount++;
		});
		tween.to({x: 200}, 2000);
		tween.setPaused(true);

		setTimeout(function () {
			tween.setPaused(false);
			tween.on("change", function () {
				expect(++changeCount).toBe(2);
				done();
			});
		}, 250);
	});

	it("setPosition() should work", function () {
		var obj = {x: 0};
		var tween = createjs.Tween.get(obj);

		tween.to({x: 200}, 2000);
		tween.setPaused(true);
		tween.setPosition(25);
		expect(obj.x).toBe(2.5);
	});

	it("wait() should work", function (done) {
		var startTime = Date.now();
		createjs.Tween.get({}).wait(500).call(function () {
			expect(Date.now() - startTime).toBeInRange(450, 510);
			done();
		});
	});

	it("removeAllTweens() should work", function () {
		var obj = {};

		createjs.Tween.get(obj).to({x: 50}, 100);

		expect(createjs.Tween.hasActiveTweens(obj)).toBe(true);
		createjs.Tween.removeAllTweens();
		expect(createjs.Tween.hasActiveTweens(obj)).toBe(false);
	});

	it("removeTweens() should work", function () {
		var obj = {};

		createjs.Tween.get(obj).to({x: 50}, 100);

		expect(createjs.Tween.hasActiveTweens(obj)).toBe(true);
		createjs.Tween.removeTweens(obj);
		expect(createjs.Tween.hasActiveTweens(obj)).toBe(false);
	});

	it("tweens should loop", function (done) {
		var obj = {};

		var count = 0;
		createjs.Tween.get(obj, {loop: true}).to({x: 50}, 100).call(function () {
			if (++count == 2) {
				expect(true).toBe(true);
				done();
			}
		});
	});
});
<commit_msg>Tweaked some tests to use spyOn()<commit_after>describe("TweenJS", function () {
	beforeEach(function () {
		jasmine.DEFAULT_TIMEOUT_INTERVAL = 2000;
	});

	afterEach(function () {
		createjs.Tween.removeAllTweens();
	});

	it("should animate x to 50", function (done) {
		var obj = {x: 0};
		createjs.Tween.get(obj)
				.to({x: 50}, 25)
				.call(function () {
						  expect(obj.x).toBe(50);
						  done();
					  });
	});

	it("should animate in a specifc amount of time.", function (done) {
		var obj = {x: 0};
		var startTime = Date.now();
		createjs.Tween.get(obj)
				.to({x: 50}, 25)
				.call(function () {
						  expect(Date.now() - startTime).toBeInRange(48, 52);
						  done();
					  });
	});

	it("hasActiveTweens should return a boolean", function () {
		var obj = {x: 0};
		expect(createjs.Tween.hasActiveTweens(obj)).toBe(false);
		createjs.Tween.get(obj).to({x: 50}, 500);
		expect(createjs.Tween.hasActiveTweens(obj)).toBe(true);
	});

	it("tweens should fire change events", function (done) {
		var obj = {x: 0};
		var tween = createjs.Tween.get(obj);

		var func =  {
			change: function() { }
		};

		spyOn(func, "change");

		tween.on("change", func.change);
		tween.to({x: 50});
		setTimeout(function() {
			expect(func.change).toHaveBeenCalled();
			done();
		}, 50);
	});

	it("setPaused() should work", function (done) {
		var obj = {x: 0};
		var tween = createjs.Tween.get(obj);

		var func = {
			change: function () {
			}
		};

		spyOn(func, "change");

		tween.on("change", func.change);
		tween.to({x: 200}, 2000);
		tween.setPaused(true);

		setTimeout(function () {
			tween.setPaused(false);
			tween.on("change", function () {
				expect(func.change.calls.count()).toBe(1);
				done();
			});
		}, 250);
	});

	it("setPosition() should work", function () {
		var obj = {x: 0};
		var tween = createjs.Tween.get(obj);

		tween.to({x: 200}, 2000);
		tween.setPaused(true);
		tween.setPosition(25);
		expect(obj.x).toBe(2.5);
	});

	it("wait() should work", function (done) {
		var startTime = Date.now();
		createjs.Tween.get({}).wait(500).call(function () {
			expect(Date.now() - startTime).toBeInRange(450, 510);
			done();
		});
	});

	it("removeAllTweens() should work", function () {
		var obj = {};

		createjs.Tween.get(obj).to({x: 50}, 100);

		expect(createjs.Tween.hasActiveTweens(obj)).toBe(true);
		createjs.Tween.removeAllTweens();
		expect(createjs.Tween.hasActiveTweens(obj)).toBe(false);
	});

	it("removeTweens() should work", function () {
		var obj = {};

		createjs.Tween.get(obj).to({x: 50}, 100);

		expect(createjs.Tween.hasActiveTweens(obj)).toBe(true);
		createjs.Tween.removeTweens(obj);
		expect(createjs.Tween.hasActiveTweens(obj)).toBe(false);
	});

	it("tweens should loop", function (done) {
		var obj = {};

		var func = {
			complete: function () {
			}
		};

		spyOn(func, "complete");

		createjs.Tween.get(obj, {loop: true}).to({x: 50}, 100).call(func.complete);

		setTimeout(function () {
			expect(func.complete.calls.count()).toBeGreaterThan(1);
			done();
		}, 500);
	});
});
<|endoftext|>


<commit_before>// qb_kafa_tests.js
// If we are getting a test.done complaint, turn this on. It helps find errors
process.on('uncaughtException', function(err) {
  console.error(err.stack);
});
process.setMaxListeners(0);
require('longjohn')

var _ = require('lodash')
  , kafka = require('kafka-node')
  , async = require('async')

var qbPkg = require('qb')
  , QB = qbPkg.backend(require('../lib/backend'))

var qb1, qb2, qb3;

//var connectionString = "localhost:2181"
var connectionString = "dev.raafl.com:2181"

var tests = exports.tests = {};

tests.setUp = function (cb) {
  qb1 = QB(
    { instance_id: 0
    , num_instances: 1
    , num_partitions: 1
    , commitInterval: 1
    , connection_string: connectionString
    , task_options: { foobar: { topic: "foobar"
                              , consumer_group: "foobarers"
                              //, key: "foo"
                              }
                    , foobar2:  { topic: "foobar"
                                , consumer_group: "foobar2ers"
                                , key: "foo"
                                }
                    }
    , prefix: 'qbBasic'
    })

  qb2 = QB(
    { instance_id: 0
    , num_instances: 2
    , num_partitions: 32
    , commitInterval: 1
    , connection_string: connectionString
    , task_options: { foobar: { topic: "foobar32"
                              , consumer_group: "foobarers"
                              //, key: "foo"
                              }
                    }
    , prefix: 'qbMulti1'
    })

  qb3 = QB(
    { instance_id: 1
    , num_instances: 2
    , num_partitions: 32
    , commitInterval: 1
    , connection_string: connectionString
    , task_options: { foobar: { topic: "foobar32"
                              , consumer_group: "foobarers"
                              //, key: "foo"
                              }
                    }
    , prefix: 'qbMulti2'
    })

  cb()
}

tests.tearDown = function (cb) {
  var enders = ([qb1,qb2,qb3]).map(function (qb) { return qb.end.bind(qb) })

  async.parallel(enders, cb)
}

// starting with a "clean" topic (no offset lag) push and process 2 messages
tests.basic = function basic (test) {
  test.expect(10)
  var calledFoobar = 0;
  var calledFoobar2 = 0;
  qb1.on('error', test.ifError)
     .can('foobar', function (task, done) {
       test.equal(task.foo, 'bar');
       calledFoobar++
       done();
     })
     .can('foobar2', function (task, done) {
       test.equal(task.foo, 'bar');
       calledFoobar2++
       done();
     })
     .post('process')
       .use(function (type, task, next) {
         test.equal(task.foo, 'bar');
         next();
       })
     .on('finish', function (type, task, next) {
       if (calledFoobar === 2 && calledFoobar2 === 2) {
        setImmediate(test.done);
       }
     })
     .on('ready', function () {
       qb1.push('foobar', {foo: 'bar'}, test.ifError);
       qb1.push('foobar2', {foo: 'bar'}, test.ifError)
     })
     .start()
}

// In order for this test to pass, a topic called foobar32
// needs to be set up with 32 partitions
tests.multiPartition = function multiPartition(test) {
  var numProcessed = 0
    , numToSend = 64

  function _process(task, done) {
    numProcessed++
    done()
  }

  function _checkFinish() {
    if (numProcessed === numToSend) {
      return setImmediate(test.done)
    } else {
      return
    }
  }

  qb2
    .on('error', test.ifError)
    .can('foobar', _process)
    .on('finish', _checkFinish)
    .on('ready', test.ifError)
    .start()

  qb3
    .on('error', test.ifError)
    .can('foobar', _process)
    .on('ready', function () {
      for (var k = 0; k < numToSend; k++) {
        qb2.push('foobar', {foo: 'bar'}, test.ifError)
      }
    })
    .on('finish', _checkFinish)
    .start()
}
<commit_msg>set connectionString back to localhost<commit_after>// qb_kafa_tests.js
// If we are getting a test.done complaint, turn this on. It helps find errors
process.on('uncaughtException', function(err) {
  console.error(err.stack);
});
process.setMaxListeners(0);
require('longjohn')

var _ = require('lodash')
  , kafka = require('kafka-node')
  , async = require('async')

var qbPkg = require('qb')
  , QB = qbPkg.backend(require('../lib/backend'))

var qb1, qb2, qb3;

var connectionString = "localhost:2181"
//var connectionString = "dev.raafl.com:2181"

var tests = exports.tests = {};

tests.setUp = function (cb) {
  qb1 = QB(
    { instance_id: 0
    , num_instances: 1
    , num_partitions: 1
    , commitInterval: 1
    , connection_string: connectionString
    , task_options: { foobar: { topic: "foobar"
                              , consumer_group: "foobarers"
                              //, key: "foo"
                              }
                    , foobar2:  { topic: "foobar"
                                , consumer_group: "foobar2ers"
                                , key: "foo"
                                }
                    }
    , prefix: 'qbBasic'
    })

  qb2 = QB(
    { instance_id: 0
    , num_instances: 2
    , num_partitions: 32
    , commitInterval: 1
    , connection_string: connectionString
    , task_options: { foobar: { topic: "foobar32"
                              , consumer_group: "foobarers"
                              //, key: "foo"
                              }
                    }
    , prefix: 'qbMulti1'
    })

  qb3 = QB(
    { instance_id: 1
    , num_instances: 2
    , num_partitions: 32
    , commitInterval: 1
    , connection_string: connectionString
    , task_options: { foobar: { topic: "foobar32"
                              , consumer_group: "foobarers"
                              //, key: "foo"
                              }
                    }
    , prefix: 'qbMulti2'
    })

  cb()
}

tests.tearDown = function (cb) {
  var enders = ([qb1,qb2,qb3]).map(function (qb) { return qb.end.bind(qb) })

  async.parallel(enders, cb)
}

// starting with a "clean" topic (no offset lag) push and process 2 messages
tests.basic = function basic (test) {
  test.expect(10)
  var calledFoobar = 0;
  var calledFoobar2 = 0;
  qb1.on('error', test.ifError)
     .can('foobar', function (task, done) {
       test.equal(task.foo, 'bar');
       calledFoobar++
       done();
     })
     .can('foobar2', function (task, done) {
       test.equal(task.foo, 'bar');
       calledFoobar2++
       done();
     })
     .post('process')
       .use(function (type, task, next) {
         test.equal(task.foo, 'bar');
         next();
       })
     .on('finish', function (type, task, next) {
       if (calledFoobar === 2 && calledFoobar2 === 2) {
        setImmediate(test.done);
       }
     })
     .on('ready', function () {
       qb1.push('foobar', {foo: 'bar'}, test.ifError);
       qb1.push('foobar2', {foo: 'bar'}, test.ifError)
     })
     .start()
}

// In order for this test to pass, a topic called foobar32
// needs to be set up with 32 partitions
tests.multiPartition = function multiPartition(test) {
  var numProcessed = 0
    , numToSend = 64

  function _process(task, done) {
    numProcessed++
    done()
  }

  function _checkFinish() {
    if (numProcessed === numToSend) {
      return setImmediate(test.done)
    } else {
      return
    }
  }

  qb2
    .on('error', test.ifError)
    .can('foobar', _process)
    .on('finish', _checkFinish)
    .on('ready', test.ifError)
    .start()

  qb3
    .on('error', test.ifError)
    .can('foobar', _process)
    .on('ready', function () {
      for (var k = 0; k < numToSend; k++) {
        qb2.push('foobar', {foo: 'bar'}, test.ifError)
      }
    })
    .on('finish', _checkFinish)
    .start()
}
<|endoftext|>


<commit_before><commit_msg>test(card): Fix orphaned focus affecting other tests (#2248)<commit_after><|endoftext|>


<commit_before>var fs = require('fs')
var http = require("http")
var https = require("https")
var spawn = require('child_process').spawn
var path = require('path')
var crypto = require('crypto')

var log = function(message){
    console.log('---------', new Date(), '---------')
    console.log(message)
    console.log()
    //TODO write to a log file
}

/*
 * settings.json looks something like this:
{
    "verboseResponses" : "true",
    "secretKey" : "sha1=somelonghashstringthatrepresentsyoursecretkey",
	"ssl" : "true",
	"sslOptions" : {},
    "repositories": [
        {
            "name": "aarongreenwald/grouper",
            "scriptDirectory": "sci/scripts/",
            "script": "grouper.sh"
        },
        {
            "name": "aarongreenwald/sci",
            "scriptDirectory": "sci/scripts/",
            "script": "sci.sh"
        }
    ],
    "port" : 31242
}
*
* port will default to 31242 if ommitted
* verboseSettings will default to false if ommitted
 */

log('sci server starting...')

try {
    var settings = JSON.parse(fs.readFileSync(path.join(__dirname, 'sci.config.json')))
}
catch (ex){
    log('Cannot parse settings file: ' + ex)
    throw ex
}

var repositories = settings.repositories
var port = settings.port || 31242

var requestListener = function(request, response) {

    var handleError = function(ex, response){
        response.writeHead(500, {"Content-Type": "text/plain"})
        if (settings.verboseResponses){
            response.write(ex.message || ex ||  'An uknown error occurred')
        }
        else {
            response.write('That didn\'t work. Try again.')
        }
        log(ex.message || ex || 'An unknown error occurred.') //TODO I should log more than this
    }

    var body = ''
    request.on('data', function (data) {
        body += data
    })

    request.on('end', function () {
        try {
            if (request.headers['user-agent'].indexOf('GitHub-Hookshot/') === -1){
                throw 'This request does not appear to originate from github. If you\'re going to try to break the system, at least try harder.'
            }

	    const key = 'sha1=' + crypto.createHmac('sha1', settings.secretKey).update(body).digest('hex')
	    const suppliedKey = request.headers['x-hub-signature']

            if (suppliedKey !== key){
                throw 'You don\'t seem to be who you say you are. You need the key to enter!!'
            }

            if (request.method !== 'POST') {
                throw 'Only POST requests are processed by this server.'
            }

            if (request.headers['x-github-event'] !== 'push'){
                throw 'Only push events are processed by this server.'
            }

            try {
                var payload = JSON.parse(body)
            } catch (ex) {
                throw   {
                            message: 'Unable to parse payload: '
                                    + body
                                    + '\n\nError: ' + ex
                        }
            }

            var found = false
            for (var i = 0; i < repositories.length; i++){
                var repository = repositories[i]
                if (payload.repository.full_name === repository.name){
                    spawn('sh', [ repository.script ], {
                        cwd: repository.scriptDirectory
                    })
                    found = true
                    break
                }
            }
            if (found){
                response.writeHead(200, {"Content-Type": "text/plain"})
                var message = 'Successfully processed continuous integration script for repository: ' + repository.name
                response.write(message)
                log(message) //log more than this
            }
            else {
                throw 'Invalid repository name.'
            }
        } catch (ex) {
            handleError(ex, response)
        }
        finally {
            response.end()
        }
    })
}

log('Listening for POST requests on port ' + port + '...')

if (!settings.ssl){
	http.createServer(requestListener).listen(port)
} else {
	https.createServer(settings.sslOptions || { }, requestListener).listen(port)
}
<commit_msg>modernize code - use const/let<commit_after>const fs = require('fs');
const http = require("http");
const https = require("https");
const spawn = require('child_process').spawn;
const path = require('path');
const crypto = require('crypto');

const log = function(message){
    console.log('---------', new Date(), '---------')
    console.log(message)
    console.log()
    //TODO write to a log file
}

/*
 * settings.json looks something like this:
{
    "verboseResponses" : "true",
    "secretKey" : "sha1=somelonghashstringthatrepresentsyoursecretkey",
	"ssl" : "true",
	"sslOptions" : {},
    "repositories": [
        {
            "name": "aarongreenwald/grouper",
            "scriptDirectory": "sci/scripts/",
            "script": "grouper.sh"
        },
        {
            "name": "aarongreenwald/sci",
            "scriptDirectory": "sci/scripts/",
            "script": "sci.sh"
        }
    ],
    "port" : 31242
}
*
* port will default to 31242 if ommitted
* verboseSettings will default to false if ommitted
 */

log('sci server starting...')

try {
    var settings = JSON.parse(fs.readFileSync(path.join(__dirname, 'sci.config.json')))
}
catch (ex){
    log('Cannot parse settings file: ' + ex)
    throw ex
}

const repositories = settings.repositories
const port = settings.port || 31242

const requestListener = (request, response) => {

    const handleError = function (ex, response) {
        response.writeHead(500, {"Content-Type": "text/plain"})
        if (settings.verboseResponses) {
            response.write(ex.message || ex || 'An unknown error occurred')
        } else {
            response.write('That didn\'t work. Try again.')
        }
        log(ex.message || ex || 'An unknown error occurred.') //TODO I should log more than this
    };

    let body = '';
    request.on('data', data => {
        body += data
    })

    request.on('end', () => {
        try {
            if (request.headers['user-agent'].indexOf('GitHub-Hookshot/') === -1){
                throw 'This request does not appear to originate from github. If you\'re going to try to break the system, at least try harder.'
            }

	    const key = 'sha1=' + crypto.createHmac('sha1', settings.secretKey).update(body).digest('hex')
	    const suppliedKey = request.headers['x-hub-signature']

            if (suppliedKey !== key){
                throw 'You don\'t seem to be who you say you are. You need the key to enter!!'
            }

            if (request.method !== 'POST') {
                throw 'Only POST requests are processed by this server.'
            }

            if (request.headers['x-github-event'] !== 'push'){
                throw 'Only push events are processed by this server.'
            }

            try {
                var payload = JSON.parse(body)
            } catch (ex) {
                throw   {
                            message: 'Unable to parse payload: '
                                    + body
                                    + '\n\nError: ' + ex
                        }
            }

            let found = false;
            for (let i = 0; i < repositories.length; i++){
                const repository = repositories[i]
                if (payload.repository.full_name === repository.name){
                    spawn('sh', [ repository.script ], {
                        cwd: repository.scriptDirectory
                    })
                    found = true
                    break
                }
            }
            if (found){
                response.writeHead(200, {"Content-Type": "text/plain"})
                const message = 'Successfully processed continuous integration script for repository: ' + repository.name;
                response.write(message)
                log(message) //log more than this
            }
            else {
                throw 'Invalid repository name.'
            }
        } catch (ex) {
            handleError(ex, response)
        }
        finally {
            response.end()
        }
    })
}

log('Listening for POST requests on port ' + port + '...')

if (!settings.ssl){
	http.createServer(requestListener).listen(port)
} else {
	https.createServer(settings.sslOptions || { }, requestListener).listen(port)
}
<|endoftext|>


<commit_before>define([
  'superapi',
  'superagent'
], function (superapi, superagent) {
  'use strict';

  describe('configuration', function () {
    it('should return the service string configuration', function () {
      var api = superapi.default({
        baseUrl: 'http://foo.domain.tld/api',
        services: {
          foo: 'bar'
        }
      });

      api.service('foo').should.eql('bar');
    });

    it('should return the service object configuration', function () {
      var api = superapi.default({
        baseUrl: 'http://foo.domain.tld/api',
        services: {
          foo: {
            path: '/foo'
          }
        }
      });

      api.service('foo').should.eql({path: '/foo'});
    });
  });

  describe('request url', function () {
    it('should append the service url to the baseUrl', function () {
      var api = superapi.default({
        baseUrl: 'http://foo.domain.tld/api',
        services: {
          foo: {
            path: '/foo'
          }
        }
      });

      api.url('foo').should.eql('http://foo.domain.tld/api/foo');
    });

    it('should add a slash in front of route path if missing', function () {
      var api = superapi.default({
        baseUrl: 'http://foo.domain.tld/api',
        services: {
          foo: {
            path: 'foo'
          }
        }
      });

      api.url('foo').should.eql('http://foo.domain.tld/api/foo');
    });

    it('should support route as a string', function () {
      var api = superapi.default({
        baseUrl: 'http://foo.domain.tld/api',
        services: {
          foo: 'bar'
        }
      });

      api.url('foo').should.eql('http://foo.domain.tld/api/bar');
    });

    it('should throw error if path is missing', function () {
      var api = superapi.default({
        baseUrl: 'http://foo.domain.tld/api',
        services: {
          foo: {}
        }
      });

      // fail in PhantomJS as bind not available
      api.url.bind(null, 'foo').should.throw();
    });
  });

  describe('request method', function () {
    it('should default to get', function () {
      var api = superapi.default({
        baseUrl: 'http://foo.domain.tld/api',
        services: {
          foo: 'bar'
        }
      });
      api.agent = superagent;
      api.request('foo').method.should.eql('GET');
    });

    it('should support POST', function () {
      var api = superapi.default({
        baseUrl: 'http://foo.domain.tld/api',
        services: {
          foo: {
            path: 'bar',
            method: 'POST'
          }
        }
      });
      api.agent = superagent;
      api.request('foo').method.should.eql('POST');
    });

    it('should support PUT', function () {
      var api = superapi.default({
        baseUrl: 'http://foo.domain.tld/api',
        services: {
          foo: {
            path: 'bar',
            method: 'PUT'
          }
        }
      });
      api.agent = superagent;
      api.request('foo').method.should.eql('PUT');
    });

    it('should support DELETE', function () {
      var api = superapi.default({
        baseUrl: 'http://foo.domain.tld/api',
        services: {
          foo: {
            path: 'bar',
            method: 'DELETE'
          }
        }
      });
      api.agent = superagent;
      api.request('foo').method.should.eql('DELETE');
    });

    it('should support HEAD', function () {
      var api = superapi.default({
        baseUrl: 'http://foo.domain.tld/api',
        services: {
          foo: {
            path: 'bar',
            method: 'HEAD'
          }
        }
      });
      api.agent = superagent;
      api.request('foo').method.should.eql('HEAD');
    });

    it('should support PATCH', function () {
      var api = superapi.default({
        baseUrl: 'http://foo.domain.tld/api',
        services: {
          foo: {
            path: 'bar',
            method: 'PATCH'
          }
        }
      });
      api.agent = superagent;
      api.request('foo').method.should.eql('PATCH');
    });
  });

  describe.skip('request headers', function () {
  });

  describe('service request headers', function () {
    it('should add service headers', function () {
      var api = superapi.default({
        baseUrl: 'http://foo.domain.tld/api',
        services: {
          foo: {
            path: 'bar',
            headers: {
              'Content-type': 'json'
            }
          }
        }
      });
      api.agent = superagent;
      api.request('foo')._header.should.haveOwnProperty('content-type');
      api.request('foo')._header['content-type'].should.eql('json');
    });
  });

  describe('service request options', function () {
    it('should add headers options', function () {
      var api = superapi.default({
        baseUrl: 'http://foo.domain.tld/api',
        services: {
          foo: {
            path: 'bar',
            options: {
              type: 'json',
              accept: 'png'
            }
          }
        }
      });
      api.agent = superagent;
      api.request('foo')._header.should.haveOwnProperty('content-type');
      api.request('foo')._header['content-type'].should.eql('application/json');

      api.request('foo')._header.should.haveOwnProperty('accept');
      api.request('foo')._header.accept.should.eql('png');
    });
  });

  describe('global request headers', function () {
    it('should add service headers', function () {
      var api = superapi.default({
        baseUrl: 'http://foo.domain.tld/api',
        services: {
          foo: {
            path: 'bar',
          }
        },
        headers: {
          'Content-type': 'json',
          'X-Requested-With': 'XMLHttpRequest'
        }
      });
      api.agent = superagent;
      api.request('foo')._header.should.haveOwnProperty('content-type');
      api.request('foo')._header['content-type'].should.eql('json');

      api.request('foo')._header.should.haveOwnProperty('x-requested-with');
      api.request('foo')._header['x-requested-with'].should.eql('XMLHttpRequest');
    });
  });

  describe('global request options', function () {
    it('should add global headers', function () {
      var api = superapi.default({
        baseUrl: 'http://foo.domain.tld/api',
        services: {
          foo: {
            path: 'bar',
          }
        },
        headers: {
          'X-Requested-With': 'XMLHttpRequest'
        },
        options: {
          type: 'json',
          accept: 'json'
        }
      });
      api.agent = superagent;
      api.request('foo')._header.should.haveOwnProperty('content-type');
      api.request('foo')._header['content-type'].should.eql('application/json');

      api.request('foo')._header.should.haveOwnProperty('accept');
      api.request('foo')._header.accept.should.eql('application/json');

      api.request('foo')._header.should.haveOwnProperty('x-requested-with');
      api.request('foo')._header['x-requested-with'].should.eql('XMLHttpRequest');
    });
  });

  describe('global options', function () {
    it('should not override service option', function () {
      var api = superapi.default({
        baseUrl: 'http://foo.domain.tld/api',
        services: {
          foo: {
            path: 'bar',
            options: {
              type: 'form'
            }
          }
        },
        options: {
          type: 'json',
        }
      });
      api.agent = superagent;
      api.request('foo')._header.should.haveOwnProperty('content-type');
      api.request('foo')._header['content-type'].should.eql('application/x-www-form-urlencoded');
    });

    it('should not override service header', function () {
      var api = superapi.default({
        baseUrl: 'http://foo.domain.tld/api',
        services: {
          foo: {
            path: 'bar',
            headers: {
              'Content-type': 'application/x-www-form-urlencoded'
            }
          }
        },
        options: {
          type: 'json'
        }
      });
      api.agent = superagent;
      api.request('foo')._header.should.haveOwnProperty('content-type');
      api.request('foo')._header['content-type'].should.eql('application/x-www-form-urlencoded');
    });
  });

  describe('global headers', function () {
    it('should not override service option', function () {
      var api = superapi.default({
        baseUrl: 'http://foo.domain.tld/api',
        services: {
          foo: {
            path: 'bar',
            options: {
              type: 'form'
            }
          }
        },
        headers: {
          'Content-type': 'application/json',
        }
      });
      api.agent = superagent;
      api.request('foo')._header.should.haveOwnProperty('content-type');
      api.request('foo')._header['content-type'].should.eql('application/x-www-form-urlencoded');
    });

    it('should not override service header', function () {
      var api = superapi.default({
        baseUrl: 'http://foo.domain.tld/api',
        services: {
          foo: {
            path: 'bar',
            headers: {
              'Content-type': 'application/x-www-form-urlencoded'
            }
          }
        },
        headers: {
          'Content-type': 'application/json',
        }
      });
      api.agent = superagent;
      api.request('foo')._header.should.haveOwnProperty('content-type');
      api.request('foo')._header['content-type'].should.eql('application/x-www-form-urlencoded');
    });
  });

  describe('runtime headers', function () {
    it('should add header', function () {
      var api = superapi.default({
        baseUrl: 'http://foo.domain.tld/api',
        services: {
          foo: {
            path: 'bar',
            headers: {
              'Content-type': 'application/x-www-form-urlencoded'
            }
          }
        }
      });
      api.agent = superagent;
      api.addHeader('csrf', 'my-awesome-csrf-token');
      api.request('foo')._header.should.haveOwnProperty('csrf');
      api.request('foo')._header.csrf.should.eql('my-awesome-csrf-token');
    });
  });

  describe('url tokenization', function () {
    it('replaceUrl - should replace tokens in a given url', function () {
      var api = superapi.default({});
      var url = api.replaceUrl('/:bar/:foo.:baz.json', {
        bar: 'user',
        foo: 'john',
        baz: 'doe'
      });
      url.should.eql('/user/john.doe.json');
    });

    it('buildUrl - should build the url of a service id and replace any tokens', function  () {
      var api = superapi.default({
        baseUrl: 'http://example.tld',
        services: {
          foo: {
            path:'/:bar/:foo.:baz.json'
          }
        }
      });
      var url = api.buildUrl('foo', {
        bar: 'user',
        foo: 'john',
        baz: 'doe'
      });
      url.should.eql('http://example.tld/user/john.doe.json')
    })
  });

});
<commit_msg>test(query): add tests for new query string feature<commit_after>define([
  'superapi',
  'superagent'
], function (superapi, superagent) {
  'use strict';

  describe('configuration', function () {
    it('should return the service string configuration', function () {
      var api = superapi.default({
        baseUrl: 'http://foo.domain.tld/api',
        services: {
          foo: 'bar'
        }
      });

      api.service('foo').should.eql('bar');
    });

    it('should return the service object configuration', function () {
      var api = superapi.default({
        baseUrl: 'http://foo.domain.tld/api',
        services: {
          foo: {
            path: '/foo'
          }
        }
      });

      api.service('foo').should.eql({path: '/foo'});
    });
  });

  describe('request url', function () {
    it('should append the service url to the baseUrl', function () {
      var api = superapi.default({
        baseUrl: 'http://foo.domain.tld/api',
        services: {
          foo: {
            path: '/foo'
          }
        }
      });

      api.url('foo').should.eql('http://foo.domain.tld/api/foo');
    });

    it('should add a slash in front of route path if missing', function () {
      var api = superapi.default({
        baseUrl: 'http://foo.domain.tld/api',
        services: {
          foo: {
            path: 'foo'
          }
        }
      });

      api.url('foo').should.eql('http://foo.domain.tld/api/foo');
    });

    it('should support route as a string', function () {
      var api = superapi.default({
        baseUrl: 'http://foo.domain.tld/api',
        services: {
          foo: 'bar'
        }
      });

      api.url('foo').should.eql('http://foo.domain.tld/api/bar');
    });

    it('should throw error if path is missing', function () {
      var api = superapi.default({
        baseUrl: 'http://foo.domain.tld/api',
        services: {
          foo: {}
        }
      });

      // fail in PhantomJS as bind not available
      api.url.bind(null, 'foo').should.throw();
    });
  });

  describe('request method', function () {
    it('should default to get', function () {
      var api = superapi.default({
        baseUrl: 'http://foo.domain.tld/api',
        services: {
          foo: 'bar'
        }
      });
      api.agent = superagent;
      api.request('foo').method.should.eql('GET');
    });

    it('should support POST', function () {
      var api = superapi.default({
        baseUrl: 'http://foo.domain.tld/api',
        services: {
          foo: {
            path: 'bar',
            method: 'POST'
          }
        }
      });
      api.agent = superagent;
      api.request('foo').method.should.eql('POST');
    });

    it('should support PUT', function () {
      var api = superapi.default({
        baseUrl: 'http://foo.domain.tld/api',
        services: {
          foo: {
            path: 'bar',
            method: 'PUT'
          }
        }
      });
      api.agent = superagent;
      api.request('foo').method.should.eql('PUT');
    });

    it('should support DELETE', function () {
      var api = superapi.default({
        baseUrl: 'http://foo.domain.tld/api',
        services: {
          foo: {
            path: 'bar',
            method: 'DELETE'
          }
        }
      });
      api.agent = superagent;
      api.request('foo').method.should.eql('DELETE');
    });

    it('should support HEAD', function () {
      var api = superapi.default({
        baseUrl: 'http://foo.domain.tld/api',
        services: {
          foo: {
            path: 'bar',
            method: 'HEAD'
          }
        }
      });
      api.agent = superagent;
      api.request('foo').method.should.eql('HEAD');
    });

    it('should support PATCH', function () {
      var api = superapi.default({
        baseUrl: 'http://foo.domain.tld/api',
        services: {
          foo: {
            path: 'bar',
            method: 'PATCH'
          }
        }
      });
      api.agent = superagent;
      api.request('foo').method.should.eql('PATCH');
    });
  });

  describe.skip('request headers', function () {
  });

  describe('service request headers', function () {
    it('should add service headers', function () {
      var api = superapi.default({
        baseUrl: 'http://foo.domain.tld/api',
        services: {
          foo: {
            path: 'bar',
            headers: {
              'Content-type': 'json'
            }
          }
        }
      });
      api.agent = superagent;
      api.request('foo')._header.should.haveOwnProperty('content-type');
      api.request('foo')._header['content-type'].should.eql('json');
    });
  });

  describe('service request options', function () {
    it('should add headers options', function () {
      var api = superapi.default({
        baseUrl: 'http://foo.domain.tld/api',
        services: {
          foo: {
            path: 'bar',
            options: {
              type: 'json',
              accept: 'png'
            }
          }
        }
      });
      api.agent = superagent;
      api.request('foo')._header.should.haveOwnProperty('content-type');
      api.request('foo')._header['content-type'].should.eql('application/json');

      api.request('foo')._header.should.haveOwnProperty('accept');
      api.request('foo')._header.accept.should.eql('png');
    });
  });

  describe('global request headers', function () {
    it('should add service headers', function () {
      var api = superapi.default({
        baseUrl: 'http://foo.domain.tld/api',
        services: {
          foo: {
            path: 'bar',
          }
        },
        headers: {
          'Content-type': 'json',
          'X-Requested-With': 'XMLHttpRequest'
        }
      });
      api.agent = superagent;
      api.request('foo')._header.should.haveOwnProperty('content-type');
      api.request('foo')._header['content-type'].should.eql('json');

      api.request('foo')._header.should.haveOwnProperty('x-requested-with');
      api.request('foo')._header['x-requested-with'].should.eql('XMLHttpRequest');
    });
  });

  describe('global request options', function () {
    it('should add global headers', function () {
      var api = superapi.default({
        baseUrl: 'http://foo.domain.tld/api',
        services: {
          foo: {
            path: 'bar',
          }
        },
        headers: {
          'X-Requested-With': 'XMLHttpRequest'
        },
        options: {
          type: 'json',
          accept: 'json'
        }
      });
      api.agent = superagent;
      api.request('foo')._header.should.haveOwnProperty('content-type');
      api.request('foo')._header['content-type'].should.eql('application/json');

      api.request('foo')._header.should.haveOwnProperty('accept');
      api.request('foo')._header.accept.should.eql('application/json');

      api.request('foo')._header.should.haveOwnProperty('x-requested-with');
      api.request('foo')._header['x-requested-with'].should.eql('XMLHttpRequest');
    });
  });

  describe('global options', function () {
    it('should not override service option', function () {
      var api = superapi.default({
        baseUrl: 'http://foo.domain.tld/api',
        services: {
          foo: {
            path: 'bar',
            options: {
              type: 'form'
            }
          }
        },
        options: {
          type: 'json',
        }
      });
      api.agent = superagent;
      api.request('foo')._header.should.haveOwnProperty('content-type');
      api.request('foo')._header['content-type'].should.eql('application/x-www-form-urlencoded');
    });

    it('should not override service header', function () {
      var api = superapi.default({
        baseUrl: 'http://foo.domain.tld/api',
        services: {
          foo: {
            path: 'bar',
            headers: {
              'Content-type': 'application/x-www-form-urlencoded'
            }
          }
        },
        options: {
          type: 'json'
        }
      });
      api.agent = superagent;
      api.request('foo')._header.should.haveOwnProperty('content-type');
      api.request('foo')._header['content-type'].should.eql('application/x-www-form-urlencoded');
    });
  });

  describe('global headers', function () {
    it('should not override service option', function () {
      var api = superapi.default({
        baseUrl: 'http://foo.domain.tld/api',
        services: {
          foo: {
            path: 'bar',
            options: {
              type: 'form'
            }
          }
        },
        headers: {
          'Content-type': 'application/json',
        }
      });
      api.agent = superagent;
      api.request('foo')._header.should.haveOwnProperty('content-type');
      api.request('foo')._header['content-type'].should.eql('application/x-www-form-urlencoded');
    });

    it('should not override service header', function () {
      var api = superapi.default({
        baseUrl: 'http://foo.domain.tld/api',
        services: {
          foo: {
            path: 'bar',
            headers: {
              'Content-type': 'application/x-www-form-urlencoded'
            }
          }
        },
        headers: {
          'Content-type': 'application/json',
        }
      });
      api.agent = superagent;
      api.request('foo')._header.should.haveOwnProperty('content-type');
      api.request('foo')._header['content-type'].should.eql('application/x-www-form-urlencoded');
    });
  });

  describe('runtime headers', function () {
    it('should add header', function () {
      var api = superapi.default({
        baseUrl: 'http://foo.domain.tld/api',
        services: {
          foo: {
            path: 'bar',
            headers: {
              'Content-type': 'application/x-www-form-urlencoded'
            }
          }
        }
      });
      api.agent = superagent;
      api.addHeader('csrf', 'my-awesome-csrf-token');
      api.request('foo')._header.should.haveOwnProperty('csrf');
      api.request('foo')._header.csrf.should.eql('my-awesome-csrf-token');
    });
  });

  describe('url tokenization', function () {
    it('replaceUrl - should replace tokens in a given url', function () {
      var api = superapi.default({});
      var url = api.replaceUrl('/:bar/:foo.:baz.json', {
        bar: 'user',
        foo: 'john',
        baz: 'doe'
      });
      url.should.eql('/user/john.doe.json');
    });

    it('buildUrl - should build the url of a service id and replace any tokens', function  () {
      var api = superapi.default({
        baseUrl: 'http://example.tld',
        services: {
          foo: {
            path:'/:bar/:foo.:baz.json'
          }
        }
      });
      var url = api.buildUrl('foo', {
        bar: 'user',
        foo: 'john',
        baz: 'doe'
      });
      url.should.eql('http://example.tld/user/john.doe.json')
    })
  });

  describe.only('url query', function () {
    it('buildUrlQuery - should create the query for an url', function () {
      var api = superapi.default({});
      var queryString = api.buildUrlQuery({
        bar: 'user',
        foo: 'john',
        baz: 'doe'
      });
      queryString.should.eql('?bar=user&foo=john&baz=doe');
    });

    it('buildUrlQuery - should support empty', function () {
      var api = superapi.default({});
      var queryString = api.buildUrlQuery({});
      queryString.should.eql('');
    });

    it('buildUrlQuery - should create the query for an url', function () {
      var api = superapi.default({
        baseUrl: 'http://example.tld',
        services: {
          foo: {
            path:'/user/:foo.:bar.json'
          }
        }
      });

      var queryString = api.buildUrl('foo', {
        foo: 'john',
        bar: 'doe'
      }, {
        content: 'post',
        since: '19700101'
      });
      queryString.should.eql('http://example.tld/user/john.doe.json?content=post&since=19700101');
    });
  });
});
<|endoftext|>


<commit_before>describe('Object', function () {
    "use strict";

    describe("Object.keys", function () {
        var obj = {
            "str": "boz",
            "obj": { },
            "arr": [],
            "bool": true,
            "num": 42,
            "null": null,
            "undefined": undefined
        };

        var loopedValues = [];
        for (var k in obj) {
            loopedValues.push(k);
        }

        var keys = Object.keys(obj);
        it('should have correct length', function () {
            expect(keys.length).toBe(7);
        });

        it('should return an Array', function () {
            expect(Array.isArray(keys)).toBe(true);
        });

        it('should return names which are own properties', function () {
            keys.forEach(function (name) {
                expect(obj.hasOwnProperty(name)).toBe(true);
            });
        });

        it('should return names which are enumerable', function () {
            keys.forEach(function (name) {
                expect(loopedValues.indexOf(name)).toNotBe(-1);
            })
        });

        it('should throw error for non object', function () {
            var e = {};
            expect(function () {
                try {
                    Object.keys(42)
                } catch (err) {
                    throw e;
                }
            }).toThrow(e);
        });

        it('should not enumerate over non-enumerable properties', function () {
             var Foo = function () {};
             expect(Object.keys(Foo.prototype)).toEqual([]);
             expect(Object.keys(Boolean.prototype)).toEqual([]);
             expect(Object.keys(Object.prototype)).toEqual([]);
        });
    });

	describe("Object.isExtensible", function () {
        var obj = { };

        it('should return true if object is extensible', function () {
            expect(Object.isExtensible(obj)).toBe(true);
        });

        it('should return false if object is not extensible', function () {
            expect(Object.isExtensible(Object.preventExtensions(obj))).toBe(false);
        });

        it('should return false if object is seal', function () {
            expect(Object.isExtensible(Object.seal(obj))).toBe(false);
        });

        it('should return false if object is freeze', function () {
            expect(Object.isExtensible(Object.freeze(obj))).toBe(false);
        });

        it('should throw error for non object', function () {
            var e1 = {};
            expect(function () {
                try {
                    Object.isExtensible(42)
                } catch (err) {
                    throw e1;
                }
            }).toThrow(e1);
        });
    });

	describe("Object.defineProperty", function () {
        var obj;

        beforeEach(function() {
           obj = {};

           Object.defineProperty(obj, 'name', {
               value : 'Testing',
               configurable: true,
               enumerable: true,
               writable: true
           });
        });

        it('should return the initial value', function () {
            expect(obj.hasOwnProperty('name')).toBeTruthy();
            expect(obj.name).toBe('Testing');
        });

        it('should be setable', function () {
            obj.name = 'Other';
            expect(obj.name).toBe('Other');
        });

        it('should return the parent initial value', function () {
            var child = Object.create(obj, {});

            expect(child.name).toBe('Testing');
            expect(child.hasOwnProperty('name')).toBeFalsy();
        });

        it('should not override the parent value', function () {
            var child = Object.create(obj, {});

            Object.defineProperty(child, 'name', {
                value : 'Other'
            });

            expect(obj.name).toBe('Testing');
            expect(child.name).toBe('Other');
        });

        it('should throw error for non object', function () {
            expect(function () {
                Object.defineProperty(42, 'name', {});
            }).toThrow();
        });
    });

	describe("Object.getOwnPropertyDescriptor", function () {
        it('should return undefined because the object does not own the property', function () {
            var descr = Object.getOwnPropertyDescriptor({}, 'name');

            expect(descr).toBeUndefined()
        });

        it('should return a data descriptor', function () {
            var descr = Object.getOwnPropertyDescriptor({name: 'Testing'}, 'name');

            expect(descr).not.toBeUndefined();
            expect(descr.value).toBe('Testing');
            expect(descr.writable).toBe(true);
            expect(descr.enumerable).toBe(true);
            expect(descr.configurable).toBe(true);
        });

        it('should return undefined because the object does not own the property', function () {
            var descr = Object.getOwnPropertyDescriptor(Object.create({name: 'Testing'}, {}), 'name');

            expect(descr).toBeUndefined()
        });

        it('should return a data descriptor', function () {
            var obj = Object.create({}, {
                name: {
                    value : 'Testing',
                    configurable: true,
                    enumerable: true,
                    writable: true
                }
            });

            var descr = Object.getOwnPropertyDescriptor(obj, 'name');

            expect(descr).not.toBeUndefined();
            expect(descr.value).toBe('Testing');
            expect(descr.writable).toBe(true);
            expect(descr.enumerable).toBe(true);
            expect(descr.configurable).toBe(true);
        });

    	it('should throw error for non object', function () {
            expect(function () {
                Object.getOwnPropertyDescriptor(42, 'name');
            }).toThrow();
        });
    });
});
<commit_msg>Adding tests for #209<commit_after>describe('Object', function () {
    "use strict";

    describe("Object.keys", function () {
        var obj = {
            "str": "boz",
            "obj": { },
            "arr": [],
            "bool": true,
            "num": 42,
            "null": null,
            "undefined": undefined
        };

        var loopedValues = [];
        for (var k in obj) {
            loopedValues.push(k);
        }

        var keys = Object.keys(obj);
        it('should have correct length', function () {
            expect(keys.length).toBe(7);
        });

        it('should return an Array', function () {
            expect(Array.isArray(keys)).toBe(true);
        });

        it('should return names which are own properties', function () {
            keys.forEach(function (name) {
                expect(obj.hasOwnProperty(name)).toBe(true);
            });
        });

        it('should return names which are enumerable', function () {
            keys.forEach(function (name) {
                expect(loopedValues.indexOf(name)).toNotBe(-1);
            })
        });

        it('should throw error for non object', function () {
            var e = {};
            expect(function () {
                try {
                    Object.keys(42)
                } catch (err) {
                    throw e;
                }
            }).toThrow(e);
        });

        it('should not enumerate over non-enumerable properties', function () {
             var Foo = function () {};
             expect(Object.keys(Foo.prototype)).toEqual([]);
             expect(Object.keys(Boolean.prototype)).toEqual([]);
             expect(Object.keys(Object.prototype)).toEqual([]);
        });

        it('works with boxed primitives', function () {
            expect(Object.keys(new String('hello'))).toEqual(['0', '1', '2', '3', '4']);
            expect(Object.keys(Object('hello'))).toEqual(['0', '1', '2', '3', '4']);
        });
    });

	describe("Object.isExtensible", function () {
        var obj = { };

        it('should return true if object is extensible', function () {
            expect(Object.isExtensible(obj)).toBe(true);
        });

        it('should return false if object is not extensible', function () {
            expect(Object.isExtensible(Object.preventExtensions(obj))).toBe(false);
        });

        it('should return false if object is seal', function () {
            expect(Object.isExtensible(Object.seal(obj))).toBe(false);
        });

        it('should return false if object is freeze', function () {
            expect(Object.isExtensible(Object.freeze(obj))).toBe(false);
        });

        it('should throw error for non object', function () {
            var e1 = {};
            expect(function () {
                try {
                    Object.isExtensible(42)
                } catch (err) {
                    throw e1;
                }
            }).toThrow(e1);
        });
    });

	describe("Object.defineProperty", function () {
        var obj;

        beforeEach(function() {
           obj = {};

           Object.defineProperty(obj, 'name', {
               value : 'Testing',
               configurable: true,
               enumerable: true,
               writable: true
           });
        });

        it('should return the initial value', function () {
            expect(obj.hasOwnProperty('name')).toBeTruthy();
            expect(obj.name).toBe('Testing');
        });

        it('should be setable', function () {
            obj.name = 'Other';
            expect(obj.name).toBe('Other');
        });

        it('should return the parent initial value', function () {
            var child = Object.create(obj, {});

            expect(child.name).toBe('Testing');
            expect(child.hasOwnProperty('name')).toBeFalsy();
        });

        it('should not override the parent value', function () {
            var child = Object.create(obj, {});

            Object.defineProperty(child, 'name', {
                value : 'Other'
            });

            expect(obj.name).toBe('Testing');
            expect(child.name).toBe('Other');
        });

        it('should throw error for non object', function () {
            expect(function () {
                Object.defineProperty(42, 'name', {});
            }).toThrow();
        });
    });

	describe("Object.getOwnPropertyDescriptor", function () {
        it('should return undefined because the object does not own the property', function () {
            var descr = Object.getOwnPropertyDescriptor({}, 'name');

            expect(descr).toBeUndefined()
        });

        it('should return a data descriptor', function () {
            var descr = Object.getOwnPropertyDescriptor({name: 'Testing'}, 'name');

            expect(descr).not.toBeUndefined();
            expect(descr.value).toBe('Testing');
            expect(descr.writable).toBe(true);
            expect(descr.enumerable).toBe(true);
            expect(descr.configurable).toBe(true);
        });

        it('should return undefined because the object does not own the property', function () {
            var descr = Object.getOwnPropertyDescriptor(Object.create({name: 'Testing'}, {}), 'name');

            expect(descr).toBeUndefined()
        });

        it('should return a data descriptor', function () {
            var obj = Object.create({}, {
                name: {
                    value : 'Testing',
                    configurable: true,
                    enumerable: true,
                    writable: true
                }
            });

            var descr = Object.getOwnPropertyDescriptor(obj, 'name');

            expect(descr).not.toBeUndefined();
            expect(descr.value).toBe('Testing');
            expect(descr.writable).toBe(true);
            expect(descr.enumerable).toBe(true);
            expect(descr.configurable).toBe(true);
        });

    	it('should throw error for non object', function () {
            expect(function () {
                Object.getOwnPropertyDescriptor(42, 'name');
            }).toThrow();
        });
    });
});
<|endoftext|>


<commit_before>
var Promise = require('es6-promise').Promise;
var expect = require('chai').expect;
var path = require('path');

describe('Tests with browser', function () {

  var server = meteor({});

  var browser1 = browser(server);

  it('should be ok', function () {
    return Promise.resolve('should be ok');
  });

  it('execute should work in browser', function () {
    return browser1.execute(function (value) {
        return value;
      }, [ 'someValue' ])
      .then(function (value) {
        expect(value).to.equal('someValue');
      });
  });

  // TODO: we should implement more tests for custom helpers
  it('should be able to use standard helpers', function () {
    return browser1.getText('h1').then(function (value) {
      expect(value).to.contain('Hello World!');
    });
  });

  var id = Math.floor(1000 * Math.random()).toString();

  describe('Database insertions', function () {
    before(function () {
      return browser1
        .promise(function (resolve, reject, id) {
          Items.insert({_id: id}, either(reject).or(resolve));
        }, [ id ])
        .then(function (value) {
          expect(value).to.equal(id);
        });
    });

    it('db insert should work in browser', function () {
      return browser1.execute(
          "return Items.findOne({_id: " + JSON.stringify(id) + "});"
        )
        .then(function (value) {
          expect(value).not.to.be.empty;
          expect(value._id).to.equal(id);
        });
    });

    it('the same element should be present on server', function () {
      return server.execute(function (id) {
          // TODO: wait?
          return Items.findOne({_id: id});
        }, [ id ])
        .then(function (value) {
          expect(value).not.to.be.empty;
          expect(value._id).to.equal(id);
        });
    });

  });

  describe('Restarting server', function () {

    var browser2 = browser(server);

    this.timeout(10000);

    before(function () {
      return server.restart(2000);
    });

    it ('should be all right', function () {
      return server.execute(function ()  {
          return Meteor.release;
        })
        .then(function (release) {
          expect(release).to.be.ok;
        });
    });

    it('should recognize that the server was restarted', function () {
      return browser2
        .wait(7000, 'until status.connected === true', function () {
          return Meteor.connection.status().connected;
        })
        .execute("return reset;")
        .then(function (numberOfResets) {
          // XXX the first "reset" occurs on startup, so we have two resets up to this point
          expect(numberOfResets).to.equal(2);
        });
    });

    it ('another restart shoud work as well', function () {
      return server.restart(2000).then(function () {
        return browser2
          .wait(7000, 'until status.connected === true', function () {
            return Meteor.connection.status().connected;
          })
          .execute("return reset;")
          .then(function (numberOfResets) {
            expect(numberOfResets).to.equal(3);
          });
      });
    });

  });

});
<commit_msg>Another improvement to that test suite<commit_after>
var Promise = require('es6-promise').Promise;
var expect = require('chai').expect;
var path = require('path');

describe('Tests with browser', function () {

  var server = meteor({});

  var browser1 = browser(server);

  it('should be ok', function () {
    return Promise.resolve('should be ok');
  });

  it('execute should work in browser', function () {
    return browser1.execute(function (value) {
        return value;
      }, [ 'someValue' ])
      .then(function (value) {
        expect(value).to.equal('someValue');
      });
  });

  // TODO: we should implement more tests for custom helpers
  it('should be able to use standard helpers', function () {
    return browser1.getText('h1').then(function (value) {
      expect(value).to.contain('Hello World!');
    });
  });

  var id = Math.floor(1000 * Math.random()).toString();

  describe('Database insertions', function () {
    before(function () {
      return browser1
        .promise(function (resolve, reject, id) {
          Items.insert({_id: id}, either(reject).or(resolve));
        }, [ id ])
        .then(function (value) {
          expect(value).to.equal(id);
        });
    });

    it('db insert should work in browser', function () {
      return browser1.execute(
          "return Items.findOne({_id: " + JSON.stringify(id) + "});"
        )
        .then(function (value) {
          expect(value).not.to.be.empty;
          expect(value._id).to.equal(id);
        });
    });

    it('the same element should be present on server', function () {
      return server.execute(function (id) {
          // TODO: wait?
          return Items.findOne({_id: id});
        }, [ id ])
        .then(function (value) {
          expect(value).not.to.be.empty;
          expect(value._id).to.equal(id);
        });
    });

  });

  describe('Restarting server', function () {

    var browser2 = browser(server);
    var value    = 0;

    this.timeout(10000);

    before(function () {
      return server.restart(2000);
    });

    before(function () {
      return browser2
        .execute("return reset;")
        .then(function (numberOfResets) {
          value = numberOfResets;
        });
    })

    it ('should be all right', function () {
      return server.execute(function ()  {
          return Meteor.release;
        })
        .then(function (release) {
          expect(release).to.be.ok;
        });
    });

    it('should recognize that the server was restarted', function () {
      return browser2
        .wait(7000, 'until status.connected === true', function () {
          return Meteor.connection.status().connected;
        })
        .execute("return reset;")
        .then(function (numberOfResets) {
          // XXX the first "reset" occurs on startup, so we have two resets up to this point
          expect(numberOfResets).to.equal(value + 1);
        });
    });

    it ('another restart shoud work as well', function () {
      return server.restart(2000).then(function () {
        return browser2
          .wait(7000, 'until status.connected === true', function () {
            return Meteor.connection.status().connected;
          })
          .execute("return reset;")
          .then(function (numberOfResets) {
            expect(numberOfResets).to.equal(value + 2);
          });
      });
    });

  });

});
<|endoftext|>


<commit_before>
var Promise = require('es6-promise').Promise;
var expect = require('chai').expect;
var path = require('path');

describe('Tests with browser', function () {

  var server = meteor({});

  var browser1 = browser(server);

  it('should be ok', function () {
    return Promise.resolve('should be ok');
  });

  it('execute should work in browser', function () {
    return browser1.execute(function (value) {
        return value;
      }, [ 'someValue' ])
      .then(function (value) {
        expect(value).to.equal('someValue');
      });
  });

  // TODO: we should implement more tests for custom helpers
  it('should be able to use standard helpers', function () {
    return browser1.getText('h1').then(function (value) {
      expect(value).to.contain('Hello World!');
    });
  });

  var id = Math.floor(1000 * Math.random()).toString();

  describe('Database insertions', function () {
    before(function () {
      return browser1
        .promise(function (resolve, reject, id) {
          Items.insert({_id: id}, either(reject).or(resolve));
        }, [ id ])
        .then(function (value) {
          expect(value).to.equal(id);
        });
    });

    it('db insert should work in browser', function () {
      return browser1.execute(
          "return Items.findOne({_id: " + JSON.stringify(id) + "});"
        )
        .then(function (value) {
          expect(value).not.to.be.empty;
          expect(value._id).to.equal(id);
        });
    });

    it('the same element should be present on server', function () {
      return server.execute(function (id) {
          // TODO: wait?
          return Items.findOne({_id: id});
        }, [ id ])
        .then(function (value) {
          expect(value).not.to.be.empty;
          expect(value._id).to.equal(id);
        });
    });

  });

  describe('Restarting server', function () {

    var browser2 = browser(server);

    this.timeout(10000);

    before(function () {
      return server.restart(2000);
    });

    it ('should be all right', function () {
      return server.execute(function ()  {
          return Meteor.release;
        })
        .then(function (release) {
          expect(release).to.be.ok;
        });
    });

    it('should recognize that the server was restarted', function () {
      return browser2
        .wait(5000, 'until reset event is detected', "return reset > 0")
        .execute("return reset;")
        .then(function (numberOfResets) {
          expect(numberOfResets).to.equal(1);
        });
    });

    it ('another restart shoud work as well', function () {
      return server.restart().then(function () {
        return browser2
          .wait(5000, 'until reset event is detected', "return reset > 1")
          .execute("return reset;")
          .then(function (numberOfResets) {
            expect(numberOfResets).to.equal(2);
          });
      });
    });

  });

});
<commit_msg>Increased timeouts for reset detection<commit_after>
var Promise = require('es6-promise').Promise;
var expect = require('chai').expect;
var path = require('path');

describe('Tests with browser', function () {

  var server = meteor({});

  var browser1 = browser(server);

  it('should be ok', function () {
    return Promise.resolve('should be ok');
  });

  it('execute should work in browser', function () {
    return browser1.execute(function (value) {
        return value;
      }, [ 'someValue' ])
      .then(function (value) {
        expect(value).to.equal('someValue');
      });
  });

  // TODO: we should implement more tests for custom helpers
  it('should be able to use standard helpers', function () {
    return browser1.getText('h1').then(function (value) {
      expect(value).to.contain('Hello World!');
    });
  });

  var id = Math.floor(1000 * Math.random()).toString();

  describe('Database insertions', function () {
    before(function () {
      return browser1
        .promise(function (resolve, reject, id) {
          Items.insert({_id: id}, either(reject).or(resolve));
        }, [ id ])
        .then(function (value) {
          expect(value).to.equal(id);
        });
    });

    it('db insert should work in browser', function () {
      return browser1.execute(
          "return Items.findOne({_id: " + JSON.stringify(id) + "});"
        )
        .then(function (value) {
          expect(value).not.to.be.empty;
          expect(value._id).to.equal(id);
        });
    });

    it('the same element should be present on server', function () {
      return server.execute(function (id) {
          // TODO: wait?
          return Items.findOne({_id: id});
        }, [ id ])
        .then(function (value) {
          expect(value).not.to.be.empty;
          expect(value._id).to.equal(id);
        });
    });

  });

  describe('Restarting server', function () {

    var browser2 = browser(server);

    this.timeout(10000);

    before(function () {
      return server.restart(2000);
    });

    it ('should be all right', function () {
      return server.execute(function ()  {
          return Meteor.release;
        })
        .then(function (release) {
          expect(release).to.be.ok;
        });
    });

    it('should recognize that the server was restarted', function () {
      return browser2
        .wait(7000, 'until reset event is detected', "return reset > 0")
        .execute("return reset;")
        .then(function (numberOfResets) {
          expect(numberOfResets).to.equal(1);
        });
    });

    it ('another restart shoud work as well', function () {
      return server.restart().then(function () {
        return browser2
          .wait(7000, 'until reset event is detected', "return reset > 1")
          .execute("return reset;")
          .then(function (numberOfResets) {
            expect(numberOfResets).to.equal(2);
          });
      });
    });

  });

});
<|endoftext|>