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

  QUnit.module("underscore.collections.walk");

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

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

  var getArrayValues = function() {
    return ["a", "a", "a", "a", "b", "c", "d", "e" ];
  };

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    // A more useful example: transforming a tree.

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

  test("containsAtLeast", function(){
    var array = getArrayValues();

    equal(_.walk.containsAtLeast(array, 3, "a"), true, "list contains at least 3 items");
    equal(_.walk.containsAtLeast(array, 1, "b"), true, "list contains at least 1 items");
    equal(_.walk.containsAtLeast(array, 1, "f"), false, "list doesn't contain item for that value");
  });

  test("containsAtMost", function(){
    var array = getArrayValues();

    equal(_.walk.containsAtMost(array, 4, "a"), true, "list contains at most 4 items");
    equal(_.walk.containsAtMost(array, 1, "b"), true, "list contains at most 1 value");
    equal(_.walk.containsAtMost(array, 1, "f"), true, "list contains at most 1 value");
  });
});
<commit_msg>Add a missing change (oops) (#208 #239)<commit_after>$(document).ready(function() {

  QUnit.module("underscore.collections.walk");

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

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

  var getArrayValues = function() {
    return ["a", "a", "a", "a", "b", "c", "d", "e" ];
  };

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    // A more useful example: transforming a tree.

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

  QUnit.test("containsAtLeast", function(assert){
    var array = getArrayValues();

    assert.equal(_.walk.containsAtLeast(array, 3, "a"), true, "list contains at least 3 items");
    assert.equal(_.walk.containsAtLeast(array, 1, "b"), true, "list contains at least 1 items");
    assert.equal(_.walk.containsAtLeast(array, 1, "f"), false, "list doesn't contain item for that value");
  });

  QUnit.test("containsAtMost", function(assert){
    var array = getArrayValues();

    assert.equal(_.walk.containsAtMost(array, 4, "a"), true, "list contains at most 4 items");
    assert.equal(_.walk.containsAtMost(array, 1, "b"), true, "list contains at most 1 value");
    assert.equal(_.walk.containsAtMost(array, 1, "f"), true, "list contains at most 1 value");
  });
});
<|endoftext|>


<commit_before>define(function () {

	return function configureAsserts (success, failure) {

		function assert (val, msg) {
			(val === true ? success : failure)(msg);
		}

		assert.equal = function equal (expected, val, msg) {
			if (val !== expected) {
				failure(msg + ' (expected: ' + expected + '. got: ' + val + ')');
			}
			else {
				success(msg);
			}
		};

		return assert;
	};

});<commit_msg>push test name into assertions<commit_after>define(function () {

	return function configureAsserts (success, failure, name) {

		function doFail (msg) {
			failure(name + (msg ? ' - ' + msg : ''));
		}

		function doSuccess (msg) {
			success(name + (msg ? ' - ' + msg : ''));
		}

		function assert (val, msg) {
			(val === true ? doSuccess : doFail)(msg);
		}

		assert.equal = function equal (expected, val, msg) {
			if (val !== expected) {
				doFail(msg + ' (expected: ' + expected + '. got: ' + val + ')');
			}
			else {
				doSuccess(msg);
			}
		};

		return assert;
	};

});
<|endoftext|>


<commit_before>var utils = require('./test-utils');
var assert = require('chai').assert;

var Domain = require('../lib/database/domain').Domain;

var context;
var temporaryDatabase;

function commonSetup() {
  temporaryDatabase = utils.createTemporaryDatabase();
  context = temporaryDatabase.get();
}

function commonTeardown() {
  context = undefined;
  temporaryDatabase.clear();
  temporaryDatabase.teardown();
  temporaryDatabase = undefined;
}

suite('cs-create-domain', function() {
  setup(commonSetup);
  teardown(commonTeardown);

  test('create', function(done) {
    utils
      .run('cs-create-domain',
           '--domain-name', 'test',
           '--database-path', temporaryDatabase.path)
      .next(function(result) {
        assert.equal(result.code, 0);
        assert.include(result.output.stdout,
                       'Domain endpoints are currently being created.');

        context.reopen();
        var domain = new Domain('test', context);
        assert.isTrue(domain.exists());

        done();
      })
      .error(function(e) {
        done(e);
      });
  });

  test('create again', function(done) {
    utils
      .run('cs-create-domain',
           '--domain-name', 'test',
           '--database-path', temporaryDatabase.path)
      .run('cs-create-domain',
           '--domain-name', 'test',
           '--database-path', temporaryDatabase.path)
      .next(function(result) {
        assert.equal(result.code, 1);
        assert.include(result.output.stdout,
                       'The domain [test] already exists.');

        context.reopen();
        var domains = Domain.getAll(context).map(function(domain) {
              return domain.name;
            });
        assert.deepEqual(domains, ['test']);

        done();
      })
      .error(function(e) {
        done(e);
      });
  });

  test('missing domain name', function(done) {
    utils
      .run('cs-create-domain',
           '--database-path', temporaryDatabase.path)
      .next(function(result) {
        assert.equal(result.code, 1);
        assert.include(result.output.stdout,
                       'You must specify the domain name.');

        context.reopen();
        assert.deepEqual(Domain.getAll(context), []);

        done();
      })
      .error(function(e) {
        done(e);
      });
  });
});

suite('cs-describe-domain', function() {
  setup(commonSetup);
  teardown(commonTeardown);

  function report(domain, hostname) {
    return [
      'Domain Name               ' + domain.name,
      'Document Service Endpoint ' + domain.getDocumentsEndpoint(hostname),
      'Search Endpoint           ' + domain.getSearchEndpoint(hostname),
      'Searchable Documents      ' + domain.searchableDocumentsCount,
      'Index Fields              ' + domain.name,
      'SearchPartitionCount      ' + domain.searchPartitionCount,
      'SearchInstanceCount       ' + domain.searchInstanceCount,
      'SearchInstanceType        ' + domain.searchInstanceType
    ].join('\n');
  }

  test('describe one', function(done) {
    utils
      .run('cs-create-domain',
           '--domain-name', 'domain2',
           '--database-path', temporaryDatabase.path)
      .run('cs-create-domain',
           '--domain-name', 'domain1',
           '--database-path', temporaryDatabase.path)
      .run('cs-describe-domain',
           '--domain-name', 'domain1',
           '--database-path', temporaryDatabase.path)
      .next(function(result) {
        assert.equal(result.code, 0);
        assert.include(result.output.stdout,
                       report(new Domain('domain1', context), 'localhost'));

        done();
      })
      .error(function(e) {
        done(e);
      });
  });

  test('describe all', function(done) {
    utils
      .run('cs-create-domain',
           '--domain-name', 'domain2',
           '--database-path', temporaryDatabase.path)
      .run('cs-create-domain',
           '--domain-name', 'domain1',
           '--database-path', temporaryDatabase.path)
      .run('cs-describe-domain',
           '--show-all',
           '--database-path', temporaryDatabase.path)
      .next(function(result) {
        assert.equal(result.code, 0);
        assert.include(result.output.stdout,
                       report(new Domain('domain2', context), 'localhost'));
        assert.include(result.output.stdout,
                       report(new Domain('domain1', context), 'localhost'));

        done();
      })
      .error(function(e) {
        done(e);
      });
  });
});

