<commit_before>'use strict';

var test = require('tape');
var vfile = require('./');

test('vfile([options])', function (t) {
  // eslint-disable-next-line new-cap
  t.ok(vfile() instanceof vfile, 'should work with new');

  t.ok(vfile() instanceof vfile, 'should work without `new`');

  t.test('should accept missing options', function (st) {
    var file = vfile();

    st.deepEqual(file.history, []);
    st.deepEqual(file.data, {});
    st.deepEqual(file.messages, []);
    st.equal(file.contents, undefined);
    st.equal(file.path, undefined);
    st.equal(file.dirname, undefined);
    st.equal(file.basename, undefined);
    st.equal(file.stem, undefined);
    st.equal(file.extname, undefined);

    st.end();
  });

  t.test('should accept a string', function (st) {
    var file = vfile('alpha');

    st.equal(file.contents, 'alpha');

    st.end();
  });

  t.test('should accept a vfile', function (st) {
    var left = vfile();
    var right = vfile(left);

    st.equal(left, right);

    st.end();
  });

  t.test('should accept an object (1)', function (st) {
    var file = vfile({path: '~/example.md'});

    st.deepEqual(file.history, ['~/example.md']);
    st.equal(file.contents, undefined);
    st.equal(file.path, '~/example.md');
    st.equal(file.dirname, '~');
    st.equal(file.basename, 'example.md');
    st.equal(file.stem, 'example');
    st.equal(file.extname, '.md');

    st.end();
  });

  t.test('should accept a object (2)', function (st) {
    var file = vfile({basename: 'example.md'});

    st.deepEqual(file.history, ['example.md']);
    st.equal(file.contents, undefined);
    st.equal(file.path, 'example.md');
    st.equal(file.dirname, '.');
    st.equal(file.basename, 'example.md');
    st.equal(file.stem, 'example');
    st.equal(file.extname, '.md');

    st.end();
  });

  t.test('should accept a object (2)', function (st) {
    var file = vfile({stem: 'example', extname: '.md', dirname: '~'});

    st.deepEqual(file.history, ['example', 'example.md', '~/example.md']);
    st.equal(file.contents, undefined);
    st.equal(file.path, '~/example.md');
    st.equal(file.dirname, '~');
    st.equal(file.basename, 'example.md');
    st.equal(file.stem, 'example');
    st.equal(file.extname, '.md');

    st.end();
  });

  t.test('should set custom props', function (st) {
    var testing = [1, 2, 3];
    var file = vfile({custom: true, testing: testing});

    st.equal(file.custom, true);
    st.equal(file.testing, testing);

    st.end();
  });

  t.test('#toString()', function (st) {
    st.equal(
      vfile().toString(),
      '',
      'should return `""` without content'
    );

    st.equal(
      vfile('foo').toString(),
      'foo',
      'string: should return the internal value'
    );

    st.equal(
      vfile(new Buffer('bar')).toString(),
      'bar',
      'buffer: should return the internal value'
    );

    st.equal(
      vfile(new Buffer('bar')).toString('hex'),
      '626172',
      'buffer encoding: should return the internal value'
    );

    st.end();
  });

  t.test('.cwd', function (st) {
    st.equal(vfile().cwd, process.cwd(), 'should start at `process.cwd()`');

    st.equal(vfile({cwd: '/'}).cwd, '/', 'should be settable');

    st.end();
  });

  t.test('.path', function (st) {
    var file = vfile();

    st.equal(file.path, undefined, 'should start `undefined`');

    file.path = '~/example.md';

    st.equal(file.path, '~/example.md', 'should set `path`s');

    file.path = '~/example/example.txt';

    st.equal(file.path, '~/example/example.txt', 'should change `path`s');

    st.deepEqual(
      file.history,
      ['~/example.md', '~/example/example.txt'],
      'should record changes'
    );

    file.path = '~/example/example.txt';

    st.deepEqual(
      file.history,
      ['~/example.md', '~/example/example.txt'],
      'should not record setting the same path'
    );

    st.throws(
      function () {
        file.path = null;
      },
      /Error: `path` cannot be empty/,
      'should not remove `path`'
    );

    st.end();
  });

  t.test('.basename', function (st) {
    var file = vfile();

    st.equal(file.basename, undefined, 'should start `undefined`');

    file.basename = 'example.md';

    st.equal(file.basename, 'example.md', 'should set `basename`');

    file.basename = 'readme.txt';

    st.equal(file.basename, 'readme.txt', 'should change `basename`');

    st.deepEqual(
      file.history,
      ['example.md', 'readme.txt'],
      'should record changes'
    );

    file = vfile({path: '~/alpha/bravo.md'});

    st.throws(
      function () {
        file.basename = null;
      },
      /Error: `basename` cannot be empty/,
      'should throw when removing `basename`'
    );

    st.throws(
      function () {
        file.basename = 'charlie/delta.js';
      },
      /Error: `basename` cannot be a path: did not expect `\/`/,
      'should throw when setting a path'
    );

    st.end();
  });

  t.test('.dirname', function (st) {
    var file = vfile();

    st.equal(file.dirname, undefined, 'should start undefined');

    st.throws(
      function () {
        file.dirname = '~/alpha/bravo';
      },
      /Error: Setting `dirname` requires `path` to be set too/,
      'should throw when setting without path'
    );

    file.path = '~/alpha/bravo';
    file.dirname = '~/charlie';

    st.equal(file.dirname, '~/charlie', 'should change paths');

    st.deepEqual(
      file.history,
      ['~/alpha/bravo', '~/charlie/bravo'],
      'should record changes'
    );

    file.dirname = null;
    st.equal(file.dirname, '.', 'should support removing `dirname` (1)');
    st.equal(file.path, 'bravo', 'should support removing `dirname` (2)');

    st.end();
  });

  t.test('.extname', function (st) {
    var file = vfile();

    st.equal(file.extname, undefined, 'should start `undefined`');

    st.throws(
      function () {
        file.extname = '.git';
      },
      /Error: Setting `extname` requires `path` to be set too/,
      'should throw when setting without `path`'
    );

    file.path = '~/alpha/bravo';
    st.equal(file.extname, '', 'should return empty without extension');

    file.extname = '.md';
    st.equal(file.extname, '.md', 'should set extensions');

    st.deepEqual(
      file.history,
      ['~/alpha/bravo', '~/alpha/bravo.md'],
      'should record changes'
    );

    st.throws(
      function () {
        file.extname = 'txt';
      },
      /Error: `extname` must start with `.`/,
      'should throw without initial `.`'
    );

    st.throws(
      function () {
        file.extname = '..md';
      },
      /Error: `extname` cannot contain multiple dots/,
      'should throw with mutiple `.`s'
    );

    file.extname = null;
    st.equal(file.extname, '', 'should support removing `extname` (1)');
    st.equal(file.path, '~/alpha/bravo', 'should support removing `extname` (2)');

    st.end();
  });

  t.test('.stem', function (st) {
    var file = vfile();

    st.equal(file.stem, undefined, 'should start `undefined`');

    file.stem = 'bravo';

    st.equal(file.stem, 'bravo', 'should set');

    file.stem = 'charlie';

    st.equal(file.stem, 'charlie', 'should change');

    st.throws(
      function () {
        file.stem = null;
      },
      /Error: `stem` cannot be empty/,
      'should throw when removing `stem`'
    );

    st.throws(
      function () {
        file.stem = 'charlie/delta.js';
      },
      /Error: `stem` cannot be a path: did not expect `\/`/,
      'should throw when setting a path'
    );

    st.end();
  });

  t.test('#message(reason[, position[, ruleId]])', function (st) {
    var file;
    var message;
    var err;
    var pos;

    st.ok(
      vfile().message('') instanceof Error,
      'should return an Error'
    );

    file = vfile({path: '~/example.md'});
    message = file.message('Foo');

    st.equal(file.messages.length, 1);
    st.equal(file.messages[0], message);

    st.equal(message.name, '~/example.md:1:1');
    st.equal(message.file, '~/example.md');
    st.equal(message.reason, 'Foo');
    st.equal(message.ruleId, null);
    st.equal(message.source, null);
    st.equal(message.stack, '');
    st.equal(message.fatal, false);
    st.equal(message.line, null);
    st.equal(message.column, null);
    st.deepEqual(message.location, {
      start: {line: null, column: null},
      end: {line: null, column: null}
    });

    st.equal(
      String(message),
      '~/example.md:1:1: Foo',
      'should have a pretty `toString()` message'
    );

    err = new Error('foo');
    message = vfile().message(err);

    st.equal(message.stack, err.stack, 'should accept an error (1)');
    st.equal(message.message, err.message, 'should accept an error (2)');

    pos = {
      position: {
        start: {line: 2, column: 3},
        end: {line: 2, column: 5}
      }
    };

    message = vfile().message('test', pos);

    st.deepEqual(message.location, pos.position, 'should accept a node (1)');
    st.equal(String(message), '2:3-2:5: test', 'should accept a node (2)');

    pos = pos.position;
    message = vfile().message('test', pos);

    st.deepEqual(message.location, pos, 'should accept a location (1)');
    st.equal(String(message), '2:3-2:5: test', 'should accept a location (2)');

    pos = pos.start;
    message = vfile().message('test', pos);

    st.deepEqual(
      message.location,
      {
        start: pos,
        end: {line: null, column: null}
      },
      'should accept a position (1)'
    );

    st.equal(String(message), '2:3: test', 'should accept a position');

    st.equal(
      vfile().message('test', null, 'charlie').ruleId,
      'charlie',
      'should accept a `ruleId`'
    );

    st.end();
  });

  t.test('#fail(reason[, position[, ruleId]])', function (st) {
    var file = vfile({path: '~/example.md'});
    var message;

    st.throws(
      function () {
        file.fail('Foo', {line: 1, column: 3}, 'baz');
      },
      /1:3: Foo/,
      'should throw the message'
    );

    st.equal(file.messages.length, 1);

    message = file.messages[0];

    st.equal(message.name, '~/example.md:1:3');
    st.equal(message.file, '~/example.md');
    st.equal(message.reason, 'Foo');
    st.equal(message.ruleId, 'baz');
    st.equal(message.source, null);
    st.equal(message.stack, '');
    st.equal(message.fatal, true);
    st.equal(message.line, 1);
    st.equal(message.column, 3);
    st.deepEqual(message.location, {
      start: {line: 1, column: 3},
      end: {line: null, column: null}
    });

    st.end();
  });

  t.end();
});
<commit_msg>Add tests for real error objects<commit_after>'use strict';

var test = require('tape');
var vfile = require('./');

/* eslint-disable no-undef */
var exception;
var changedMessage;
var multilineException;

try {
  variable = 1;
} catch (err) {
  err.stack = cleanStack(err.stack, 3);
  exception = err;
}

try {
  variable = 1;
} catch (err) {
  err.message = 'foo';
  err.stack = cleanStack(err.stack, 3);
  changedMessage = err;
}

try {
  variable = 1;
} catch (err) {
  err.message = 'foo\nbar\nbaz';
  err.stack = cleanStack(err.stack, 5);
  multilineException = err;
}
/* eslint-enable no-undef */

