<commit_before>const dotest = require ('dotest');
const pkg = require ('./');

let app = pkg();

dotest.add ('Interface', test => {
  const price = app && app.price;
  const avg = price && price.average;
  const buy = price && price.buy;
  const sell = price && price.sell;

  test()
    .isFunction ('fail', 'exports', pkg)
    .isObject ('fail', 'app', app)
    .isObject ('fail', '.price', price)
    .isFunction ('fail', '.price.average', avg)
    .isFunction ('fail', '.price.buy', buy)
    .isFunction ('fail', '.price.sell', sell)
    .done();
});

dotest.add ('price.average', test => {
  app.price.average ((err, data) => {
    test (err)
      .isObject ('fail', 'data', data)
      .isNumber ('fail', 'data.price', data && data.price)
      .isNumber ('fail', 'data.volume', data && data.volume)
      .done();
  });
});

dotest.add ('price.buy - default method', test => {
  app.price.buy ('btc', 2, (err, data) => {
    test (err)
      .isObject ('fail', 'data', data)
      .isNumber ('fail', 'data.price', data && data.price)
      .isNumber ('fail', 'data.eur', data && data.eur)
      .isExactly ('fail', 'data.btc', data && data.btc, 2)
      .isExactly ('fail', 'data.method', data && data.method, 'ideal')
      .done();
  });
});

dotest.add ('price.buy - set method', test => {
  app.price.buy ('eur', 20, 'bancontact', (err, data) => {
    test (err)
      .isObject ('fail', 'data', data)
      .isNumber ('fail', 'data.price', data && data.price)
      .isNumber ('fail', 'data.btc', data && data.btc)
      .isExactly ('fail', 'data.eur', data && data.eur, 20)
      .isExactly ('fail', 'data.method', data && data.method, 'bancontact')
      .done();
  });
});

dotest.add ('Error: timeout', test => {
  const tmp = pkg ({
    timeout: 1
  });

  tmp.price.average ((err, data) => {
    test()
      .isError ('fail', 'err', err)
      .isUndefined ('fail', 'data', data)
      .isExactly ('fail', 'err.code', err && err.code, 'TIMEOUT')
      .done();
  });
});

dotest.run (1000);
<commit_msg>Test(main): Added price.sell test<commit_after>const dotest = require ('dotest');
const pkg = require ('./');

let app = pkg();

dotest.add ('Interface', test => {
  const price = app && app.price;
  const avg = price && price.average;
  const buy = price && price.buy;
  const sell = price && price.sell;

  test()
    .isFunction ('fail', 'exports', pkg)
    .isObject ('fail', 'app', app)
    .isObject ('fail', '.price', price)
    .isFunction ('fail', '.price.average', avg)
    .isFunction ('fail', '.price.buy', buy)
    .isFunction ('fail', '.price.sell', sell)
    .done();
});

dotest.add ('price.average', test => {
  app.price.average ((err, data) => {
    test (err)
      .isObject ('fail', 'data', data)
      .isNumber ('fail', 'data.price', data && data.price)
      .isNumber ('fail', 'data.volume', data && data.volume)
      .done();
  });
});

dotest.add ('price.buy - default method', test => {
  app.price.buy ('btc', 2, (err, data) => {
    test (err)
      .isObject ('fail', 'data', data)
      .isNumber ('fail', 'data.price', data && data.price)
      .isNumber ('fail', 'data.eur', data && data.eur)
      .isExactly ('fail', 'data.btc', data && data.btc, 2)
      .isExactly ('fail', 'data.method', data && data.method, 'ideal')
      .done();
  });
});

dotest.add ('price.buy - set method', test => {
  app.price.buy ('eur', 20, 'bancontact', (err, data) => {
    test (err)
      .isObject ('fail', 'data', data)
      .isNumber ('fail', 'data.price', data && data.price)
      .isNumber ('fail', 'data.btc', data && data.btc)
      .isExactly ('fail', 'data.eur', data && data.eur, 20)
      .isExactly ('fail', 'data.method', data && data.method, 'bancontact')
      .done();
  });
});

dotest.add ('price.sell', test => {
  app.price.sell ('btc', 2.5, (err, data) => {
    test (err)
      .isObject ('fail', 'data', data)
      .isNumber ('fail', 'data.price', data && data.price)
      .isNumber ('fail', 'data.eur', data && data.eur)
      .isNumber ('fail', 'data.price', data && data.price)
      .isExactly ('fail', 'data.btc', data && data.btc, 2.5)
      .done();
  });
});

dotest.add ('Error: timeout', test => {
  const tmp = pkg ({
    timeout: 1
  });

  tmp.price.average ((err, data) => {
    test()
      .isError ('fail', 'err', err)
      .isUndefined ('fail', 'data', data)
      .isExactly ('fail', 'err.code', err && err.code, 'TIMEOUT')
      .done();
  });
});

dotest.run (1000);
<|endoftext|>


<commit_before>'use strict';
var path = require('path');
var assert = require('assert');
var gutil = require('gulp-util');
var rev = require('./');

it('should rev files', function (cb) {
	var stream = rev();

	stream.on('data', function (file) {
		assert.equal(file.path, 'unicorn-d41d8cd98f.css');
		assert.equal(file.revOrigPath, 'unicorn.css');
		cb();
	});

	stream.write(new gutil.File({
		path: 'unicorn.css',
		contents: new Buffer('')
	}));
});

it('should add the revision hash before the first `.` in the filename', function (cb) {
	var stream = rev();

	stream.on('data', function (file) {
		assert.equal(file.path, 'unicorn-d41d8cd98f.css.map');
		assert.equal(file.revOrigPath, 'unicorn.css.map');
		cb();
	});

	stream.write(new gutil.File({
		path: 'unicorn.css.map',
		contents: new Buffer('')
	}));

	stream.end();
});

it('should build a rev manifest file', function (cb) {
	var stream = rev.manifest();

	stream.on('data', function (newFile) {
		assert.equal(newFile.relative, 'rev-manifest.json');
		assert.deepEqual(
			JSON.parse(newFile.contents.toString()),
			{'unicorn.css': 'unicorn-d41d8cd98f.css'}
		);
		cb();
	});

	var file = new gutil.File({
		path: 'unicorn-d41d8cd98f.css',
		contents: new Buffer('')
	});

	file.revOrigPath = 'unicorn.css';

	stream.write(file);
	stream.end();
});

it('should allow naming the manifest file', function (cb) {
	var path = 'manifest.json';
	var stream = rev.manifest({path: path});

	stream.on('data', function (newFile) {
		assert.equal(newFile.relative, path);
		cb();
	});

	var file = new gutil.File({
		path: 'unicorn-d41d8cd98f.css',
		contents: new Buffer('')
	});

	file.revOrigPath = 'unicorn.css';

	stream.write(file);
	stream.end();
});

it('should append to an existing rev manifest file', function (cb) {
	var stream = rev.manifest({
		path: 'test.manifest-fixture.json',
		merge: true
	});

	stream.on('data', function (newFile) {
		assert.equal(newFile.relative, 'test.manifest-fixture.json');
		assert.deepEqual(
			JSON.parse(newFile.contents.toString()),
			{'app.js': 'app-a41d8cd1.js', 'unicorn.css': 'unicorn-d41d8cd98f.css'}
		);
		cb();
	});

	var file = new gutil.File({
		path: 'unicorn-d41d8cd98f.css',
		contents: new Buffer('')
	});

	file.revOrigPath = 'unicorn.css';

	stream.write(file);
	stream.end();
});

it('should not append to an existing rev manifest by default', function (cb) {
	var stream = rev.manifest({path: 'test.manifest-fixture.json'});

	stream.on('data', function (newFile) {
		assert.equal(newFile.relative, 'test.manifest-fixture.json');
		assert.deepEqual(
			JSON.parse(newFile.contents.toString()),
			{'unicorn.css': 'unicorn-d41d8cd98f.css'}
		);
		cb();
	});

	var file = new gutil.File({
		path: 'unicorn-d41d8cd98f.css',
		contents: new Buffer('')
	});

	file.revOrigPath = 'unicorn.css';

	stream.write(file);
	stream.end();
});

it('should sort the rev manifest keys', function (cb) {
	var stream = rev.manifest({
		path: 'test.manifest-fixture.json',
		merge: true
	});

	stream.on('data', function (newFile) {
		assert.deepEqual(
			Object.keys(JSON.parse(newFile.contents.toString())),
			['app.js', 'pony.css', 'unicorn.css']
		);
		cb();
	});

	var file = new gutil.File({
		path: 'unicorn-d41d8cd98f.css',
		contents: new Buffer('')
	});

	file.revOrigPath = 'unicorn.css';

	var fileTwo = new gutil.File({
		path: 'pony-d41d8cd98f.css',
		contents: new Buffer('')
	});

	fileTwo.revOrigPath = 'pony.css';

	stream.write(file);
	stream.write(fileTwo);
	stream.end();
});

it('should respect directories', function (cb) {
	var stream = rev.manifest();

	stream.on('data', function (newFile) {
		var MANIFEST = {};
		MANIFEST[path.join('foo', 'unicorn.css')] = path.join('foo', 'unicorn-d41d8cd98f.css');
		MANIFEST[path.join('bar', 'pony.css')] = path.join('bar', 'pony-d41d8cd98f.css');

		assert.equal(newFile.relative, 'rev-manifest.json');
		assert.deepEqual(JSON.parse(newFile.contents.toString()), MANIFEST);
		cb();
	});

	var file1 = new gutil.File({
		cwd: __dirname,
		base: __dirname,
		path: path.join(__dirname, 'foo', 'unicorn-d41d8cd98f.css'),
		contents: new Buffer('')
	});

	file1.revOrigBase = __dirname;
	file1.revOrigPath = path.join(__dirname, 'foo', 'unicorn.css');
	file1.origName = 'unicorn.css';
	file1.revName = 'unicorn-d41d8cd98f.css';

	var file2 = new gutil.File({
		cwd: __dirname,
		base: __dirname,
		path: path.join(__dirname, 'bar', 'pony-d41d8cd98f.css'),
		contents: new Buffer('')
	});

	file2.revOrigBase = __dirname;
	file2.revOrigPath = path.join(__dirname, 'bar', 'pony.css');
	file2.origName = 'pony.css';
	file2.revName = 'pony-d41d8cd98f.css';

	stream.write(file1);
	stream.write(file2);
	stream.end();
});

it('should respect files coming from directories with different bases', function (cb) {
	var stream = rev.manifest();

	stream.on('data', function (newFile) {
		var MANIFEST = {};
		MANIFEST[path.join('foo', 'scriptfoo.js')] = path.join('foo', 'scriptfoo-d41d8cd98f.js');
		MANIFEST[path.join('bar', 'scriptbar.js')] = path.join('bar', 'scriptbar-d41d8cd98f.js');

		assert.equal(newFile.relative, 'rev-manifest.json');
		assert.deepEqual(JSON.parse(newFile.contents.toString()), MANIFEST);
		cb();
	});

	var file1 = new gutil.File({
		cwd: __dirname,
		base: path.join(__dirname, 'output'),
		path: path.join(__dirname, 'output', 'foo', 'scriptfoo-d41d8cd98f.js'),
		contents: new Buffer('')
	});

	file1.revOrigBase = path.join(__dirname, 'vendor1');
	file1.revOrigPath = path.join(__dirname, 'vendor1', 'foo', 'scriptfoo.js');
	file1.origName = 'scriptfoo.js';
	file1.revName = 'scriptfoo-d41d8cd98f.js';

	var file2 = new gutil.File({
		cwd: __dirname,
		base: path.join(__dirname, 'output'),
		path: path.join(__dirname, 'output', 'bar', 'scriptbar-d41d8cd98f.js'),
		contents: new Buffer('')
	});

	file2.revOrigBase = path.join(__dirname, 'vendor2');
	file2.revOrigPath = path.join(__dirname, 'vendor2', 'bar', 'scriptbar.js');
	file2.origName = 'scriptfoo.js';
	file2.revName = 'scriptfoo-d41d8cd98f.js';

	stream.write(file1);
	stream.write(file2);
	stream.end();
});