suite('cs-configure-fields', function() {
  setup(commonSetup);
  teardown(commonTeardown);

  function testCreateField(done, name, type) {
    utils
      .run('cs-create-domain',
           '--domain-name', 'companies',
           '--database-path', temporaryDatabase.path)
      .run('cs-configure-fields',
           '--domain-name', 'companies',
           '--name', name,
           '--type', type,
           '--database-path', temporaryDatabase.path)
      .next(function(result) {
        assert.equal(result.code, 0);
        assert.equal(result.output.stdout,
                     'Updated 1 Index Field:\n' +
                     name + ' RequiresIndexDocuments ' + type + ' ()\n');

        context.reopen();
        var domain = new Domain('companies', context);
        var field = domain.getIndexField(name);
        assert.deepEqual({ type: field.type, exists: field.exists() },
                         { type: type, exists: true });

        done();
      })
      .error(function(e) {
        done(e);
      });
  }

  test('create text field', function(done) {
    testCreateField(done, 'name', 'text');
  });
  test('create uint field', function(done) {
    testCreateField(done, 'age', 'uint');
  });
  test('create literal field', function(done) {
    testCreateField(done, 'product', 'literal');
  });

  function testDeleteField(done, name, type) {
    utils
      .run('cs-create-domain',
           '--domain-name', 'companies',
           '--database-path', temporaryDatabase.path)
      .run('cs-configure-fields',
           '--domain-name', 'companies',
           '--name', name,
           '--type', type,
           '--database-path', temporaryDatabase.path)
      .run('cs-configure-fields',
           '--domain-name', 'companies',
           '--name', name,
           '--delete',
           '--database-path', temporaryDatabase.path)
      .next(function(result) {
        assert.equal(result.code, 0);
        assert.equal(result.output.stdout,
                     'Updated 1 Index Field:\n');

        context.reopen();
        var domain = new Domain('companies', context);
        var field = domain.getIndexField(name);
        assert.isFalse(field.exists());

        done();
      })
      .error(function(e) {
        done(e);
      });
  }

  test('delete text field', function(done) {
    testDeleteField(done, 'name', 'text');
  });
  test('delete uint field', function(done) {
    testDeleteField(done, 'age', 'uint');
  });
  test('delete literal field', function(done) {
    testDeleteField(done, 'product', 'literal');
  });

  function testRecreateField(done, name, type) {
    utils
      .run('cs-create-domain',
           '--domain-name', 'companies',
           '--database-path', temporaryDatabase.path)
      .run('cs-configure-fields',
           '--domain-name', 'companies',
           '--name', name,
           '--type', type,
           '--database-path', temporaryDatabase.path)
      .run('cs-configure-fields',
           '--domain-name', 'companies',
           '--name', name,
           '--type', type,
           '--database-path', temporaryDatabase.path)
      .next(function(result) {
        assert.equal(result.code, 1);
        assert.equal(result.output.stdout,
                     'You must specify not-existing field name.\n');
        done();
      })
      .error(function(e) {
        done(e);
      });
  }

  test('re-create text field', function(done) {
    testRecreateField(done, 'name', 'text');
  });
  test('re-create uint field', function(done) {
    testRecreateField(done, 'age', 'uint');
  });
  test('re-create literal field', function(done) {
    testRecreateField(done, 'product', 'literal');
  });

  test('delete not-existing field', function(done) {
    utils
      .run('cs-create-domain',
           '--domain-name', 'companies',
           '--database-path', temporaryDatabase.path)
      .run('cs-configure-fields',
           '--domain-name', 'companies',
           '--name', 'name',
           '--delete',
           '--database-path', temporaryDatabase.path)
      .next(function(result) {
        assert.equal(result.code, 1);
        assert.equal(result.output.stdout,
                     'You must specify an existing field.\n');
        done();
      })
      .error(function(e) {
        done(e);
      });
  });

  test('create field without type', function(done) {
    utils
      .run('cs-create-domain',
           '--domain-name', 'companies',
           '--database-path', temporaryDatabase.path)
      .run('cs-configure-fields',
           '--domain-name', 'companies',
           '--name', 'name',
           '--database-path', temporaryDatabase.path)
      .next(function(result) {
        assert.equal(result.code, 1);
        assert.equal(result.output.stdout,
                     'You must specify the field type.\n');
        done();
      })
      .error(function(e) {
        done(e);
      });
  });
});
<commit_msg>Add test for error case of cs-configure-fields<commit_after>var utils = require('./test-utils');
var assert = require('chai').assert;

var Domain = require('../lib/database/domain').Domain;

var context;
var temporaryDatabase;

function commonSetup() {
  temporaryDatabase = utils.createTemporaryDatabase();
  context = temporaryDatabase.get();
}

function commonTeardown() {
  context = undefined;
  temporaryDatabase.clear();
  temporaryDatabase.teardown();
  temporaryDatabase = undefined;
}

suite('cs-create-domain', function() {
  setup(commonSetup);
  teardown(commonTeardown);

  test('create', function(done) {
    utils
      .run('cs-create-domain',
           '--domain-name', 'test',
           '--database-path', temporaryDatabase.path)
      .next(function(result) {
        assert.equal(result.code, 0);
        assert.include(result.output.stdout,
                       'Domain endpoints are currently being created.');

        context.reopen();
        var domain = new Domain('test', context);
        assert.isTrue(domain.exists());

        done();
      })
      .error(function(e) {
        done(e);
      });
  });

  test('create again', function(done) {
    utils
      .run('cs-create-domain',
           '--domain-name', 'test',
           '--database-path', temporaryDatabase.path)
      .run('cs-create-domain',
           '--domain-name', 'test',
           '--database-path', temporaryDatabase.path)
      .next(function(result) {
        assert.equal(result.code, 1);
        assert.include(result.output.stdout,
                       'The domain [test] already exists.');

        context.reopen();
        var domains = Domain.getAll(context).map(function(domain) {
              return domain.name;
            });
        assert.deepEqual(domains, ['test']);

        done();
      })
      .error(function(e) {
        done(e);
      });
  });

  test('missing domain name', function(done) {
    utils
      .run('cs-create-domain',
           '--database-path', temporaryDatabase.path)
      .next(function(result) {
        assert.equal(result.code, 1);
        assert.include(result.output.stdout,
                       'You must specify the domain name.');

        context.reopen();
        assert.deepEqual(Domain.getAll(context), []);

        done();
      })
      .error(function(e) {
        done(e);
      });
  });
});

suite('cs-describe-domain', function() {
  setup(commonSetup);
  teardown(commonTeardown);

  function report(domain, hostname) {
    return [
      'Domain Name               ' + domain.name,
      'Document Service Endpoint ' + domain.getDocumentsEndpoint(hostname),
      'Search Endpoint           ' + domain.getSearchEndpoint(hostname),
      'Searchable Documents      ' + domain.searchableDocumentsCount,
      'Index Fields              ' + domain.name,
      'SearchPartitionCount      ' + domain.searchPartitionCount,
      'SearchInstanceCount       ' + domain.searchInstanceCount,
      'SearchInstanceType        ' + domain.searchInstanceType
    ].join('\n');
  }

  test('describe one', function(done) {
    utils
      .run('cs-create-domain',
           '--domain-name', 'domain2',
           '--database-path', temporaryDatabase.path)
      .run('cs-create-domain',
           '--domain-name', 'domain1',
           '--database-path', temporaryDatabase.path)
      .run('cs-describe-domain',
           '--domain-name', 'domain1',
           '--database-path', temporaryDatabase.path)
      .next(function(result) {
        assert.equal(result.code, 0);
        assert.include(result.output.stdout,
                       report(new Domain('domain1', context), 'localhost'));

        done();
      })
      .error(function(e) {
        done(e);
      });
  });

  test('describe all', function(done) {
    utils
      .run('cs-create-domain',
           '--domain-name', 'domain2',
           '--database-path', temporaryDatabase.path)
      .run('cs-create-domain',
           '--domain-name', 'domain1',
           '--database-path', temporaryDatabase.path)
      .run('cs-describe-domain',
           '--show-all',
           '--database-path', temporaryDatabase.path)
      .next(function(result) {
        assert.equal(result.code, 0);
        assert.include(result.output.stdout,
                       report(new Domain('domain2', context), 'localhost'));
        assert.include(result.output.stdout,
                       report(new Domain('domain1', context), 'localhost'));

        done();
      })
      .error(function(e) {
        done(e);
      });
  });
});

suite('cs-configure-fields', function() {
  setup(commonSetup);
  teardown(commonTeardown);

  function testCreateField(done, name, type) {
    utils
      .run('cs-create-domain',
           '--domain-name', 'companies',
           '--database-path', temporaryDatabase.path)
      .run('cs-configure-fields',
           '--domain-name', 'companies',
           '--name', name,
           '--type', type,
           '--database-path', temporaryDatabase.path)
      .next(function(result) {
        assert.deepEqual({ code:    result.code,
                           message: result.output.stdout },
                         { code:    0,
                           message: 'Updated 1 Index Field:\n' +
                                    name + ' RequiresIndexDocuments ' + type + ' ()\n' });

        context.reopen();
        var domain = new Domain('companies', context);
        var field = domain.getIndexField(name);
        assert.deepEqual({ type: field.type, exists: field.exists() },
                         { type: type, exists: true });

        done();
      })
      .error(function(e) {
        done(e);
      });
  }

  test('create text field', function(done) {
    testCreateField(done, 'name', 'text');
  });
  test('create uint field', function(done) {
    testCreateField(done, 'age', 'uint');
  });
  test('create literal field', function(done) {
    testCreateField(done, 'product', 'literal');
  });

  function testDeleteField(done, name, type) {
    utils
      .run('cs-create-domain',
           '--domain-name', 'companies',
           '--database-path', temporaryDatabase.path)
      .run('cs-configure-fields',
           '--domain-name', 'companies',
           '--name', name,
           '--type', type,
           '--database-path', temporaryDatabase.path)
      .run('cs-configure-fields',
           '--domain-name', 'companies',
           '--name', name,
           '--delete',
           '--database-path', temporaryDatabase.path)
      .next(function(result) {
        assert.deepEqual({ code:    result.code,
                           message: result.output.stdout },
                         { code:    0,
                           message: 'Updated 1 Index Field:\n' });

        context.reopen();
        var domain = new Domain('companies', context);
        var field = domain.getIndexField(name);
        assert.isFalse(field.exists());

        done();
      })
      .error(function(e) {
        done(e);
      });
  }

  test('delete text field', function(done) {
    testDeleteField(done, 'name', 'text');
  });
  test('delete uint field', function(done) {
    testDeleteField(done, 'age', 'uint');
  });
  test('delete literal field', function(done) {
    testDeleteField(done, 'product', 'literal');
  });

  function testRecreateField(done, name, type) {
    utils
      .run('cs-create-domain',
           '--domain-name', 'companies',
           '--database-path', temporaryDatabase.path)
      .run('cs-configure-fields',
           '--domain-name', 'companies',
           '--name', name,
           '--type', type,
           '--database-path', temporaryDatabase.path)
      .run('cs-configure-fields',
           '--domain-name', 'companies',
           '--name', name,
           '--type', type,
           '--database-path', temporaryDatabase.path)
      .next(function(result) {
        assert.deepEqual({ code:    result.code,
                           message: result.output.stdout },
                         { code:    1,
                           message: 'You must specify not-existing field name.\n' });
        done();
      })
      .error(function(e) {
        done(e);
      });
  }

  test('re-create text field', function(done) {
    testRecreateField(done, 'name', 'text');
  });
  test('re-create uint field', function(done) {
    testRecreateField(done, 'age', 'uint');
  });
  test('re-create literal field', function(done) {
    testRecreateField(done, 'product', 'literal');
  });

  test('delete not-existing field', function(done) {
    utils
      .run('cs-create-domain',
           '--domain-name', 'companies',
           '--database-path', temporaryDatabase.path)
      .run('cs-configure-fields',
           '--domain-name', 'companies',
           '--name', 'name',
           '--delete',
           '--database-path', temporaryDatabase.path)
      .next(function(result) {
        assert.deepEqual({ code:    result.code,
                           message: result.output.stdout },
                         { code:    1,
                           message: 'You must specify an existing field.\n' });
        done();
      })
      .error(function(e) {
        done(e);
      });
  });

  test('create field without type', function(done) {
    utils
      .run('cs-create-domain',
           '--domain-name', 'companies',
           '--database-path', temporaryDatabase.path)
      .run('cs-configure-fields',
           '--domain-name', 'companies',
           '--name', 'name',
           '--database-path', temporaryDatabase.path)
      .next(function(result) {
        assert.deepEqual({ code:    result.code,
                           message: result.output.stdout },
                         { code:    1,
                           message: 'You must specify the field type.\n' });
        done();
      })
      .error(function(e) {
        done(e);
      });
  });

  test('create field without domain', function(done) {
    utils
      .run('cs-configure-fields',
           '--name', 'name',
           '--database-path', temporaryDatabase.path)
      .next(function(result) {
        assert.deepEqual({ code:    result.code,
                           message: result.output.stdout },
                         { code:    1,
                           message: 'You must specify an existing domain name.\n' });
        done();
      })
      .error(function(e) {
        done(e);
      });
  });
});
<|endoftext|>