test('vfile([options])', function (t) {
  // eslint-disable-next-line new-cap
  t.ok(vfile() instanceof vfile, 'should work with new');

  t.ok(vfile() instanceof vfile, 'should work without `new`');

  t.test('should accept missing options', function (st) {
    var file = vfile();

    st.deepEqual(file.history, []);
    st.deepEqual(file.data, {});
    st.deepEqual(file.messages, []);
    st.equal(file.contents, undefined);
    st.equal(file.path, undefined);
    st.equal(file.dirname, undefined);
    st.equal(file.basename, undefined);
    st.equal(file.stem, undefined);
    st.equal(file.extname, undefined);

    st.end();
  });

  t.test('should accept a string', function (st) {
    var file = vfile('alpha');

    st.equal(file.contents, 'alpha');

    st.end();
  });

  t.test('should accept a vfile', function (st) {
    var left = vfile();
    var right = vfile(left);

    st.equal(left, right);

    st.end();
  });

  t.test('should accept an object (1)', function (st) {
    var file = vfile({path: '~/example.md'});

    st.deepEqual(file.history, ['~/example.md']);
    st.equal(file.contents, undefined);
    st.equal(file.path, '~/example.md');
    st.equal(file.dirname, '~');
    st.equal(file.basename, 'example.md');
    st.equal(file.stem, 'example');
    st.equal(file.extname, '.md');

    st.end();
  });

  t.test('should accept a object (2)', function (st) {
    var file = vfile({basename: 'example.md'});

    st.deepEqual(file.history, ['example.md']);
    st.equal(file.contents, undefined);
    st.equal(file.path, 'example.md');
    st.equal(file.dirname, '.');
    st.equal(file.basename, 'example.md');
    st.equal(file.stem, 'example');
    st.equal(file.extname, '.md');

    st.end();
  });

  t.test('should accept a object (2)', function (st) {
    var file = vfile({stem: 'example', extname: '.md', dirname: '~'});

    st.deepEqual(file.history, ['example', 'example.md', '~/example.md']);
    st.equal(file.contents, undefined);
    st.equal(file.path, '~/example.md');
    st.equal(file.dirname, '~');
    st.equal(file.basename, 'example.md');
    st.equal(file.stem, 'example');
    st.equal(file.extname, '.md');

    st.end();
  });

  t.test('should set custom props', function (st) {
    var testing = [1, 2, 3];
    var file = vfile({custom: true, testing: testing});

    st.equal(file.custom, true);
    st.equal(file.testing, testing);

    st.end();
  });

  t.test('#toString()', function (st) {
    st.equal(
      vfile().toString(),
      '',
      'should return `""` without content'
    );

    st.equal(
      vfile('foo').toString(),
      'foo',
      'string: should return the internal value'
    );

    st.equal(
      vfile(new Buffer('bar')).toString(),
      'bar',
      'buffer: should return the internal value'
    );

    st.equal(
      vfile(new Buffer('bar')).toString('hex'),
      '626172',
      'buffer encoding: should return the internal value'
    );

    st.end();
  });

  t.test('.cwd', function (st) {
    st.equal(vfile().cwd, process.cwd(), 'should start at `process.cwd()`');

    st.equal(vfile({cwd: '/'}).cwd, '/', 'should be settable');

    st.end();
  });

  t.test('.path', function (st) {
    var file = vfile();

    st.equal(file.path, undefined, 'should start `undefined`');

    file.path = '~/example.md';

    st.equal(file.path, '~/example.md', 'should set `path`s');

    file.path = '~/example/example.txt';

    st.equal(file.path, '~/example/example.txt', 'should change `path`s');

    st.deepEqual(
      file.history,
      ['~/example.md', '~/example/example.txt'],
      'should record changes'
    );

    file.path = '~/example/example.txt';

    st.deepEqual(
      file.history,
      ['~/example.md', '~/example/example.txt'],
      'should not record setting the same path'
    );

    st.throws(
      function () {
        file.path = null;
      },
      /Error: `path` cannot be empty/,
      'should not remove `path`'
    );

    st.end();
  });

  t.test('.basename', function (st) {
    var file = vfile();

    st.equal(file.basename, undefined, 'should start `undefined`');

    file.basename = 'example.md';

    st.equal(file.basename, 'example.md', 'should set `basename`');

    file.basename = 'readme.txt';

    st.equal(file.basename, 'readme.txt', 'should change `basename`');

    st.deepEqual(
      file.history,
      ['example.md', 'readme.txt'],
      'should record changes'
    );

    file = vfile({path: '~/alpha/bravo.md'});

    st.throws(
      function () {
        file.basename = null;
      },
      /Error: `basename` cannot be empty/,
      'should throw when removing `basename`'
    );

    st.throws(
      function () {
        file.basename = 'charlie/delta.js';
      },
      /Error: `basename` cannot be a path: did not expect `\/`/,
      'should throw when setting a path'
    );

    st.end();
  });

  t.test('.dirname', function (st) {
    var file = vfile();

    st.equal(file.dirname, undefined, 'should start undefined');

    st.throws(
      function () {
        file.dirname = '~/alpha/bravo';
      },
      /Error: Setting `dirname` requires `path` to be set too/,
      'should throw when setting without path'
    );

    file.path = '~/alpha/bravo';
    file.dirname = '~/charlie';

    st.equal(file.dirname, '~/charlie', 'should change paths');

    st.deepEqual(
      file.history,
      ['~/alpha/bravo', '~/charlie/bravo'],
      'should record changes'
    );

    file.dirname = null;
    st.equal(file.dirname, '.', 'should support removing `dirname` (1)');
    st.equal(file.path, 'bravo', 'should support removing `dirname` (2)');

    st.end();
  });

  t.test('.extname', function (st) {
    var file = vfile();

    st.equal(file.extname, undefined, 'should start `undefined`');

    st.throws(
      function () {
        file.extname = '.git';
      },
      /Error: Setting `extname` requires `path` to be set too/,
      'should throw when setting without `path`'
    );

    file.path = '~/alpha/bravo';
    st.equal(file.extname, '', 'should return empty without extension');

    file.extname = '.md';
    st.equal(file.extname, '.md', 'should set extensions');

    st.deepEqual(
      file.history,
      ['~/alpha/bravo', '~/alpha/bravo.md'],
      'should record changes'
    );

    st.throws(
      function () {
        file.extname = 'txt';
      },
      /Error: `extname` must start with `.`/,
      'should throw without initial `.`'
    );

    st.throws(
      function () {
        file.extname = '..md';
      },
      /Error: `extname` cannot contain multiple dots/,
      'should throw with mutiple `.`s'
    );

    file.extname = null;
    st.equal(file.extname, '', 'should support removing `extname` (1)');
    st.equal(file.path, '~/alpha/bravo', 'should support removing `extname` (2)');

    st.end();
  });

  t.test('.stem', function (st) {
    var file = vfile();

    st.equal(file.stem, undefined, 'should start `undefined`');

    file.stem = 'bravo';

    st.equal(file.stem, 'bravo', 'should set');

    file.stem = 'charlie';

    st.equal(file.stem, 'charlie', 'should change');

    st.throws(
      function () {
        file.stem = null;
      },
      /Error: `stem` cannot be empty/,
      'should throw when removing `stem`'
    );

    st.throws(
      function () {
        file.stem = 'charlie/delta.js';
      },
      /Error: `stem` cannot be a path: did not expect `\/`/,
      'should throw when setting a path'
    );

    st.end();
  });

  t.test('#message(reason[, position[, ruleId]])', function (st) {
    var file;
    var message;
    var pos;

    st.ok(
      vfile().message('') instanceof Error,
      'should return an Error'
    );

    file = vfile({path: '~/example.md'});
    message = file.message('Foo');

    st.equal(file.messages.length, 1);
    st.equal(file.messages[0], message);

    st.equal(message.name, '~/example.md:1:1');
    st.equal(message.file, '~/example.md');
    st.equal(message.reason, 'Foo');
    st.equal(message.ruleId, null);
    st.equal(message.source, null);
    st.equal(message.stack, '');
    st.equal(message.fatal, false);
    st.equal(message.line, null);
    st.equal(message.column, null);
    st.deepEqual(message.location, {
      start: {line: null, column: null},
      end: {line: null, column: null}
    });

    st.equal(
      String(message),
      '~/example.md:1:1: Foo',
      'should have a pretty `toString()` message'
    );

    message = vfile().message(exception);

    st.equal(message.message, 'variable is not defined', 'should accept an error (1)');

    st.equal(
      message.stack,
      [
        'ReferenceError: variable is not defined',
        '    at Object.<anonymous> (test.js:1:1)',
        '    at Module._compile (module.js:1:1)'
      ].join('\n'),
      'should accept an error (2)'
    );

    message = vfile().message(changedMessage);

    st.equal(message.message, 'foo', 'should accept a changed error (1)');

    st.equal(
      message.stack,
      [
        'ReferenceError: foo',
        '    at Object.<anonymous> (test.js:1:1)',
        '    at Module._compile (module.js:1:1)'
      ].join('\n'),
      'should accept a changed error (2)'
    );

    message = vfile().message(multilineException);

    st.equal(message.message, 'foo\nbar\nbaz', 'should accept a multiline error (1)');

    st.equal(
      message.stack,
      [
        'ReferenceError: foo',
        'bar',
        'baz',
        '    at Object.<anonymous> (test.js:1:1)',
        '    at Module._compile (module.js:1:1)'
      ].join('\n'),
      'should accept a multiline error (2)'
    );

    pos = {
      position: {
        start: {line: 2, column: 3},
        end: {line: 2, column: 5}
      }
    };

    message = vfile().message('test', pos);

    st.deepEqual(message.location, pos.position, 'should accept a node (1)');
    st.equal(String(message), '2:3-2:5: test', 'should accept a node (2)');

    pos = pos.position;
    message = vfile().message('test', pos);

    st.deepEqual(message.location, pos, 'should accept a location (1)');
    st.equal(String(message), '2:3-2:5: test', 'should accept a location (2)');

    pos = pos.start;
    message = vfile().message('test', pos);

    st.deepEqual(
      message.location,
      {
        start: pos,
        end: {line: null, column: null}
      },
      'should accept a position (1)'
    );

    st.equal(String(message), '2:3: test', 'should accept a position');

    st.equal(
      vfile().message('test', null, 'charlie').ruleId,
      'charlie',
      'should accept a `ruleId`'
    );

    st.end();
  });

  t.test('#fail(reason[, position[, ruleId]])', function (st) {
    var file = vfile({path: '~/example.md'});
    var message;

    st.throws(
      function () {
        file.fail('Foo', {line: 1, column: 3}, 'baz');
      },
      /1:3: Foo/,
      'should throw the message'
    );

    st.equal(file.messages.length, 1);

    message = file.messages[0];

    st.equal(message.name, '~/example.md:1:3');
    st.equal(message.file, '~/example.md');
    st.equal(message.reason, 'Foo');
    st.equal(message.ruleId, 'baz');
    st.equal(message.source, null);
    st.equal(message.stack, '');
    st.equal(message.fatal, true);
    st.equal(message.line, 1);
    st.equal(message.column, 3);
    st.deepEqual(message.location, {
      start: {line: 1, column: 3},
      end: {line: null, column: null}
    });

    st.end();
  });

  t.end();
});