it('should store the hashes for later', function (cb) {
	var stream = rev();

	stream.on('data', function (file) {
		assert.equal(file.path, 'unicorn-d41d8cd98f.css');
		assert.equal(file.revOrigPath, 'unicorn.css');
		assert.equal(file.revHash, 'd41d8cd98f');
		cb();
	});

	stream.write(new gutil.File({
		path: 'unicorn.css',
		contents: new Buffer('')
	}));
});

it('should handle sourcemaps transparently', function (cb) {
	var stream = rev();

	stream.on('data', function (file) {
		if (path.extname(file.path) === '.map') {
			assert.equal(file.path, 'maps/pastissada-d41d8cd98f.css.map');
			cb();
		}
	});

	stream.write(new gutil.File({
		path: 'pastissada.css',
		contents: new Buffer('')
	}));

	stream.end(new gutil.File({
		path: 'maps/pastissada.css.map',
		contents: new Buffer(JSON.stringify({file: 'pastissada.css'}))
	}));
});

it('should handle unparseable sourcemaps correctly', function (cb) {
	var stream = rev();

	stream.on('data', function (file) {
		if (path.extname(file.path) === '.map') {
			assert.equal(file.path, 'pastissada-d41d8cd98f.css.map');
			cb();
		}
	});

	stream.write(new gutil.File({
		path: 'pastissada.css',
		contents: new Buffer('')
	}));

	stream.end(new gutil.File({
		path: 'pastissada.css.map',
		contents: new Buffer('Wait a minute, this is invalid JSON!')
	}));
});

it('should be okay when the optional sourcemap.file is not defined', function (cb) {
	var stream = rev();

	stream.on('data', function (file) {
		if (path.extname(file.path) === '.map') {
			assert.equal(file.path, 'pastissada-d41d8cd98f.css.map');
			cb();
		}
	});

	stream.write(new gutil.File({
		path: 'pastissada.css',
		contents: new Buffer('')
	}));

	stream.end(new gutil.File({
		path: 'pastissada.css.map',
		contents: new Buffer(JSON.stringify({}))
	}));
});

it('should handle a . in the folder name', function (cb) {
	var stream = rev();

	stream.on('data', function (file) {
		assert.equal(file.path, 'mysite.io/unicorn-d41d8cd98f.css');
		assert.equal(file.revOrigPath, 'mysite.io/unicorn.css');
		cb();
	});

	stream.write(new gutil.File({
		path: 'mysite.io/unicorn.css',
		contents: new Buffer('')
	}));
});

it('should use correct base path for each file', function (cb) {
	var stream = rev.manifest();

	stream.on('data', function (newFile) {
		var MANIFEST = {};
		MANIFEST[path.join('foo', 'scriptfoo.js')] = path.join('foo', 'scriptfoo-d41d8cd98f.js');
		MANIFEST[path.join('bar', 'scriptbar.js')] = path.join('bar', 'scriptbar-d41d8cd98f.js');

		assert.deepEqual(JSON.parse(newFile.contents.toString()), MANIFEST);
		cb();
	});

	var fileFoo = new gutil.File({
		cwd: 'app/',
		base: 'app/',
		path: path.join('app', 'foo', 'scriptfoo-d41d8cd98f.js'),
		contents: new Buffer('')
	});
	fileFoo.revOrigPath = 'scriptfoo.js';

	var fileBar = new gutil.File({
		cwd: 'assets/',
		base: 'assets/',
		path: path.join('assets', 'bar', 'scriptbar-d41d8cd98f.js'),
		contents: new Buffer('')
	});
	fileBar.revOrigPath = 'scriptbar.js';

	stream.write(fileFoo);
	stream.write(fileBar);
	stream.end();
});
<commit_msg>fix XO lint issues<commit_after>'use strict';
var path = require('path');
var assert = require('assert');
var gutil = require('gulp-util');
var rev = require('./');

it('should rev files', function (cb) {
	var stream = rev();

	stream.on('data', function (file) {
		assert.equal(file.path, 'unicorn-d41d8cd98f.css');
		assert.equal(file.revOrigPath, 'unicorn.css');
		cb();
	});

	stream.write(new gutil.File({
		path: 'unicorn.css',
		contents: new Buffer('')
	}));
});

it('should add the revision hash before the first `.` in the filename', function (cb) {
	var stream = rev();

	stream.on('data', function (file) {
		assert.equal(file.path, 'unicorn-d41d8cd98f.css.map');
		assert.equal(file.revOrigPath, 'unicorn.css.map');
		cb();
	});

	stream.write(new gutil.File({
		path: 'unicorn.css.map',
		contents: new Buffer('')
	}));

	stream.end();
});

it('should build a rev manifest file', function (cb) {
	var stream = rev.manifest();

	stream.on('data', function (newFile) {
		assert.equal(newFile.relative, 'rev-manifest.json');
		assert.deepEqual(
			JSON.parse(newFile.contents.toString()),
			{'unicorn.css': 'unicorn-d41d8cd98f.css'}
		);
		cb();
	});

	var file = new gutil.File({
		path: 'unicorn-d41d8cd98f.css',
		contents: new Buffer('')
	});

	file.revOrigPath = 'unicorn.css';

	stream.write(file);
	stream.end();
});

it('should allow naming the manifest file', function (cb) {
	var path = 'manifest.json';
	var stream = rev.manifest({path: path});

	stream.on('data', function (newFile) {
		assert.equal(newFile.relative, path);
		cb();
	});

	var file = new gutil.File({
		path: 'unicorn-d41d8cd98f.css',
		contents: new Buffer('')
	});

	file.revOrigPath = 'unicorn.css';

	stream.write(file);
	stream.end();
});

it('should append to an existing rev manifest file', function (cb) {
	var stream = rev.manifest({
		path: 'test.manifest-fixture.json',
		merge: true
	});

	stream.on('data', function (newFile) {
		assert.equal(newFile.relative, 'test.manifest-fixture.json');
		assert.deepEqual(
			JSON.parse(newFile.contents.toString()),
			{
				'app.js': 'app-a41d8cd1.js',
				'unicorn.css': 'unicorn-d41d8cd98f.css'
			}
		);
		cb();
	});

	var file = new gutil.File({
		path: 'unicorn-d41d8cd98f.css',
		contents: new Buffer('')
	});

	file.revOrigPath = 'unicorn.css';

	stream.write(file);
	stream.end();
});

it('should not append to an existing rev manifest by default', function (cb) {
	var stream = rev.manifest({path: 'test.manifest-fixture.json'});

	stream.on('data', function (newFile) {
		assert.equal(newFile.relative, 'test.manifest-fixture.json');
		assert.deepEqual(
			JSON.parse(newFile.contents.toString()),
			{'unicorn.css': 'unicorn-d41d8cd98f.css'}
		);
		cb();
	});

	var file = new gutil.File({
		path: 'unicorn-d41d8cd98f.css',
		contents: new Buffer('')
	});

	file.revOrigPath = 'unicorn.css';

	stream.write(file);
	stream.end();
});

it('should sort the rev manifest keys', function (cb) {
	var stream = rev.manifest({
		path: 'test.manifest-fixture.json',
		merge: true
	});

	stream.on('data', function (newFile) {
		assert.deepEqual(
			Object.keys(JSON.parse(newFile.contents.toString())),
			['app.js', 'pony.css', 'unicorn.css']
		);
		cb();
	});

	var file = new gutil.File({
		path: 'unicorn-d41d8cd98f.css',
		contents: new Buffer('')
	});

	file.revOrigPath = 'unicorn.css';

	var fileTwo = new gutil.File({
		path: 'pony-d41d8cd98f.css',
		contents: new Buffer('')
	});

	fileTwo.revOrigPath = 'pony.css';

	stream.write(file);
	stream.write(fileTwo);
	stream.end();
});

it('should respect directories', function (cb) {
	var stream = rev.manifest();

	stream.on('data', function (newFile) {
		var MANIFEST = {};
		MANIFEST[path.join('foo', 'unicorn.css')] = path.join('foo', 'unicorn-d41d8cd98f.css');
		MANIFEST[path.join('bar', 'pony.css')] = path.join('bar', 'pony-d41d8cd98f.css');

		assert.equal(newFile.relative, 'rev-manifest.json');
		assert.deepEqual(JSON.parse(newFile.contents.toString()), MANIFEST);
		cb();
	});

	var file1 = new gutil.File({
		cwd: __dirname,
		base: __dirname,
		path: path.join(__dirname, 'foo', 'unicorn-d41d8cd98f.css'),
		contents: new Buffer('')
	});

	file1.revOrigBase = __dirname;
	file1.revOrigPath = path.join(__dirname, 'foo', 'unicorn.css');
	file1.origName = 'unicorn.css';
	file1.revName = 'unicorn-d41d8cd98f.css';

	var file2 = new gutil.File({
		cwd: __dirname,
		base: __dirname,
		path: path.join(__dirname, 'bar', 'pony-d41d8cd98f.css'),
		contents: new Buffer('')
	});

	file2.revOrigBase = __dirname;
	file2.revOrigPath = path.join(__dirname, 'bar', 'pony.css');
	file2.origName = 'pony.css';
	file2.revName = 'pony-d41d8cd98f.css';

	stream.write(file1);
	stream.write(file2);
	stream.end();
});

it('should respect files coming from directories with different bases', function (cb) {
	var stream = rev.manifest();

	stream.on('data', function (newFile) {
		var MANIFEST = {};
		MANIFEST[path.join('foo', 'scriptfoo.js')] = path.join('foo', 'scriptfoo-d41d8cd98f.js');
		MANIFEST[path.join('bar', 'scriptbar.js')] = path.join('bar', 'scriptbar-d41d8cd98f.js');

		assert.equal(newFile.relative, 'rev-manifest.json');
		assert.deepEqual(JSON.parse(newFile.contents.toString()), MANIFEST);
		cb();
	});

	var file1 = new gutil.File({
		cwd: __dirname,
		base: path.join(__dirname, 'output'),
		path: path.join(__dirname, 'output', 'foo', 'scriptfoo-d41d8cd98f.js'),
		contents: new Buffer('')
	});

	file1.revOrigBase = path.join(__dirname, 'vendor1');
	file1.revOrigPath = path.join(__dirname, 'vendor1', 'foo', 'scriptfoo.js');
	file1.origName = 'scriptfoo.js';
	file1.revName = 'scriptfoo-d41d8cd98f.js';

	var file2 = new gutil.File({
		cwd: __dirname,
		base: path.join(__dirname, 'output'),
		path: path.join(__dirname, 'output', 'bar', 'scriptbar-d41d8cd98f.js'),
		contents: new Buffer('')
	});

	file2.revOrigBase = path.join(__dirname, 'vendor2');
	file2.revOrigPath = path.join(__dirname, 'vendor2', 'bar', 'scriptbar.js');
	file2.origName = 'scriptfoo.js';
	file2.revName = 'scriptfoo-d41d8cd98f.js';

	stream.write(file1);
	stream.write(file2);
	stream.end();
});