<commit_before>/* global protractor, describe, beforeEach, it, expect, browser, element, by */
'use strict';

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

describe('register.', function() {
    var ptor;

    beforeEach(function() {
        // Tell backend to reload the fixtures
        browser.get('test/e2e/bridge.html#/basic');

        // Go to the app
        browser.get('app/index.html#/');
        ptor = protractor.getInstance();

        // TODO: not so great to logout before every test
        var menuButton = element(by.css('button.menuButton'));
        menuButton.click();
        browser.sleep(helpers.MENU_DELAY);
        var logoutButton = element(by.css('button.navLogout'));
        logoutButton.isDisplayed().then(function(isDisplayed) {
            if (isDisplayed) {
                logoutButton.click();
            }
            else {
                menuButton.click();
            }
        });
    });

    it('should have a link to the register form.', function() {
        element(by.css('button.menuButton')).click();
        browser.sleep(helpers.MENU_DELAY);
        var button = element.all(by.css('.navRegister'));
        expect(button.count()).toBe(1);

        button.first().click();
        expect(ptor.getCurrentUrl()).toMatch(/\/register/);
    });

    it('should be possible to register as a new user.', function() {
        browser.get('app/index.html#/register');

        element(by.model('form.email')).sendKeys('cody@testerburger.com');
        element(by.model('form.fullName')).sendKeys('Cody Testerburger');
        element(by.model('form.password')).sendKeys('so secure brah');
        element(by.model('form.passwordRepeat')).sendKeys('so secure brah\n');
        expect(element.all(by.css('.alert-success')).count()).toBe(1, 'should have a success message');

        // Should show a social graph with me and two dummies and no connections
        expect(ptor.getCurrentUrl()).toMatch(/\/socialGraph/);
        expect(element.all(by.css('social-graph .node')).count()).toBe(3, 'total nodes');
        expect(element.all(by.css('social-graph .link')).count()).toBe(0, 'total links');
    });
});
<commit_msg>Failing test for setting nickname when registering<commit_after>/* global protractor, describe, beforeEach, it, expect, browser, element, by */
'use strict';

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

describe('register.', function() {
    var ptor;

    beforeEach(function() {
        // Tell backend to reload the fixtures
        browser.get('test/e2e/bridge.html#/basic');

        // Go to the app
        browser.get('app/index.html#/');
        ptor = protractor.getInstance();

        // TODO: not so great to logout before every test
        var menuButton = element(by.css('button.menuButton'));
        menuButton.click();
        browser.sleep(helpers.MENU_DELAY);
        var logoutButton = element(by.css('button.navLogout'));
        logoutButton.isDisplayed().then(function(isDisplayed) {
            if (isDisplayed) {
                logoutButton.click();
            }
            else {
                menuButton.click();
            }
        });
    });

    it('should have a link to the register form.', function() {
        element(by.css('button.menuButton')).click();
        browser.sleep(helpers.MENU_DELAY);
        var button = element.all(by.css('.navRegister'));
        expect(button.count()).toBe(1);

        button.first().click();
        expect(ptor.getCurrentUrl()).toMatch(/\/register/);
    });

    it('should be possible to register as a new user.', function() {
        browser.get('app/index.html#/register');

        element(by.model('form.email')).sendKeys('cody@testerburger.com');
        element(by.model('form.fullName')).sendKeys('Cody Testerburger');
        element(by.model('form.nickname')).sendKeys('The Cody');
        element(by.model('form.password')).sendKeys('so secure brah');
        element(by.model('form.passwordRepeat')).sendKeys('so secure brah\n');
        expect(element.all(by.css('.alert-success')).count()).toBe(1, 'should have a success message');

        // Should show a social graph with me and two dummies and no connections
        expect(ptor.getCurrentUrl()).toMatch(/\/socialGraph/);
        expect(element.all(by.css('social-graph .node')).count()).toBe(3, 'total nodes');
        expect(element.all(by.css('social-graph .link')).count()).toBe(0, 'total links');
    });
});
<|endoftext|>


<commit_before>
var expect = require('expect.js');
var eio = require('../');

describe('engine.io-client', function () {
  var open;

  before(function() {
    open = eio.prototype.open;
    // override Socket#open to not connect
    eio.prototype.open = function() {};
  });

  after(function() {
    eio.prototype.open = open;
  });

  it('should expose protocol number', function () {
    expect(eio.protocol).to.be.a('number');
  });

  it('should properly parse http uri without port', function() {
    var client = eio('http://localhost');
    expect(client.port).to.be('80');
  });

  it('should properly parse https uri without port', function() {
    var client = eio('https://localhost');
    expect(client.hostname).to.be('localhost');
    expect(client.port).to.be('443');
  });

  it('should properly parse wss uri without port', function() {
    var client = eio('wss://localhost');
    expect(client.hostname).to.be('localhost');
    expect(client.port).to.be('443');
  });

  it('should properly parse wss uri with port', function() {
    var client = eio('wss://localhost:2020');
    expect(client.hostname).to.be('localhost');
    expect(client.port).to.be('2020');
  });

  it('should properly parse a host without port', function() {
    var client = eio({ host: 'localhost' });
    expect(client.hostname).to.be('localhost');
    expect(client.port).to.be('80');
  });

  it('should properly parse a host with port', function() {
    var client = eio({ host: 'localhost', port: '8080' });
    expect(client.hostname).to.be('localhost');
    expect(client.port).to.be('8080');
  });

  it('should properly parse an IPv6 uri without port', function() {
    var client = eio('http://[::1]');
    expect(client.hostname).to.be('::1');
    expect(client.port).to.be('80');
  });

  it('should properly parse an IPv6 uri with port', function() {
    var client = eio('http://[::1]:8080');
    expect(client.hostname).to.be('::1');
    expect(client.port).to.be('8080');
  });

  it('should properly parse an IPv6 host without port (1/2)', function() {
    var client = eio({ host: '[::1]' });
    expect(client.hostname).to.be('::1');
    expect(client.port).to.be('80');
  });

  it('should properly parse an IPv6 host without port (2/2)', function() {
    var client = eio({ secure: true, host: '[::1]' });
    expect(client.hostname).to.be('::1');
    expect(client.port).to.be('443');
  });

  it('should properly parse an IPv6 host with port', function() {
    var client = eio({ host: '[::1]', port: '8080' });
    expect(client.hostname).to.be('::1');
    expect(client.port).to.be('8080');
  });

});
<commit_msg>add a test<commit_after>
var expect = require('expect.js');
var eio = require('../');