function cleanStack(stack, max) {
  return stack
    .replace(/\(\/.+\//g, '(').replace(/\d+:\d+/g, '1:1')
    .split('\n').slice(0, max).join('\n');
}
<|endoftext|>


<commit_before>
var test = require('tap').test
  , mq = require('./')

test('it should support on and emit', function(t) {
  t.plan(2)

  var e = mq()
    , expected = { my: 'message' }

  e.on('hello world', function(topic, message, cb) {
    t.equal(topic, 'hello world')
    t.equal(message, expected)
    cb()
  })

  e.emit('hello world', expected, function() {
    t.end()
  })
})

test('it should support multiple subscribers', function(t) {
  t.plan(2)

  var e = mq()
    , expected = { my: 'message' }

  e.on('hello world', function(topic, message, cb) {
    t.ok(true)
    cb()
  })

  e.on('hello world', function(topic, message, cb) {
    t.ok(true)
    cb()
  })

  e.emit('hello world', expected, function() {
    t.end()
  })
})
<commit_msg>Added wildcard test.<commit_after>
var test = require('tap').test
  , mq = require('./')

test('it should support on and emit', function(t) {
  t.plan(2)

  var e = mq()
    , expected = { my: 'message' }

  e.on('hello world', function(topic, message, cb) {
    t.equal(topic, 'hello world')
    t.equal(message, expected)
    cb()
  })

  e.emit('hello world', expected, function() {
    t.end()
  })
})

test('it should support multiple subscribers', function(t) {
  t.plan(2)

  var e = mq()
    , expected = { my: 'message' }

  e.on('hello world', function(topic, message, cb) {
    t.ok(true)
    cb()
  })

  e.on('hello world', function(topic, message, cb) {
    t.ok(true)
    cb()
  })

  e.emit('hello world', expected, function() {
    t.end()
  })
})

test('it should support wildcards', function(t) {
  t.plan(1)

  var e = mq()
    , expected = { my: 'message' }

  e.on('hello.*', function(topic, message, cb) {
    t.equal(topic, 'hello.world')
    cb()
  })

  e.emit('hello.world', expected, function() {
    t.end()
  })
})
<|endoftext|>


<commit_before>const test = require('ava');
const random = require('./helpers/random');
const all = require('./products');

test('all()', t => {
  t.true(all.length < 0);
});

test('random()', t => {
  t.truthy(random(all));
  t.not(random(all), random(all));
});
<commit_msg>🤖(fix): 2017-7-17 09:58:31<commit_after>const test = require('ava');
const random = require('./helpers/random');
const all = require('./products');

test('all()', t => {
  t.true(all.length > 0);
});

test('random()', t => {
  t.truthy(random(all));
  t.not(random(all), random(all));
});
<|endoftext|>


<commit_before>import test from 'ava';
import sinon from 'sinon';
import fs from 'fs';

const script = fs.readFileSync('index.js').toString();

test.beforeEach(t => {
    t.context.log = console.log;
    sinon.stub(console, 'log');
});

test.afterEach(() => {
    console.log.restore();
    process.stdin.removeAllListeners(['data', 'end']);
});

/*
checkにテストケース、correctに正解をいれていく
正解の末尾改行はcorrectに含まない
 */

test('test 1', t => {
    const check = `A`;
    const correct = `A`;

    equal(t, check, correct);
});

test('test 2', t => {
    const check = `B
1 2 3 4 5
10 9 8 7 6`;
    const correct = `B
10 9 8 7 6
1 2 3 4 5`;

    equal(t, check, correct);
});

function equal(t, check, correct) {
    eval(script);
    process.stdin.emit('data', check);
    process.stdin.emit('end');
    t.is(getCalled(), correct);
}

/**
 * 呼ばれたconsole.logの内容を改行でくっつけて返す
 * @return {string}
 */
function getCalled() {
    let count = console.log.callCount;
    const strs = [];
    for(let i = 0; i < count; i++) {
        strs.push(console.log.getCall(i).args[0]);
    }

    return strs.join('\n');
}<commit_msg>fix console.log.reset<commit_after>import test from 'ava';
import sinon from 'sinon';
import fs from 'fs';

const script = fs.readFileSync('index.js').toString();

sinon.stub(console, 'log');
let ignoreCallCount = 0;

test.beforeEach(t => {
    t.context.log = console.log;
    console.log.reset();
});

test.afterEach(() => {
    console.log.reset();
    process.stdin.removeAllListeners(['data', 'end']);
});

function equal(t, check, correct) {
    eval(script);
    process.stdin.emit('data', check);
    process.stdin.emit('end');
    t.is(getCalled(), correct);
    // resetきかない・・・
    ignoreCallCount = console.log.callCount;
}

/**
 * 呼ばれたconsole.logの内容を改行でくっつけて返す
 * @return {string}
 */
function getCalled() {
    let count = console.log.callCount - ignoreCallCount;
    console.info('ifnore: ', ignoreCallCount, 'callCount: ', console.log.callCount);
    const strs = [];
    for(let i = 0; i < count; i++) {
        strs.push(console.log.getCall(i).args[0]);
    }

    return strs.join('\n');
}

/*
checkにテストケース、correctに正解をいれていく
正解の末尾改行はcorrectに含まない
 */

test('test 1', t => {
    const check = ``;
    const correct = ``;

    equal(t, check, correct);
});

test('test 2', t => {
    const check = ``;
    const correct = ``;

    equal(t, check, correct);
});<|endoftext|>


<commit_before>const test = require('ava');
const random = require('./helpers/random');
const all = require('./products');

test('all()', t => {
  t.true(all.length > 0);
});

test('random()', t => {
  t.truthy(random(all));
  t.not(random(all), random(all));
});
<commit_msg>🤖(break): 2017-7-20 11:55:30<commit_after>const test = require('ava');
const random = require('./helpers/random');
const all = require('./products');

test('all()', t => {
  t.true(all.length < 0);
});

test('random()', t => {
  t.truthy(random(all));
  t.not(random(all), random(all));
});
<|endoftext|>


<commit_before>const test = require('ava');
const random = require('./helpers/random');
const all = require('./products');

test('all()', t => {
  t.true(all.length < 0);
});

test('random()', t => {
  t.truthy(random(all));
  t.not(random(all), random(all));
});
<commit_msg>🤖(fix): 2017-6-9 17:46:49<commit_after>const test = require('ava');
const random = require('./helpers/random');
const all = require('./products');

test('all()', t => {
  t.true(all.length > 0);
});

test('random()', t => {
  t.truthy(random(all));
  t.not(random(all), random(all));
});
<|endoftext|>


<commit_before>const { Vector,sum,product } = require("./vecto");

// let v = Vector.zeroes([2]);
// console.log(v);

// let v2 = Vector.zeroes([2,3]);
// console.log(v2);
// console.log(v2.size);
// let v3 = new Vector([6]);
// v3.arrange();
// let sm = Vector.add(v2,v3);
// console.log(sm);

// let n2v = Vector.array([[4,2,1],[7,8,9]]);
// // console.log(nv.calc_shape(nv.array));
// // console.log(nv.calc_size(nv.shape));
// // console.log(nv);

// let tnv = new Vector([2,2,3,4]);
// tnv.arrange(4);
// console.log(tnv);
// tnv.reshape([6,8]);
// console.log(tnv);
// n2v.reshape([6]);
// console.log(`reshaped = `,n2v);
// n2v.resize([5,5]);
// console.log(`resized = `,n2v);

// let nv = new Vector([2,3]);
// nv.arrange(2);
// console.log(nv.array);
// let nv2 = new Vector([2,3]);
// nv2.arrange(4);
// console.log(nv2.array);
// console.log(Vector.add(nv,nv2));

// let nnv = new Vector([5,5]);
// nnv.arrange(5);
// console.log(nnv);

// console.log(product(nnv.array,n2v.array));

let nv = new Vector([5,5]);
nv.arrange(6);

let nv2 = new Vector(nv.shape);
nv2.arrange(5);

console.log(product(nv.array,nv2.array));<commit_msg>fixing_bugs<commit_after>const { Vector,sum,product } = require("./vecto");

let v = Vector.zeroes([2]);
console.log(v);

let v2 = Vector.zeroes([2,3]);
console.log(v2);
console.log(v2.size);
let v3 = new Vector([6]);
v3.arrange();
let sm = Vector.add(v2,v3);
console.log(sm);

let n2v = Vector.array([[4,2,1],[7,8,9]]);
// console.log(nv.calc_shape(nv.array));
// console.log(nv.calc_size(nv.shape));
// console.log(nv);

let tnv = new Vector([2,2,3,4]);
tnv.arrange(4);
console.log(tnv);
tnv.reshape([6,8]);
console.log(tnv);
n2v.reshape([6]);
console.log(`reshaped = `,n2v);
n2v.resize([5,5]);
console.log(`resized = `,n2v);

let nv = new Vector([2,3]);
nv.arrange(2);
console.log(nv.array);
let nv2 = new Vector([2,3]);
nv2.arrange(4);
console.log(nv2.array);
console.log(Vector.add(nv,nv2));

let nnv = new Vector([5,5]);
nnv.arrange(5);
console.log(nnv);

console.log(product(nnv.array,n2v.array));

let nvvn = new Vector([5,5]);
nvvn.arrange(6);

let nv22 = new Vector(nvvn.shape);
nv22.arrange(5);

console.log(product(nvvn.array,nv22.array));
console.log(sum(nvvn.array,nv22.array));
console.log(sum(nvvn.array));
console.log(product(nvvn.array,[2,2,2,2,2]));
console.log(product(nvvn.array,2));
<|endoftext|>


<commit_before>const test = require('ava');
const random = require('./helpers/random');
const all = require('./products');

test('all()', t => {
  t.true(all.length > 0);
});

test('random()', t => {
  t.truthy(random(all));
  t.not(random(all), random(all));
});
<commit_msg>🤖(break): 2017-7-24 01:30:21<commit_after>const test = require('ava');
const random = require('./helpers/random');
const all = require('./products');

test('all()', t => {
  t.true(all.length < 0);
});

test('random()', t => {
  t.truthy(random(all));
  t.not(random(all), random(all));
});
<|endoftext|>


<commit_before>var assert = require('assert');
var SParse = require(process.cwd() + '/');
var SyntaxError = SParse.SyntaxError;

assert.deepEqual(SParse('((a b c)(()()))'), [['a','b','c'],[[],[]]]);
assert.deepEqual(SParse('((a b c) (() ()))'), [['a','b','c'],[[],[]]]);
assert.deepEqual(SParse("((a 'b 'c))"), [['a',['quote','b'],['quote','c']]]);
assert.deepEqual(SParse("(a '(a b c))"), ['a', ['quote', 'a', 'b', 'c']]);
assert.deepEqual(SParse("(a ' (a b c))"), ['a', ['quote', 'a', 'b', 'c']]);
assert.deepEqual(SParse("(a '' (a b c))"), ['a', ['quote', ['quote', 'a', 'b', 'c']]], 'Multiple quotes should not be flattened');
assert.deepEqual(SParse("((a `b `c))"), [['a',['quasiquote','b'],['quasiquote','c']]]);
assert.deepEqual(SParse("(a `(a b c))"), ['a', ['quasiquote', 'a', 'b', 'c']]);
assert.deepEqual(SParse("(a ` (a b c))"), ['a', ['quasiquote', 'a', 'b', 'c']]);
assert.deepEqual(SParse("(a `` (a b c))"), ['a', ['quasiquote', ['quasiquote', 'a', 'b', 'c']]], 'Multiple quasiquotes should not be flattened');
assert.deepEqual(SParse("((a ,b ,c))"), [['a',['unquote','b'],['unquote','c']]]);
assert.deepEqual(SParse("(a ,(a b c))"), ['a', ['unquote', 'a', 'b', 'c']]);
assert.deepEqual(SParse("(a , (a b c))"), ['a', ['unquote', 'a', 'b', 'c']]);
assert.deepEqual(SParse("(a ,, (a b c))"), ['a', ['unquote', ['unquote', 'a', 'b', 'c']]], 'Multiple unquotes should not be flattened');
assert.deepEqual(SParse("((a ,@b ,@c))"), [['a',['unquote-splicing','b'],['unquote-splicing','c']]]);
assert.deepEqual(SParse("(a ,@(a b c))"), ['a', ['unquote-splicing', 'a', 'b', 'c']]);
assert.deepEqual(SParse("(a ,@ (a b c))"), ['a', ['unquote-splicing', 'a', 'b', 'c']]);
assert.deepEqual(SParse("(a ,@,@ (a b c))"), ['a', ['unquote-splicing', ['unquote-splicing', 'a', 'b', 'c']]], 'Multiple unquote-splicings should not be flattened');
assert(SParse("()()") instanceof SyntaxError, 'Any character after a complete expression should be an error');
assert(SParse("((a) b))") instanceof SyntaxError, 'Any character after a complete expression should be an error');
assert(SParse("((a))abc") instanceof SyntaxError, 'Any character after a complete expression should be an error');
assert(SParse("(')") instanceof SyntaxError, 'A \' without anything to quote should be an error');
assert.deepEqual(SParse("'()"), ['quote'], 'A quoted empty list should parse');
assert.deepEqual(SParse("()"), [], 'An empty list should parse');
assert.deepEqual(SParse("'a"), ['quote', 'a'], 'A quoted atom should parse');
assert.deepEqual(SParse("a"), 'a', 'An atom should parse');
assert.deepEqual(SParse("(a'b)"), ['a', ['quote', 'b']], 'Quotes should act symbol delimiting');
assert.deepEqual(SParse("(a\\'b)"), ['a\'b'], 'Escaped quotes in symbols should parse');
assert.deepEqual(SParse("(a\\\"b)"), ['a\"b'], 'Escaped quotes in symbols should parse');
assert.deepEqual(SParse("(a\\\\b)"), ['a\\b'], 'Escaped \\ in symbols should parse as \\');
assert.deepEqual(SParse("(a\\b)"), ['ab'], 'Escaped normal characters in symbols should parse as normal');

var error = SParse("(\n'");
assert(error instanceof SyntaxError, "Parsing (\\n' Should be an error");
assert(error.line == 2, "line should be 2");
assert(error.col == 2, "col should be 2");

error = SParse("(\r\n'");
assert(error instanceof SyntaxError, "Parsing (\\r\\n' Should be an error");
assert(error.line == 2, "line should be 2");
assert(error.col == 2, "col should be 1");

assert.deepEqual(SParse('(a "a")'), ['a', new String('a')], 'Strings should parse as String objects');
assert.deepEqual(SParse('(a"s"b)'), ['a', new String('s'), 'b'], 'Strings should act symbol delimiting');
assert.deepEqual(SParse('(a\\"s\\"b)'), ['a"s"b'], 'Escaped double quotes in symbols should parse');
assert.deepEqual(SParse('(a "\\"\n")'), ['a', new String('"\n')], 'Escaped double quotes \\" should work in Strings');
assert.deepEqual(SParse('(a "\\\\")'), ['a', new String('\\')], 'Escaped \\ should work in Strings');
assert.deepEqual(SParse('(a "\\a")'), ['a', new String('a')], 'Escaped characters should work in Strings');
assert(SParse('(a "string)') instanceof SyntaxError, 'Prematurely ending strings should produce an error');
assert(SParse('\'"string"', ['quote', new String('string')], 'A quoted string should parse'));

error = SParse("(\"a)");
assert(error instanceof SyntaxError);
assert(error.message == "Syntax error: Unterminated string literal", error.message);

assert.deepEqual(SParse('  a   '), 'a', 'Whitespace should be ignored');
assert.deepEqual(SParse('    '), '', 'The empty expression should parse');
<commit_msg>Failing tests for correct list quoting<commit_after>var assert = require('assert');
var SParse = require(process.cwd() + '/');
var SyntaxError = SParse.SyntaxError;

assert.deepEqual(SParse('((a b c)(()()))'), [['a','b','c'],[[],[]]]);
assert.deepEqual(SParse('((a b c) (() ()))'), [['a','b','c'],[[],[]]]);
assert.deepEqual(SParse("((a 'b 'c))"), [['a',['quote','b'],['quote','c']]]);
assert.deepEqual(SParse("(a '(a b c))"),  ['a', ['quote', ['a', 'b', 'c']]]);
assert.deepEqual(SParse("(a ' (a b c))"), ['a', ['quote', ['a', 'b', 'c']]]);
assert.deepEqual(SParse("(a '' (a b c))"), ['a', ['quote', ['quote', ['a', 'b', 'c']]]], 'Multiple quotes should not be flattened');
assert.deepEqual(SParse("((a `b `c))"), [['a',['quasiquote','b'],['quasiquote','c']]]);
assert.deepEqual(SParse("(a `(a b c))"),  ['a', ['quasiquote', ['a', 'b', 'c']]]);
assert.deepEqual(SParse("(a ` (a b c))"), ['a', ['quasiquote', ['a', 'b', 'c']]]);
assert.deepEqual(SParse("(a `` (a b c))"), ['a', ['quasiquote', ['quasiquote', ['a', 'b', 'c']]]], 'Multiple quasiquotes should not be flattened');
assert.deepEqual(SParse("((a ,b ,c))"), [['a',['unquote','b'],['unquote','c']]]);
assert.deepEqual(SParse("(a ,(a b c))"),  ['a', ['unquote', ['a', 'b', 'c']]]);
assert.deepEqual(SParse("(a , (a b c))"), ['a', ['unquote', ['a', 'b', 'c']]]);
assert.deepEqual(SParse("(a ,, (a b c))"), ['a', ['unquote', ['unquote', ['a', 'b', 'c']]]], 'Multiple unquotes should not be flattened');
assert.deepEqual(SParse("((a ,@b ,@c))"), [['a',['unquote-splicing','b'],['unquote-splicing','c']]]);
assert.deepEqual(SParse("(a ,@(a b c))"),  ['a', ['unquote-splicing', ['a', 'b', 'c']]]);
assert.deepEqual(SParse("(a ,@ (a b c))"), ['a', ['unquote-splicing', ['a', 'b', 'c']]]);
assert.deepEqual(SParse("(a ,@,@ (a b c))"), ['a', ['unquote-splicing', ['unquote-splicing', ['a', 'b', 'c']]]], 'Multiple unquote-splicings should not be flattened');
assert(SParse("()()") instanceof SyntaxError, 'Any character after a complete expression should be an error');
assert(SParse("((a) b))") instanceof SyntaxError, 'Any character after a complete expression should be an error');
assert(SParse("((a))abc") instanceof SyntaxError, 'Any character after a complete expression should be an error');
assert(SParse("(')") instanceof SyntaxError, 'A \' without anything to quote should be an error');
assert.deepEqual(SParse("'()"), ['quote', []], 'A quoted empty list should parse');
assert.deepEqual(SParse("()"), [], 'An empty list should parse');
assert.deepEqual(SParse("'a"), ['quote', 'a'], 'A quoted atom should parse');
assert.deepEqual(SParse("'(a)"), ['quote', ['a']], 'A quoted atom in a list should parse');
assert.deepEqual(SParse("a"), 'a', 'An atom should parse');
assert.deepEqual(SParse("(a'b)"), ['a', ['quote', 'b']], 'Quotes should act symbol delimiting');
assert.deepEqual(SParse("(a\\'b)"), ['a\'b'], 'Escaped quotes in symbols should parse');
assert.deepEqual(SParse("(a\\\"b)"), ['a\"b'], 'Escaped quotes in symbols should parse');
assert.deepEqual(SParse("(a\\\\b)"), ['a\\b'], 'Escaped \\ in symbols should parse as \\');
assert.deepEqual(SParse("(a\\b)"), ['ab'], 'Escaped normal characters in symbols should parse as normal');

var error = SParse("(\n'");
assert(error instanceof SyntaxError, "Parsing (\\n' Should be an error");
assert(error.line == 2, "line should be 2");
assert(error.col == 2, "col should be 2");

error = SParse("(\r\n'");
assert(error instanceof SyntaxError, "Parsing (\\r\\n' Should be an error");
assert(error.line == 2, "line should be 2");
assert(error.col == 2, "col should be 1");

assert.deepEqual(SParse('(a "a")'), ['a', new String('a')], 'Strings should parse as String objects');
assert.deepEqual(SParse('(a"s"b)'), ['a', new String('s'), 'b'], 'Strings should act symbol delimiting');
assert.deepEqual(SParse('(a\\"s\\"b)'), ['a"s"b'], 'Escaped double quotes in symbols should parse');
assert.deepEqual(SParse('(a "\\"\n")'), ['a', new String('"\n')], 'Escaped double quotes \\" should work in Strings');
assert.deepEqual(SParse('(a "\\\\")'), ['a', new String('\\')], 'Escaped \\ should work in Strings');
assert.deepEqual(SParse('(a "\\a")'), ['a', new String('a')], 'Escaped characters should work in Strings');
assert(SParse('(a "string)') instanceof SyntaxError, 'Prematurely ending strings should produce an error');
assert(SParse('\'"string"', ['quote', new String('string')], 'A quoted string should parse'));

error = SParse("(\"a)");
assert(error instanceof SyntaxError);
assert(error.message == "Syntax error: Unterminated string literal", error.message);

assert.deepEqual(SParse('  a   '), 'a', 'Whitespace should be ignored');
assert.deepEqual(SParse('    '), '', 'The empty expression should parse');
<|endoftext|>


<commit_before>var co = require('co');
var compose = require('./');

describe('Koa Compose', function(){
  it('should work', function(done){
    var arr = [];
    var stack = [];

    stack.push(function *(next){
      arr.push(1);
      yield next();
      arr.push(6);
    })

    stack.push(function *(next){
      arr.push(2);
      yield next();
      arr.push(5);
    })

    stack.push(function *(next){
      arr.push(3);
      yield next();
      arr.push(4);
    })

    co(compose(stack))(function(err){
      if (err) throw err;

      arr.should.eql([1, 2, 3, 4, 5, 6]);
      done();
    })
  })

  it('should work with 0 middleware', function(done){
    co(compose([]))(done);
  })

  it('should work within a generator', function(done){
    var arr = [];

    co(function *(){
      arr.push(0);

      var stack = [];

      stack.push(function* (next){
        arr.push(1);
        yield next();
        arr.push(4);
      });

      stack.push(function *(next){
        arr.push(2);
        yield next();
        arr.push(3);
      });

      yield compose(stack)

      arr.push(5);
    })(function(err){
      if (err) throw err;

      arr.should.eql([0, 1, 2, 3, 4, 5]);
      done();
    })
  })

  it('should work when yielding at the end of the stack', function(done) {
    var stack = [];

    stack.push(function *(next){
      yield next();
    });

    co(compose(stack))(done);
  })

  it('should keep the context', function(done){
    var ctx = {};

    var stack = [];

    stack.push(function *(next){
      this.should.equal(ctx);
    })

    stack.push(function *(next){
      this.should.equal(ctx);
    })

    stack.push(function *(next){
      this.should.equal(ctx);
    })

    co.call(ctx, compose(stack))(done);
  })

  it('should throw when `next()` out of the stack', function(done){
    var stack = [];

    stack.push(function *(next){
      yield next();
      yield next();
    })

    co(compose(stack))(function(err){
      err.should.be.ok;
      done();
    })
  })
})<commit_msg>some more tests<commit_after>var co = require('co');
var compose = require('./');

function wait(ms) {
  return function (done) {
    setTimeout(done, ms || 0);
  }
}

describe('Koa Compose', function(){
  it('should work', function(done){
    var arr = [];
    var stack = [];

    stack.push(function *(next){
      arr.push(1);
      wait(1);
      yield next();
      wait(1);
      arr.push(6);
    })

    stack.push(function *(next){
      arr.push(2);
      wait(1);
      yield next();
      wait(1);
      arr.push(5);
    })

    stack.push(function *(next){
      arr.push(3);
      wait(1);
      yield next();
      wait(1);
      arr.push(4);
    })

    co(compose(stack))(function(err){
      if (err) throw err;

      arr.should.eql([1, 2, 3, 4, 5, 6]);
      done();
    })
  })

  it('should work with 0 middleware', function(done){
    co(compose([]))(done);
  })

  it('should work within a generator', function(done){
    var arr = [];

    co(function *(){
      arr.push(0);

      var stack = [];

      stack.push(function* (next){
        arr.push(1);
        yield next();
        arr.push(4);
      });

      stack.push(function *(next){
        arr.push(2);
        yield next();
        arr.push(3);
      });

      yield compose(stack)

      arr.push(5);
    })(function(err){
      if (err) throw err;

      arr.should.eql([0, 1, 2, 3, 4, 5]);
      done();
    })
  })

  it('should work when yielding at the end of the stack', function(done) {
    var stack = [];

    stack.push(function *(next){
      yield next();
    });

    co(compose(stack))(done);
  })

  it('should keep the context', function(done){
    var ctx = {};

    var stack = [];

    stack.push(function *(next){
      this.should.equal(ctx);
    })

    stack.push(function *(next){
      this.should.equal(ctx);
    })

    stack.push(function *(next){
      this.should.equal(ctx);
    })

    co.call(ctx, compose(stack))(done);
  })

  it('should throw when `next()` out of the stack', function(done){
    var stack = [];

    stack.push(function *(next){
      yield next();
      yield next();
    })

    co(compose(stack))(function(err){
      err.should.be.ok;
      done();
    })
  })

  it('should catch downstream errors', function(done){
    var arr = [];
    var stack = [];

    stack.push(function *(next){
      arr.push(1);
      try {
        yield next();
      } catch (err) {
        arr.push(2);
      }
      arr.push(3);
    })

    stack.push(function *(next){
      arr.push(4);
      throw new Error();
      arr.push(5);
    })

    co(compose(stack))(function(err){
      if (err) throw err;

      arr.should.eql([1, 4, 2, 3]);
      done();
    })
  })
})<|endoftext|>


<commit_before>'use strict';

var http = require('http');
var assert = require('assert');
var EventEmitter = require('events').EventEmitter;
var requestStats = require('./index');
var Request = require('./lib/request');
var StatsEmitter = require('./lib/stats_emitter');
var KeepAliveAgent = require('keep-alive-agent');

assert._statsCommon = function (stats) {
  assert(stats.req.bytes > 0); // different headers will result in different results
  assert.equal(typeof stats.req.headers.connection, 'string');
  assert.equal(stats.req.method, 'PUT');
  assert.equal(stats.req.path, '/');
  assert.equal(stats.res.status, 200);
};

// assertion helper for validating stats from HTTP requests that finished correctly
assert.statsFinished = function (stats) {
  assert(stats.ok);
  assert(stats.time >= 9); // The reason we don't just do >= 10, is because setTimeout is not that precise
  assert(stats.res.bytes > 0); // different headers will result in different results
  assert.equal(typeof stats.res.headers.connection, 'string');
  assert._statsCommon(stats);
};

// assertion helper for validating stats from HTTP requests that are closed before finishing
assert.statsClosed = function (stats) {
  assert(!stats.ok);
  assert(stats.time >= 0);
  assert.equal(stats.res.bytes, 0);
  assert.deepEqual(stats.res.headers, {});
  assert._statsCommon(stats);
};

var _start = function (server, errorHandler) {
  server.listen(0, function () {
    var options = {
      port: server.address().port,
      method: 'PUT'
    };

    var req = http.request(options, function (res) {
      res.resume();
      res.once('end', function () {
        server.close();
      });
    });

    if (errorHandler)
      req.on('error', errorHandler);

    req.end('42');
  });
};

var _respond = function (req, res) {
  req.on('end', function () {
    setTimeout(function () {
      res.end('Answer to the Ultimate Question of Life, The Universe, and Everything');
    }, 10);
  });
  req.resume();
};

describe('StatsEmitter', function () {
  it('should be retuned from requestStats()', function () {
    var statsEmitter = requestStats();
    assert(statsEmitter instanceof StatsEmitter);
  });

  it('should be instance of EventEmitter', function () {
    var statsEmitter = requestStats();
    assert(statsEmitter instanceof EventEmitter);
  });

  it('should emit a "request" event', function (done) {
    var server = http.createServer(_respond);
    requestStats(server).on('request', function () {
      done();
    });
    _start(server);
  });

  it('should emit a "complete" event', function (done) {
    var server = http.createServer(_respond);
    requestStats(server).on('complete', function () {
      done();
    });
    _start(server);
  });
});

describe('requestStats(server, onStats)', function () {
  it('should call the stats-listener on request end', function (done) {
    var server = http.createServer(_respond);
    requestStats(server, function (stats) {
      assert.statsFinished(stats);
      done();
    });
    _start(server);
  });

  it('should call the stats-listener when the request is destroyed', function (done) {
    var server = http.createServer(function (req, res) {
      req.destroy();
    });
    requestStats(server, function (stats) {
      assert.statsClosed(stats);
    });
    _start(server, function (err) {
      assert(err instanceof Error);
      done();
    });
  });

  it('should calculate correct bytes read/written on keep-alive connections', function (done) {
    var agent = new http.Agent();
    agent.maxSockets = 1; // force connection reuse for every connection

    var server = http.createServer(function (req, res) {
      req.on('end', function () {
        res.end();
      });
      req.resume();
    });

    server.once('connection', function () {
      server.once('connection', function () {
        assert(false, 'Expected the TCP connection to be reused');
      });
    });

    requestStats(server, function (stats) {
      // assert req.bytes are around 1 million (we cannot know exactly since
      // request headers will vary depending on the host system)
      assert(stats.req.bytes > 1000000);
      assert(stats.req.bytes < 1000300);
    });

    var performRequest = function (port, callback) {
      var req = http.request({ port: port, method: 'PUT', agent: agent }, function (res) {
        res.on('end', callback);
        res.resume();
      });
      for (var n = 0, s = ''; n < 100000; n++) s += '1234567890'; // 1 million
      req.end(s);
    };

    server.listen(0, function () {
      var port = server.address().port;
      performRequest(port, function () {
        performRequest(port, function () {
          server.close();
          done();
        });
      });
    });
  });
});

describe('requestStats(req, res).once(...)', function () {
  it('should call the stats-listener on request end', function (done) {
    _start(http.createServer(function (req, res) {
      requestStats(req, res).once('complete', function (stats) {
        assert.statsFinished(stats);
        done();
      });
      _respond(req, res);
    }));
  });
});

describe('requestStats(server).once(...)', function () {
  it('should call the stats-listener on request end', function (done) {
    var server = http.createServer(_respond);
    requestStats(server).once('complete', function (stats) {
      assert.statsFinished(stats);
      done();
    });
    _start(server);
  });
});

describe('requestStats(req, res, onStats)', function () {
  it('should call the stats-listener on request end', function (done) {
    _start(http.createServer(function (req, res) {
      requestStats(req, res, function (stats) {
        assert.statsFinished(stats);
        done();
      });
      _respond(req, res);
    }));
  });
});

describe('Request instance', function () {
  it('should expose a .progress() function', function (done) {
    _start(http.createServer(function (req, res) {
      var request = new Request(req, res);
      assert(typeof request.progress === 'function');
      done();
    }));
  });

  it('should be emitted on the "request" event', function (done) {
    var server = http.createServer(_respond);
    var statsEmitter = requestStats(server)
    var request;
    statsEmitter.on('request', function (obj) {
      request = obj;
    });
    statsEmitter.on('complete', function (stats) {
      assert(request instanceof Request);
      done();
    });
    _start(server);
  });
});

describe('request.progress()', function () {
  it('should return a progress object', function (done) {
    var server = http.createServer(_respond);
    var statsEmitter = requestStats(server);
    statsEmitter.on('request', function (request) {
      var progress = request.progress();
      assert.equal(progress.completed, false);
      assert(progress.time >= 0);
      assert(progress.timeDelta >= 0);
      assert(progress.req.bytes > 0);
      assert(progress.req.bytesDelta > 0);
      assert(progress.req.speed > 0);
      assert.equal(progress.res.bytes, 0);
      assert.equal(progress.res.bytesDelta, 0);
      assert.equal(progress.res.speed, 0);
      done();
    });
    _start(server);
  });

  it('should not mix progress from two request', function (done) {
    var server = http.createServer(_respond);
    var statsEmitter = requestStats(server);
    var requests = [];
    var progress = [];

    statsEmitter.on('request', function (request) {
      requests.push(request);
      assert.strictEqual(typeof request._connection, 'object');
    });

    statsEmitter.on('complete', function (stats) {
      progress.push(requests[requests.length-1].progress());
      if (requests.length < 2) return;
      assert.strictEqual(requests[0]._connection, requests[1]._connection);
      assert.strictEqual(progress[0].req.bytes, progress[1].req.bytes);
      assert.strictEqual(progress[0].res.bytes, progress[1].res.bytes);
      assert.strictEqual(progress[0].req.bytes + progress[1].req.bytes, requests[0]._connection.bytesRead);
      assert.strictEqual(progress[0].res.bytes + progress[1].res.bytes, requests[0]._connection.bytesWritten);
      done();
    });

    server.listen(0, function () {
      var options = {
        port: server.address().port,
        method: 'PUT',
        agent: new KeepAliveAgent()
      };

      http.request(options, function (res) {
        res.resume();
      }).end('42');

      setTimeout(function () {
        http.request(options, function (res) {
          res.resume();
          res.once('end', function () {
            server.close();
          });
        }).end('42');
      }, 100);
    });
  });
});
<commit_msg>Improve test output<commit_after>'use strict';

var http = require('http');
var assert = require('assert');
var EventEmitter = require('events').EventEmitter;
var requestStats = require('./index');
var Request = require('./lib/request');
var StatsEmitter = require('./lib/stats_emitter');
var KeepAliveAgent = require('keep-alive-agent');

assert._statsCommon = function (stats) {
  assert(stats.req.bytes > 0); // different headers will result in different results
  assert.equal(typeof stats.req.headers.connection, 'string');
  assert.equal(stats.req.method, 'PUT');
  assert.equal(stats.req.path, '/');
  assert.equal(stats.res.status, 200);
};

// assertion helper for validating stats from HTTP requests that finished correctly
assert.statsFinished = function (stats) {
  assert(stats.ok);
  assert(stats.time >= 9); // The reason we don't just do >= 10, is because setTimeout is not that precise
  assert(stats.res.bytes > 0); // different headers will result in different results
  assert.equal(typeof stats.res.headers.connection, 'string');
  assert._statsCommon(stats);
};

// assertion helper for validating stats from HTTP requests that are closed before finishing
assert.statsClosed = function (stats) {
  assert(!stats.ok);
  assert(stats.time >= 0);
  assert.equal(stats.res.bytes, 0);
  assert.deepEqual(stats.res.headers, {});
  assert._statsCommon(stats);
};

var _start = function (server, errorHandler) {
  server.listen(0, function () {
    var options = {
      port: server.address().port,
      method: 'PUT'
    };

    var req = http.request(options, function (res) {
      res.resume();
      res.once('end', function () {
        server.close();
      });
    });

    if (errorHandler)
      req.on('error', errorHandler);

    req.end('42');
  });
};

var _respond = function (req, res) {
  req.on('end', function () {
    setTimeout(function () {
      res.end('Answer to the Ultimate Question of Life, The Universe, and Everything');
    }, 10);
  });
  req.resume();
};

describe('StatsEmitter', function () {
  it('should be retuned from requestStats()', function () {
    var statsEmitter = requestStats();
    assert(statsEmitter instanceof StatsEmitter);
  });

  it('should be instance of EventEmitter', function () {
    var statsEmitter = requestStats();
    assert(statsEmitter instanceof EventEmitter);
  });

  it('should emit a "request" event', function (done) {
    var server = http.createServer(_respond);
    requestStats(server).on('request', function () {
      done();
    });
    _start(server);
  });

  it('should emit a "complete" event', function (done) {
    var server = http.createServer(_respond);
    requestStats(server).on('complete', function () {
      done();
    });
    _start(server);
  });
});

describe('requestStats(server, onStats)', function () {
  it('should call the stats-listener on request end', function (done) {
    var server = http.createServer(_respond);
    requestStats(server, function (stats) {
      assert.statsFinished(stats);
      done();
    });
    _start(server);
  });

  it('should call the stats-listener when the request is destroyed', function (done) {
    var server = http.createServer(function (req, res) {
      req.destroy();
    });
    requestStats(server, function (stats) {
      assert.statsClosed(stats);
    });
    _start(server, function (err) {
      assert(err instanceof Error);
      done();
    });
  });

  it('should calculate correct bytes read/written on keep-alive connections', function (done) {
    var agent = new http.Agent();
    agent.maxSockets = 1; // force connection reuse for every connection

    var server = http.createServer(function (req, res) {
      req.on('end', function () {
        res.end();
      });
      req.resume();
    });

    server.once('connection', function () {
      server.once('connection', function () {
        assert(false, 'Expected the TCP connection to be reused');
      });
    });

    requestStats(server, function (stats) {
      // assert req.bytes are around 1 million (we cannot know exactly since
      // request headers will vary depending on the host system)
      assert(stats.req.bytes > 1000000);
      assert(stats.req.bytes < 1000300);
    });

    var performRequest = function (port, callback) {
      var req = http.request({ port: port, method: 'PUT', agent: agent }, function (res) {
        res.on('end', callback);
        res.resume();
      });
      for (var n = 0, s = ''; n < 100000; n++) s += '1234567890'; // 1 million
      req.end(s);
    };

    server.listen(0, function () {
      var port = server.address().port;
      performRequest(port, function () {
        performRequest(port, function () {
          server.close();
          done();
        });
      });
    });
  });
});

describe('requestStats(req, res).once(...)', function () {
  it('should call the stats-listener on request end', function (done) {
    _start(http.createServer(function (req, res) {
      requestStats(req, res).once('complete', function (stats) {
        assert.statsFinished(stats);
        done();
      });
      _respond(req, res);
    }));
  });
});

describe('requestStats(server).once(...)', function () {
  it('should call the stats-listener on request end', function (done) {
    var server = http.createServer(_respond);
    requestStats(server).once('complete', function (stats) {
      assert.statsFinished(stats);
      done();
    });
    _start(server);
  });
});

describe('requestStats(req, res, onStats)', function () {
  it('should call the stats-listener on request end', function (done) {
    _start(http.createServer(function (req, res) {
      requestStats(req, res, function (stats) {
        assert.statsFinished(stats);
        done();
      });
      _respond(req, res);
    }));
  });
});

describe('Request instance', function () {
  it('should expose a .progress() function', function (done) {
    _start(http.createServer(function (req, res) {
      var request = new Request(req, res);
      assert(typeof request.progress === 'function');
      done();
    }));
  });

  it('should be emitted on the "request" event', function (done) {
    var server = http.createServer(_respond);
    var statsEmitter = requestStats(server)
    var request;
    statsEmitter.on('request', function (obj) {
      request = obj;
    });
    statsEmitter.on('complete', function (stats) {
      assert(request instanceof Request);
      done();
    });
    _start(server);
  });
});

describe('request.progress()', function () {
  it('should return a progress object', function (done) {
    var server = http.createServer(_respond);
    var statsEmitter = requestStats(server);
    statsEmitter.on('request', function (request) {
      var progress = request.progress();
      assert.equal(progress.completed, false);
      assert(progress.time >= 0);
      assert(progress.timeDelta >= 0);
      assert(progress.req.bytes > 0);
      assert(progress.req.bytesDelta > 0);
      assert(progress.req.speed > 0);
      assert.equal(progress.res.bytes, 0);
      assert.equal(progress.res.bytesDelta, 0);
      assert.equal(progress.res.speed, 0);
      done();
    });
    _start(server);
  });

  it('should not mix progress from two request', function (done) {
    var server = http.createServer(_respond);
    var statsEmitter = requestStats(server);
    var requests = [];
    var progress = [];

    statsEmitter.on('request', function (request) {
      requests.push(request);
      assert.strictEqual(typeof request._connection, 'object');
    });

    statsEmitter.on('complete', function (stats) {
      progress.push(requests[requests.length-1].progress());
      if (requests.length < 2) return;
      assert.strictEqual(requests[0]._connection, requests[1]._connection, 'should re-use the http connection');
      assert.strictEqual(progress[0].req.bytes, progress[1].req.bytes, 'should receive the same amount of data');
      assert.strictEqual(progress[0].res.bytes, progress[1].res.bytes, 'should send the same amount of data');
      assert.strictEqual(progress[0].req.bytes + progress[1].req.bytes, requests[0]._connection.bytesRead, 'should not accumulate received data');
      assert.strictEqual(progress[0].res.bytes + progress[1].res.bytes, requests[0]._connection.bytesWritten, 'should not accumulate sent data');
      done();
    });

    server.listen(0, function () {
      var options = {
        port: server.address().port,
        method: 'PUT',
        agent: new KeepAliveAgent()
      };

      http.request(options, function (res) {
        res.resume();
      }).end('42');

      setTimeout(function () {
        http.request(options, function (res) {
          res.resume();
          res.once('end', function () {
            server.close();
          });
        }).end('42');
      }, 100);
    });
  });
});
<|endoftext|>


<commit_before>/*
Name:           geoip2ws - test.js
Description:    Maxmind GeoIP2 Web Services for node.js
Source & docs:  https://github.com/fvdm/nodejs-geoip2ws
Feedback:       https://github.com/fvdm/nodejs-geoip2ws/issues
License:        Unlicense (public domain)
*/

var doTest = require ('dotest');
var app = require ('./');

var geo;

// Setup
// set env GEOIP2WS_USERID and GEOIP2WS_LICENSE  (CI tests)
var config = {
  userId: process.env.GEOIP2WS_USERID || null,
  licenseKey: process.env.GEOIP2WS_LICENSE || null,
  service: process.env.GEOIP2WS_SERVICE || 'city',
  endpoint: process.env.GEOIP2WS_ENDPOINT || 'https://geoip.maxmind.com/geoip/v2.1/',
  requestTimeout: process.env.GEOIP2WS_TIMEOUT || 5000
};

if (!config.userId || !config.licenseKey) {
  config.endpoint = 'https://frankl.in/u/ci_test.php?a=geoip2ws&b=';
}

geo = app (config);

// METHOD
doTest.add ('Module', function () {
  doTest.test ()
    .isFunction ('fail', 'exports', app)
    .isFunction ('fail', 'geo', geo)
    .done ();
});

// Test success
doTest.add ('lookup', function () {
  geo ('74.125.206.100', function (err, data) {
    doTest.test (err)
      .isString ('fail', 'city name', data && data.city.names.en)
      .done ();
  });
});

// Test errors
doTest.add ('Error: invalid ip', function () {
  geo ('invalid input', function (err) {
    doTest.test ()
      .isError ('fail', 'err', err)
      .isExactly ('fail', 'err.message', err && err.message, 'invalid ip')
      .done ();
  });
});

doTest.add ('Error: invalid service', function () {
  geo ('invalid service', '74.125.206.100', function (err) {
    doTest.test ()
      .isError ('fail', 'err', err)
      .isExactly ('fail', 'err.message', err && err.message, 'invalid service')
      .done ();
  });
});

doTest.add ('Error: API error', function () {
  geo ('0.0.0.0', function (err) {
    doTest.test ()
      .isError ('fail', 'err', err)
      .isExactly ('fail', 'err.message', err && err.message, 'API error')
      .done ();
  });
});

doTest.add ('Error: request timeout', function () {
  var tmp = app (
    config.userId,
    config.licenseKey,
    config.service,
    1
  );

  tmp ('74.125.206.100', function (err) {
    doTest.test ()
      .isError ('fail', 'err', err)
      .isExactly ('fail', 'err.message', err && err.message, 'request failed')
      .isExactly ('fail', 'err.error.code', err && err.error.code, 'TIMEOUT')
      .done ();
  });
});

// Start the tests
doTest.run ();
<commit_msg>Test: wrap endpoint selection in test<commit_after>/*
Name:           geoip2ws - test.js
Description:    Maxmind GeoIP2 Web Services for node.js
Source & docs:  https://github.com/fvdm/nodejs-geoip2ws
Feedback:       https://github.com/fvdm/nodejs-geoip2ws/issues
License:        Unlicense (public domain)
*/

var doTest = require ('dotest');
var app = require ('./');

var geo;

// Setup
// set env GEOIP2WS_USERID and GEOIP2WS_LICENSE  (CI tests)
var config = {
  userId: process.env.GEOIP2WS_USERID || null,
  licenseKey: process.env.GEOIP2WS_LICENSE || null,
  service: process.env.GEOIP2WS_SERVICE || 'city',
  endpoint: process.env.GEOIP2WS_ENDPOINT || 'https://geoip.maxmind.com/geoip/v2.1/',
  requestTimeout: process.env.GEOIP2WS_TIMEOUT || 5000
};

// TESTS
doTest.add ('Configuration', function (test) {
  if (!config.userId || !config.licenseKey) {
    config.endpoint = 'https://frankl.in/u/ci_test.php?a=geoip2ws&b=';

    test ()
      .warn ('userId or licenseKey not set')
      .info ('Using test endpoint with fake data');
  } else {
    test ()
      .good ('userId and licenseKey are set')
      .info ('Using MaxMind endpoint with real data');
  }

  geo = app (config);

  test ()
    .info ('config.service:         ' + config.service)
    .info ('config.requestTimeout:  ' + config.requestTimeout)
    .done ();
});

// METHOD
doTest.add ('Module', function () {
  doTest.test ()
    .isFunction ('fail', 'exports', app)
    .isFunction ('fail', 'geo', geo)
    .done ();
});

// Test success
doTest.add ('lookup', function () {
  geo ('74.125.206.100', function (err, data) {
    doTest.test (err)
      .isString ('fail', 'city name', data && data.city.names.en)
      .done ();
  });
});

// Test errors
doTest.add ('Error: invalid ip', function () {
  geo ('invalid input', function (err) {
    doTest.test ()
      .isError ('fail', 'err', err)
      .isExactly ('fail', 'err.message', err && err.message, 'invalid ip')
      .done ();
  });
});

doTest.add ('Error: invalid service', function () {
  geo ('invalid service', '74.125.206.100', function (err) {
    doTest.test ()
      .isError ('fail', 'err', err)
      .isExactly ('fail', 'err.message', err && err.message, 'invalid service')
      .done ();
  });
});

doTest.add ('Error: API error', function () {
  geo ('0.0.0.0', function (err) {
    doTest.test ()
      .isError ('fail', 'err', err)
      .isExactly ('fail', 'err.message', err && err.message, 'API error')
      .done ();
  });
});

doTest.add ('Error: request timeout', function () {
  var tmp = app (
    config.userId,
    config.licenseKey,
    config.service,
    1
  );

  tmp ('74.125.206.100', function (err) {
    doTest.test ()
      .isError ('fail', 'err', err)
      .isExactly ('fail', 'err.message', err && err.message, 'request failed')
      .isExactly ('fail', 'err.error.code', err && err.error.code, 'TIMEOUT')
      .done ();
  });
});

// Start the tests
doTest.run ();
<|endoftext|>


<commit_before>/*
Name:           geoip2ws - test.js
Description:    Maxmind GeoIP2 Web Services for node.js
Source & docs:  https://github.com/fvdm/nodejs-geoip2ws
Feedback:       https://github.com/fvdm/nodejs-geoip2ws/issues
License:        Unlicense (public domain)
*/

var app = require ('./');

// Setup
// set env GEOIP2WS_USERID and GEOIP2WS_LICENSE  (CI tests)
var config = {
  userId: process.env.GEOIP2WS_USERID || null,
  licenseKey: process.env.GEOIP2WS_LICENSE || null,
  service: process.env.GEOIP2WS_SERVICE || 'city',
  endpoint: process.env.GEOIP2WS_ENDPOINT || 'https://geoip.maxmind.com/geoip/v2.1/',
  requestTimeout: process.env.GEOIP2WS_TIMEOUT || 5000
}

if (!config.userId || !config.licenseKey) {
  config.endpoint = 'https://frankl.in/u/ci_test.php?a=geoip2ws&b=';
}

var geo = app (config);

// handle exits
var errors = 0;
process.on ('exit', function () {
  if (errors === 0) {
    console.log ('\n\u001b[1mDONE, no errors.\u001b[0m\n');
    process.exit (0);
  } else {
    console.log ('\n\u001b[1mFAIL, '+ errors +' error'+  (errors > 1 ? 's' : '') +' occurred!\u001b[0m\n');
    process.exit (1);
  }
});

// prevent errors from killing the process
process.on ('uncaughtException', function (err) {
  console.log ();
  console.error (err.stack);
  console.log ();
  errors++;
});

// Queue to prevent flooding
var queue = [];
var next = 0;

function doNext () {
  next++;
  if (queue[next]) {
    queue[next] ();
  }
}

// doTest (passErr, 'methods', [
//   ['feeds', typeof feeds === 'object']
// ])
function doTest (err, label, tests) {
  if (err instanceof Error) {
    console.error (label +': \u001b[1m\u001b[31mERROR\u001b[0m\n');
    console.dir (err, { depth: null, colors: true });
    console.log ();
    console.error (err.stack);
    console.log ();
    errors++;
  } else {
    var testErrors = [];
    tests.forEach (function (test) {
      if (test[1] !== true) {
        testErrors.push (test[0]);
        errors++;
      }
    });

    if (testErrors.length === 0) {
      console.log (label +': \u001b[1m\u001b[32mok\u001b[0m');
    } else {
      console.error (label +': \u001b[1m\u001b[31mfailed\u001b[0m  ('+ testErrors.join (', ') +')');
    }
  }

  doNext ();
}

// METHOD
queue.push (function () {
  doTest (null, 'module', [
    ['function type', typeof geo === 'function']
  ]);
});

// Test success
queue.push (function () {
  geo ('74.125.206.100', function (err, data) {
    doTest (err, 'lookup', [
      ['city name', !err && data && typeof data.city.names.en === 'string']
    ]);
  });
});

// Test errors
queue.push (function () {
  geo ('invalid input', function (err) {
    doTest (null, 'Error: invalid ip', [
      ['type', err instanceof Error],
      ['message', err.message === 'invalid ip']
    ]);
  });
});

queue.push (function () {
  geo ('invalid service', '74.125.206.100', function (err) {
    doTest (null, 'Error: invalid service', [
      ['type', err instanceof Error],
      ['message', err.message === 'invalid service']
    ]);
  });
});

queue.push (function () {
  geo ('0.0.0.0', function (err) {
    doTest (null, 'Error: API error', [
      ['type', err instanceof Error],
      ['message', err.message === 'API error']
    ]);
  });
});

queue.push (function () {
  var tmp = app (
    config.userId,
    config.licenseKey,
    config.service,
    1
  );

  tmp ('74.125.206.100', function (err) {
    doTest (null, 'Error: request timeout', [
      ['type', err instanceof Error],
      ['message', err.error.code === 'TIMEOUT']
    ]);
  });
});

// Start the tests
queue[0] ();
<commit_msg>Fixed eslint errors<commit_after>/*
Name:           geoip2ws - test.js
Description:    Maxmind GeoIP2 Web Services for node.js
Source & docs:  https://github.com/fvdm/nodejs-geoip2ws
Feedback:       https://github.com/fvdm/nodejs-geoip2ws/issues
License:        Unlicense (public domain)
*/

var app = require ('./');
var geo;
var errors = 0;
var queue = [];
var next = 0;

// Setup
// set env GEOIP2WS_USERID and GEOIP2WS_LICENSE  (CI tests)
var config = {
  userId: process.env.GEOIP2WS_USERID || null,
  licenseKey: process.env.GEOIP2WS_LICENSE || null,
  service: process.env.GEOIP2WS_SERVICE || 'city',
  endpoint: process.env.GEOIP2WS_ENDPOINT || 'https://geoip.maxmind.com/geoip/v2.1/',
  requestTimeout: process.env.GEOIP2WS_TIMEOUT || 5000
};

if (!config.userId || !config.licenseKey) {
  config.endpoint = 'https://frankl.in/u/ci_test.php?a=geoip2ws&b=';
}

geo = app (config);

// handle exits
process.on ('exit', function () {
  if (errors === 0) {
    console.log ('\n\u001b[1mDONE, no errors.\u001b[0m\n');
    process.exit (0);
  } else {
    console.log ('\n\u001b[1mFAIL, ' + errors + ' error' + (errors > 1 ? 's' : '') + ' occurred!\u001b[0m\n');
    process.exit (1);
  }
});

// prevent errors from killing the process
process.on ('uncaughtException', function (err) {
  console.log ();
  console.error (err.stack);
  console.log ();
  errors++;
});

// Queue to prevent flooding
function doNext () {
  next++;
  if (queue[next]) {
    queue[next] ();
  }
}

// doTest (passErr, 'methods', [
//   ['feeds', typeof feeds === 'object']
// ])
function doTest (err, label, tests) {
  var testErrors = [];

  if (err instanceof Error) {
    console.error (label + ': \u001b[1m\u001b[31mERROR\u001b[0m\n');
    console.dir (err, { depth: null, colors: true });
    console.log ();
    console.error (err.stack);
    console.log ();
    errors++;
  } else {
    tests.forEach (function (test) {
      if (test[1] !== true) {
        testErrors.push (test[0]);
        errors++;
      }
    });

    if (testErrors.length === 0) {
      console.log (label + ': \u001b[1m\u001b[32mok\u001b[0m');
    } else {
      console.error (label + ': \u001b[1m\u001b[31mfailed\u001b[0m  (' + testErrors.join (', ') + ')');
    }
  }

  doNext ();
}

// METHOD
queue.push (function () {
  doTest (null, 'module', [
    ['function type', typeof geo === 'function']
  ]);
});

// Test success
queue.push (function () {
  geo ('74.125.206.100', function (err, data) {
    doTest (err, 'lookup', [
      ['city name', !err && data && typeof data.city.names.en === 'string']
    ]);
  });
});

// Test errors
queue.push (function () {
  geo ('invalid input', function (err) {
    doTest (null, 'Error: invalid ip', [
      ['type', err instanceof Error],
      ['message', err.message === 'invalid ip']
    ]);
  });
});

queue.push (function () {
  geo ('invalid service', '74.125.206.100', function (err) {
    doTest (null, 'Error: invalid service', [
      ['type', err instanceof Error],
      ['message', err.message === 'invalid service']
    ]);
  });
});

queue.push (function () {
  geo ('0.0.0.0', function (err) {
    doTest (null, 'Error: API error', [
      ['type', err instanceof Error],
      ['message', err.message === 'API error']
    ]);
  });
});

queue.push (function () {
  var tmp = app (
    config.userId,
    config.licenseKey,
    config.service,
    1
  );

  tmp ('74.125.206.100', function (err) {
    doTest (null, 'Error: request timeout', [
      ['type', err instanceof Error],
      ['message', err.error.code === 'TIMEOUT']
    ]);
  });
});

// Start the tests
queue[0] ();
<|endoftext|>


<commit_before>import test from 'ava';
import m from '.';

test('main', t => {
	t.is(m('abcde'), 5);
	t.is(m('古池や'), 6);
	t.is(m('あいうabc'), 9);
	t.is(m('ノード.js'), 9);
	t.is(m('你好'), 4);
	t.is(m('안녕하세요'), 10);
	t.is(m('A\ud83c\ude00BC'), 5, 'surrogate');
	t.is(m('\u001b[31m\u001b[39m'), 0);
});

test('ignores control characters', t => {
	t.is(m(String.fromCharCode(0)), 0);
	t.is(m(String.fromCharCode(31)), 0);
	t.is(m(String.fromCharCode(127)), 0);
	t.is(m(String.fromCharCode(134)), 0);
	t.is(m(String.fromCharCode(159)), 0);
	t.is(m('\u001b'), 0);
});
<commit_msg>Add failing test for #6<commit_after>import test from 'ava';
import m from '.';

test('main', t => {
	t.is(m('abcde'), 5);
	t.is(m('古池や'), 6);
	t.is(m('あいうabc'), 9);
	t.is(m('ノード.js'), 9);
	t.is(m('你好'), 4);
	t.is(m('안녕하세요'), 10);
	t.is(m('A\ud83c\ude00BC'), 5, 'surrogate');
	t.is(m('\u001b[31m\u001b[39m'), 0);
});

test('ignores control characters', t => {
	t.is(m(String.fromCharCode(0)), 0);
	t.is(m(String.fromCharCode(31)), 0);
	t.is(m(String.fromCharCode(127)), 0);
	t.is(m(String.fromCharCode(134)), 0);
	t.is(m(String.fromCharCode(159)), 0);
	t.is(m('\u001b'), 0);
});

test.failing('handles combining characters', t => {
	t.is(m('x\u0300'), 1);
});
<|endoftext|>


<commit_before>/* global it, beforeEach, afterEach */
'use strict'

const assert = require('assert')
const fs = require('fs')
const path = require('path')
const broccoli = require('broccoli')
const postcssCompiler = require('./')
const postcss = require('postcss')
const rimraf = require('rimraf')
const glob = require('glob')
const async = require('async')

const basicOptionSet = {
  plugins: [
    {
      module: require('postcss-color-rebeccapurple')
    }
  ]
}

const testWarnOptionsSet = {
  errors: {
    showSourceCode: true,
    terminalColors: false
  },
  plugins: [
    {
      module: postcss.plugin('postcss-test-warn', function (opts) {
        return function (root, result) {
          result.warn('This is a warning.')
        }
      })
    }
  ]
}

const browsersOptionSet = {
  plugins: [
    {
      module: postcss.plugin('return-options', (options) => {
        return (root, result) => {
          result.warn(options.browsers.join(', '))
        }
      })
    }
  ],
  browsers: ['last 2 versions', 'ie > 9', 'ios >= 8', '> 5%']
}

const map = {
  inline: false,
  annotation: false
}

basicOptionSet.map = map
testWarnOptionsSet.map = map

let warnings = []
let warningStreamStub = {
  write: function (warning) {
    warnings.push(warning)
  }
}

beforeEach(function () {
  warnings = []
})

afterEach(function () {
  glob('tmp/*', function (err, files) {
    if (err) {
      console.error(err)
    } else {
      async.forEach(files, rimraf)
    }
  })
})

function processCss (outputTree) {
  let builder = new broccoli.Builder(outputTree) // eslint-disable-line no-new
  outputTree.warningStream = warningStreamStub

  return builder.build().then(function () {
    let content = fs.readFileSync(path.join(builder.outputPath, 'output.css'), 'utf8')
    let sourceMap = JSON.parse(fs.readFileSync(path.join(builder.outputPath, 'output.css.map'), 'utf8'))

    assert.strictEqual(content.trim(), 'body {\n  color: #639\n}')
    assert.strictEqual(sourceMap.mappings, 'AAAA;EACE,WAAoB;CACrB')
    assert.deepStrictEqual(warnings, [])
  })
}

it('should process css', function () {
  let outputTree = postcssCompiler(['fixture/success'], 'fixture.css', 'output.css', basicOptionSet)
  return processCss(outputTree)
})

it('should expose warnings', function () {
  let outputTree = postcssCompiler(['fixture/warning'], 'fixture.css', 'output.css', testWarnOptionsSet)
  let builder = new broccoli.Builder(outputTree) // eslint-disable-line no-new
  outputTree.warningStream = warningStreamStub

  return builder.build().then((dir) => {
    let content = fs.readFileSync(path.join(builder.outputPath, 'output.css'), 'utf8')
    assert.strictEqual(content.trim(), 'a {}')
    assert.deepStrictEqual(warnings, [ 'postcss-test-warn: This is a warning.' ])
  })
})

it('should expose syntax errors', function () {
  let outputTree = postcssCompiler(['fixture/syntax-error'], 'fixture.css', 'output.css', testWarnOptionsSet)
  let builder = new broccoli.Builder(outputTree) // eslint-disable-line no-new
  let count = 0

  outputTree.warningStream = warningStreamStub

  return builder.build()
    .catch((error) => {
      count++
      assert.strictEqual(error.broccoliPayload.originalError.name, 'CssSyntaxError')
      assert.strictEqual(error.broccoliPayload.originalError.message, `${error.broccoliPayload.originalError.input.file}:1:1: Unknown word\n> 1 | a }\n    | ^\n  2 | `)
    })
    .then(() => {
      assert.strictEqual(count, 1)
      assert.deepStrictEqual(warnings, [])
    })
})

it('should expose non-syntax errors', function () {
  let outputTree = postcssCompiler(['fixture/missing-file'], 'fixture.css', 'output.css', testWarnOptionsSet)
  let count = 0

  outputTree.warningStream = warningStreamStub

  try {
    new broccoli.Builder(outputTree) // eslint-disable-line no-new
  } catch (err) {
    count++
    assert.strictEqual(err.name, 'BuilderError')
  }

  assert.strictEqual(count, 1)
  assert.deepStrictEqual(warnings, [])
})

it('should use browser options', function () {
  let outputTree = postcssCompiler(['fixture/success'], 'fixture.css', 'output.css', browsersOptionSet)
  let builder = new broccoli.Builder(outputTree) // eslint-disable-line no-new
  outputTree.warningStream = warningStreamStub

  assert.strictEqual(outputTree.browsers.join(', '), 'last 2 versions, ie > 9, ios >= 8, > 5%')

  return builder.build().then((dir) => {
    assert.deepStrictEqual(warnings, [ 'return-options: last 2 versions, ie > 9, ios >= 8, > 5%' ])
  })
})

it('supports an array of plugin instances', function () {
  let basicPlugin = basicOptionSet.plugins[0].module
  let basicOptions = basicOptionSet.plugins[0].options
  let pluginInstance = basicPlugin(basicOptions)

  let outputTree = postcssCompiler(['fixture/success'], 'fixture.css', 'output.css', {
    plugins: [
      pluginInstance
    ],
    map: map
  })
  return processCss(outputTree)
})
<commit_msg>fix tests with sourcemap postcss update<commit_after>/* global it, beforeEach, afterEach */
'use strict'

const assert = require('assert')
const fs = require('fs')
const path = require('path')
const broccoli = require('broccoli')
const postcssCompiler = require('./')
const postcss = require('postcss')
const rimraf = require('rimraf')
const glob = require('glob')
const async = require('async')

const basicOptionSet = {
  plugins: [
    {
      module: require('postcss-color-rebeccapurple')
    }
  ]
}

const testWarnOptionsSet = {
  errors: {
    showSourceCode: true,
    terminalColors: false
  },
  plugins: [
    {
      module: postcss.plugin('postcss-test-warn', function (opts) {
        return function (root, result) {
          result.warn('This is a warning.')
        }
      })
    }
  ]
}

const browsersOptionSet = {
  plugins: [
    {
      module: postcss.plugin('return-options', (options) => {
        return (root, result) => {
          result.warn(options.browsers.join(', '))
        }
      })
    }
  ],
  browsers: ['last 2 versions', 'ie > 9', 'ios >= 8', '> 5%']
}

const map = {
  inline: false,
  annotation: false
}

basicOptionSet.map = map
testWarnOptionsSet.map = map

let warnings = []
let warningStreamStub = {
  write: function (warning) {
    warnings.push(warning)
  }
}

beforeEach(function () {
  warnings = []
})

afterEach(function () {
  glob('tmp/*', function (err, files) {
    if (err) {
      console.error(err)
    } else {
      async.forEach(files, rimraf)
    }
  })
})

function processCss (outputTree) {
  let builder = new broccoli.Builder(outputTree) // eslint-disable-line no-new
  outputTree.warningStream = warningStreamStub

  return builder.build().then(function () {
    let content = fs.readFileSync(path.join(builder.outputPath, 'output.css'), 'utf8')
    let sourceMap = JSON.parse(fs.readFileSync(path.join(builder.outputPath, 'output.css.map'), 'utf8'))

    assert.strictEqual(content.trim(), 'body {\n  color: #639\n}')
    assert.strictEqual(sourceMap.mappings, 'AAAA;EACE;AACF')
    assert.deepStrictEqual(warnings, [])
  })
}

it('should process css', function () {
  let outputTree = postcssCompiler(['fixture/success'], 'fixture.css', 'output.css', basicOptionSet)
  return processCss(outputTree)
})

it('should expose warnings', function () {
  let outputTree = postcssCompiler(['fixture/warning'], 'fixture.css', 'output.css', testWarnOptionsSet)
  let builder = new broccoli.Builder(outputTree) // eslint-disable-line no-new
  outputTree.warningStream = warningStreamStub

  return builder.build().then((dir) => {
    let content = fs.readFileSync(path.join(builder.outputPath, 'output.css'), 'utf8')
    assert.strictEqual(content.trim(), 'a {}')
    assert.deepStrictEqual(warnings, [ 'postcss-test-warn: This is a warning.' ])
  })
})

it('should expose syntax errors', function () {
  let outputTree = postcssCompiler(['fixture/syntax-error'], 'fixture.css', 'output.css', testWarnOptionsSet)
  let builder = new broccoli.Builder(outputTree) // eslint-disable-line no-new
  let count = 0

  outputTree.warningStream = warningStreamStub

  return builder.build()
    .catch((error) => {
      count++
      assert.strictEqual(error.broccoliPayload.originalError.name, 'CssSyntaxError')
      assert.strictEqual(error.broccoliPayload.originalError.message, `${error.broccoliPayload.originalError.input.file}:1:1: Unknown word\n> 1 | a }\n    | ^\n  2 | `)
    })
    .then(() => {
      assert.strictEqual(count, 1)
      assert.deepStrictEqual(warnings, [])
    })
})

it('should expose non-syntax errors', function () {
  let outputTree = postcssCompiler(['fixture/missing-file'], 'fixture.css', 'output.css', testWarnOptionsSet)
  let count = 0

  outputTree.warningStream = warningStreamStub

  try {
    new broccoli.Builder(outputTree) // eslint-disable-line no-new
  } catch (err) {
    count++
    assert.strictEqual(err.name, 'BuilderError')
  }

  assert.strictEqual(count, 1)
  assert.deepStrictEqual(warnings, [])
})

it('should use browser options', function () {
  let outputTree = postcssCompiler(['fixture/success'], 'fixture.css', 'output.css', browsersOptionSet)
  let builder = new broccoli.Builder(outputTree) // eslint-disable-line no-new
  outputTree.warningStream = warningStreamStub

  assert.strictEqual(outputTree.browsers.join(', '), 'last 2 versions, ie > 9, ios >= 8, > 5%')

  return builder.build().then((dir) => {
    assert.deepStrictEqual(warnings, [ 'return-options: last 2 versions, ie > 9, ios >= 8, > 5%' ])
  })
})

it('supports an array of plugin instances', function () {
  let basicPlugin = basicOptionSet.plugins[0].module
  let basicOptions = basicOptionSet.plugins[0].options
  let pluginInstance = basicPlugin(basicOptions)

  let outputTree = postcssCompiler(['fixture/success'], 'fixture.css', 'output.css', {
    plugins: [
      pluginInstance
    ],
    map: map
  })
  return processCss(outputTree)
})
<|endoftext|>


<commit_before>'use strict';

const { parseQuery } = require('./parse');
const { getHandleQuery } = require('./query');
const { isIntrospectionQuery, getHandleIntrospection } = require('./introspection');

// GraphQL query handling
const executeGraphql = async function (opts) {
  const { idl } = opts;
  const handleIntrospection = getHandleIntrospection({ idl });
  const handleQuery = getHandleQuery({ idl });
  return async function (request) {
    // Parameters can be in either query variables or payload (including by using application/graphql)
    const { params, payload, method } = request;
    const { query, variables, operationName } = Object.assign({}, params, payload);

    // GraphQL parsing
    const { queryDocument, graphqlMethod } = parseQuery({ query, method, operationName });

    // GraphQL execution
    let content;
    // Introspection GraphQL query
    if (isIntrospectionQuery({ query })) {
      content = await handleIntrospection({ queryDocument, variables, operationName });
    // Normal GraphQL query
    } else {
      const callback = fireNext.bind(this, request);
      content = await handleQuery({
        queryDocument,
        variables,
        operationName,
        context: { graphqlMethod, callback },
        rootValue: {},
      });
    }

    const type = getResponseType({ content });

    const response = { content, type };
    return response;
  };
};

const fireNext = async function (request, apiInput) {
  const input = Object.assign({}, request, { api: apiInput });
  const response = await this.next(input);
  return response;
};

const getResponseType = function ({ content }) {
  const mainData = content[Object.keys(content)[0]];
  return mainData instanceof Array ? 'collection' : 'model';
};

module.exports = {
  executeGraphql,
};
<commit_msg>Wrap GraphQL response in `data` envelope<commit_after>'use strict';

const { parseQuery } = require('./parse');
const { getHandleQuery } = require('./query');
const { isIntrospectionQuery, getHandleIntrospection } = require('./introspection');

// GraphQL query handling
const executeGraphql = async function (opts) {
  const { idl } = opts;
  const handleIntrospection = getHandleIntrospection({ idl });
  const handleQuery = getHandleQuery({ idl });
  return async function (request) {
    // Parameters can be in either query variables or payload (including by using application/graphql)
    const { params, payload, method } = request;
    const { query, variables, operationName } = Object.assign({}, params, payload);

    // GraphQL parsing
    const { queryDocument, graphqlMethod } = parseQuery({ query, method, operationName });

    // GraphQL execution
    let content;
    // Introspection GraphQL query
    if (isIntrospectionQuery({ query })) {
      content = await handleIntrospection({ queryDocument, variables, operationName });
    // Normal GraphQL query
    } else {
      const callback = fireNext.bind(this, request);
      const data = await handleQuery({
        queryDocument,
        variables,
        operationName,
        context: { graphqlMethod, callback },
        rootValue: {},
      });
      content = { data };
    }

    const type = getResponseType({ content });

    const response = { content, type };
    return response;
  };
};

const fireNext = async function (request, apiInput) {
  const input = Object.assign({}, request, { api: apiInput });
  const response = await this.next(input);
  return response;
};

const getResponseType = function ({ content: { data } }) {
  const mainData = data[Object.keys(data)[0]];
  return mainData instanceof Array ? 'collection' : 'model';
};

module.exports = {
  executeGraphql,
};
<|endoftext|>


<commit_before>const { companies, interactions } = require('../../../../../src/lib/urls')

describe('Dashboard - Investment details', () => {
  beforeEach(() => {
    cy.setFeatureFlag(
      'layoutTesting:9010dd28-9798-e211-a939-e4115bead28a',
      true
    )
    cy.visit('/')
    cy.get('[data-test="investment-details"]').as('allDetails')
    cy.get('[data-test="investment-details"]').eq(1).as('secondProjectDetails')
    cy.get('[data-test="investment-details"]').eq(2).as('thirdProjectDetails')
    cy.get('[data-test="investment-details"]')
      .eq(0)
      .find('h3')
      .as('header')
      .next()
      .find('li')
      .as('listItem')
  })
  after(() => {
    cy.resetFeatureFlags()
  })

  it('should have a details section for each project', () => {
    cy.get('@allDetails').should('have.length', 10)
  })

  it('should display a header', () => {
    cy.get('@header').should('have.text', 'Details')
  })

  it('should display the investor details with a link to the investor', () => {
    cy.get('@listItem')
      .eq(0)
      .should('have.text', 'Investor: Venus Ltd')
      .find('a')
      .should(
        'have.attr',
        'href',
        companies.details('0f5216e0-849f-11e6-ae22-56b6b6499611')
      )
  })
  it('should display the sector details', () => {
    cy.get('@listItem')
      .eq(1)
      .should('have.text', 'Sector: Renewable Energy : Wind : Onshore')
  })
  it('should display the country of origin details', () => {
    cy.get('@listItem').eq(2).should('have.text', 'Country of origin: Italy')
  })
  it('should display the date of the last interaction', () => {
    cy.get('@listItem')
      .eq(3)
      .should('have.text', 'Last interaction: 16 Mar 2021')
  })
  it('should display the last interaction subject with a link to the interaction', () => {
    cy.get('@listItem')
      .eq(4)
      .should('have.text', 'Interaction subject: A project interaction')
      .find('a')
      .should(
        'have.attr',
        'href',
        interactions.detail('3fd90013-4bcb-4c39-b8df-df264471ea85')
      )
      .should('have.text', 'A project interaction')
  })

  context("when a project doesn't have a country of origin", () => {
    it('should not contain a country of origin', () => {
      cy.get('@secondProjectDetails').should('not.contain', 'Country of origin')
    })
  })
  context("when a project doesn't have an interaction", () => {
    it('should not contain an interaction', () => {
      cy.get('@thirdProjectDetails').should('not.contain', 'Last interaction')
      cy.get('@thirdProjectDetails').should(
        'not.contain',
        'Interaction subject'
      )
    })
  })
})
<commit_msg>Invesment details functional tests refactor<commit_after>const { companies, interactions } = require('../../../../../src/lib/urls')

describe('Dashboard - Investment details', () => {
  beforeEach(() => {
    cy.setFeatureFlag(
      'layoutTesting:9010dd28-9798-e211-a939-e4115bead28a',
      true
    )
    cy.visit('/')
    cy.get('[data-test="investment-details"]').as('allInvestmentDetails')
    cy.get('[data-test="investment-details"]').eq(0).as('firstProjectDetails')
    cy.get('[data-test="investment-details"]').eq(1).as('secondProjectDetails')
    cy.get('[data-test="investment-details"]').eq(2).as('thirdProjectDetails')
    cy.get('@firstProjectDetails').find('dt').as('allTerms')
    cy.get('@firstProjectDetails').find('dd').as('allDescriptions')
  })

  after(() => {
    cy.resetFeatureFlags()
  })

  it('should have a details section for each project', () => {
    cy.get('@allInvestmentDetails').should('have.length', 10)
  })

  it("should display 'Details' in a h3 header", () => {
    cy.get('@firstProjectDetails').find('h3').should('have.text', 'Details')
  })

  it('should display the investor details with a link to the investor', () => {
    cy.get('@allTerms')
      .eq(0)
      .should('have.text', 'Investor:')
      .get('@allDescriptions')
      .eq(0)
      .children()
      .should('have.text', 'Venus Ltd')
      .should(
        'have.attr',
        'href',
        companies.details('0f5216e0-849f-11e6-ae22-56b6b6499611')
      )
  })

  it('should display the sector details', () => {
    cy.get('@allTerms')
      .eq(1)
      .should('have.text', 'Sector:')
      .get('@allDescriptions')
      .eq(1)
      .should('have.text', 'Renewable Energy : Wind : Onshore')
  })

  it('should display the country of origin details', () => {
    cy.get('@allTerms')
      .eq(2)
      .should('have.text', 'Country of origin:')
      .get('@allDescriptions')
      .eq(2)
      .should('have.text', 'Italy')
  })

  it('should display the date of the last interaction', () => {
    cy.get('@allTerms')
      .eq(3)
      .should('have.text', 'Last interaction:')
      .get('@allDescriptions')
      .eq(3)
      .should('have.text', '16 Mar 2021')
  })

  it('should display the last interaction subject with a link to the interaction', () => {
    cy.get('@allTerms')
      .eq(4)
      .should('have.text', 'Interaction subject:')
      .get('@allDescriptions')
      .eq(4)
      .children()
      .should('have.text', 'A project interaction')
      .should(
        'have.attr',
        'href',
        interactions.detail('3fd90013-4bcb-4c39-b8df-df264471ea85')
      )
  })

  context("when a project doesn't have a country of origin", () => {
    it('should not contain a country of origin', () => {
      cy.get('@secondProjectDetails').should('not.contain', 'Country of origin')
    })
  })

  context("when a project doesn't have an interaction", () => {
    it('should not contain an interaction', () => {
      cy.get('@thirdProjectDetails')
        .should('not.contain', 'Last interaction')
        .get('@thirdProjectDetails')
        .should('not.contain', 'Interaction subject')
    })
  })
})
<|endoftext|>