it('should store the hashes for later', function (cb) {
	var stream = rev();

	stream.on('data', function (file) {
		assert.equal(file.path, 'unicorn-d41d8cd98f.css');
		assert.equal(file.revOrigPath, 'unicorn.css');
		assert.equal(file.revHash, 'd41d8cd98f');
		cb();
	});

	stream.write(new gutil.File({
		path: 'unicorn.css',
		contents: new Buffer('')
	}));
});

it('should handle sourcemaps transparently', function (cb) {
	var stream = rev();

	stream.on('data', function (file) {
		if (path.extname(file.path) === '.map') {
			assert.equal(file.path, 'maps/pastissada-d41d8cd98f.css.map');
			cb();
		}
	});

	stream.write(new gutil.File({
		path: 'pastissada.css',
		contents: new Buffer('')
	}));

	stream.end(new gutil.File({
		path: 'maps/pastissada.css.map',
		contents: new Buffer(JSON.stringify({file: 'pastissada.css'}))
	}));
});

it('should handle unparseable sourcemaps correctly', function (cb) {
	var stream = rev();

	stream.on('data', function (file) {
		if (path.extname(file.path) === '.map') {
			assert.equal(file.path, 'pastissada-d41d8cd98f.css.map');
			cb();
		}
	});

	stream.write(new gutil.File({
		path: 'pastissada.css',
		contents: new Buffer('')
	}));

	stream.end(new gutil.File({
		path: 'pastissada.css.map',
		contents: new Buffer('Wait a minute, this is invalid JSON!')
	}));
});

it('should be okay when the optional sourcemap.file is not defined', function (cb) {
	var stream = rev();

	stream.on('data', function (file) {
		if (path.extname(file.path) === '.map') {
			assert.equal(file.path, 'pastissada-d41d8cd98f.css.map');
			cb();
		}
	});

	stream.write(new gutil.File({
		path: 'pastissada.css',
		contents: new Buffer('')
	}));

	stream.end(new gutil.File({
		path: 'pastissada.css.map',
		contents: new Buffer(JSON.stringify({}))
	}));
});

it('should handle a . in the folder name', function (cb) {
	var stream = rev();

	stream.on('data', function (file) {
		assert.equal(file.path, 'mysite.io/unicorn-d41d8cd98f.css');
		assert.equal(file.revOrigPath, 'mysite.io/unicorn.css');
		cb();
	});

	stream.write(new gutil.File({
		path: 'mysite.io/unicorn.css',
		contents: new Buffer('')
	}));
});

it('should use correct base path for each file', function (cb) {
	var stream = rev.manifest();

	stream.on('data', function (newFile) {
		var MANIFEST = {};
		MANIFEST[path.join('foo', 'scriptfoo.js')] = path.join('foo', 'scriptfoo-d41d8cd98f.js');
		MANIFEST[path.join('bar', 'scriptbar.js')] = path.join('bar', 'scriptbar-d41d8cd98f.js');

		assert.deepEqual(JSON.parse(newFile.contents.toString()), MANIFEST);
		cb();
	});

	var fileFoo = new gutil.File({
		cwd: 'app/',
		base: 'app/',
		path: path.join('app', 'foo', 'scriptfoo-d41d8cd98f.js'),
		contents: new Buffer('')
	});
	fileFoo.revOrigPath = 'scriptfoo.js';

	var fileBar = new gutil.File({
		cwd: 'assets/',
		base: 'assets/',
		path: path.join('assets', 'bar', 'scriptbar-d41d8cd98f.js'),
		contents: new Buffer('')
	});
	fileBar.revOrigPath = 'scriptbar.js';

	stream.write(fileFoo);
	stream.write(fileBar);
	stream.end();
});
<|endoftext|>


<commit_before>/*
Name:         skyhook-api test script
Description:  Test script for skyhook-api node.js module
Author:       Franklin van de Meent (https://frankl.in)
Source:       https://github.com/fvdm/nodejs-skyhook
Feedback:     https://github.com/fvdm/nodejs-skyhook/issues
License       Unlicense (Public Domain)
              See https://github.com/fvdm/nodejs-skyhook/raw/master/LICENSE
*/

const dotest = require ('dotest');
const app = require ('./');

// Setup
// set env SKYHOOK_USER SKYHOOK_KEY (Travis CI)
const user = process.env.SKYHOOK_USER || null;
const key = process.env.SKYHOOK_KEY || null;
const timeout = process.env.SKYHOOK_TIMEOUT || 5000;

const skyhook = app && app (user, key, timeout);

// T-Mobile NL IP
dotest.add ('good ip', function (test) {
  skyhook ('84.241.201.227', function (err, data) {
    const location = data && data.location;
    const civic = data && data.civic;

    test (err)
      .isObject ('fail', 'data', data)
      .isObject ('fail', 'data.location', location)
      .isNumber ('fail', 'data.location.latitude', location && location.latitude)
      .isNumber ('fail', 'data.location.hpe', location && location.hpe)
      .isExactly ('fail', 'data.ip', data && data.ip, '84.241.201.227')
      .isObject ('fail', 'data.civic', civic)
      .isExactly ('fail', 'data.civic.countryIso', civic && civic.countryIso, 'NL')
      .done ();
  });
});

// API error
dotest.add ('Error: api error', function (test) {
  skyhook ('invalid input', function (err, data) {
    test ()
      .isError ('fail', 'err', err)
      .isExactly ('fail', 'err.message', err && err.message, 'api error')
      .isExactly ('warn', 'err.code', err && err.code, 400)
      .isExactly ('warn', 'err.test', err && err.text, 'malformed ip')
      .isUndefined ('fail', 'data', data)
      .done ();
  });
});

// Run tests
dotest.run ();
<commit_msg>Test(main): Add Error request failed test<commit_after>/*
Name:         skyhook-api test script
Description:  Test script for skyhook-api node.js module
Author:       Franklin van de Meent (https://frankl.in)
Source:       https://github.com/fvdm/nodejs-skyhook
Feedback:     https://github.com/fvdm/nodejs-skyhook/issues
License       Unlicense (Public Domain)
              See https://github.com/fvdm/nodejs-skyhook/raw/master/LICENSE
*/

const dotest = require ('dotest');
const app = require ('./');

// Setup
// set env SKYHOOK_USER SKYHOOK_KEY (Travis CI)
const user = process.env.SKYHOOK_USER || null;
const key = process.env.SKYHOOK_KEY || null;
const timeout = process.env.SKYHOOK_TIMEOUT || 5000;

const skyhook = app && app (user, key, timeout);

// T-Mobile NL IP
dotest.add ('good ip', function (test) {
  skyhook ('84.241.201.227', function (err, data) {
    const location = data && data.location;
    const civic = data && data.civic;

    test (err)
      .isObject ('fail', 'data', data)
      .isObject ('fail', 'data.location', location)
      .isNumber ('fail', 'data.location.latitude', location && location.latitude)
      .isNumber ('fail', 'data.location.hpe', location && location.hpe)
      .isExactly ('fail', 'data.ip', data && data.ip, '84.241.201.227')
      .isObject ('fail', 'data.civic', civic)
      .isExactly ('fail', 'data.civic.countryIso', civic && civic.countryIso, 'NL')
      .done ();
  });
});

// API error
dotest.add ('Error: api error', function (test) {
  skyhook ('invalid input', function (err, data) {
    test ()
      .isError ('fail', 'err', err)
      .isExactly ('fail', 'err.message', err && err.message, 'api error')
      .isExactly ('warn', 'err.code', err && err.code, 400)
      .isExactly ('warn', 'err.test', err && err.text, 'malformed ip')
      .isUndefined ('fail', 'data', data)
      .done ();
  });
});

// Request failed
dotest.add ('Error: request failed', function (test) {
  const tmp = app && app (user, key, 1);

  tmp ('invalid input', function (err, data) {
    test ()
      .isError ('fail', 'err', err)
      .isExactly ('fail', 'err.message', err && err.message, 'request failed')
      .isError ('fail', 'err.error', err && err.error)
      .isExactly ('fail', 'err.error.code', err && err.error && err.error.code, 'TIMEOUT')
      .isUndefined ('fail', 'data', data)
      .done ();
  });
});

// Run tests
dotest.run ();
<|endoftext|>


<commit_before>'use strict'

var test = require('tape')
var partial = require('ap').partial
var Promise = require('bluebird')
var promiseWaterfall = require('./')

var addOne = makeAdder(1)
var addTwo = makeAdder(2)

function makeAdder (a) {
  return function (b) {
    b = b || 0
    return Promise.resolve(a + b)
  }
}

function rejection () {
  return Promise.reject(new Error('andrew joslin'))
}

test('run array of promises sequentially', function (t) {
  promiseWaterfall([
    addOne,
    addTwo
  ]).then(function (sum) {
    t.equals(sum, 3)
    t.end()
  })
})

test('reject array', function (t) {
  t.plan(1)

  promiseWaterfall([
    addOne,
    addTwo,
    rejection
  ]).catch(partial(t.pass, 'error caught'))
})
<commit_msg>remove bluebird from test<commit_after>'use strict'

var test = require('tape')
var partial = require('ap').partial
var promiseWaterfall = require('./')

var addOne = makeAdder(1)
var addTwo = makeAdder(2)

function makeAdder (a) {
  return function (b) {
    b = b || 0
    return Promise.resolve(a + b)
  }
}

function rejection () {
  return Promise.reject(new Error('andrew joslin'))
}

test('run array of promises sequentially', function (t) {
  promiseWaterfall([
    addOne,
    addTwo
  ]).then(function (sum) {
    t.equals(sum, 3)
    t.end()
  })
})

test('reject array', function (t) {
  t.plan(1)

  promiseWaterfall([
    addOne,
    addTwo,
    rejection
  ]).catch(partial(t.pass, 'error caught'))
})
<|endoftext|>


<commit_before>import test from 'ava';
import concat from 'stream-string';
import spawnShell from './';

test('Use shell to run commands', async t => {
	const p = spawnShell('echo "it works"', {
		stdio: [0, 'pipe', 2]
	});

	const output = await concat(p.stdout);
	t.is(output, 'it works\n');
});

test('Returned ChildProcess has a exitPromise prop that resolve with process exit code', async t => {
	const p = spawnShell('exit 1');
	const exitCode = await p.exitPromise;
	t.is(exitCode, 1);
});

test('Returned ChildProcess exitPromise is rejected on spawn errors', async t => {
	const p = spawnShell('', {shell: 'unknown'});

	const err = await t.throws(p.exitPromise);
	t.is(err.code, 'ENOENT');
});

test('inject your package `node_modules/.bin` directory in path', async t => {
	const p = spawnShell('which eslint', {
		stdio: [0, 'pipe', 2],
		shell: 'sh'
	});

	const output = await concat(p.stdout);
	t.is(output, `${__dirname}/node_modules/.bin/eslint\n`);
});
<commit_msg>fix for node 4<commit_after>import {join} from 'path';
import test from 'ava';
import concat from 'stream-string';
import spawnShell from './';

test('Use shell to run commands', async t => {
	const p = spawnShell('echo "it works"', {
		stdio: [0, 'pipe', 2]
	});

	const output = await concat(p.stdout);
	t.is(output, 'it works\n');
});

test('Returned ChildProcess has a exitPromise prop that resolve with process exit code', async t => {
	const p = spawnShell('exit 1');
	const exitCode = await p.exitPromise;
	t.is(exitCode, 1);
});

test('Returned ChildProcess exitPromise is rejected on spawn errors', async t => {
	const p = spawnShell('', {shell: 'unknown'});

	const err = await t.throws(p.exitPromise);
	t.is(err.code, 'ENOENT');
});