describe('engine.io-client', function () {
  var open;

  before(function() {
    open = eio.prototype.open;
    // override Socket#open to not connect
    eio.prototype.open = function() {};
  });

  after(function() {
    eio.prototype.open = open;
  });

  it('should expose protocol number', function () {
    expect(eio.protocol).to.be.a('number');
  });

  it('should properly parse http uri without port', function() {
    var client = eio('http://localhost');
    expect(client.port).to.be('80');
  });

  it('should properly parse https uri without port', function() {
    var client = eio('https://localhost');
    expect(client.hostname).to.be('localhost');
    expect(client.port).to.be('443');
  });

  it('should properly parse wss uri without port', function() {
    var client = eio('wss://localhost');
    expect(client.hostname).to.be('localhost');
    expect(client.port).to.be('443');
  });

  it('should properly parse wss uri with port', function() {
    var client = eio('wss://localhost:2020');
    expect(client.hostname).to.be('localhost');
    expect(client.port).to.be('2020');
  });

  it('should properly parse a host without port', function() {
    var client = eio({ host: 'localhost' });
    expect(client.hostname).to.be('localhost');
    expect(client.port).to.be('80');
  });

  it('should properly parse a host with port', function() {
    var client = eio({ host: 'localhost', port: '8080' });
    expect(client.hostname).to.be('localhost');
    expect(client.port).to.be('8080');
  });

  it('should properly parse an IPv6 uri without port', function() {
    var client = eio('http://[::1]');
    expect(client.hostname).to.be('::1');
    expect(client.port).to.be('80');
  });

  it('should properly parse an IPv6 uri with port', function() {
    var client = eio('http://[::1]:8080');
    expect(client.hostname).to.be('::1');
    expect(client.port).to.be('8080');
  });

  it('should properly parse an IPv6 host without port (1/2)', function() {
    var client = eio({ host: '[::1]' });
    expect(client.hostname).to.be('::1');
    expect(client.port).to.be('80');
  });

  it('should properly parse an IPv6 host without port (2/2)', function() {
    var client = eio({ secure: true, host: '[::1]' });
    expect(client.hostname).to.be('::1');
    expect(client.port).to.be('443');
  });

  it('should properly parse an IPv6 host with port', function() {
    var client = eio({ host: '[::1]', port: '8080' });
    expect(client.hostname).to.be('::1');
    expect(client.port).to.be('8080');
  });

  it('should properly parse an IPv6 host without brace', function() {
    var client = eio({ host: '::1' });
    expect(client.hostname).to.be('::1');
    expect(client.port).to.be('80');
  });
});
<|endoftext|>


<commit_before>var basic   = require('../../lib/index'),
    http    = require('http');

var auth    = basic(function (user, pass, callback) {
    if (user === 'let' && pass === 'me in') return callback(null);
    callback(401);
});

http.createServer(function (req, res) {
    auth(req, res, function (err) {
        if (err) {
            res.writeHead(err);
            res.end();
        }

        res.writeHead(200);
        res.end();
    });
}).listen(8000);<commit_msg>Update example<commit_after>var basic   = require('../../lib/index'),
    http    = require('http');

var auth    = basic(function (user, pass, callback) {
    if (user === 'let' && pass === 'me in') return callback(null);
    callback(401);
});

http.createServer(function (req, res) {
    auth(req, res, function (err) {
        res.writeHead(err || 200);
        res.end();
    });
}).listen(8000);<|endoftext|>


<commit_before>'use strict';

require('dotenv').config({path: `${__dirname}/../.test.env`});
require('./lib/mock-aws.js');
const superagent = require('superagent');
const expect = require('expect');
const faker = require('faker');

const clearDB = require('./lib/clearDB.js');
const mockGoat = require('./lib/mock-goat.js');
const mockGuardian = require('./lib/mock-guardian.js');

const server = require('../lib/server.js');
const API_URL = process.env.API_URL;

describe('testing routes for goat model', () => {
  before(server.start);
  after(server.stop);
  afterEach(clearDB);

  describe('testing POST /api/goats', () => {
    it('should return a new goat and respond with 200', () => {
      let tempData;
      let tempAddress = faker.address.streetAddress();
      let tempCity = faker.address.city();
      let tempState = faker.address.stateAbbr();
      let tempStory = faker.lorem.sentence();
      return mockGuardian.createOne()
        .then((userGuardData) => {
          tempData = userGuardData;
          return superagent.post(`${API_URL}/api/goats`)
            .set('Authorization', `Bearer ${tempData.user.token}`)
            .field('address', tempAddress)
            .field('city', tempCity)
            .field('state', tempState)
            .field('story', tempStory)
            .field('guardianID', tempData.guardian._id.toString())
            .attach('image', `${__dirname}/test-assets/goat.jpg`)
            .then((res) => {
              expect(res.status).toEqual(200);
              expect(res.body.address).toEqual(tempAddress);
              expect(res.body.city).toEqual(tempCity);
              expect(res.body.state).toEqual(tempState);
              expect(res.body.photoURI).toExist();
              expect(res.body.story).toEqual(tempStory);
              expect(res.body.guardianID).toEqual(tempData.guardian._id);
              expect(res.body.userID).toEqual(tempData.user.user._id);
            });
        });
    });
    it('should return a 400 error due to missing field address', () => {
      let tempData;
      let tempCity = faker.address.city();
      let tempState = faker.address.stateAbbr();
      let tempStory = faker.lorem.sentence();
      return mockGuardian.createOne()
        .then((userGuardData) => {
          tempData = userGuardData;
          return superagent.post(`${API_URL}/api/goats`)
            .set('Authorization', `Bearer ${tempData.user.token}`)
            .field('city', tempCity)
            .field('state', tempState)
            .field('story', tempStory)
            .field('guardianID', tempData.guardian._id.toString())
            .attach('image', `${__dirname}/test-assets/goat.jpg`)
            .catch((res) => {
              expect(res.status).toEqual(400);
            });
        });
    });
    it('should return a 401 unauthorized error due to missing Authorization header', () => {
      let tempData;
      let tempAddress = faker.address.streetAddress();
      let tempCity = faker.address.city();
      let tempState = faker.address.stateAbbr();
      let tempStory = faker.lorem.sentence();
      return mockGuardian.createOne()
        .then((userGuardData) => {
          tempData = userGuardData;
          return superagent.post(`${API_URL}/api/goats`)
            .set('potato', `Bearer ${tempData.user.token}`)
            .field('address', tempAddress)
            .field('city', tempCity)
            .field('state', tempState)
            .field('story', tempStory)
            .field('guardianID', tempData.guardian._id.toString())
            .attach('image', `${__dirname}/test-assets/goat.jpg`)
            .catch((res) => {
              expect(res.status).toEqual(401);
            });
        });
    });
    it('should return a 415 due to unexpected field', () => {
      let tempData;
      let tempAddress = faker.address.streetAddress();
      let tempCity = faker.address.city();
      let tempState = faker.address.stateAbbr();
      let tempStory = faker.lorem.sentence();
      return mockGuardian.createOne()
        .then((userGuardData) => {
          tempData = userGuardData;
          return superagent.post(`${API_URL}/api/goats`)
            .set('Authorization', `Bearer ${tempData.user.token}`)
            .field('address', tempAddress)
            .field('city', tempCity)
            .field('state', tempState)
            .field('story', tempStory)
            .field('guardianID', tempData.guardian._id.toString())
            .attach('potato', `${__dirname}/test-assets/goat.jpg`)
            .catch((res) => {
              expect(res.status).toEqual(415);
            });
        });
    });
    it('should return a 400 due to malformed jwt', () => {
      let tempData;
      let tempAddress = faker.address.streetAddress();
      let tempCity = faker.address.city();
      let tempState = faker.address.stateAbbr();
      let tempStory = faker.lorem.sentence();
      return mockGuardian.createOne()
        .then((userGuardData) => {
          tempData = userGuardData;
          return superagent.post(`${API_URL}/api/goats`)
            .set('Authorization', `Bearer cars`)
            .field('address', tempAddress)
            .field('city', tempCity)
            .field('state', tempState)
            .field('story', tempStory)
            .field('guardianID', tempData.guardian._id.toString())
            .attach('potato', `${__dirname}/test-assets/goat.jpg`)
            .catch((res) => {
              expect(res.status).toEqual(400);
            });
        });
    });
  });
  describe('testing GET /api/goats/:id', () => {
    it('should respond with a 200 and a goat message', () => {
      let tempData;
      return mockGoat.createOne()
        .then((userGuardGoatData) => {
          tempData = userGuardGoatData;
          return superagent.get(`${API_URL}/api/goats/${userGuardGoatData.goat._id}`)
            .set('Authorization', `Bearer ${tempData.user.token}`)
            .then((res) => {
              expect(res.status).toEqual(200);
              expect(res.body.address).toEqual(tempData.goat.address);
              expect(res.body.city).toEqual(tempData.goat.city);
              expect(res.body.state).toEqual(tempData.goat.state);
              expect(res.body.story).toEqual(tempData.goat.story);
              expect(res.body.userID).toEqual(tempData.goat.userID);
              expect(res.body.guardianID).toEqual(tempData.goat.guardianID);
              expect(res.body.photoURI).toExist();
            });
        });
    });
    it('should respond with a 404 due to bad :id in url', () => {
      let tempData;
      return mockGoat.createOne()
        .then((userGuardGoatData) => {
          tempData = userGuardGoatData;
          return superagent.get(`${API_URL}/api/goats/carboy`)
            .set('Authorization', `Bearer ${tempData.user.token}`)
            .catch((res) => {
              expect(res.status).toEqual(404);
            });
        });
    });
    it('should respond with a 401 due to bad authorization header', () => {
      let tempData;
      return mockGoat.createOne()
        .then((userGuardGoatData) => {
          tempData = userGuardGoatData;
          return superagent.get(`${API_URL}/api/goats/${userGuardGoatData.goat._id}`)
            .set('coolshoes', `Bearer ${tempData.user.token}`)
            .catch((res) => {
              expect(res.status).toEqual(401);
            });
        });
    });
  });
  describe('testing PUT at /api/goats/:id', () => {
    it('should respond with 200 and updated goat body', () => {
      let tempData;
      let tempGoat = {
        address: faker.address.streetAddress(),
        city: faker.address.city(),
        state: faker.address.stateAbbr(),
        story: faker.lorem.sentence(),
      };
      return mockGoat.createOne()
        .then((userGuardGoatData) => {
          tempData = userGuardGoatData;
          return superagent.put(`${API_URL}/api/goats/${userGuardGoatData.goat._id}`)
            .set('Authorization', `Bearer ${tempData.user.token}`)
            .send(tempGoat)
            .then((res) => {
              expect(res.status).toEqual(200);
              expect(res.body.address).toEqual(tempGoat.address);
              expect(res.body.city).toEqual(tempGoat.city);
              expect(res.body.state).toEqual(tempGoat.state);
              expect(res.body.story).toEqual(tempGoat.story);
              expect(res.body.userID).toEqual(tempData.goat.userID);
              expect(res.body.guardianID).toEqual(tempData.goat.guardianID);
              expect(res.body.photoURI).toExist();
            });
        });
    });
    it('should respond with 404 due to bad :id', () => {
      let tempData;
      let tempGoat = {
        address: faker.address.streetAddress(),
        city: faker.address.city(),
        state: faker.address.stateAbbr(),
        story: faker.lorem.sentence(),
      };
      return mockGoat.createOne()
        .then((userGuardGoatData) => {
          tempData = userGuardGoatData;
          return superagent.put(`${API_URL}/api/goats/dogshow`)
            .set('Authorization', `Bearer ${tempData.user.token}`)
            .send(tempGoat)
            .catch((res) => {
              expect(res.status).toEqual(404);
            });
        });
    });
    it('should respond with 401 due to no authorization header', () => {
      let tempData;
      let tempGoat = {
        address: faker.address.streetAddress(),
        city: faker.address.city(),
        state: faker.address.stateAbbr(),
        story: faker.lorem.sentence(),
      };
      return mockGoat.createOne()
        .then((userGuardGoatData) => {
          tempData = userGuardGoatData;
          return superagent.put(`${API_URL}/api/goats/${userGuardGoatData.goat._id}`)
            .set('yeaaaaabooooiiii', `Bearer ${tempData.user.token}`)
            .send(tempGoat)
            .catch((res) => {
              expect(res.status).toEqual(401);
            });
        });
    });
  });
  describe('testing DELETE at /api/goats/:id', () => {
    it('should respond with 204 and delete the goat, then a 404 when attempt to GET goat', () => {
      let tempData;
      return mockGoat.createOne()
        .then((userGuardGoatData) => {
          tempData = userGuardGoatData;
          return superagent.delete(`${API_URL}/api/goats/${userGuardGoatData.goat._id}`)
            .set('Authorization', `Bearer ${tempData.user.token}`)
            .then((res) => {
              expect(res.status).toEqual(204);
            })
            .then((res) => {
              return superagent.get(`${API_URL}/api/goats/${tempData.goat._id}`)
                .set('Authorization', `Bearer ${tempData.user.token}`)
                .catch((err) => {
                  expect(err.status).toEqual(404);
                });
            });
        });
    });
    it('should respond with 404 due to missing id', () => {
      let tempData;
      return mockGoat.createOne()
        .then((userGuardGoatData) => {
          tempData = userGuardGoatData;
          return superagent.delete(`${API_URL}/api/goats/uhohspaghettios`)
            .set('Authorization', `Bearer ${tempData.user.token}`)
            .catch((res) => {
              expect(res.status).toEqual(404);
            });
        });
    });
    it('should respond with 401 due to bad auth', () => {
      let tempData;
      return mockGoat.createOne()
        .then((userGuardGoatData) => {
          tempData = userGuardGoatData;
          return superagent.delete(`${API_URL}/api/goats/${userGuardGoatData.goat._id}`)
            .set('potatohouse', `Bearer ${tempData.user.token}`)
            .catch((res) => {
              expect(res.status).toEqual(401);
            });
        });
    });
  });
});
<commit_msg>dustin-test-for-goat-router-PUT-400<commit_after>'use strict';

require('dotenv').config({path: `${__dirname}/../.test.env`});
require('./lib/mock-aws.js');
const superagent = require('superagent');
const expect = require('expect');
const faker = require('faker');

const clearDB = require('./lib/clearDB.js');
const mockGoat = require('./lib/mock-goat.js');
const mockGuardian = require('./lib/mock-guardian.js');

const server = require('../lib/server.js');
const API_URL = process.env.API_URL;

describe('testing routes for goat model', () => {
  before(server.start);
  after(server.stop);
  afterEach(clearDB);

  describe('testing POST /api/goats', () => {
    it('should return a new goat and respond with 200', () => {
      let tempData;
      let tempAddress = faker.address.streetAddress();
      let tempCity = faker.address.city();
      let tempState = faker.address.stateAbbr();
      let tempStory = faker.lorem.sentence();
      return mockGuardian.createOne()
        .then((userGuardData) => {
          tempData = userGuardData;
          return superagent.post(`${API_URL}/api/goats`)
            .set('Authorization', `Bearer ${tempData.user.token}`)
            .field('address', tempAddress)
            .field('city', tempCity)
            .field('state', tempState)
            .field('story', tempStory)
            .field('guardianID', tempData.guardian._id.toString())
            .attach('image', `${__dirname}/test-assets/goat.jpg`)
            .then((res) => {
              expect(res.status).toEqual(200);
              expect(res.body.address).toEqual(tempAddress);
              expect(res.body.city).toEqual(tempCity);
              expect(res.body.state).toEqual(tempState);
              expect(res.body.photoURI).toExist();
              expect(res.body.story).toEqual(tempStory);
              expect(res.body.guardianID).toEqual(tempData.guardian._id);
              expect(res.body.userID).toEqual(tempData.user.user._id);
            });
        });
    });
    it('should return a 400 error due to missing field address', () => {
      let tempData;
      let tempCity = faker.address.city();
      let tempState = faker.address.stateAbbr();
      let tempStory = faker.lorem.sentence();
      return mockGuardian.createOne()
        .then((userGuardData) => {
          tempData = userGuardData;
          return superagent.post(`${API_URL}/api/goats`)
            .set('Authorization', `Bearer ${tempData.user.token}`)
            .field('city', tempCity)
            .field('state', tempState)
            .field('story', tempStory)
            .field('guardianID', tempData.guardian._id.toString())
            .attach('image', `${__dirname}/test-assets/goat.jpg`)
            .catch((res) => {
              expect(res.status).toEqual(400);
            });
        });
    });
    it('should return a 401 unauthorized error due to missing Authorization header', () => {
      let tempData;
      let tempAddress = faker.address.streetAddress();
      let tempCity = faker.address.city();
      let tempState = faker.address.stateAbbr();
      let tempStory = faker.lorem.sentence();
      return mockGuardian.createOne()
        .then((userGuardData) => {
          tempData = userGuardData;
          return superagent.post(`${API_URL}/api/goats`)
            .set('potato', `Bearer ${tempData.user.token}`)
            .field('address', tempAddress)
            .field('city', tempCity)
            .field('state', tempState)
            .field('story', tempStory)
            .field('guardianID', tempData.guardian._id.toString())
            .attach('image', `${__dirname}/test-assets/goat.jpg`)
            .catch((res) => {
              expect(res.status).toEqual(401);
            });
        });
    });
    it('should return a 415 due to unexpected field', () => {
      let tempData;
      let tempAddress = faker.address.streetAddress();
      let tempCity = faker.address.city();
      let tempState = faker.address.stateAbbr();
      let tempStory = faker.lorem.sentence();
      return mockGuardian.createOne()
        .then((userGuardData) => {
          tempData = userGuardData;
          return superagent.post(`${API_URL}/api/goats`)
            .set('Authorization', `Bearer ${tempData.user.token}`)
            .field('address', tempAddress)
            .field('city', tempCity)
            .field('state', tempState)
            .field('story', tempStory)
            .field('guardianID', tempData.guardian._id.toString())
            .attach('potato', `${__dirname}/test-assets/goat.jpg`)
            .catch((res) => {
              expect(res.status).toEqual(415);
            });
        });
    });
    it('should return a 400 due to malformed jwt', () => {
      let tempData;
      let tempAddress = faker.address.streetAddress();
      let tempCity = faker.address.city();
      let tempState = faker.address.stateAbbr();
      let tempStory = faker.lorem.sentence();
      return mockGuardian.createOne()
        .then((userGuardData) => {
          tempData = userGuardData;
          return superagent.post(`${API_URL}/api/goats`)
            .set('Authorization', `Bearer cars`)
            .field('address', tempAddress)
            .field('city', tempCity)
            .field('state', tempState)
            .field('story', tempStory)
            .field('guardianID', tempData.guardian._id.toString())
            .attach('potato', `${__dirname}/test-assets/goat.jpg`)
            .catch((res) => {
              expect(res.status).toEqual(400);
            });
        });
    });
  });
  describe('testing GET /api/goats/:id', () => {
    it('should respond with a 200 and a goat message', () => {
      let tempData;
      return mockGoat.createOne()
        .then((userGuardGoatData) => {
          tempData = userGuardGoatData;
          return superagent.get(`${API_URL}/api/goats/${userGuardGoatData.goat._id}`)
            .set('Authorization', `Bearer ${tempData.user.token}`)
            .then((res) => {
              expect(res.status).toEqual(200);
              expect(res.body.address).toEqual(tempData.goat.address);
              expect(res.body.city).toEqual(tempData.goat.city);
              expect(res.body.state).toEqual(tempData.goat.state);
              expect(res.body.story).toEqual(tempData.goat.story);
              expect(res.body.userID).toEqual(tempData.goat.userID);
              expect(res.body.guardianID).toEqual(tempData.goat.guardianID);
              expect(res.body.photoURI).toExist();
            });
        });
    });
    it('should respond with a 404 due to bad :id in url', () => {
      let tempData;
      return mockGoat.createOne()
        .then((userGuardGoatData) => {
          tempData = userGuardGoatData;
          return superagent.get(`${API_URL}/api/goats/carboy`)
            .set('Authorization', `Bearer ${tempData.user.token}`)
            .catch((res) => {
              expect(res.status).toEqual(404);
            });
        });
    });
    it('should respond with a 401 due to bad authorization header', () => {
      let tempData;
      return mockGoat.createOne()
        .then((userGuardGoatData) => {
          tempData = userGuardGoatData;
          return superagent.get(`${API_URL}/api/goats/${userGuardGoatData.goat._id}`)
            .set('coolshoes', `Bearer ${tempData.user.token}`)
            .catch((res) => {
              expect(res.status).toEqual(401);
            });
        });
    });
  });
  describe('testing PUT at /api/goats/:id', () => {
    it('should respond with 200 and updated goat body', () => {
      let tempData;
      let tempGoat = {
        address: faker.address.streetAddress(),
        city: faker.address.city(),
        state: faker.address.stateAbbr(),
        story: faker.lorem.sentence(),
      };
      return mockGoat.createOne()
        .then((userGuardGoatData) => {
          tempData = userGuardGoatData;
          return superagent.put(`${API_URL}/api/goats/${userGuardGoatData.goat._id}`)
            .set('Authorization', `Bearer ${tempData.user.token}`)
            .send(tempGoat)
            .then((res) => {
              expect(res.status).toEqual(200);
              expect(res.body.address).toEqual(tempGoat.address);
              expect(res.body.city).toEqual(tempGoat.city);
              expect(res.body.state).toEqual(tempGoat.state);
              expect(res.body.story).toEqual(tempGoat.story);
              expect(res.body.userID).toEqual(tempData.goat.userID);
              expect(res.body.guardianID).toEqual(tempData.goat.guardianID);
              expect(res.body.photoURI).toExist();
            });
        });
    });
    it('should respond with 404 due to bad :id', () => {
      let tempData;
      let tempGoat = {
        address: faker.address.streetAddress(),
        city: faker.address.city(),
        state: faker.address.stateAbbr(),
        story: faker.lorem.sentence(),
      };
      return mockGoat.createOne()
        .then((userGuardGoatData) => {
          tempData = userGuardGoatData;
          return superagent.put(`${API_URL}/api/goats/dogshow`)
            .set('Authorization', `Bearer ${tempData.user.token}`)
            .send(tempGoat)
            .catch((res) => {
              expect(res.status).toEqual(404);
            });
        });
    });
    it('should respond with 401 due to no authorization header', () => {
      let tempData;
      let tempGoat = {
        address: faker.address.streetAddress(),
        city: faker.address.city(),
        state: faker.address.stateAbbr(),
        story: faker.lorem.sentence(),
      };
      return mockGoat.createOne()
        .then((userGuardGoatData) => {
          tempData = userGuardGoatData;
          return superagent.put(`${API_URL}/api/goats/${userGuardGoatData.goat._id}`)
            .set('yeaaaaabooooiiii', `Bearer ${tempData.user.token}`)
            .send(tempGoat)
            .catch((res) => {
              expect(res.status).toEqual(401);
            });
        });
    });
  });
  describe('testing DELETE at /api/goats/:id', () => {
    it('should respond with 204 and delete the goat, then a 404 when attempt to GET goat', () => {
      let tempData;
      return mockGoat.createOne()
        .then((userGuardGoatData) => {
          tempData = userGuardGoatData;
          return superagent.delete(`${API_URL}/api/goats/${userGuardGoatData.goat._id}`)
            .set('Authorization', `Bearer ${tempData.user.token}`)
            .then((res) => {
              expect(res.status).toEqual(204);
            })
            .then((res) => {
              return superagent.get(`${API_URL}/api/goats/${tempData.goat._id}`)
                .set('Authorization', `Bearer ${tempData.user.token}`)
                .catch((err) => {
                  expect(err.status).toEqual(404);
                });
            });
        });
    });
    it('should respond with 404 due to missing id', () => {
      let tempData;
      return mockGoat.createOne()
        .then((userGuardGoatData) => {
          tempData = userGuardGoatData;
          return superagent.delete(`${API_URL}/api/goats/uhohspaghettios`)
            .set('Authorization', `Bearer ${tempData.user.token}`)
            .catch((res) => {
              expect(res.status).toEqual(404);
            });
        });
    });
    it('should respond with 401 due to bad auth', () => {
      let tempData;
      return mockGoat.createOne()
        .then((userGuardGoatData) => {
          tempData = userGuardGoatData;
          return superagent.delete(`${API_URL}/api/goats/${userGuardGoatData.goat._id}`)
            .set('potatohouse', `Bearer ${tempData.user.token}`)
            .catch((res) => {
              expect(res.status).toEqual(401);
            });
        });
    });
    it('should respond with 400 due to lack of keys', () => {
      let tempData;
      let tempGoat = {};
      return mockGoat.createOne()
        .then((userGuardGoatData) => {
          tempData = userGuardGoatData;
          return superagent.put(`${API_URL}/api/goats/${userGuardGoatData.goat._id}`)
            .set('Authorization', `Bearer ${tempData.user.token}`)
            .send(tempGoat)
            .catch((res) => {
              expect(res.status).toEqual(400);
            });
        });
    });
  });
});
<|endoftext|>