test('inject your package `node_modules/.bin` directory in path', async t => {
	const p = spawnShell('which eslint', {
		stdio: [0, 'pipe', 2],
		shell: 'sh'
	});

	const output = await concat(p.stdout);
	t.is(output, join(__dirname, '/node_modules/.bin/eslint\n'));
});
<|endoftext|>


<commit_before>var player = require('./player');
player.bet_request({
  "players": [{
    "name": "Player 1",
    "stack": 1000,
    "status": "active",
    "bet": 0,
    "hole_cards": [],
    "version": "Version name 1",
    "id": 0
  }, {
    "name": "Player 2",
    "stack": 1000,
    "status": "active",
    "bet": 0,
    "hole_cards": [],
    "version": "Version name 2",
    "id": 1
  }],
  "tournament_id": "550d1d68cd7bd10003000003",
  "game_id": "550da1cb2d909006e90004b1",
  "round": 0,
  "bet_index": 0,
  "small_blind": 10,
  "orbits": 0,
  "dealer": 0,
  "community_cards": [],
  "current_buy_in": 0,
  "pot": 0
});<commit_msg>real game_state for test<commit_after>var player = require('./player');
player.bet_request({
  tournament_id: '5592bba01c450b0003000003',
  game_id: '55bc57aecc04560003000048',
  round: 14,
  players: [{
    name: 'Awesome Incredible Poker Bot',
    stack: 0,
    status: 'out',
    bet: 0,
    version: 'Awesome Incredible Poker Bot',
    id: 0
  },
    {
      name: 'LeanNodeJS',
      stack: 2235,
      status: 'active',
      bet: 30,
      hole_cards: [Object],
      version: 'LeanNodeJS engineered player',
      id: 1
    },
    {
      name: 'Boris',
      stack: 0,
      status: 'out',
      bet: 0,
      version: 'Boris Raiser v1.0',
      id: 2
    },
    {
      name: 'PythonPokerTeam',
      stack: 1010,
      status: 'active',
      bet: 30,
      version: 'Inky 0.1',
      id: 3
    },
    {
      name: 'sevenbits',
      stack: 1625,
      status: 'active',
      bet: 70,
      version: 'Crazy Bot',
      id: 4
    },
    {
      name: 'JBot',
      stack: 0,
      status: 'out',
      bet: 0,
      version: 'Default Java folding player',
      id: 5
    }],
  small_blind: 10,
  orbits: 2,
  dealer: 1,
  community_cards: [],
  current_buy_in: 70,
  pot: 130,
  in_action: 1,
  minimum_raise: 40,
  bet_index: 10
});<|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-6-14 08:37:27<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>'use strict';

var path = require('path');
var level = require('level');
var async = require('async');
var rimraf = require('rimraf');
var mkdirp = require('mkdirp');
var assert = require('assert');
var bytewise = require('bytewise');
var defaults = require('level-defaults');
var sublevel = require('level-sublevel/bytewise');
var digits = require('digits');

var opts = {
  keyEncoding: bytewise,
  valueEncoding: 'json'
};

var dbPath = path.join(__dirname, '.data');
var tables = [
  'product',
  'contact',
  'account',
  'user',
  'item',
  'invoice',
  'order'
];

var db = null;
var ids = null;

describe('level-id-gen', function () {
  beforeEach(function (done) {
    rimraf(dbPath, function (err) {
      if (err) return done(err);
      mkdirp.sync(dbPath);
      db = level(path.join(dbPath, 'db'));
      db = defaults(db, opts);
      db = sublevel(db);

      var identities = db.sublevel('identities');
      var generator = require('./')(identities);
      var IdGen = require('id-gen');
      ids = new IdGen(generator);
      tables.forEach(function (table) {
        ids.create(table, { digits: 10, prefix: table.toUpperCase() + '-' });
      });
      done();
    });
  });

  afterEach(rimraf.bind(rimraf, dbPath));

  it('should make ids', function (done) {
    async.eachSeries(tables, function (table, next) {
      var i = 0;
      async.until(function () { return (i++) === 100;},
        function (cb) {
          var expected = table.toUpperCase() + '-' + digits(''+i, 10, '0');
          ids.next(table, function (err, id) {
            if (err) return cb(err);
            assert(id, expected);
            cb();
          });
        }, next);
    }, done);
  });
});

<commit_msg>tests<commit_after>'use strict';

var path = require('path');
var level = require('level');
var async = require('async');
var rimraf = require('rimraf');
var mkdirp = require('mkdirp');
var assert = require('assert');
var bytewise = require('bytewise');
var defaults = require('level-defaults');
var sublevel = require('level-sublevel/bytewise');
var digits = require('digits');

var opts = {
  keyEncoding: bytewise,
  valueEncoding: 'json'
};

var dbPath = path.join(__dirname, '.data');
var tables = ['foo', 'bar', 'baz'];

var db = null;
var ids = null;

describe('level-id-gen', function () {
  beforeEach(function (done) {
    rimraf(dbPath, function (err) {
      if (err) return done(err);
      mkdirp.sync(dbPath);
      db = level(path.join(dbPath, 'db'));
      db = defaults(db, opts);
      db = sublevel(db);

      var identities = db.sublevel('identities');
      var generator = require('./')(identities);
      var IdGen = require('id-gen');
      ids = new IdGen(generator);
      tables.forEach(function (table) {
        ids.create(table, { digits: 10, prefix: table.toUpperCase() + '-' });
      });
      done();
    });
  });

  afterEach(rimraf.bind(rimraf, dbPath));

  it('should make ids', function (done) {
    async.eachSeries(tables, function (table, next) {
      var i = 0;
      async.until(function () { return (i++) === 100;},
        function (cb) {
          var expected = table.toUpperCase() + '-' + digits(''+i, 10, '0');
          ids.next(table, function (err, id) {
            if (err) return cb(err);
            assert(id, expected);
            cb();
          });
        }, next);
    }, done);
  });
});

<|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-24 01:23:25<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 chimneypot = require('./index.js');

// Empty constructor
shouldThrowError(function() {
  new chimneypot();
});

// No port
shouldThrowError(function() {
  new chimneypot({
    path: '/',
    secret: 'spooky'
  });
});

// No path
shouldThrowError(function() {
  new chimneypot({
    port: 1996,
    secret: 'spooky'
  });
});

// No secret
shouldNotThrowError(function() {
  new chimneypot({
    port: 1996,
    path: '/'
  });
});

// Non numeric port
(function() {
  // String port
  shouldThrowError(function() {
    new chimneypot({
      port: 'wrong',
      path: '/',
      secret: 'spooky'
    });
  });

  // Boolean port (false)
  shouldThrowError(function() {
    new chimneypot({
      port: false,
      path: '/',
      secret: 'spooky'
    });
  });

  // Boolean port (true)
  shouldThrowError(function() {
    new chimneypot({
      port: true,
      path: '/',
      secret: 'spooky'
    });
  });

  // Array port
  shouldThrowError(function() {
    new chimneypot({
      port: [],
      path: '/',
      secret: 'spooky'
    });
  });

  // Object port
  shouldThrowError(function() {
    new chimneypot({
      port: {},
      path: '/',
      secret: 'spooky'
    });
  });

  // Non-integer port
  shouldThrowError(function() {
    new chimneypot({
      port: 50.5,
      path: '/',
      secret: 'spooky'
    });
  });
})();

console.log("all tests passed");

function shouldThrowError(func) {
  if (!_throws(func)) {
    throw new Error("Expected error to be thrown, but was not thrown");
  }
}

function shouldNotThrowError(func) {
  if (_throws(func)) {
    throw new Error("Expected error to not be thrown, but was thrown");
  }
}

function _setupValidChimneypot() {
  return new chimneypot({
    port: 1996,
    path: '/'
  });
}

function _throws(func) {
  try {
    func();
  } catch (err) {
    return true;
  }
  return false;
}
<commit_msg>Check for error throw when listening before route<commit_after>var chimneypot = require('./index.js');

// Empty constructor
shouldThrowError(function() {
  new chimneypot();
});

// No port
shouldThrowError(function() {
  new chimneypot({
    path: '/',
    secret: 'spooky'
  });
});

// No path
shouldThrowError(function() {
  new chimneypot({
    port: 1996,
    secret: 'spooky'
  });
});

// No secret
shouldNotThrowError(function() {
  new chimneypot({
    port: 1996,
    path: '/'
  });
});

// Non numeric port
(function() {
  // String port
  shouldThrowError(function() {
    new chimneypot({
      port: 'wrong',
      path: '/',
      secret: 'spooky'
    });
  });

  // Boolean port (false)
  shouldThrowError(function() {
    new chimneypot({
      port: false,
      path: '/',
      secret: 'spooky'
    });
  });

  // Boolean port (true)
  shouldThrowError(function() {
    new chimneypot({
      port: true,
      path: '/',
      secret: 'spooky'
    });
  });

  // Array port
  shouldThrowError(function() {
    new chimneypot({
      port: [],
      path: '/',
      secret: 'spooky'
    });
  });

  // Object port
  shouldThrowError(function() {
    new chimneypot({
      port: {},
      path: '/',
      secret: 'spooky'
    });
  });

  // Non-integer port
  shouldThrowError(function() {
    new chimneypot({
      port: 50.5,
      path: '/',
      secret: 'spooky'
    });
  });
})();

// Call listen before routing
shouldThrowError(function() {
  var c = _setupValidChimneypot();

  c.listen();
});

console.log("all tests passed");

function shouldThrowError(func) {
  if (!_throws(func)) {
    throw new Error("Expected error to be thrown, but was not thrown");
  }
}

function shouldNotThrowError(func) {
  if (_throws(func)) {
    throw new Error("Expected error to not be thrown, but was thrown");
  }
}

function _setupValidChimneypot() {
  return new chimneypot({
    port: 1996,
    path: '/'
  });
}

function _throws(func) {
  try {
    func();
  } catch (err) {
    return true;
  }
  return false;
}
<|endoftext|>


<commit_before>var test = require('tape');
var player = require('./player');

test('first test', function (t) {
    t.plan(4);

    var self = '11011011011111111111111111111111';
    var enemy = '00011111111111111111111111111000';

    var matrixEmpty = [
        0, 0, 0,
        0, 1, 0,
        0, 0, 0
    ];

    t.deepEqual([5, 5, 5, self], player(matrixEmpty));

    var matrixSelf = [
        self, self, self,
        self, 1,    self,
        self, self, self
    ];

    t.deepEqual([0, 0, 0, self], player(matrixSelf));

    var matrixEnemy = [
        0,  enemy,  0,
        0,  1,      0,
        0,  0,      0
    ];

    t.deepEqual([1, 1, 1, self], player(matrixEnemy));

    var matrixEnemyRest = [
        self,   self,   enemy,
        0,      1,      self,
        0,      0,      0
    ];

    t.deepEqual([3, 3, 3, self], player(matrixEnemyRest));
});<commit_msg>covers left enemy<commit_after>var test = require('tape');
var player = require('./player');

test('first test', function (t) {
    t.plan(5);

    var self = '11011011011111111111111111111111';
    var enemy = '00011111111111111111111111111000';

    var matrixEmpty = [
        0, 0, 0,
        0, 1, 0,
        0, 0, 0
    ];

    t.deepEqual([5, 5, 5, self], player(matrixEmpty));

    var matrixSelf = [
        self, self, self,
        self, 1,    self,
        self, self, self
    ];

    t.deepEqual([0, 0, 0, self], player(matrixSelf));

    var matrixEnemy = [
        0,  enemy,  0,
        0,  1,      0,
        0,  0,      0
    ];

    t.deepEqual([1, 1, 1, self], player(matrixEnemy));

    var matrixRestLeftFree = [
        self,   self,   enemy,
        0,      1,      self,
        0,      0,      0
    ];

    t.deepEqual([3, 3, 3, self], player(matrixRestLeftFree));

    var matrixRestLeftEnemy = [
        self,   self,   enemy,
        enemy,  1,      self,
        0,      0,      0
    ];

    t.deepEqual([3, 3, 3, self], player(matrixRestLeftEnemy));
});<|endoftext|>


<commit_before>var finish = require('./finish')
  , assert = require('assert')

function echo(value, callback) {
  setTimeout(function() {
    if (value === undefined) {
      callback(new Error('an error occured'));
    } else {
      callback(null, value)
    }
  }, Math.random() * 10);
}

describe('finish', function() {
  var list = [];

  before(function() {
    for (var i = 0; i < 1000; ++i) { list[i] = i; };
  });

  it('should finish all async tasks', function(done) {
    finish(function(async) {
      list.forEach(function(i) {
        async(function(done) { echo(i, done); });
      });
    }, function(err, results) {
      assert.equal(results.length, list.length);
      results.sort(function(a, b) { return a - b; });
      list.forEach(function(i) { assert.equal(results[i], i); });
      done();
    });
  });

  describe('.map()', function() {
    it('should finish async tasks on each element', function(done) {
      finish.map(list, function(i, done) {
        echo(i, done);
      }, function(err, results) {
        assert.equal(results.length, list.length);
        results.sort(function(a, b) { return a - b; });
        list.forEach(function(i) { assert.equal(results[i], i); });
        done();
      });
    });
  });

  describe('.ordered()', function() {
    it('should finish async tasks in order', function(done) {
      finish.ordered(function(async) {
        list.forEach(function(i) {
          async(function(done) { echo(i, done); });
        });
      }, function(err, results) {
        assert.equal(results.length, list.length);
        list.forEach(function(i) { assert.equal(results[i], i); });
        done();
      });
    });
  });

  describe('.ordered.map()', function() {
    it('should finish async tasks on each element in order', function(done) {
      finish.ordered.map(list, function(i, done) {
        echo(i, done);
      }, function(err, results) {
        assert.equal(results.length, list.length);
        list.forEach(function(i) { assert.equal(results[i], i); });
        done();
      });
    });
  });

  describe('when invoked with a reducer', function() {
    it('should reduce results before callback', function(done) {
      finish(function(async) {
        list.forEach(function(i) {
          async(function(done) { echo(i, done); });
        });
      }, function(prev, curr) {
        return prev += curr;
      }, 0, function(err, results) {
        assert.equal(results, list.reduce(function(prev, curr) {
          return prev += curr;
        }, 0));
        done();
      });
    });
  });

  describe('when an error occurs', function() {
    it('should invoke callback with an error', function(done) {
      finish(function(async) {
        list.forEach(function(i) {
          async(function(done) { echo(i == 9 ? undefined : i, done); });
        });
      }, function(err, results) {
        assert(err);
        assert.equal(err.message, 'an error occured');
        done();
      });
    });
  });
});

<commit_msg>Add test for keyed finish.<commit_after>var finish = require('./finish')
  , assert = require('assert')

function echo(value, callback) {
  setTimeout(function() {
    if (value === undefined) {
      callback(new Error('an error occured'));
    } else {
      callback(null, value)
    }
  }, Math.random() * 10);
}

describe('finish', function() {
  var list = [];

  before(function() {
    for (var i = 0; i < 1000; ++i) { list[i] = i; };
  });

  it('should finish all async tasks', function(done) {
    finish(function(async) {
      list.forEach(function(i) {
        async(function(done) { echo(i, done); });
      });
    }, function(err, results) {
      assert.equal(results.length, list.length);
      results.sort(function(a, b) { return a - b; });
      list.forEach(function(i) { assert.equal(results[i], i); });
      done();
    });
  });

  describe('when spawning with keys', function() {
    it('should return an object', function(done) {
      finish(function(async) {
        list.forEach(function(i) {
          async(i, function(done) { echo(i, done); });
        });
      }, function(err, results) {
        assert.equal(typeof results, 'object');
        assert.equal(results instanceof Array, false);
        for (var key in results) {
          assert.equal(key, results[key]);
        }
        done();
      });
    });
  });

  describe('.map()', function() {
    it('should finish async tasks on each element', function(done) {
      finish.map(list, function(i, done) {
        echo(i, done);
      }, function(err, results) {
        assert.equal(results.length, list.length);
        results.sort(function(a, b) { return a - b; });
        list.forEach(function(i) { assert.equal(results[i], i); });
        done();
      });
    });

    describe('when mapping an object', function() {
      it('should map async tasks to each property', function(done) {
        var obj = Object.create(null);

        list.forEach(function(i) { obj[i] = i; });

        finish.map(obj, function(i, done) {
          echo(i, done);
        }, function(err, results) {
          assert.equal(typeof results, 'object');
          assert.equal(results instanceof Array, false);
          for (var key in results) {
            assert.equal(key, results[key]);
          }
          done();
        });
      });
    });
  });

  describe('.ordered()', function() {
    it('should finish async tasks in order', function(done) {
      finish.ordered(function(async) {
        list.forEach(function(i) {
          async(function(done) { echo(i, done); });
        });
      }, function(err, results) {
        assert.equal(results.length, list.length);
        list.forEach(function(i) { assert.equal(results[i], i); });
        done();
      });
    });
  });

  describe('.ordered.map()', function() {
    it('should finish async tasks on each element in order', function(done) {
      finish.ordered.map(list, function(i, done) {
        echo(i, done);
      }, function(err, results) {
        assert.equal(results.length, list.length);
        list.forEach(function(i) { assert.equal(results[i], i); });
        done();
      });
    });
  });

  describe('when invoked with a reducer', function() {
    it('should reduce results before callback', function(done) {
      finish(function(async) {
        list.forEach(function(i) {
          async(function(done) { echo(i, done); });
        });
      }, function(prev, curr) {
        return prev += curr;
      }, 0, function(err, results) {
        assert.equal(results, list.reduce(function(prev, curr) {
          return prev += curr;
        }, 0));
        done();
      });
    });
  });

  describe('when an error occurs', function() {
    it('should invoke callback with an error', function(done) {
      finish(function(async) {
        list.forEach(function(i) {
          async(function(done) { echo(i == 9 ? undefined : i, done); });
        });
      }, function(err, results) {
        assert(err);
        assert.equal(err.message, 'an error occured');
        done();
      });
    });
  });
});

<|endoftext|>


<commit_before>'use strict';
var fs = require('fs');
var assert = require('assert');
var stringifyObject = require('./');

it('should stringify an object', function () {
	var expected;
	var obj = {
		foo: "bar 'bar'",
		foo2: [
			"foo",
			"bar",
			{
				foo: "bar 'bar'"
			}
		],
		"foo-foo": "bar",
		"2foo": "bar",
		"@#": "bar",
		$el: "bar",
		_private: "bar",
		number: 1,
		boolean: true,
		date: new Date("2014-01-29T22:41:05.665Z"),
		escapedString: "\"\"",
		null: null,
		undefined: undefined,
		function: function () {},
		regexp: /./,
		NaN: NaN,
		Infinity: Infinity,
		newlines: "foo\nbar\r\nbaz"
	};

	obj.circular = obj;

	var actual = stringifyObject(obj, {
		indent: '  ',
		singleQuotes: false
	});

	assert.equal(actual + '\n', fs.readFileSync('fixture.js', 'utf8'));
	assert.equal(
		stringifyObject({foo: "a ' b \' c \\' d"}, {singleQuotes: true}),
		"{\n\tfoo: 'a \\' b \\' c \\\\' d'\n}"
	);
});

it('should not detect reused object values as circular reference', function () {
	var val = {val: 10};
	var obj = {foo: val, bar: val};
	assert.equal(stringifyObject(obj), '{\n\tfoo: {\n\t\tval: 10\n\t},\n\tbar: {\n\t\tval: 10\n\t}\n}');
});

it('should not detect reused array values as false circular references', function () {
	var val = [10];
	var obj = {foo: val, bar: val};
	assert.equal(stringifyObject(obj), '{\n\tfoo: [\n\t\t10\n\t],\n\tbar: [\n\t\t10\n\t]\n}');
});

it('considering filter option to stringify an object', function () {
	var val = {val: 10};
	var obj = {foo: val, bar: val};
	var actual = stringifyObject(obj, {
		filter: function (obj, prop) {
			return prop !== 'foo';
		}
	});
	assert.equal(actual, '{\n\tbar: {\n\t\tval: 10\n\t}\n}');
});

it('should not crash with circular recursion in arrays', function () {
	var array = [];
	array.push(array);
	assert.doesNotThrow(
		function () {
			stringifyObject(array);
		}, RangeError);

	var nestedArray = [[]];
	nestedArray[0][0] = nestedArray;
	assert.doesNotThrow(
		function () {
			stringifyObject(nestedArray);
		}, RangeError);
});

it('should stringify complex circular arrays', function () {
	var array = [[[]]];
	array[0].push(array);
	array[0][0].push(array);
	array[0][0].push(10);
	array[0][0][0] = array;
	assert.equal(stringifyObject(array), '[\n\t[\n\t\t[\n\t\t\t"[Circular]",\n\t\t\t10\n\t\t],\n\t\t"[Circular]"\n\t]\n]');
});
<commit_msg>add another testcase for handling of circular references in arrays<commit_after>'use strict';
var fs = require('fs');
var assert = require('assert');
var stringifyObject = require('./');

it('should stringify an object', function () {
	var expected;
	var obj = {
		foo: "bar 'bar'",
		foo2: [
			"foo",
			"bar",
			{
				foo: "bar 'bar'"
			}
		],
		"foo-foo": "bar",
		"2foo": "bar",
		"@#": "bar",
		$el: "bar",
		_private: "bar",
		number: 1,
		boolean: true,
		date: new Date("2014-01-29T22:41:05.665Z"),
		escapedString: "\"\"",
		null: null,
		undefined: undefined,
		function: function () {},
		regexp: /./,
		NaN: NaN,
		Infinity: Infinity,
		newlines: "foo\nbar\r\nbaz"
	};

	obj.circular = obj;

	var actual = stringifyObject(obj, {
		indent: '  ',
		singleQuotes: false
	});

	assert.equal(actual + '\n', fs.readFileSync('fixture.js', 'utf8'));
	assert.equal(
		stringifyObject({foo: "a ' b \' c \\' d"}, {singleQuotes: true}),
		"{\n\tfoo: 'a \\' b \\' c \\\\' d'\n}"
	);
});

it('should not detect reused object values as circular reference', function () {
	var val = {val: 10};
	var obj = {foo: val, bar: val};
	assert.equal(stringifyObject(obj), '{\n\tfoo: {\n\t\tval: 10\n\t},\n\tbar: {\n\t\tval: 10\n\t}\n}');
});

it('should not detect reused array values as false circular references', function () {
	var val = [10];
	var obj = {foo: val, bar: val};
	assert.equal(stringifyObject(obj), '{\n\tfoo: [\n\t\t10\n\t],\n\tbar: [\n\t\t10\n\t]\n}');
});

it('considering filter option to stringify an object', function () {
	var val = {val: 10};
	var obj = {foo: val, bar: val};
	var actual = stringifyObject(obj, {
		filter: function (obj, prop) {
			return prop !== 'foo';
		}
	});
	assert.equal(actual, '{\n\tbar: {\n\t\tval: 10\n\t}\n}');
});