<commit_before>import {HttpClient} from '../src/http-client';

describe('HttpClient', () => {
  let originalFetch = window.fetch;
  let client;
  let fetch;

  function setUpTests() {
    beforeEach(() => {
      client = new HttpClient();
      fetch = window.fetch = jasmine.createSpy('fetch');
    });

    afterEach(() => {
      fetch = window.fetch = originalFetch;
    });
  }

  setUpTests();

  it('makes requests', (done) => {
    fetch.and.returnValue(emptyResponse(200));

    client
      .fetch('http://example.com/some/cool/path')
      .then(result => {
        expect(result.ok).toBe(true);
      })
      .catch(result => {
        expect(result).not.toBe(result);
      })
      .then(() => {
        expect(fetch).toHaveBeenCalled();
        done();
      });
  });

  describe('interceptors', () => {
    setUpTests();

    it('run on request', (done) => {
      fetch.and.returnValue(emptyResponse(200));
      let interceptor = { request(r) { return r; }, requestError(r) { throw r; } };
      spyOn(interceptor, 'request').and.callThrough();
      spyOn(interceptor, 'requestError').and.callThrough();

      client.interceptors.push(interceptor);

      client.fetch('path')
        .then(() => {
          expect(interceptor.request).toHaveBeenCalledWith(jasmine.any(Request));
          expect(interceptor.requestError).not.toHaveBeenCalled();
          done();
        });
    });

    it('run on request error', (done) => {
      fetch.and.returnValue(emptyResponse(200));
      let interceptor = { request(r) { return r; }, requestError(r) { throw r; } };
      spyOn(interceptor, 'request').and.callThrough();
      spyOn(interceptor, 'requestError').and.callThrough();

      client.interceptors.push({ request() { return Promise.reject(new Error('test')); }});
      client.interceptors.push(interceptor);

      client.fetch()
        .catch(() => {
          expect(interceptor.request).not.toHaveBeenCalled();
          expect(interceptor.requestError).toHaveBeenCalledWith(jasmine.any(Error));
          done();
        });
    });

    it('run on response', (done) => {
      fetch.and.returnValue(emptyResponse(200));
      let interceptor = { response(r) { return r; }, responseError(r) { throw r; } };
      spyOn(interceptor, 'response').and.callThrough();
      spyOn(interceptor, 'responseError').and.callThrough();

      client.interceptors.push(interceptor);

      client.fetch('path')
        .then(() => {
          expect(interceptor.response).toHaveBeenCalledWith(jasmine.any(Response));
          expect(interceptor.responseError).not.toHaveBeenCalled();
          done();
        });
    });

    it('run on response error', (done) => {
      fetch.and.returnValue(Promise.reject(Response.error()));
      let interceptor = { response(r) { return r; }, responseError(r) { throw r; } };
      spyOn(interceptor, 'response').and.callThrough();
      spyOn(interceptor, 'responseError').and.callThrough();

      client.interceptors.push(interceptor);

      client.fetch('path')
        .catch(() => {
          expect(interceptor.response).not.toHaveBeenCalled();
          expect(interceptor.responseError).toHaveBeenCalledWith(jasmine.any(Response));
          done();
        });
    });

    it('normalizes input for interceptors', (done) => {
      fetch.and.returnValue(emptyResponse(200));
      let request;
      client.interceptors.push({ request(r) { request = r; return r; } });

      client
        .fetch('http://example.com/some/cool/path')
        .then(() => {
          expect(request instanceof Request).toBe(true);
          done();
        });
    });

    it('runs multiple interceptors', (done) => {
      fetch.and.returnValue(emptyResponse(200));
      let first = { request(r) { return r; } };
      let second = { request(r) { return r; } };
      spyOn(first, 'request').and.callThrough();
      spyOn(second, 'request').and.callThrough();

      client.interceptors.push(first);
      client.interceptors.push(second);

      client.fetch('path')
        .then(() => {
          expect(first.request).toHaveBeenCalledWith(jasmine.any(Request));
          expect(second.request).toHaveBeenCalledWith(jasmine.any(Request));
          done();
        });
    });

    it('request interceptors can modify request', (done) => {
      fetch.and.returnValue(emptyResponse(200));
      let interceptor = { request() { return new Request('http://aurelia.io/'); } };

      client.interceptors.push(interceptor);

      client.fetch('first')
        .then(() => {
          expect(fetch.calls.mostRecent().args[0].url).toBe('http://aurelia.io/');
          done();
        });
    });

    it('request interceptors can short circuit request', (done) => {
      let response = new Response();
      let interceptor = { request() { return response; } };

      client.interceptors.push(interceptor);

      client.fetch('path')
        .then((r) => {
          expect(r).toBe(response);
          expect(fetch).not.toHaveBeenCalled();
          done();
        });
    });
  });

  describe('default request parameters', () => {
    setUpTests();

    it('applies baseUrl to requests', (done) => {
      fetch.and.returnValue(emptyResponse(200));
      client.baseUrl = 'http://aurelia.io/';

      client.fetch('path')
        .then(() => {
          let [request] = fetch.calls.first().args;
          expect(request.url).toBe('http://aurelia.io/path');
          done();
        });
    });

    it('applies default headers to requests with no headers', (done) => {
      fetch.and.returnValue(emptyResponse(200));
      client.defaults = { headers: { 'x-foo': 'bar' } };

      client.fetch('path')
        .then(() => {
          let [request] = fetch.calls.first().args;
          expect(request.headers.has('x-foo')).toBe(true);
          expect(request.headers.get('x-foo')).toBe('bar');
          done();
        });
    });

    it('applies default headers to requests with other headers', (done) => {
      fetch.and.returnValue(emptyResponse(200));
      client.defaults = { headers: { 'x-foo': 'bar' } };

      client.fetch('path', { headers: { 'x-baz': 'bat' } })
        .then(() => {
          let [request] = fetch.calls.first().args;
          expect(request.headers.has('x-foo')).toBe(true);
          expect(request.headers.has('x-baz')).toBe(true);
          expect(request.headers.get('x-foo')).toBe('bar');
          expect(request.headers.get('x-baz')).toBe('bat');
          done();
        });
    });

    it('applies default headers to requests using Headers instance', (done) => {
      fetch.and.returnValue(emptyResponse(200));
      client.defaults = { headers: { 'x-foo': 'bar' } };

      client.fetch('path', { headers: new Headers({ 'x-baz': 'bat' }) })
        .then(() => {
          let [request] = fetch.calls.first().args;
          expect(request.headers.has('x-foo')).toBe(true);
          expect(request.headers.has('x-baz')).toBe(true);
          expect(request.headers.get('x-foo')).toBe('bar');
          expect(request.headers.get('x-baz')).toBe('bat');
          done();
        });
    });

    it('does not overwrite request headers with default headers', (done) => {
      fetch.and.returnValue(emptyResponse(200));
      client.defaults = { headers: { 'x-foo': 'bar' } };

      client.fetch('path', { headers: { 'x-foo': 'baz' } })
        .then(() => {
          let [request] = fetch.calls.first().args;
          expect(request.headers.has('x-foo')).toBe(true);
          expect(request.headers.get('x-foo')).toBe('baz');
          expect(request.headers.getAll('x-foo').length).toBe(1);
          done();
        });
    });

    it('evaluates default header function values with no headers', (done) => {
      fetch.and.returnValue(emptyResponse(200));
      client.defaults = { headers: { 'x-foo': () => 'bar' } };

      client.fetch('path')
        .then(() => {
          let [request] = fetch.calls.first().args;
          expect(request.headers.has('x-foo')).toBe(true);
          expect(request.headers.get('x-foo')).toBe('bar');
          done();
        });
    });

    it('evaluates default header function values with other headers', (done) => {
      fetch.and.returnValue(emptyResponse(200));
      client.defaults = { headers: { 'x-foo': () => 'bar' } };

      client.fetch('path', { headers: { 'x-baz': 'bat' } })
        .then(() => {
          let [request] = fetch.calls.first().args;
          expect(request.headers.has('x-foo')).toBe(true);
          expect(request.headers.has('x-baz')).toBe(true);
          expect(request.headers.get('x-foo')).toBe('bar');
          expect(request.headers.get('x-baz')).toBe('bat');
          done();
        });
    });

    it('evaluates default header function values on each request', (done) => {
      fetch.and.returnValue(emptyResponse(200));
      let value = 0;
      client.defaults = {
        headers: {
          'x-foo': () => {
            value++;
            return value;
          }
        }
      };

      let promises = [];
      promises.push(client.fetch('path1'));
      promises.push(client.fetch('path2'));

      Promise.all(promises)
        .then(() => {
          let [request1] = fetch.calls.first().args;
          let [request2] = fetch.calls.mostRecent().args;
          expect(request1.headers.has('x-foo')).toBe(true);
          expect(request1.headers.get('x-foo')).toBe('1');
          expect(request2.headers.has('x-foo')).toBe(true);
          expect(request2.headers.get('x-foo')).toBe('2');
          done();
        });
    });
  });
});