it.skip('should not crash with circular references in arrays', function () {
	var array = [];
	array.push(array);
	assert.doesNotThrow(
		function () {
			stringifyObject(array);
		}, RangeError);

	var nestedArray = [[]];
	nestedArray[0][0] = nestedArray;
	assert.doesNotThrow(
		function () {
			stringifyObject(nestedArray);
		}, RangeError);
});

it.skip('should handle circular references in arrays', function () {
	var array2 = [];
	var array = [array2];
	array2[0] = array2;

	assert.doesNotThrow(
		function () {
			stringifyObject(array);
		}, RangeError);
});

it.skip('should stringify complex circular arrays', function () {
	var array = [[[]]];
	array[0].push(array);
	array[0][0].push(array);
	array[0][0].push(10);
	array[0][0][0] = array;
	assert.equal(stringifyObject(array), '[\n\t[\n\t\t[\n\t\t\t"[Circular]",\n\t\t\t10\n\t\t],\n\t\t"[Circular]"\n\t]\n]');
});
<|endoftext|>


<commit_before>assert = require('assert'), Buffer = require('buffer').Buffer, Iconv = require('iconv').Iconv;

// unknown source/target encoding
assert.throws(function() { new Iconv('utf-8', 'xxx'); });
assert.throws(function() { new Iconv('xxx', 'utf-8'); });

iconv = new Iconv('utf-8', 'iso-8859-1');
assert.equal(iconv.convert(), undefined);
assert.equal(iconv.convert(1), undefined);
assert.equal(iconv.convert({}), undefined);

assert.ok(iconv.convert('xxx') instanceof Buffer);
assert.ok(iconv.convert(new Buffer('xxx')) instanceof Buffer);

assert.equal(iconv.convert('xxx').inspect(), new Buffer('xxx').inspect());
assert.equal(iconv.convert(new Buffer('xxx')).inspect(), new Buffer('xxx').inspect());

buffer = new Buffer(1); buffer[0] = 235; // ë
assert.equal(iconv.convert('ë').inspect(), buffer.inspect());

// partial character sequence should throw EINVAL
buffer = new Buffer(1); buffer[0] = 195;
try {
	iconv.convert(buffer);
} catch (e) {
	assert.equal(e.errno, process.EINVAL);
}

// belongs to partial character sequence test - new input should be recoded without issues
buffer = new Buffer(1); buffer[0] = 235; // ë
assert.equal(iconv.convert('ë').inspect(), buffer.inspect());

// input too big to fit in single (internal) buffer
s = 'x'; for (var i = 0; i < 14; i++) s = s + s; s += '1234'; // 16384 + 4 for good measure
assert.ok(new Buffer(s).inspect() == iconv.convert(s).inspect());

// non-convertible character sequence should throw EILSEQ
iconv = new Iconv('utf-8', 'ascii');
try {
	iconv.convert('ë');
} catch (e) {
	assert.equal(e.errno, process.EILSEQ);
}

// prototypical inheritance should work
Foo = function() { Foo.prototype.call(this, 'utf-8', 'ascii'); };
Foo.prototype = Iconv;
new Foo();
<commit_msg>Thanks to the introduction of FastBuffers/SlowBuffers, a successful test run is now dependent on the order in which the tests are run. See http://groups.google.com/group/nodejs-dev/browse_thread/thread/7da5781df8f88da6 for details.<commit_after>assert = require('assert'), Buffer = require('buffer').Buffer, Iconv = require('iconv').Iconv;

// unknown source/target encoding
assert.throws(function() { new Iconv('utf-8', 'xxx'); });
assert.throws(function() { new Iconv('xxx', 'utf-8'); });

iconv = new Iconv('utf-8', 'iso-8859-1');
assert.equal(iconv.convert(), undefined);
assert.equal(iconv.convert(1), undefined);
assert.equal(iconv.convert({}), undefined);

assert.ok(iconv.convert(new Buffer('xxx')) instanceof Buffer);
assert.ok(iconv.convert('xxx') instanceof Buffer);

assert.equal(iconv.convert('xxx').inspect(), new Buffer('xxx').inspect());
assert.equal(iconv.convert(new Buffer('xxx')).inspect(), new Buffer('xxx').inspect());

buffer = new Buffer(1); buffer[0] = 235; // ë
assert.equal(iconv.convert('ë').inspect(), buffer.inspect());

// partial character sequence should throw EINVAL
buffer = new Buffer(1); buffer[0] = 195;
try {
	iconv.convert(buffer);
} catch (e) {
	assert.equal(e.errno, process.EINVAL);
}

// belongs to partial character sequence test - new input should be recoded without issues
buffer = new Buffer(1); buffer[0] = 235; // ë
assert.equal(iconv.convert('ë').inspect(), buffer.inspect());

// input too big to fit in single (internal) buffer
s = 'x'; for (var i = 0; i < 14; i++) s = s + s; s += '1234'; // 16384 + 4 for good measure
assert.ok(new Buffer(s).inspect() == iconv.convert(s).inspect());

// non-convertible character sequence should throw EILSEQ
iconv = new Iconv('utf-8', 'ascii');
try {
	iconv.convert('ë');
} catch (e) {
	assert.equal(e.errno, process.EILSEQ);
}

// prototypical inheritance should work
Foo = function() { Foo.prototype.call(this, 'utf-8', 'ascii'); };
Foo.prototype = Iconv;
new Foo();
<|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-12-4 02:01:04<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>🤖(break): 2017-6-14 08:39:34<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-7-23 23:45:26<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 levelup = require('levelup')
var LevelIterator = require('./index')
var db = levelup('./testdb1')
var assert = require('assert')

describe('Iterator Class', function () {
    it('Should Construct', function () {
        var iter = new LevelIterator(db)
        assert(iter instanceof LevelIterator)
        assert(iter.readStream !== undefined)
        assert(iter.readable === false)
        assert(iter.ended === false)
    })

    beforeEach(function (done) {
        for (var i = 0; i < 4; i += 1) {
            db.put(i, 'string' + i)
        }

        db.put(4, 'string4', function () {
            done()
        })
    })

    describe('Iterator.next', function () {
        it('Should return the next in the sequence', function (done){
            var iter = new LevelIterator(db)
            iter.next(function (err, result) {
                assert(result.value === 'string0')
                iter.next(function (err, result) {
                    assert(result.value === 'string1')
                    done()
                })
            })
        })
    })

    describe('Iterator.hasNext', function () {
        it(
            'Should return true if there is another record else false',
            function (done) {
                var iter = new LevelIterator(db)
                iter.hasNext(function (res) {
                    if (res) {
                        iter.next(function (err, res) {
                            assert(res.key === '0')
                            assert(res.value === 'string0')
                            done()
                        })
                    }
                })
            })
    })

    describe('Iterator.hasNextSync', function () {
        it(
            'Should return true if there is another record else false',
            function (done) {
                var iter = new LevelIterator(db)
                iter.on('readable', function () {
                    assert(iter.hasNextSync() === true)
                    iter.next(function () { })
                })
                iter.on('end', function () {
                    assert(iter.hasNextSync() === false)
                    done()
                })
            })

	it('Should store skipped results in buffer', function (done){
            var iter = new LevelIterator(db)
            iter.once('readable', function () {
                setTimeout(function () {
                    iter.hasNextSync()
                    iter.next(function (err, res) {
                        assert(res.key === '0')
                        assert(res.value === 'string0')
                        done()
                    })
                }, 10)
            })
        })

    })

    describe('Iterator.seek', function () {
        it('Should seek 2 places forward', function (done) {
            var iter = new LevelIterator(db)
            iter.seek(2, function () {
                iter.next(function (err, res) {
                    assert(res.key === '2')
                    assert(res.value === 'string2')
                    done()
                })
            })
        })
    })

    describe('Iterator.seekSync', function () {
        it('Should seek 2 places forward', function (done) {
            var iter = new LevelIterator(db)
            iter.once('readable', function () {
                setTimeout(function () {
                    iter.seekSync(2)
                    iter.next(function (err, res) {
                        assert(res.value === 'string2')
                        assert(res.key === '2')
                        done()
                    })
                }, 10)
            })
        })
    })

    describe('Iterator.read', function () {
        it('Should read 3 values', function (done) {
            var iter = new LevelIterator(db)
            iter.read(3, function (err, res) {
                assert(res.length === 3)
                done()
            })
        })
        it('Should return results in order', function (done) {
            var iter = new LevelIterator(db)
            iter.read(3, function (err, res) {
                assert(res.length === 3)
                for (var i = 0; i < 3; i += 1) {
                    var _res = res[i];
                    assert(_res.key === i)
                    assert(_res.value === 'string' + i)
                }
                done()
            })
        })
    })
})
<commit_msg>Fixed comparison error in test<commit_after>var levelup = require('levelup')
var LevelIterator = require('./index')
var db = levelup('./testdb1')
var assert = require('assert')

describe('Iterator Class', function () {
    it('Should Construct', function () {
        var iter = new LevelIterator(db)
        assert(iter instanceof LevelIterator)
        assert(iter.readStream !== undefined)
        assert(iter.readable === false)
        assert(iter.ended === false)
    })

    beforeEach(function (done) {
        for (var i = 0; i < 4; i += 1) {
            db.put(i, 'string' + i)
        }

        db.put(4, 'string4', function () {
            done()
        })
    })

    describe('Iterator.next', function () {
        it('Should return the next in the sequence', function (done){
            var iter = new LevelIterator(db)
            iter.next(function (err, result) {
                assert(result.value === 'string0')
                iter.next(function (err, result) {
                    assert(result.value === 'string1')
                    done()
                })
            })
        })
    })

    describe('Iterator.hasNext', function () {
        it(
            'Should return true if there is another record else false',
            function (done) {
                var iter = new LevelIterator(db)
                iter.hasNext(function (res) {
                    if (res) {
                        iter.next(function (err, res) {
                            assert(res.key === '0')
                            assert(res.value === 'string0')
                            done()
                        })
                    }
                })
            })
    })

    describe('Iterator.hasNextSync', function () {
        it(
            'Should return true if there is another record else false',
            function (done) {
                var iter = new LevelIterator(db)
                iter.on('readable', function () {
                    assert(iter.hasNextSync() === true)
                    iter.next(function () { })
                })
                iter.on('end', function () {
                    assert(iter.hasNextSync() === false)
                    done()
                })
            })

	it('Should store skipped results in buffer', function (done){
            var iter = new LevelIterator(db)
            iter.once('readable', function () {
                setTimeout(function () {
                    iter.hasNextSync()
                    iter.next(function (err, res) {
                        assert(res.key === '0')
                        assert(res.value === 'string0')
                        done()
                    })
                }, 10)
            })
        })

    })

    describe('Iterator.seek', function () {
        it('Should seek 2 places forward', function (done) {
            var iter = new LevelIterator(db)
            iter.seek(2, function () {
                iter.next(function (err, res) {
                    assert(res.key === '2')
                    assert(res.value === 'string2')
                    done()
                })
            })
        })
    })

    describe('Iterator.seekSync', function () {
        it('Should seek 2 places forward', function (done) {
            var iter = new LevelIterator(db)
            iter.once('readable', function () {
                setTimeout(function () {
                    iter.seekSync(2)
                    iter.next(function (err, res) {
                        assert(res.value === 'string2')
                        assert(res.key === '2')
                        done()
                    })
                }, 10)
            })
        })
    })

    describe('Iterator.read', function () {
        it('Should read 3 values', function (done) {
            var iter = new LevelIterator(db)
            iter.read(3, function (err, res) {
                assert(res.length === 3)
                done()
            })
        })
        it('Should return results in order', function (done) {
            var iter = new LevelIterator(db)
            iter.read(3, function (err, res) {
                assert(res.length === 3)
                for (var i = 0; i < 3; i += 1) {
                    var _res = res[i];
                    assert(parseInt(_res.key) === i)
                    assert(_res.value === 'string' + i)
                }
                done()
            })
        })
    })
})
<|endoftext|>