function emptyResponse(status) {
  return Promise.resolve(new Response(null, { status }));
}
<commit_msg>test(http-client): avoid Response.error, which isn't available in some polyfills<commit_after>import {HttpClient} from '../src/http-client';

describe('HttpClient', () => {
  let originalFetch = window.fetch;
  let client;
  let fetch;

  function setUpTests() {
    beforeEach(() => {
      client = new HttpClient();
      fetch = window.fetch = jasmine.createSpy('fetch');
    });

    afterEach(() => {
      fetch = window.fetch = originalFetch;
    });
  }

  setUpTests();

  it('makes requests', (done) => {
    fetch.and.returnValue(emptyResponse(200));

    client
      .fetch('http://example.com/some/cool/path')
      .then(result => {
        expect(result.ok).toBe(true);
      })
      .catch(result => {
        expect(result).not.toBe(result);
      })
      .then(() => {
        expect(fetch).toHaveBeenCalled();
        done();
      });
  });

  describe('interceptors', () => {
    setUpTests();

    it('run on request', (done) => {
      fetch.and.returnValue(emptyResponse(200));
      let interceptor = { request(r) { return r; }, requestError(r) { throw r; } };
      spyOn(interceptor, 'request').and.callThrough();
      spyOn(interceptor, 'requestError').and.callThrough();

      client.interceptors.push(interceptor);

      client.fetch('path')
        .then(() => {
          expect(interceptor.request).toHaveBeenCalledWith(jasmine.any(Request));
          expect(interceptor.requestError).not.toHaveBeenCalled();
          done();
        });
    });

    it('run on request error', (done) => {
      fetch.and.returnValue(emptyResponse(200));
      let interceptor = { request(r) { return r; }, requestError(r) { throw r; } };
      spyOn(interceptor, 'request').and.callThrough();
      spyOn(interceptor, 'requestError').and.callThrough();

      client.interceptors.push({ request() { return Promise.reject(new Error('test')); }});
      client.interceptors.push(interceptor);

      client.fetch()
        .catch(() => {
          expect(interceptor.request).not.toHaveBeenCalled();
          expect(interceptor.requestError).toHaveBeenCalledWith(jasmine.any(Error));
          done();
        });
    });

    it('run on response', (done) => {
      fetch.and.returnValue(emptyResponse(200));
      let interceptor = { response(r) { return r; }, responseError(r) { throw r; } };
      spyOn(interceptor, 'response').and.callThrough();
      spyOn(interceptor, 'responseError').and.callThrough();

      client.interceptors.push(interceptor);

      client.fetch('path')
        .then(() => {
          expect(interceptor.response).toHaveBeenCalledWith(jasmine.any(Response));
          expect(interceptor.responseError).not.toHaveBeenCalled();
          done();
        });
    });

    it('run on response error', (done) => {
      fetch.and.returnValue(Promise.reject(new Response(null, { status: 500 })));
      let interceptor = { response(r) { return r; }, responseError(r) { throw r; } };
      spyOn(interceptor, 'response').and.callThrough();
      spyOn(interceptor, 'responseError').and.callThrough();

      client.interceptors.push(interceptor);

      client.fetch('path')
        .catch(() => {
          expect(interceptor.response).not.toHaveBeenCalled();
          expect(interceptor.responseError).toHaveBeenCalledWith(jasmine.any(Response));
          done();
        });
    });

    it('normalizes input for interceptors', (done) => {
      fetch.and.returnValue(emptyResponse(200));
      let request;
      client.interceptors.push({ request(r) { request = r; return r; } });

      client
        .fetch('http://example.com/some/cool/path')
        .then(() => {
          expect(request instanceof Request).toBe(true);
          done();
        });
    });

    it('runs multiple interceptors', (done) => {
      fetch.and.returnValue(emptyResponse(200));
      let first = { request(r) { return r; } };
      let second = { request(r) { return r; } };
      spyOn(first, 'request').and.callThrough();
      spyOn(second, 'request').and.callThrough();

      client.interceptors.push(first);
      client.interceptors.push(second);

      client.fetch('path')
        .then(() => {
          expect(first.request).toHaveBeenCalledWith(jasmine.any(Request));
          expect(second.request).toHaveBeenCalledWith(jasmine.any(Request));
          done();
        });
    });

    it('request interceptors can modify request', (done) => {
      fetch.and.returnValue(emptyResponse(200));
      let interceptor = { request() { return new Request('http://aurelia.io/'); } };

      client.interceptors.push(interceptor);

      client.fetch('first')
        .then(() => {
          expect(fetch.calls.mostRecent().args[0].url).toBe('http://aurelia.io/');
          done();
        });
    });

    it('request interceptors can short circuit request', (done) => {
      let response = new Response();
      let interceptor = { request() { return response; } };

      client.interceptors.push(interceptor);

      client.fetch('path')
        .then((r) => {
          expect(r).toBe(response);
          expect(fetch).not.toHaveBeenCalled();
          done();
        });
    });
  });

  describe('default request parameters', () => {
    setUpTests();

    it('applies baseUrl to requests', (done) => {
      fetch.and.returnValue(emptyResponse(200));
      client.baseUrl = 'http://aurelia.io/';

      client.fetch('path')
        .then(() => {
          let [request] = fetch.calls.first().args;
          expect(request.url).toBe('http://aurelia.io/path');
          done();
        });
    });

    it('applies default headers to requests with no headers', (done) => {
      fetch.and.returnValue(emptyResponse(200));
      client.defaults = { headers: { 'x-foo': 'bar' } };

      client.fetch('path')
        .then(() => {
          let [request] = fetch.calls.first().args;
          expect(request.headers.has('x-foo')).toBe(true);
          expect(request.headers.get('x-foo')).toBe('bar');
          done();
        });
    });

    it('applies default headers to requests with other headers', (done) => {
      fetch.and.returnValue(emptyResponse(200));
      client.defaults = { headers: { 'x-foo': 'bar' } };

      client.fetch('path', { headers: { 'x-baz': 'bat' } })
        .then(() => {
          let [request] = fetch.calls.first().args;
          expect(request.headers.has('x-foo')).toBe(true);
          expect(request.headers.has('x-baz')).toBe(true);
          expect(request.headers.get('x-foo')).toBe('bar');
          expect(request.headers.get('x-baz')).toBe('bat');
          done();
        });
    });

    it('applies default headers to requests using Headers instance', (done) => {
      fetch.and.returnValue(emptyResponse(200));
      client.defaults = { headers: { 'x-foo': 'bar' } };

      client.fetch('path', { headers: new Headers({ 'x-baz': 'bat' }) })
        .then(() => {
          let [request] = fetch.calls.first().args;
          expect(request.headers.has('x-foo')).toBe(true);
          expect(request.headers.has('x-baz')).toBe(true);
          expect(request.headers.get('x-foo')).toBe('bar');
          expect(request.headers.get('x-baz')).toBe('bat');
          done();
        });
    });

    it('does not overwrite request headers with default headers', (done) => {
      fetch.and.returnValue(emptyResponse(200));
      client.defaults = { headers: { 'x-foo': 'bar' } };

      client.fetch('path', { headers: { 'x-foo': 'baz' } })
        .then(() => {
          let [request] = fetch.calls.first().args;
          expect(request.headers.has('x-foo')).toBe(true);
          expect(request.headers.get('x-foo')).toBe('baz');
          expect(request.headers.getAll('x-foo').length).toBe(1);
          done();
        });
    });

    it('evaluates default header function values with no headers', (done) => {
      fetch.and.returnValue(emptyResponse(200));
      client.defaults = { headers: { 'x-foo': () => 'bar' } };

      client.fetch('path')
        .then(() => {
          let [request] = fetch.calls.first().args;
          expect(request.headers.has('x-foo')).toBe(true);
          expect(request.headers.get('x-foo')).toBe('bar');
          done();
        });
    });

    it('evaluates default header function values with other headers', (done) => {
      fetch.and.returnValue(emptyResponse(200));
      client.defaults = { headers: { 'x-foo': () => 'bar' } };

      client.fetch('path', { headers: { 'x-baz': 'bat' } })
        .then(() => {
          let [request] = fetch.calls.first().args;
          expect(request.headers.has('x-foo')).toBe(true);
          expect(request.headers.has('x-baz')).toBe(true);
          expect(request.headers.get('x-foo')).toBe('bar');
          expect(request.headers.get('x-baz')).toBe('bat');
          done();
        });
    });

    it('evaluates default header function values on each request', (done) => {
      fetch.and.returnValue(emptyResponse(200));
      let value = 0;
      client.defaults = {
        headers: {
          'x-foo': () => {
            value++;
            return value;
          }
        }
      };

      let promises = [];
      promises.push(client.fetch('path1'));
      promises.push(client.fetch('path2'));

      Promise.all(promises)
        .then(() => {
          let [request1] = fetch.calls.first().args;
          let [request2] = fetch.calls.mostRecent().args;
          expect(request1.headers.has('x-foo')).toBe(true);
          expect(request1.headers.get('x-foo')).toBe('1');
          expect(request2.headers.has('x-foo')).toBe(true);
          expect(request2.headers.get('x-foo')).toBe('2');
          done();
        });
    });
  });
});

function emptyResponse(status) {
  return Promise.resolve(new Response(null, { status }));
}
<|endoftext|>


<commit_before>var assert = require('chai').assert;
var request = require('supertest');

var app = require('../../src/server');

describe('GET /', function() {
    it('initial load', function(done) {
        request(app)
            .get('/')
            .expect(200)
            .expect('set-cookie', /_csrf=.*?; Path=\//, done);
    });

    it('reset parameter resets cookie', function(done) {
        var preExistingCookie = createCookieString({foo: "bar"});
        var responseCookie = new RegExp(createCookieString() + "; Path=/");

        request(app)
            .get('/?reset=true')
            .set('Cookie', preExistingCookie)
            .expect(200)
            .expect('set-cookie', responseCookie, done);
    });
});

function createCookieString(cookie) {
    if(cookie) { return "oAuth2ClientShell=" + JSON.stringify(cookie); }
    return "oAuth2ClientShell=";
}
<commit_msg>ci - adding tests around clearing specific values. (#42)<commit_after>var assert = require('chai').assert;
var request = require('supertest');

var app = require('../../src/server');
var JSONCookie = require('cookie-parser').JSONCookie;

describe('GET /', function() {
    it('initial load', function(done) {
        request(app)
            .get('/')
            .expect(200)
            .expect('set-cookie', /_csrf=.*?; Path=\//, done);
    });

    it('reset parameter resets cookie', function(done) {
        var preExistingCookie = createCookieString({foo: "bar"});
        var responseCookie = new RegExp(createCookieString() + "; Path=/");

        request(app)
            .get('/?reset=true')
            .set('Cookie', preExistingCookie)
            .expect(200)
            .expect('set-cookie', responseCookie, done);
    });

    it('clear parameter clears certain cookie values', function(done) {
        var preExistingCookie = createCookieString({
            authCode: "authCode",
            authEndpoint: "authEndpoint",
            accessToken: "accessToken",
            refreshToken: "refreshToken",
            focus: "focus"
        });
        var responseCookie = new RegExp(
            createCookieString({
                authCode: null,
                authEndpoint: "authEndpoint",
                accessToken: null,
                refreshToken: null,
                focus: null
            })
            + "; Path=/"
        );

        request(app)
            .get('/?clear=true')
            .set('Cookie', preExistingCookie)
            .expect(200)
            .expect('set-cookie', responseCookie, done);
    });
});

function createCookieString(cookie) {
    if(cookie) {
        return "oAuth2ClientShell="
            // https://github.com/expressjs/express/issues/2815
            + encodeURIComponent("j:" + JSON.stringify(cookie));
        }
    return "oAuth2ClientShell=";
}
<|endoftext|>