<commit_before>var WooCommerce = require('./index.js');
var chai = require('chai');
var nock = require('nock');

describe('#Construct', function() {
  it('should throw an error if the url, consumerKey or consumerSecret are missing', function() {
    chai.expect(function() {
      new WooCommerce();
    }).to.throw(Error);
  });

  it('should set the default options', function() {
    var api = new WooCommerce({
      url: 'http://test.dev',
      consumerKey: 'ck_XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX',
      consumerSecret: 'cs_XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX'
    });

    chai.expect(api.version).to.equal('v3');
    chai.expect(api.isSsl).to.be.false;
    chai.expect(api.verifySsl).to.be.true;
    chai.expect(api.encoding).to.equal('utf8');
  });
});

describe('#Requests', function() {
  beforeEach(function() {
    nock.cleanAll();
  });

  var api = new WooCommerce({
    url: 'https://test.dev',
    consumerKey: 'ck_XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX',
    consumerSecret: 'cs_XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX'
  });

  it('should return full API url', function() {
    var endpoint = 'products';
    var expected = 'https://test.dev/wc-api/v3/products';
    var url      = api._getUrl(endpoint);

    chai.assert.equal(url, expected);
  });

  it('should return sorted by name query string', function() {
    var url        = 'http://test.dev/wc-api/v3/products?filter[q]=Woo+Album&fields=id&filter[limit]=1';
    var expected   = 'http://test.dev/wc-api/v3/products?fields=id&filter[limit]=1&filter[q]=Woo%20Album';
    var normalized = api._normalizeQueryString(url);

    chai.assert.equal(normalized, expected);
  });

  it('should return content for basic auth', function(done) {
    nock('https://test.dev/wc-api/v3').post('/orders', {}).reply(200, {
      ok: true
    });

    api.post('orders', {}, function(err, data) {
      chai.expect(err).to.not.exist;
      chai.expect(data).be.a.string;
      done();
    });
  });

  it('should return content for get requests', function(done) {
    nock('https://test.dev/wc-api/v3').get('/orders').reply(200, {
      ok: true
    });

    api.get('orders', function(err, data) {
      chai.expect(err).to.not.exist;
      chai.expect(data).be.a.string;
      done();
    });
  });

  it('should return content for put requests', function(done) {
    nock('https://test.dev/wc-api/v3').put('/orders', {}).reply(200, {
      ok: true
    });

    api.put('orders', {}, function(err, data) {
      chai.expect(err).to.not.exist;
      chai.expect(data).be.a.string;
      done();
    });
  });

  it('should return content for delete requests', function(done) {
    nock('https://test.dev/wc-api/v3').delete('/orders').reply(200, {
      ok: true
    });

    api.delete('orders', function(err, data) {
      chai.expect(err).to.not.exist;
      chai.expect(data).be.a.string;
      done();
    });
  });

  it('should return content for options requests', function(done) {
    nock('https://test.dev/wc-api/v3').intercept('/orders', 'OPTIONS').reply(400);

    api.options('orders', function(err, data) {
      chai.expect(err).to.not.exist;
      chai.expect(data).be.a.string;
      done();
    });
  });

  it('should return content for OAuth', function(done) {
    var oAuth = new WooCommerce({
      url: 'http://test.dev',
      consumerKey: 'ck_XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX',
      consumerSecret: 'cs_XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX'
    });

    nock('http://test.dev/wc-api/v3').filteringPath(/\?.*/, '?params').get('/orders?params').reply(200, {
      ok: true
    });

    oAuth.get('orders', function(err, data) {
      chai.expect(err).to.not.exist;
      chai.expect(data).be.a.string;
      done();
    });
  });

  it('should timeout', function(done) {
    var api = new WooCommerce({
      url: 'https://test.dev',
      consumerKey: 'ck_XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX',
      consumerSecret: 'cs_XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX',
      timeout: 1
    });

    nock('https://test.dev/wc-api/v3')
      .get('/orders')
      .reply(function(uri, requestBody, cb) {
        setTimeout(function() {
          return cb(null, {
            orders: []
          });
        }, 2);
      });

    api.get('orders', function(err) {
      chai.expect(err).to.be.a('error');
      chai.expect(err.message).to.equal('ETIMEDOUT');
      return done();
    });
  });
});
<commit_msg>No need to test timeout since is a "request" feature<commit_after>var WooCommerce = require('./index.js');
var chai = require('chai');
var nock = require('nock');

describe('#Construct', function() {
  it('should throw an error if the url, consumerKey or consumerSecret are missing', function() {
    chai.expect(function() {
      new WooCommerce();
    }).to.throw(Error);
  });

  it('should set the default options', function() {
    var api = new WooCommerce({
      url: 'http://test.dev',
      consumerKey: 'ck_XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX',
      consumerSecret: 'cs_XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX'
    });

    chai.expect(api.version).to.equal('v3');
    chai.expect(api.isSsl).to.be.false;
    chai.expect(api.verifySsl).to.be.true;
    chai.expect(api.encoding).to.equal('utf8');
  });
});

describe('#Requests', function() {
  beforeEach(function() {
    nock.cleanAll();
  });

  var api = new WooCommerce({
    url: 'https://test.dev',
    consumerKey: 'ck_XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX',
    consumerSecret: 'cs_XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX'
  });

  it('should return full API url', function() {
    var endpoint = 'products';
    var expected = 'https://test.dev/wc-api/v3/products';
    var url      = api._getUrl(endpoint);

    chai.assert.equal(url, expected);
  });

  it('should return sorted by name query string', function() {
    var url        = 'http://test.dev/wc-api/v3/products?filter[q]=Woo+Album&fields=id&filter[limit]=1';
    var expected   = 'http://test.dev/wc-api/v3/products?fields=id&filter[limit]=1&filter[q]=Woo%20Album';
    var normalized = api._normalizeQueryString(url);

    chai.assert.equal(normalized, expected);
  });

  it('should return content for basic auth', function(done) {
    nock('https://test.dev/wc-api/v3').post('/orders', {}).reply(200, {
      ok: true
    });

    api.post('orders', {}, function(err, data) {
      chai.expect(err).to.not.exist;
      chai.expect(data).be.a.string;
      done();
    });
  });

  it('should return content for get requests', function(done) {
    nock('https://test.dev/wc-api/v3').get('/orders').reply(200, {
      ok: true
    });

    api.get('orders', function(err, data) {
      chai.expect(err).to.not.exist;
      chai.expect(data).be.a.string;
      done();
    });
  });

  it('should return content for put requests', function(done) {
    nock('https://test.dev/wc-api/v3').put('/orders', {}).reply(200, {
      ok: true
    });

    api.put('orders', {}, function(err, data) {
      chai.expect(err).to.not.exist;
      chai.expect(data).be.a.string;
      done();
    });
  });

  it('should return content for delete requests', function(done) {
    nock('https://test.dev/wc-api/v3').delete('/orders').reply(200, {
      ok: true
    });

    api.delete('orders', function(err, data) {
      chai.expect(err).to.not.exist;
      chai.expect(data).be.a.string;
      done();
    });
  });

  it('should return content for options requests', function(done) {
    nock('https://test.dev/wc-api/v3').intercept('/orders', 'OPTIONS').reply(400);

    api.options('orders', function(err, data) {
      chai.expect(err).to.not.exist;
      chai.expect(data).be.a.string;
      done();
    });
  });

  it('should return content for OAuth', function(done) {
    var oAuth = new WooCommerce({
      url: 'http://test.dev',
      consumerKey: 'ck_XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX',
      consumerSecret: 'cs_XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX'
    });

    nock('http://test.dev/wc-api/v3').filteringPath(/\?.*/, '?params').get('/orders?params').reply(200, {
      ok: true
    });

    oAuth.get('orders', function(err, data) {
      chai.expect(err).to.not.exist;
      chai.expect(data).be.a.string;
      done();
    });
  });

});
<|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:44:59<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 Park = require("./parkBase");
var DisneyBase = require("./Disney/DisneyBase");
var parks = require("./index");
var moment = require("moment-timezone");

// optional environment variable to print out API results
var PRINTDATA = process.env.PRINTDATA ? true : false;

if (!process.env.PARKID) {
  describe("ParkBase", function() {
    var parkBase = new Park();

    it("should error attempting to fetch wait times", function(done) {
      parkBase.GetWaitTimes(function(err, res) {
        assert(err);
        assert(!res);
        done();
      });
    });
  });

  describe("DisneyBase", function() {
    // be super-lenient for these tests
    this.timeout(1000 * 60 * 2);

    var DisneyPark = new DisneyBase();

    var access_token = null;
    it("should get a valid access token", function(done) {
      DisneyPark.GetAccessToken(function(err, token) {
        assert(!err, "GetAccessToken returned an error: " + err);
        assert(token && token.length, "Invalid access token returned: " + token);
        access_token = token;
        done();
      });
    });

    it("fetching again should have same token (from cache)", function(done) {
      DisneyPark.GetAccessToken(function(err, token) {
        assert(!err, "Second call to GetAccessToken returned an error: " + err);
        assert(token && token.length, "Invalid access token returned second time: " + token);
        assert(access_token == token, "Tokens are not identical! Caching has failed");
        done();
      });
    });
  });
}

function TestPark(park) {
  // === Test Wait Times Fetching ===
  describe("Get Park Wait Times", function() {
    // give each test 2 minutes to finish
    this.timeout(1000 * 60 * 2);

    var times = [];

    it("should not return an error fetching ride times", function(done) {
      park.GetWaitTimes(function(err, _times) {
        times = _times;
        if (PRINTDATA) console.log(JSON.stringify(times, null, 2));
        assert(!err);
        done(err);
      });
    });

    it("should have some ride data", function() {
      assert(times);

      // Sesame Place doesn't return data in downtime, so sorry. This is a bad unit test.
      if (park.name == "Sesame Place") return;

      assert(times.length > 3, "Not enough ride times to be valid data (<= 3), actual: " + times.length);
    });

    it("should have an ID for every ride", function() {
      for (var i = 0, ride; ride = times[i++];) ValidateType(ride, "id", ["string", "number"]);
    });

    it("should have a wait time for every ride", function() {
      for (var i = 0, ride; ride = times[i++];) ValidateType(ride, "waitTime", "number");
    });

    it("should have a name for every ride", function() {
      for (var i = 0, ride; ride = times[i++];) ValidateType(ride, "name", "string");
    });

    it("should have an active state for every ride", function() {
      for (var i = 0, ride; ride = times[i++];) ValidateType(ride, "active", "boolean");
    });

    it("should have a fastpass field for every ride", function() {
      for (var i = 0, ride; ride = times[i++];) ValidateType(ride, "fastPass", "boolean");
    });

    it("should have a status field for every ride", function() {
      for (var i = 0, ride; ride = times[i++];) {
        ValidateType(ride, "status", "string");
        // status string should only ever be one of these three options
        assert(
          ride.status == "Operating" || ride.status == "Down" || ride.status == "Closed",
          "Invalid status string returned by " + ride.name + ": " + ride.status
        );
      }
    });

    it("should have matching status and active fields", function() {
      for (var i = 0, ride; ride = times[i++];) {
        // check status and active variables match up
        if (ride.status == "Operating") assert(ride.active, "Ride cannot have Operating status and be inactive");
        else assert(!ride.active, "Ride can't be active without Operating status");
      }
    });

    // if park supports ride schedules, check they're valid
    if (park.supports_ride_schedules) {
      it("should have a schedule field for every ride", function() {
        for (var i = 0, ride; ride = times[i++];) {
          ValidateType(ride, "schedule", "object");

          // TODO - validate schedule object data
        }
      });
    }
  });

  // === Test Schedule Fetching ===
  describe("Get Schedule", function() {
    // give each test 2 minutes to finish
    this.timeout(1000 * 60 * 2);

    var schedule = [];
    it("should not error when fetching schedule", function(done) {
      park.GetOpeningTimes(function(err, _schedule) {
        assert(!err, "GetOpeningTimes returned an error: " + err);

        schedule = _schedule;

        if (PRINTDATA) console.log(JSON.stringify(schedule, null, 2));

        done(err);
      });
    });

    it("should have schedule data", function() {
      assert(schedule);
      assert(schedule.length > 3, "Should be at least 4 schedule items. Found " + schedule.length);
    });

    it("should have a valid date for each schedule entry", function() {
      for (var i = 0, day; day = schedule[i++];) ValidateDateTime(day, "date");
    });

    // skip if this day is closed
    it("should have a valid opening time for each schedule entry", function() {
      for (var i = 0, day; day = schedule[i++];) {
        if (day.type && day.type == "Closed") continue;
        ValidateDateTime(day, "openingTime");
      }
    });

    it("should have a valid closing time for each schedule entry", function() {
      for (var i = 0, day; day = schedule[i++];) {
        if (day.type && day.type == "Closed") continue;
        ValidateDateTime(day, "closingTime");
      }
    });

    // TODO - test the "special hours" array has valid data too
  });
}

function ValidateDateTime(obj, key) {
  assert(obj, "Date parent is not a valid object");
  assert(obj[key], "Date field " + key + " is not a valid object");

  // parse date using momentjs
  var date = moment(obj[key]);
  var yesterday = moment().subtract(1, "day");
  // make sure date is valid
  assert(date.isValid(), "Date " + obj[key] + " is invalid");
  // dates returned should be from today onwards
  // TODO - fix this logic, timezones mean that some parks will genuinely be open "yesterday"
  //assert(date.isAfter(yesterday), "Date " + obj[key] + " is before today (<= " + yesterday.format() + ")");
}

function ValidateType(obj, key, types) {
  // force types to an array
  types = [].concat(types);

  assert(obj, "Object passed to type validator is not valid");

  var objectType = typeof(obj[key]);
  for (var i = 0, t; t = types[i++];) {
    // exit function if we find a required type
    if (objectType == t) return;
  }

  assert.fail("Object " + obj[key] + " is not of any required types: " + JSON.stringify(types) + " (got " + objectType + ")");
}

function Run() {
  if (process.env.PARKID) {
    var park_id = process.env.PARKID;
    if (parks[park_id]) {
      // run tests against a single park
      describe("Park " + parks[park_id].name, function() {
        TestPark(new parks[park_id]());
      });
      return;
    }
    // else park missing, just fall through to standard full test
  }

  // test all parks supported (and exposed) by the API
  for (var park in parks) {
    describe("Park " + parks[park].name, function() {
      TestPark(new parks[park]());
    });
  }
}
Run();<commit_msg>Test ride schedule times to make sure they're strings and valid date strings<commit_after>var assert = require("assert");
var Park = require("./parkBase");
var DisneyBase = require("./Disney/DisneyBase");
var parks = require("./index");
var moment = require("moment-timezone");

// optional environment variable to print out API results
var PRINTDATA = process.env.PRINTDATA ? true : false;

if (!process.env.PARKID) {
  describe("ParkBase", function() {
    var parkBase = new Park();

    it("should error attempting to fetch wait times", function(done) {
      parkBase.GetWaitTimes(function(err, res) {
        assert(err);
        assert(!res);
        done();
      });
    });
  });

  describe("DisneyBase", function() {
    // be super-lenient for these tests
    this.timeout(1000 * 60 * 2);

    var DisneyPark = new DisneyBase();

    var access_token = null;
    it("should get a valid access token", function(done) {
      DisneyPark.GetAccessToken(function(err, token) {
        assert(!err, "GetAccessToken returned an error: " + err);
        assert(token && token.length, "Invalid access token returned: " + token);
        access_token = token;
        done();
      });
    });

    it("fetching again should have same token (from cache)", function(done) {
      DisneyPark.GetAccessToken(function(err, token) {
        assert(!err, "Second call to GetAccessToken returned an error: " + err);
        assert(token && token.length, "Invalid access token returned second time: " + token);
        assert(access_token == token, "Tokens are not identical! Caching has failed");
        done();
      });
    });
  });
}

function TestPark(park) {
  // === Test Wait Times Fetching ===
  describe("Get Park Wait Times", function() {
    // give each test 2 minutes to finish
    this.timeout(1000 * 60 * 2);

    var times = [];

    it("should not return an error fetching ride times", function(done) {
      park.GetWaitTimes(function(err, _times) {
        times = _times;
        if (PRINTDATA) console.log(JSON.stringify(times, null, 2));
        assert(!err);
        done(err);
      });
    });

    it("should have some ride data", function() {
      assert(times);

      // Sesame Place doesn't return data in downtime, so sorry. This is a bad unit test.
      if (park.name == "Sesame Place") return;

      assert(times.length > 3, "Not enough ride times to be valid data (<= 3), actual: " + times.length);
    });

    it("should have an ID for every ride", function() {
      for (var i = 0, ride; ride = times[i++];) ValidateType(ride, "id", ["string", "number"]);
    });

    it("should have a wait time for every ride", function() {
      for (var i = 0, ride; ride = times[i++];) ValidateType(ride, "waitTime", "number");
    });

    it("should have a name for every ride", function() {
      for (var i = 0, ride; ride = times[i++];) ValidateType(ride, "name", "string");
    });

    it("should have an active state for every ride", function() {
      for (var i = 0, ride; ride = times[i++];) ValidateType(ride, "active", "boolean");
    });

    it("should have a fastpass field for every ride", function() {
      for (var i = 0, ride; ride = times[i++];) ValidateType(ride, "fastPass", "boolean");
    });

    it("should have a status field for every ride", function() {
      for (var i = 0, ride; ride = times[i++];) {
        ValidateType(ride, "status", "string");
        // status string should only ever be one of these three options
        assert(
          ride.status == "Operating" || ride.status == "Down" || ride.status == "Closed",
          "Invalid status string returned by " + ride.name + ": " + ride.status
        );
      }
    });

    it("should have matching status and active fields", function() {
      for (var i = 0, ride; ride = times[i++];) {
        // check status and active variables match up
        if (ride.status == "Operating") assert(ride.active, "Ride cannot have Operating status and be inactive");
        else assert(!ride.active, "Ride can't be active without Operating status");
      }
    });

    // if park supports ride schedules, check they're valid
    if (park.supports_ride_schedules) {
      it("should have valid schedule field for every ride", function() {
        for (var i = 0, ride; ride = times[i++];) {
          ValidateType(ride, "schedule", "object");

          // validate schedule object data
          ValidateType(ride.schedule, "openingTime", "string");
          ValidateType(ride.schedule, "closingTime", "string");
          assert(moment(ride.schedule.openingTime).isValid(), "Ride schedule opening time should be valid: " + ride.schedule.openingTime);
          assert(moment(ride.schedule.closingTime).isValid(), "Ride schedule closing time should be valid: " + ride.schedule.closingTime);
        }
      });
    }
  });

  // === Test Schedule Fetching ===
  describe("Get Schedule", function() {
    // give each test 2 minutes to finish
    this.timeout(1000 * 60 * 2);

    var schedule = [];
    it("should not error when fetching schedule", function(done) {
      park.GetOpeningTimes(function(err, _schedule) {
        assert(!err, "GetOpeningTimes returned an error: " + err);

        schedule = _schedule;

        if (PRINTDATA) console.log(JSON.stringify(schedule, null, 2));

        done(err);
      });
    });

    it("should have schedule data", function() {
      assert(schedule);
      assert(schedule.length > 3, "Should be at least 4 schedule items. Found " + schedule.length);
    });

    it("should have a valid date for each schedule entry", function() {
      for (var i = 0, day; day = schedule[i++];) ValidateDateTime(day, "date");
    });

    // skip if this day is closed
    it("should have a valid opening time for each schedule entry", function() {
      for (var i = 0, day; day = schedule[i++];) {
        if (day.type && day.type == "Closed") continue;
        ValidateDateTime(day, "openingTime");
      }
    });

    it("should have a valid closing time for each schedule entry", function() {
      for (var i = 0, day; day = schedule[i++];) {
        if (day.type && day.type == "Closed") continue;
        ValidateDateTime(day, "closingTime");
      }
    });

    // TODO - test the "special hours" array has valid data too
  });
}

function ValidateDateTime(obj, key) {
  assert(obj, "Date parent is not a valid object");
  assert(obj[key], "Date field " + key + " is not a valid object");

  // parse date using momentjs
  var date = moment(obj[key]);
  var yesterday = moment().subtract(1, "day");
  // make sure date is valid
  assert(date.isValid(), "Date " + obj[key] + " is invalid");
  // dates returned should be from today onwards
  // TODO - fix this logic, timezones mean that some parks will genuinely be open "yesterday"
  //assert(date.isAfter(yesterday), "Date " + obj[key] + " is before today (<= " + yesterday.format() + ")");
}

function ValidateType(obj, key, types) {
  // force types to an array
  types = [].concat(types);

  assert(obj, "Object passed to type validator is not valid");

  var objectType = typeof(obj[key]);
  for (var i = 0, t; t = types[i++];) {
    // exit function if we find a required type
    if (objectType == t) return;
  }

  assert.fail("Object " + obj[key] + " is not of any required types: " + JSON.stringify(types) + " (got " + objectType + ")");
}

function Run() {
  if (process.env.PARKID) {
    var park_id = process.env.PARKID;
    if (parks[park_id]) {
      // run tests against a single park
      describe("Park " + parks[park_id].name, function() {
        TestPark(new parks[park_id]());
      });
      return;
    }
    // else park missing, just fall through to standard full test
  }

  // test all parks supported (and exposed) by the API
  for (var park in parks) {
    describe("Park " + parks[park].name, function() {
      TestPark(new parks[park]());
    });
  }
}
Run();<|endoftext|>


<commit_before>'use strict';
var test = require('ava');
var fn = require('./');

test(function (t) {
	t.is(fn('http://sindresorhus.com/foo/bar/baz/faz', 30), 'http://sindresorhus.com/…/faz');
	t.is(fn('http://example.com/a/cool/page/that-is-really-deeply/nested/', 40), 'http://example.com/…/nested/');
	t.is(fn('http://example.com/a/b/c/d', 24).length, 24);
	t.is(fn('http://example.com/a/b/c', 24), 'http://example.com/a/b/c');
	t.end();
});
<commit_msg>Test to fail<commit_after>'use strict';
var test = require('ava');
var fn = require('./');

test('should truncate url', function (t) {
	t.is(fn('http://sindresorhus.com/foo/bar/baz/faz', 30), 'http://sindresorhus.com/…/faz');
	t.is(fn('http://example.com/a/cool/page/that-is-really-deeply/nested/', 40), 'http://example.com/…/nested/');
	t.is(fn('http://example.com/a/b/c/d', 24).length, 24);
	t.is(fn('http://example.com/a/b/c', 24), 'http://example.com/a/b/c');
	t.end();
});

test('should pass corner case', function (t) {
	var result = fn('http://example.com/a/b/cd', 24);
	t.true(result.length <= 24, result + ' is > 24');
	t.end();
});
<|endoftext|>