<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 00:15: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>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-12-3 21:22:52<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 test = require('ava');
var tildify = require('./');

test(function (t) {
	var fixture = process.cwd();
	t.assert(tildify(fixture)[0] === '~');
	t.assert(/tildify$/.test(tildify(fixture)));
	t.assert(tildify(fixture) !== fixture);
});
<commit_msg>minor test tweak<commit_after>'use strict';
var test = require('ava');
var tildify = require('./');

test(function (t) {
	var fixture = process.cwd();
	t.assert(tildify(fixture)[0] === '~');
	t.assert(/tildify$/.test(tildify(fixture)));
	t.assert(tildify(fixture) !== fixture);
	t.end();
});
<|endoftext|>


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

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

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

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

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


<commit_before>import test from 'ava';
import stripJsonComments from './index.js';

test('replace comments with whitespace', t => {
	t.is(stripJsonComments('//comment\n{"a":"b"}'), '         \n{"a":"b"}');
	t.is(stripJsonComments('/*//comment*/{"a":"b"}'), '             {"a":"b"}');
	t.is(stripJsonComments('{"a":"b"//comment\n}'), '{"a":"b"         \n}');
	t.is(stripJsonComments('{"a":"b"/*comment*/}'), '{"a":"b"           }');
	t.is(stripJsonComments('{"a"/*\n\n\ncomment\r\n*/:"b"}'), '{"a"  \n\n\n       \r\n  :"b"}');
	t.is(stripJsonComments('/*!\n * comment\n */\n{"a":"b"}'), '   \n          \n   \n{"a":"b"}');
	t.is(stripJsonComments('{/*comment*/"a":"b"}'), '{           "a":"b"}');
});

test('remove comments', t => {
	const options = {whitespace: false};
	t.is(stripJsonComments('//comment\n{"a":"b"}', options), '\n{"a":"b"}');
	t.is(stripJsonComments('/*//comment*/{"a":"b"}', options), '{"a":"b"}');
	t.is(stripJsonComments('{"a":"b"//comment\n}', options), '{"a":"b"\n}');
	t.is(stripJsonComments('{"a":"b"/*comment*/}', options), '{"a":"b"}');
	t.is(stripJsonComments('{"a"/*\n\n\ncomment\r\n*/:"b"}', options), '{"a":"b"}');
	t.is(stripJsonComments('/*!\n * comment\n */\n{"a":"b"}', options), '\n{"a":"b"}');
	t.is(stripJsonComments('{/*comment*/"a":"b"}', options), '{"a":"b"}');
});

test('doesn\'t strip comments inside strings', t => {
	t.is(stripJsonComments('{"a":"b//c"}'), '{"a":"b//c"}');
	t.is(stripJsonComments('{"a":"b/*c*/"}'), '{"a":"b/*c*/"}');
	t.is(stripJsonComments('{"/*a":"b"}'), '{"/*a":"b"}');
	t.is(stripJsonComments('{"\\"/*a":"b"}'), '{"\\"/*a":"b"}');
});

test('consider escaped slashes when checking for escaped string quote', t => {
	t.is(stripJsonComments('{"\\\\":"https://foobar.com"}'), '{"\\\\":"https://foobar.com"}');
	t.is(stripJsonComments('{"foo\\"":"https://foobar.com"}'), '{"foo\\"":"https://foobar.com"}');
});

test('line endings - no comments', t => {
	t.is(stripJsonComments('{"a":"b"\n}'), '{"a":"b"\n}');
	t.is(stripJsonComments('{"a":"b"\r\n}'), '{"a":"b"\r\n}');
});

test('line endings - single line comment', t => {
	t.is(stripJsonComments('{"a":"b"//c\n}'), '{"a":"b"   \n}');
	t.is(stripJsonComments('{"a":"b"//c\r\n}'), '{"a":"b"   \r\n}');
});

test('line endings - single line block comment', t => {
	t.is(stripJsonComments('{"a":"b"/*c*/\n}'), '{"a":"b"     \n}');
	t.is(stripJsonComments('{"a":"b"/*c*/\r\n}'), '{"a":"b"     \r\n}');
});

test('line endings - multi line block comment', t => {
	t.is(stripJsonComments('{"a":"b",/*c\nc2*/"x":"y"\n}'), '{"a":"b",   \n    "x":"y"\n}');
	t.is(stripJsonComments('{"a":"b",/*c\r\nc2*/"x":"y"\r\n}'), '{"a":"b",   \r\n    "x":"y"\r\n}');
});

test('line endings - works at EOF', t => {
	const options = {whitespace: false};
	t.is(stripJsonComments('{\r\n\t"a":"b"\r\n} //EOF'), '{\r\n\t"a":"b"\r\n}      ');
	t.is(stripJsonComments('{\r\n\t"a":"b"\r\n} //EOF', options), '{\r\n\t"a":"b"\r\n} ');
});

test('handles weird escaping', t => {
	t.is(stripJsonComments(String.raw`{"x":"x \"sed -e \\\"s/^.\\\\{46\\\\}T//\\\" -e \\\"s/#033/\\\\x1b/g\\\"\""}`), String.raw`{"x":"x \"sed -e \\\"s/^.\\\\{46\\\\}T//\\\" -e \\\"s/#033/\\\\x1b/g\\\"\""}`);
});
<commit_msg>Add failing test for #51<commit_after>import test from 'ava';
import stripJsonComments from './index.js';

test('replace comments with whitespace', t => {
	t.is(stripJsonComments('//comment\n{"a":"b"}'), '         \n{"a":"b"}');
	t.is(stripJsonComments('/*//comment*/{"a":"b"}'), '             {"a":"b"}');
	t.is(stripJsonComments('{"a":"b"//comment\n}'), '{"a":"b"         \n}');
	t.is(stripJsonComments('{"a":"b"/*comment*/}'), '{"a":"b"           }');
	t.is(stripJsonComments('{"a"/*\n\n\ncomment\r\n*/:"b"}'), '{"a"  \n\n\n       \r\n  :"b"}');
	t.is(stripJsonComments('/*!\n * comment\n */\n{"a":"b"}'), '   \n          \n   \n{"a":"b"}');
	t.is(stripJsonComments('{/*comment*/"a":"b"}'), '{           "a":"b"}');
});

test('remove comments', t => {
	const options = {whitespace: false};
	t.is(stripJsonComments('//comment\n{"a":"b"}', options), '\n{"a":"b"}');
	t.is(stripJsonComments('/*//comment*/{"a":"b"}', options), '{"a":"b"}');
	t.is(stripJsonComments('{"a":"b"//comment\n}', options), '{"a":"b"\n}');
	t.is(stripJsonComments('{"a":"b"/*comment*/}', options), '{"a":"b"}');
	t.is(stripJsonComments('{"a"/*\n\n\ncomment\r\n*/:"b"}', options), '{"a":"b"}');
	t.is(stripJsonComments('/*!\n * comment\n */\n{"a":"b"}', options), '\n{"a":"b"}');
	t.is(stripJsonComments('{/*comment*/"a":"b"}', options), '{"a":"b"}');
});

test('doesn\'t strip comments inside strings', t => {
	t.is(stripJsonComments('{"a":"b//c"}'), '{"a":"b//c"}');
	t.is(stripJsonComments('{"a":"b/*c*/"}'), '{"a":"b/*c*/"}');
	t.is(stripJsonComments('{"/*a":"b"}'), '{"/*a":"b"}');
	t.is(stripJsonComments('{"\\"/*a":"b"}'), '{"\\"/*a":"b"}');
});

test('consider escaped slashes when checking for escaped string quote', t => {
	t.is(stripJsonComments('{"\\\\":"https://foobar.com"}'), '{"\\\\":"https://foobar.com"}');
	t.is(stripJsonComments('{"foo\\"":"https://foobar.com"}'), '{"foo\\"":"https://foobar.com"}');
});

test('line endings - no comments', t => {
	t.is(stripJsonComments('{"a":"b"\n}'), '{"a":"b"\n}');
	t.is(stripJsonComments('{"a":"b"\r\n}'), '{"a":"b"\r\n}');
});

test('line endings - single line comment', t => {
	t.is(stripJsonComments('{"a":"b"//c\n}'), '{"a":"b"   \n}');
	t.is(stripJsonComments('{"a":"b"//c\r\n}'), '{"a":"b"   \r\n}');
});

test('line endings - single line block comment', t => {
	t.is(stripJsonComments('{"a":"b"/*c*/\n}'), '{"a":"b"     \n}');
	t.is(stripJsonComments('{"a":"b"/*c*/\r\n}'), '{"a":"b"     \r\n}');
});

test('line endings - multi line block comment', t => {
	t.is(stripJsonComments('{"a":"b",/*c\nc2*/"x":"y"\n}'), '{"a":"b",   \n    "x":"y"\n}');
	t.is(stripJsonComments('{"a":"b",/*c\r\nc2*/"x":"y"\r\n}'), '{"a":"b",   \r\n    "x":"y"\r\n}');
});

test('line endings - works at EOF', t => {
	const options = {whitespace: false};
	t.is(stripJsonComments('{\r\n\t"a":"b"\r\n} //EOF'), '{\r\n\t"a":"b"\r\n}      ');
	t.is(stripJsonComments('{\r\n\t"a":"b"\r\n} //EOF', options), '{\r\n\t"a":"b"\r\n} ');
});

test('handles weird escaping', t => {
	t.is(stripJsonComments(String.raw`{"x":"x \"sed -e \\\"s/^.\\\\{46\\\\}T//\\\" -e \\\"s/#033/\\\\x1b/g\\\"\""}`), String.raw`{"x":"x \"sed -e \\\"s/^.\\\\{46\\\\}T//\\\" -e \\\"s/#033/\\\\x1b/g\\\"\""}`);
});

test.failing('handles malformed block comments', t => {
	t.is(stripJsonComments('[] */'), '[] */');
	t.is(stripJsonComments('[] /*'), '[] /*'); // Fails
});
<|endoftext|>


<commit_before>#!/usr/bin/env node

'use strict';

var assert = require('assert');

var EquationParser = require('./EquationParser');
var equationParser = new EquationParser();

var parseEquationWithInvalidCharacters = equationParser.parseEquation.bind(equationParser, '1+c+2+b+3');
var parseEquationWithInvalidDot = equationParser.parseEquation.bind(equationParser, '1+.-2');
var parseEquationWithInvalidParens = equationParser.parseEquation.bind(equationParser, '1+(1-(1)))(');
var parseEquationSkipSanitization = equationParser.parseEquation.bind(equationParser, '1 + 1', { skipSanitize: true });
var parseEquationSkipValidate = equationParser.parseEquation.bind(equationParser, '1+1+z', { skipValidate: true });
var eq1 = equationParser.parseEquation('2*6+5-2%2-5^3-1+1/5-1');
var eq2 = equationParser.parseEquation('.5+2./.1');
var eq3 = equationParser.parseEquation(' 1    + 2+ 4   /2   ');
var eq4 = equationParser.parseEquation('1+++2**4//2-4..0--....5^^4');
var eq5 = equationParser.parseEquation('2*(1+1)');
var eq6 = equationParser.parseEquation('2^2^3');
var eq7 = equationParser.parseEquation('10%30%8');
var eq8 = equationParser.parseEquation('abs(-1)+sqrt(101-abs(-1))');
var eq9 = equationParser.parseEquation('*1+2-abs');

try {
  assert.throws(parseEquationWithInvalidCharacters, Error, 'should throw if equation contains characters');
  assert.throws(parseEquationWithInvalidDot, Error, 'should throw if equation uses dot incorrectly');
  assert.throws(parseEquationWithInvalidParens, Error, 'should throw if parentheses are not in balance');
  assert.throws(parseEquationSkipSanitization, Error, 'should throw if equation contains whitespace');
  assert.throws(parseEquationSkipValidate, Error, 'should not be able to compute an equation containing invalid characters');
  assert.equal(eq1.compute(), -109.8, 'should handle supported operands');
  assert.equal(eq2.compute(), 20.5, 'should handle floats');
  assert.equal(eq3.compute(), 5, 'should handle whitespace input');
  assert.equal(eq4.compute(), 0.9375, 'should handle input with repeating operands and decimal points');
  assert.equal(eq5.compute(), 4, 'should handle parentheses');
  assert.equal(eq6.compute(), 256, 'should handle power of power');
  assert.equal(eq7.compute(), 4, 'should handle modulo of modulo');
  assert.equal(eq8.compute(), 11, 'should handle unary operands');
  assert.equal(eq9.compute(), 3, 'should handle leading/trailing operands');
  console.log('OK!');
} catch (e) {
  console.log(e.name + ':', e.message);
}
<commit_msg>Use better wording in test.js<commit_after>#!/usr/bin/env node

'use strict';

var assert = require('assert');

var EquationParser = require('./EquationParser');
var equationParser = new EquationParser();

var parseEquationWithInvalidCharacters = equationParser.parseEquation.bind(equationParser, '1+c+2+b+3');
var parseEquationWithInvalidDecimal = equationParser.parseEquation.bind(equationParser, '1+.-2');
var parseEquationWithInvalidParens = equationParser.parseEquation.bind(equationParser, '1+(1-(1)))(');
var parseEquationSkipSanitization = equationParser.parseEquation.bind(equationParser, '1 + 1', { skipSanitize: true });
var parseEquationSkipValidate = equationParser.parseEquation.bind(equationParser, '1+1+z', { skipValidate: true });
var eq1 = equationParser.parseEquation('2*6+5-2%2-5^3-1+1/5-1');
var eq2 = equationParser.parseEquation('.5+2./.1');
var eq3 = equationParser.parseEquation(' 1    + 2+ 4   /2   ');
var eq4 = equationParser.parseEquation('1+++2**4//2-4..0--....5^^4');
var eq5 = equationParser.parseEquation('2*(1+1)');
var eq6 = equationParser.parseEquation('2^2^3');
var eq7 = equationParser.parseEquation('10%30%8');
var eq8 = equationParser.parseEquation('abs(-1)+sqrt(101-abs(-1))');
var eq9 = equationParser.parseEquation('*1+2-abs');

try {
  assert.throws(parseEquationWithInvalidCharacters, Error, 'should throw if equation contains invalid characters');
  assert.throws(parseEquationWithInvalidDecimal, Error, 'should throw if equation uses the decimal point incorrectly');
  assert.throws(parseEquationWithInvalidParens, Error, 'should throw if parentheses are not in balance');
  assert.throws(parseEquationSkipSanitization, Error, 'should throw if equation contains whitespace');
  assert.throws(parseEquationSkipValidate, Error, 'should not be able to compute an equation containing invalid characters');
  assert.equal(eq1.compute(), -109.8, 'should handle ternary operands');
  assert.equal(eq2.compute(), 20.5, 'should handle floats');
  assert.equal(eq3.compute(), 5, 'should handle whitespace input');
  assert.equal(eq4.compute(), 0.9375, 'should handle repeated operands and decimal points');
  assert.equal(eq5.compute(), 4, 'should handle parentheses');
  assert.equal(eq6.compute(), 256, 'should handle power of power');
  assert.equal(eq7.compute(), 4, 'should handle modulo of modulo');
  assert.equal(eq8.compute(), 11, 'should handle unary operands');
  assert.equal(eq9.compute(), 3, 'should handle leading/trailing operands');
  console.log('OK!');
} catch (e) {
  console.log(e.name + ':', e.message);
}
<|endoftext|>


<commit_before>import test from 'ava';
import hashbow from './';

const person = {
  name: 'Randy Smasher',
  job: 'Banana',
  banana: true
};

function personFunction() {
  return person;
}

function isValidHexColor(t) {
  return item => {
    var hash = hashbow(item);
    t.is(typeof hash, 'string');
    t.is(hash.charAt(0), '#');
    t.is(hash.length, 7);
  };
}

test('Booleans return hexadecimal strings', t => {
  [true, false].forEach(isValidHexColor(t));
});

test('Strings return hexadecimal strings', t => {
  ['', 'Hi Mum!', '+\n++_\t)(*&^%$#@\n'].forEach(isValidHexColor(t));
});

test('Numbers return hexadecimal strings', t => {
  [Number.MAX_VALUE, -500, Infinity, 0, 10, 40.2434].forEach(isValidHexColor(t));
});

test('RegExps return hexadecimal strings', t => {
  [new RegExp(), new RegExp(/[a]/)].forEach(isValidHexColor);
});

test('Objects return hexadecimal strings', t => {
  [person, {}].forEach(isValidHexColor(t));
});

test('Arrays return hexadecimal strings', t => {
  [['asdf', person, {}, -2], []].forEach(isValidHexColor(t));
});

test('Functions return hexadecimal strings', t => {
  [function () {}, ()=>{}, personFunction].forEach(isValidHexColor);
});

test('Null returns a hexadecimal string', t => {
  isValidHexColor(t)(null);
});

test('Undefined returns a hexadecimal string', t => {
  isValidHexColor(t)(undefined);
});

<commit_msg>Add comments<commit_after>import test from 'ava';
import hashbow from './';

/**
 * Dummy values for tests
 */

const person = {
  name: 'Randy Smasher',
  job: 'Banana',
  banana: true
};

function personFunction() {
  return person;
}

/**
 * Check all types return valid hexadecimal strings i.e. '#000000'
 */

function isValidHexColor(t) {
  return item => {
    var hash = hashbow(item);
    t.is(typeof hash, 'string');
    t.is(hash.charAt(0), '#');
    t.is(hash.length, 7);
  };
}

test('Booleans return hexadecimal strings', t => {
  [true, false].forEach(isValidHexColor(t));
});

test('Strings return hexadecimal strings', t => {
  ['', 'Hi Mum!', '+\n++_\t)(*&^%$#@\n'].forEach(isValidHexColor(t));
});

test('Numbers return hexadecimal strings', t => {
  [Number.MAX_VALUE, -500, Infinity, 0, 10, 40.2434].forEach(isValidHexColor(t));
});

test('RegExps return hexadecimal strings', t => {
  [new RegExp(), new RegExp(/[a]/)].forEach(isValidHexColor);
});

test('Objects return hexadecimal strings', t => {
  [person, {}].forEach(isValidHexColor(t));
});

test('Arrays return hexadecimal strings', t => {
  [['asdf', person, {}, -2], []].forEach(isValidHexColor(t));
});

test('Functions return hexadecimal strings', t => {
  [function () {}, ()=>{}, personFunction].forEach(isValidHexColor);
});

test('Null returns a hexadecimal string', t => {
  isValidHexColor(t)(null);
});

test('Undefined returns a hexadecimal string', t => {
  isValidHexColor(t)(undefined);
});

<|endoftext|>


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

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

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

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

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


<commit_before>/*!
 * encode-image-stream <https://github.com/tunnckoCore/encode-image-stream>
 *
 * Copyright (c) 2015 Charlike Mike Reagent <@tunnckoCore> (http://www.tunnckocore.tk)
 * Released under the MIT license.
 */

/* jshint asi:true */

'use strict'

var fs = require('fs')
var test = require('assertit')
var encodeImageStream = require('./index')
var concatStream = require('concat-stream')
var through2 = require('through2')

test('encode-image-stream works for images', function (done) {
  fs.createReadStream('./foo.png')
    .pipe(encodeImageStream())
    .pipe(concatStream(function (body) {
      var str = body.toString('utf-8')
      test.ok(str.length > 10)
      test.equal(str[str.length - 1], '=')
      done()
    }))
})

test('works correctly when writing to html ', function (done) {
  var w = fs.createWriteStream('foo.html')
  w.write('<img src="data:image/png;base64,')
  w.on('close', function () {
    var data = fs.readFileSync('foo.html')
    test.ok(data.indexOf('') !== -1)
    done()
  })

  fs.createReadStream('./foo.png')
    .pipe(encodeImageStream())
    .pipe(through2(function (chunk, enc, callback) {
      callback(null, chunk)
    }, function (cb) {
      this.push('">')
      cb()
    }))
    .pipe(w)
})

test('should encode other files, but not correctly', function (done) {
  var chunks = []
  fs.createReadStream('./index.js')
    .pipe(encodeImageStream())
    .pipe(through2(function (chunk, enc, next) {
      chunks.push(chunk)
      next(null, chunk)
    }, function () {
      var last = chunks[chunks.length - 1]
      var chunk = last.toString('utf-8')
      test.ok(chunk.indexOf('==') === -1)
      done()
    }))
})
<commit_msg>fix test<commit_after>/*!
 * encode-image-stream <https://github.com/tunnckoCore/encode-image-stream>
 *
 * Copyright (c) 2015 Charlike Mike Reagent <@tunnckoCore> (http://www.tunnckocore.tk)
 * Released under the MIT license.
 */

/* jshint asi:true */

'use strict'

var fs = require('fs')
var test = require('assertit')
var encodeImageStream = require('./index')
var concatStream = require('concat-stream')
var through2 = require('through2')

test('encode-image-stream works for images', function (done) {
  fs.createReadStream('./foo.png')
    .pipe(encodeImageStream())
    .pipe(concatStream(function (body) {
      var str = body.toString('utf-8')
      test.ok(str.length > 10)
      test.equal(str[str.length - 1], '=')
      done()
    }))
})

test('works correctly when writing to html ', function (done) {
  var w = fs.createWriteStream('foo.html')
  w.write('<img src="data:image/png;base64,')
  w.on('close', function () {
    var data = fs.readFileSync('foo.html', 'utf-8')
    test.ok(data.indexOf('') !== -1)
    done()
  })

  fs.createReadStream('./foo.png')
    .pipe(encodeImageStream())
    .pipe(through2(function (chunk, enc, callback) {
      callback(null, chunk)
    }, function (cb) {
      this.push('">')
      cb()
    }))
    .pipe(w)
})

test('should encode other files, but not correctly', function (done) {
  var chunks = []
  fs.createReadStream('./index.js')
    .pipe(encodeImageStream())
    .pipe(through2(function (chunk, enc, next) {
      chunks.push(chunk)
      next(null, chunk)
    }, function () {
      var last = chunks[chunks.length - 1]
      var chunk = last.toString('utf-8')
      test.ok(chunk.indexOf('==') === -1)
      done()
    }))
})
<|endoftext|>


<commit_before>'use strict'

/*!
 * imports.
 */

var decode = require('punycode').ucs2.decode
var test = require('tape-catch')

/*!
 * imports (local).
 */

var map = require('./')

/*!
 * fixtures.
 */

var ucs2decode = (letter) => decode(letter)[0]
var characters = ['a', 'b', 'c']
var codepoints = [ 97, 98, 99 ]
var collection = [ { char: 'a' }, { char: 'b' }, { char: 'c' } ]

/*!
 * tests.
 */

test('map()', function (t) {
  t.deepEqual(map(ucs2decode, characters), codepoints, 'full application')
  t.deepEqual(map(ucs2decode)(characters), codepoints, 'partial application')
  t.deepEqual(map('char', collection), characters, 'dot-notation accessor is auto-created')
  t.end()
})
<commit_msg>use regular function declaration instead of arrow for test fixture<commit_after>'use strict'

/*!
 * imports.
 */

var decode = require('punycode').ucs2.decode
var test = require('tape-catch')

/*!
 * imports (local).
 */

var map = require('./')

/*!
 * fixtures.
 */

function ucs2decode (letter) {
  return decode(letter)[0]
}

var characters = ['a', 'b', 'c']
var codepoints = [ 97, 98, 99 ]
var collection = [ { char: 'a' }, { char: 'b' }, { char: 'c' } ]

/*!
 * tests.
 */

test('map()', function (t) {
  t.deepEqual(map(ucs2decode, characters), codepoints, 'full application')
  t.deepEqual(map(ucs2decode)(characters), codepoints, 'partial application')
  t.deepEqual(map('char', collection), characters, 'dot-notation accessor is auto-created')
  t.end()
})
<|endoftext|>


<commit_before>var util = require ('util');
/*
Name:           piwik - test.js
Description:    Access a Piwik API or track hits with node.js
Author:         Franklin van de Meent (https://frankl.in)
Source & docs:  https://github.com/fvdm/nodejs-piwik
Feedback:       https://github.com/fvdm/nodejs-piwik/issues
License:        Unlicense / Public Domain (see UNLICENSE file)
                (https://github.com/fvdm/nodejs-piwik/raw/develop/UNLICENSE)
*/

// Setup
// $ env PIWIK_URL= PIWIK_TOKEN= PIWIK_SITEID= npm test
var url = process.env.PIWIK_URL || null;
var token = process.env.PIWIK_TOKEN || null;
var siteId = process.env.PIWIK_SITEID || null;
var timeout = process.env.PIWIK_TIMEOUT || 5000;

var piwik = require ('./') .setup (url, token, timeout);

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

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

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

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

// doTest( passErr, 'methods', [
//   ['feeds', typeof feeds === 'object']
// ])
function doTest (err, label, tests) {
  if (err instanceof Error) {
    console.error (label +': \033[1m\033[31mERROR\033[0m\n');
    console.error (util.inspect (err, false, 10, true));
    console.log ();
    console.error (err.stack);
    console.log ();
    errors++;
  } else {
    var testErrors = [];
    for (var i = 0; i < tests.length; i++) {
      if (tests [i] [1] !== true) {
        testErrors.push (tests [i] [0]);
        errors++;
      }
    }

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

  doNext ();
}

// ! API access
queue.push (function () {
  piwik.api (
    {method: 'API.getPiwikVersion'},
    function (err) {
      if (err) {
        console.log ('API access: failed ('+ err.message +')');
        console.log (err.stack);
        errors++;
        process.exit (1);
      } else {
        console.log ('API access: \033[1m\033[32mok\033[0m');
        doNext ();
      }
    }
  );
});

// ! API error
queue.push (function () {
  piwik.api (
    {method: 'invalid method name'},
    function (err, data) {
      doTest (null, 'API error', [
        ['type', err && err instanceof Error],
        ['message', err && err.message === 'api error']
      ]);
    }
  );
});

// ! Track one
queue.push (function () {
  piwik.track (
    {
      idsite: siteId,
      url: 'https://www.npmjs.com/package/piwik',
      cvar: {'1': ['node test', process.version]}
    },
    function (err, data) {
      doTest (err, 'track one', [
        ['data type', typeof data === 'object'],
        ['data.status', data && data.status === 'success'],
        ['data.tracked', data && data.tracked === 1]
      ]);
    }
  );
});

// ! Track multi
queue.push (function () {
  piwik.track (
    [
      {
        idsite: siteId,
        url: 'https://www.npmjs.com/package/piwik',
        cvar: {'1': ['node test', process.version]}
      },
      {
        idsite: siteId,
        url: 'https://github.com/fvdm/nodejs-piwik',
        cvar: {'1': ['node test', process.version]}
      }
    ],
    function (err, data) {
      doTest (err, 'track multi', [
        ['data type', typeof data === 'object'],
        ['data.status', data && data.status === 'success'],
        ['data.tracked', data && data.tracked === 2]
      ]);
    }
  );
});

// ! API
queue.push (function () {
  piwik.api (
    {
      method: 'Actions.getPageUrls',
      idSite: siteId,
      period: 'year',
      date: 'today'
    },
    function (err, data) {
      doTest (err, 'api', [
        ['data type', data instanceof Array],
        ['data length', data && data.length >= 1],
        ['item type', data && data [0] instanceof Object],
        ['item label', data && data [0] && typeof data [0] .label === 'string']
      ]);
    }
  );
});

// ! loadSpammers
queue.push (function () {
  piwik.loadSpammers (function (err, data) {
    doTest (err, 'loadSpammers', [
      ['data type', data instanceof Array],
      ['data length', data && data.length >= 1],
      ['item type', data && data [0] && typeof data [0] === 'string']
    ]);
  });
});

// Start the tests
console.log ('Running tests...\n');
queue [0] ();
<commit_msg>Test: replaced util.inspect with console.dir<commit_after>/*
Name:           piwik - test.js
Description:    Access a Piwik API or track hits with node.js
Author:         Franklin van de Meent (https://frankl.in)
Source & docs:  https://github.com/fvdm/nodejs-piwik
Feedback:       https://github.com/fvdm/nodejs-piwik/issues
License:        Unlicense / Public Domain (see UNLICENSE file)
                (https://github.com/fvdm/nodejs-piwik/raw/develop/UNLICENSE)
*/

// Setup
// $ env PIWIK_URL= PIWIK_TOKEN= PIWIK_SITEID= npm test
var url = process.env.PIWIK_URL || null;
var token = process.env.PIWIK_TOKEN || null;
var siteId = process.env.PIWIK_SITEID || null;
var timeout = process.env.PIWIK_TIMEOUT || 5000;

var piwik = require ('./') .setup (url, token, timeout);

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

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

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

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

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

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

  doNext ();
}

// ! API access
queue.push (function () {
  piwik.api (
    {method: 'API.getPiwikVersion'},
    function (err) {
      if (err) {
        console.log ('API access: failed ('+ err.message +')');
        console.log (err.stack);
        errors++;
        process.exit (1);
      } else {
        console.log ('API access: \033[1m\033[32mok\033[0m');
        doNext ();
      }
    }
  );
});

// ! API error
queue.push (function () {
  piwik.api (
    {method: 'invalid method name'},
    function (err, data) {
      doTest (null, 'API error', [
        ['type', err && err instanceof Error],
        ['message', err && err.message === 'api error']
      ]);
    }
  );
});

// ! Track one
queue.push (function () {
  piwik.track (
    {
      idsite: siteId,
      url: 'https://www.npmjs.com/package/piwik',
      cvar: {'1': ['node test', process.version]}
    },
    function (err, data) {
      doTest (err, 'track one', [
        ['data type', typeof data === 'object'],
        ['data.status', data && data.status === 'success'],
        ['data.tracked', data && data.tracked === 1]
      ]);
    }
  );
});

// ! Track multi
queue.push (function () {
  piwik.track (
    [
      {
        idsite: siteId,
        url: 'https://www.npmjs.com/package/piwik',
        cvar: {'1': ['node test', process.version]}
      },
      {
        idsite: siteId,
        url: 'https://github.com/fvdm/nodejs-piwik',
        cvar: {'1': ['node test', process.version]}
      }
    ],
    function (err, data) {
      doTest (err, 'track multi', [
        ['data type', typeof data === 'object'],
        ['data.status', data && data.status === 'success'],
        ['data.tracked', data && data.tracked === 2]
      ]);
    }
  );
});

// ! API
queue.push (function () {
  piwik.api (
    {
      method: 'Actions.getPageUrls',
      idSite: siteId,
      period: 'year',
      date: 'today'
    },
    function (err, data) {
      doTest (err, 'api', [
        ['data type', data instanceof Array],
        ['data length', data && data.length >= 1],
        ['item type', data && data [0] instanceof Object],
        ['item label', data && data [0] && typeof data [0] .label === 'string']
      ]);
    }
  );
});

// ! loadSpammers
queue.push (function () {
  piwik.loadSpammers (function (err, data) {
    doTest (err, 'loadSpammers', [
      ['data type', data instanceof Array],
      ['data length', data && data.length >= 1],
      ['item type', data && data [0] && typeof data [0] === 'string']
    ]);
  });
});

// Start the tests
console.log ('Running tests...\n');
queue [0] ();
<|endoftext|>


<commit_before>import postcss from 'postcss';
import test from 'ava';
import plugin from './';

function run(t, input, output, opts = {}) {
  return postcss([plugin(opts)]).process(input)
    .then(result => {
      t.deepEqual(result.css, output);
      t.deepEqual(result.warnings().length, 0);
    });
}

test('Append to parent selector', t => {
  return run(t,
    'body{div{h2{@in <.mod{prop: value;}}}}',
    'body{div{h2{}}}body{div.mod{h2{prop: value}}}');
});

test('Append to parent multiselector', t => {
  return run(t,
    'body{div, span{h2{@in <.mod{prop: value;}}}}',
    'body{div, span{h2{}}}body{div.mod, span.mod{h2{prop: value}}}');
});

test('Append multiple to parent selector', t => {
  return run(t,
    'body{div{h2{@in <.mod1 <<[mod2]{prop: value;}}}}',
    'body{div{h2{}}}body[mod2]{div.mod1{h2{prop: value}}}');
});

test('Insert in parent selector', t => {
  return run(t,
    'body{div{h2{@in ^.mod{prop: value;}}}}',
    'body{div{h2{}}}body{div .mod{h2{prop: value}}}');
});

test('Insert in parent multiselector', t => {
  return run(t,
    'body{div, span{h2{@in ^.mod{prop: value;}}}}',
    'body{div, span{h2{}}}body{div .mod, span .mod{h2{prop: value}}}');
});

test('Insert multiple in parent selector', t => {
  return run(t,
    'body{div{h2{@in ^.mod1 ^^[mod2]{prop: value;}}}}',
    'body{div{h2{}}}body [mod2]{div .mod1{h2{prop: value}}}');
});

test('Replace in parent selector', t => {
  return run(t,
    'body{div{h2{@in @.mod{prop: value;}}}}',
    'body{div{h2{}}}body{.mod{h2{prop: value}}}');
});

test('Replace in parent multiselector', t => {
  return run(t,
    'body{div, span{h2{@in @.mod{prop: value;}}}}',
    'body{div, span{h2{}}}body{.mod{h2{prop: value}}}');
});

test('Replace multiple in parent selector', t => {
  return run(t,
    'body{div{h2{@in @.mod1 @@[mod2]{prop: value;}}}}',
    'body{div{h2{}}}[mod2]{.mod1{h2{prop: value}}}');
});
<commit_msg>more tests<commit_after>import postcss from 'postcss';
import test from 'ava';
import plugin from './';

function run(t, input, output, opts = {}) {
  return postcss([plugin(opts)]).process(input)
    .then(result => {
      t.deepEqual(result.css, output);
      t.deepEqual(result.warnings().length, 0);
    });
}

test('Append to parent selector', t => {
  return run(t,
    'body{div{h2{@in <.mod{prop: value;}}}}',
    'body{div{h2{}}}body{div.mod{h2{prop: value}}}');
});

test('Append to parent multiselector', t => {
  return run(t,
    'body{div, span{h2{@in <.mod{prop: value;}}}}',
    'body{div, span{h2{}}}body{div.mod, span.mod{h2{prop: value}}}');
});

test('Append multiple to parent selector', t => {
  return run(t,
    'body{div{h2{@in <.mod1 <<[mod2]{prop: value;}}}}',
    'body{div{h2{}}}body[mod2]{div.mod1{h2{prop: value}}}');
});

test('Insert in parent selector', t => {
  return run(t,
    'body{div{h2{@in ^.mod{prop: value;}}}}',
    'body{div{h2{}}}body{div .mod{h2{prop: value}}}');
});

test('Insert in parent multiselector', t => {
  return run(t,
    'body{div, span{h2{@in ^.mod{prop: value;}}}}',
    'body{div, span{h2{}}}body{div .mod, span .mod{h2{prop: value}}}');
});

test('Insert multiple in parent selector', t => {
  return run(t,
    'body{div{h2{@in ^.mod1 ^^[mod2]{prop: value;}}}}',
    'body{div{h2{}}}body [mod2]{div .mod1{h2{prop: value}}}');
});

test('Replace in parent selector', t => {
  return run(t,
    'body{div{h2{@in @.mod{prop: value;}}}}',
    'body{div{h2{}}}body{.mod{h2{prop: value}}}');
});

test('Replace in parent multiselector', t => {
  return run(t,
    'body{div, span{h2{@in @.mod{prop: value;}}}}',
    'body{div, span{h2{}}}body{.mod{h2{prop: value}}}');
});

test('Replace multiple in parent selector', t => {
  return run(t,
    'body{div{h2{@in @.mod1 @@[mod2]{prop: value;}}}}',
    'body{div{h2{}}}[mod2]{.mod1{h2{prop: value}}}');
});

test('Multiple operations in selector', t => {
  return run(t,
    'body{div{h2{span{@in <.mod1 ^^.mod2 @@@.mod3{prop: value;}}}}}',
    'body{div{h2{span{}}}}.mod3{div .mod2{h2.mod1{span{prop: value}}}}');
});

test('Multiple space separated operations in selector', t => {
  return run(t,
    'body{div{h2{span{@in <.mod1 ^^.mod2 @@@.mod3, <.mod3 ^^.mod1 @@@.mod2{prop: value;}}}}}', // eslint-disable-line max-len
    'body{div{h2{span{}}}}.mod3{div .mod2{h2.mod1{span{prop: value}}}}.mod2{div .mod1{h2.mod3{span{prop: value}}}}'); // eslint-disable-line max-len
});

test('Passing custom tag options', t => {
  return run(t,
    'body{div{h2{span{@in +.mod1 **.mod2 %%%.mod3{prop: value;}}}}}',
    'body{div{h2{span{}}}}.mod3{div .mod2{h2.mod1{span{prop: value}}}}',
    { tagAppend: '\\+', tagInsert: '\\*', tagReplace: '%' });
});
<|endoftext|>


<commit_before>var context = require('gl-context')
var test = require('tape')
var material = require('./index')

var canvas = document.body.appendChild(document.createElement('canvas'))
var gl = context(canvas)

test('construction', function (t) {
  var flat = {
    fragment: 'precision highp float; struct Style {vec3 color;};uniform Style style;void main() {gl_FragColor = vec4(style.color, 1.0);}',
    styles: {
      color: {type: 'vec3', default: [0, 100, 0]}
    },
    name: 'my-flat-material'
  }
  var result = material(gl, flat)
  t.ok(result.shader, 'shader defined')
  t.deepEqual(result.defaults.color, [0, 100, 0])
  t.end()
})

test('replacement', function (t) {
  var flat = {
    fragment: 'precision highp float; uniform vec3 test[COUNT]; struct Style {vec3 color;};uniform Style style;void main() {gl_FragColor = vec4(style.color, 1.0);}',
    styles: {
      color: {type: 'vec3', default: [0, 100, 0]}
    },
    name: 'my-flat-material'
  }
  var result = material(gl, flat, {'COUNT': 10})
  t.ok(result.shader, 'shader defined')
  t.equal(result.shader._fref.src.indexOf('test[10]'), 36, 'line found')
  t.deepEqual(result.defaults.color, [0, 100, 0])
  t.end()
})

test('multiple replacement', function (t) {
  var flat = {
    fragment: 'precision highp float; uniform vec3 a[COUNT]; uniform vec3 b[COUNT]; struct Style {vec3 color;};uniform Style style;void main() {gl_FragColor = vec4(style.color, 1.0);}',
    styles: {
      color: {type: 'vec3', default: [0, 100, 0]}
    },
    name: 'my-flat-material'
  }
  var result = material(gl, flat, {'COUNT': 10})
  t.ok(result.shader, 'shader defined')
  t.equal(result.shader._fref.src.indexOf('a[10]'), 36, 'line found')
  t.equal(result.shader._fref.src.indexOf('b[10]'), 56, 'line found')
  t.deepEqual(result.defaults.color, [0, 100, 0])
  t.end()
})<commit_msg>standard<commit_after>var context = require('gl-context')
var test = require('tape')
var material = require('./index')

var canvas = document.body.appendChild(document.createElement('canvas'))
var gl = context(canvas)

test('construction', function (t) {
  var flat = {
    fragment: 'precision highp float; struct Style {vec3 color;};uniform Style style;void main() {gl_FragColor = vec4(style.color, 1.0);}',
    styles: {
      color: {type: 'vec3', default: [0, 100, 0]}
    },
    name: 'my-flat-material'
  }
  var result = material(gl, flat)
  t.ok(result.shader, 'shader defined')
  t.deepEqual(result.defaults.color, [0, 100, 0])
  t.end()
})

test('replacement', function (t) {
  var flat = {
    fragment: 'precision highp float; uniform vec3 test[COUNT]; struct Style {vec3 color;};uniform Style style;void main() {gl_FragColor = vec4(style.color, 1.0);}',
    styles: {
      color: {type: 'vec3', default: [0, 100, 0]}
    },
    name: 'my-flat-material'
  }
  var result = material(gl, flat, {'COUNT': 10})
  t.ok(result.shader, 'shader defined')
  t.equal(result.shader._fref.src.indexOf('test[10]'), 36, 'line found')
  t.deepEqual(result.defaults.color, [0, 100, 0])
  t.end()
})

test('multiple replacement', function (t) {
  var flat = {
    fragment: 'precision highp float; uniform vec3 a[COUNT]; uniform vec3 b[COUNT]; struct Style {vec3 color;};uniform Style style;void main() {gl_FragColor = vec4(style.color, 1.0);}',
    styles: {
      color: {type: 'vec3', default: [0, 100, 0]}
    },
    name: 'my-flat-material'
  }
  var result = material(gl, flat, {'COUNT': 10})
  t.ok(result.shader, 'shader defined')
  t.equal(result.shader._fref.src.indexOf('a[10]'), 36, 'line found')
  t.equal(result.shader._fref.src.indexOf('b[10]'), 56, 'line found')
  t.deepEqual(result.defaults.color, [0, 100, 0])
  t.end()
})
<|endoftext|>


<commit_before>'use strict';

var test = require('tape');
var m = require('mithril');
var render = require('./index');

test('render', function(t) {
  t.equal(render(m('span', 'content')),
    'content', 'should render tag');
  t.equal(render(m('.foo', 'content')),
    '
content
', 'should render classname');
  t.equal(render(m('#bar', 'content')),
    '
content
', 'should render id');
  t.equal(render(m('br')), '
', 'should render short nodes when no children');
  t.equal(render(m('span', {
    'data-foo': 'bar',
    selected: 'selected'
  })), '', 'should render attributes');
  t.equal(render(m('ul', 'huhu')), '
huhu
', 'should render string');
  t.equal(render([m('span', 'foo'), m('div', 'bar')]),
    'foo
bar
', 'should render arrays');
  t.equal(render(m('span', m('div'))), '

', 'should render children');
  t.equal(render(m('span', {
    onmousemove: function(event) {}
  })), '', 'should not render events');
  t.equal(render(m('span', {
    style: {
      paddingLeft: '10px',
      color: 'red'
    }
  })), '', 'should render children');
  t.equal(render(m('div', [
    1,
    m('span'),
    "2"
  ])), '
12
', 'should render numbers as text nodes');
  t.equal(render(m('div', 0)), '
0
');
  t.equal(render(m('div', false)), '
false
');
  t.equal(render(m('div', { a: true})), '

');
  t.equal(render(m('div', { a: false})), '

');
  t.equal(render(m('div', m.trust('<foo></foo>'))), '
<foo></foo>
');
  t.equal(render(m('div', '<foo></foo>')), '
<foo></foo>
');
  t.end();
});
<commit_msg>Added a test for uppercase VOID_TAGS.<commit_after>'use strict';

var test = require('tape');
var m = require('mithril');
var render = require('./index');

test('render', function(t) {
  t.equal(render(m('span', 'content')),
    'content', 'should render tag');
  t.equal(render(m('.foo', 'content')),
    '
content
', 'should render classname');
  t.equal(render(m('#bar', 'content')),
    '
content
', 'should render id');
  t.equal(render(m('br')), '
', 'should render short nodes when no children');
  t.equal(render(m('HR')), '
', 'should render short nodes when no children and tag name is uppercase');
  t.equal(render(m('span', {
    'data-foo': 'bar',
    selected: 'selected'
  })), '', 'should render attributes');
  t.equal(render(m('ul', 'huhu')), '
huhu
', 'should render string');
  t.equal(render([m('span', 'foo'), m('div', 'bar')]),
    'foo
bar
', 'should render arrays');
  t.equal(render(m('span', m('div'))), '

', 'should render children');
  t.equal(render(m('span', {
    onmousemove: function(event) {}
  })), '', 'should not render events');
  t.equal(render(m('span', {
    style: {
      paddingLeft: '10px',
      color: 'red'
    }
  })), '', 'should render children');
  t.equal(render(m('div', [
    1,
    m('span'),
    "2"
  ])), '
12
', 'should render numbers as text nodes');
  t.equal(render(m('div', 0)), '
0
');
  t.equal(render(m('div', false)), '
false
');
  t.equal(render(m('div', { a: true})), '

');
  t.equal(render(m('div', { a: false})), '

');
  t.equal(render(m('div', m.trust('<foo></foo>'))), '
<foo></foo>
');
  t.equal(render(m('div', '<foo></foo>')), '
<foo></foo>
');
  t.end();
});
<|endoftext|>


<commit_before>var dsfm = require('./');
var assert = require('assert');
var stream = require('readable-stream');

describe('dsfm()', function () {
  it('should return a Function instance,', function () {
    assert(dsfm('') instanceof Function);
  });
  it('should deal with arbitrary delims,', function () {
    var csfm = new dsfm(',,,', function (data) {
      return data.replace('dash', 'comma');
    });
    var ret = csfm(',,,\ndash-seperated\n,,,\ncontent');
    assert.equal(ret.attributes, 'comma-seperated');
    assert.equal(ret.body, 'content');

    // no newline after closing delim (eos)
    var bsfm = dsfm(['[[[', ']]]'], function (data) {
      return data.replace('dash', 'square-bracket');
    });
    ret = bsfm('[[[\ndash-seperated\n]]]');
    assert.equal(ret.attributes, 'square-bracket-seperated');
    assert.equal(ret.body, '');
  });
  it('even when constructed without a transform', function () {
    var csfm = new dsfm(',,,', null);
    var ret = csfm(',,,\ndata\n,,,\ncontent');
    assert.equal(ret.attributes, 'data');
    assert.equal(ret.body, 'content');
  });
  it('should throw on invalid delims type', function () {
    assert.throws(function () { new dsfm.Parser({}); });
  });
  it('should throw on invalid fn type', function () {
    assert.throws(function () { new dsfm.Parser('', 2); });
  });

  /**
   * testing yaml() and json() is an appropriate
   * test for return values of the parser
   * constructor, given arbitrary args.
   */
  describe('#yaml()', function () {
    it('should correctly parse a document', function () {
      var post = dsfm.yaml('---\ntesting: true\npassing: hopefully\n---\ncontent');
      assert.deepEqual(post.attributes, { testing: true, passing: 'hopefully' });
      assert.equal(post.body, 'content');
    });
    it('should parse a document using dos newlines', function () {
      var post = dsfm.yaml('---\r\ntesting: true\r\npassing: hopefully\r\n---\r\ncontent');
      assert.deepEqual(post.attributes, { testing: true, passing: 'hopefully' });
      assert.equal(post.body, 'content');
    });
    it('should parse a document containing no front-matter', function () {
      var post = dsfm.yaml('content');
      assert.equal(post.attributes, null);
      assert.equal(post.body, 'content');
    });
    it('should parse a document containing only front-matter', function () {
      var post = dsfm.yaml('---\ntesting: true\npassing: hopefully\n---\n');
      assert.deepEqual(post.attributes, { testing: true, passing: 'hopefully' });
      assert.equal(post.body, '');
    });
    it('should parse an empty document', function () {
      var post = dsfm.yaml('');
      assert.equal(post.attributes, null);
      assert.equal(post.body, '');
    });
    describe('#test()', function () {
      it('should test for yaml front-matter in a document', function () {
        var test = dsfm.yaml.test;
        assert(test('---\ntesting: true\npassing: hopefully\n---\ncontent'));
        assert(!test('no-front-matter'));
      });
    });
    describe('#through()', function () {
      var through = dsfm.yaml.through();
      it('should return `through` stream', function () {
        assert(through instanceof stream.Transform);
      });
      it('that emits `attributes` and `data`', function (complete) {
        var attributes;
        var body = '';
        var readable = new stream.Readable({
          read: function () {
            this.push('---\ntesting: true\npassing: hopefully\n---\ncontent');
            this.push(null);
          },
        });
        through.on('attributes', function (attr) {
          attributes = attr;
        });
        through.on('data', function (data) {
          body += data;
        });
        through.on('end', function () {
          assert(attributes, { testing: true, passing: 'hopefully' });
          assert(body, 'content');
          complete();
        });
        readable.pipe(through);
      });
    });
  });

  describe('#json()', function () {
    it('should correctly parse a document', function () {
      var post = dsfm.json('{{{\n"testing":true,"passing":"hopefully"\n}}}\ncontent');
      assert.deepEqual(post.attributes, { testing: true, passing: 'hopefully' });
      assert.equal('content', post.body);
    });
    it('should parse a document using dos newlines', function () {
      var post = dsfm.json('{{{\r\n"testing":true,"passing":"hopefully"\r\n}}}\r\ncontent');
      assert.deepEqual(post.attributes, { testing: true, passing: 'hopefully' });
      assert.equal(post.body, 'content');
    });
    it('should parse a document containing no front-matter', function () {
      var post = dsfm.json('content');
      assert.equal(post.attributes, null);
      assert.equal(post.body, 'content');
    });
    it('should parse a document containing only front-matter', function () {
      var post = dsfm.json('{{{\n"testing":true,"passing":"hopefully"\n}}}\n');
      assert.deepEqual(post.attributes, { testing: true, passing: 'hopefully' });
      assert.equal(post.body, '');
    });
    it('should parse an empty document', function () {
      var post = dsfm.json('');
      assert.equal(post.attributes, null);
      assert.equal(post.body, '');
    });
    describe('#test()', function () {
      it('should test for json front-matter in a document', function () {
        var test = dsfm.json.test;
        assert(test('{{{\n"testing":true,"passing":"hopefully"\n}}}\ncontent'));
        assert(!test('no-front-matter'));
      });
    });
    describe('#through()', function () {
      var through = dsfm.json.through();
      it('should return `through` stream', function () {
        assert(through instanceof stream.Transform);
      });
      it('that emits `attributes` and `data`', function (complete) {
        var attributes;
        var body = '';
        var readable = new stream.Readable({
          read: function () {
            this.push('{{{\n"testing":true,"passing":"hopefully"\n}}}\ncontent');
            this.push(null);
          },
        });
        through.on('attributes', function (attr) {
          attributes = attr;
        });
        through.on('data', function (data) {
          body += data;
        });
        through.on('end', function () {
          assert.deepEqual(attributes, { testing: true, passing: 'hopefully' });
          assert.deepEqual(body, 'content');
          complete();
        });
        readable.pipe(through);
      });
    });
  });
});
<commit_msg>some test changes<commit_after>const parser = require('./');
const assert = require('assert');
const stream = require('readable-stream');

describe('parser()', function () {
  it('should return a Function instance,', function () {
    assert(parser('') instanceof Function);
  });

  it('should deal with arbitrary delims,', function () {
    var csfm = new parser(',,,', function (data) {
      return data.replace('dash', 'comma');
    });
    var ret = csfm(',,,\ndash-seperated\n,,,\ncontent');
    assert.equal(ret.attributes, 'comma-seperated');
    assert.equal(ret.body, 'content');

    // no newline after closing delim (eos)
    var bsfm = parser(['[[[', ']]]'], function (data) {
      return data.replace('dash', 'square-bracket');
    });
    ret = bsfm('[[[\ndash-seperated\n]]]');
    assert.equal(ret.attributes, 'square-bracket-seperated');
    assert.equal(ret.body, '');
  });

  it('even when constructed without a transform', function () {
    var csfm = new parser(',,,', null);
    var ret = csfm(',,,\ndata\n,,,\ncontent');
    assert.equal(ret.attributes, 'data');
    assert.equal(ret.body, 'content');
  });

  it('should throw on invalid delims type', function () {
    assert.throws(function () { new parser({}); });
  });

  it('should throw on invalid fn type', function () {
    assert.throws(function () { new parser('', 2); });
  });

  /**
   * testing yaml() and json() is an appropriate
   * test for return values of the parser
   * constructor, given arbitrary args.
   */
  describe('#yaml()', function () {
    it('should correctly parse a document', function () {
      var post = parser.yaml('---\ntesting: true\npassing: hopefully\n---\ncontent');
      assert.deepEqual(post.attributes, { testing: true, passing: 'hopefully' });
      assert.equal(post.body, 'content');
    });

    it('should parse a document using dos newlines', function () {
      var post = parser.yaml('---\r\ntesting: true\r\npassing: hopefully\r\n---\r\ncontent');
      assert.deepEqual(post.attributes, { testing: true, passing: 'hopefully' });
      assert.equal(post.body, 'content');
    });

    it('should parse a document containing no front-matter', function () {
      var post = parser.yaml('content');
      assert.equal(post.attributes, null);
      assert.equal(post.body, 'content');
    });

    it('should parse a document containing only front-matter', function () {
      var post = parser.yaml('---\ntesting: true\npassing: hopefully\n---\n');
      assert.deepEqual(post.attributes, { testing: true, passing: 'hopefully' });
      assert.equal(post.body, '');
    });

    it('should parse an empty document', function () {
      var post = parser.yaml('');
      assert.equal(post.attributes, null);
      assert.equal(post.body, '');
    });

    describe('#test()', function () {
      it('should test for yaml front-matter in a document', function () {
        var test = parser.yaml.test;
        assert(test('---\ntesting: true\npassing: hopefully\n---\ncontent'));
        assert(!test('no-front-matter'));
      });
    });

    describe('#through()', function () {
      var through = parser.yaml.through();
      it('should return `through` stream', function () {
        assert(through instanceof stream.Transform);
      });

      it('that emits `attributes` and `data`', function (complete) {
        var attributes;
        var body = '';
        var readable = new stream.Readable({
          read: function () {
            this.push('---\ntesting: true\npassing: hopefully\n---\ncontent');
            this.push(null);
          },
        });

        through.on('attributes', function (attr) {
          attributes = attr;
        });

        through.on('data', function (data) {
          body += data;
        });

        through.on('end', function () {
          assert(attributes, { testing: true, passing: 'hopefully' });
          assert(body, 'content');
          complete();
        });

        readable.pipe(through);
      });
    });
  });

  describe('#json()', function () {
    it('should correctly parse a document', function () {
      var post = parser.json('{{{\n"testing":true,"passing":"hopefully"\n}}}\ncontent');
      assert.deepEqual(post.attributes, { testing: true, passing: 'hopefully' });
      assert.equal('content', post.body);
    });

    it('should parse a document using dos newlines', function () {
      var post = parser.json('{{{\r\n"testing":true,"passing":"hopefully"\r\n}}}\r\ncontent');
      assert.deepEqual(post.attributes, { testing: true, passing: 'hopefully' });
      assert.equal(post.body, 'content');
    });

    it('should parse a document containing no front-matter', function () {
      var post = parser.json('content');
      assert.equal(post.attributes, null);
      assert.equal(post.body, 'content');
    });

    it('should parse a document containing only front-matter', function () {
      var post = parser.json('{{{\n"testing":true,"passing":"hopefully"\n}}}\n');
      assert.deepEqual(post.attributes, { testing: true, passing: 'hopefully' });
      assert.equal(post.body, '');
    });

    it('should parse an empty document', function () {
      var post = parser.json('');
      assert.equal(post.attributes, null);
      assert.equal(post.body, '');
    });

    describe('#test()', function () {
      it('should test for json front-matter in a document', function () {
        var test = parser.json.test;
        assert(test('{{{\n"testing":true,"passing":"hopefully"\n}}}\ncontent'));
        assert(!test('no-front-matter'));
      });
    });

    describe('#through()', function () {
      var through = parser.json.through();
      it('should return `through` stream', function () {
        assert(through instanceof stream.Transform);
      });

      it('that emits `attributes` and `data`', function (complete) {
        var attributes;
        var body = '';
        var readable = new stream.Readable({
          read: function () {
            this.push('{{{\n"testing":true,"passing":"hopefully"\n}}}\ncontent');
            this.push(null);
          },
        });

        through.on('attributes', function (attr) {
          attributes = attr;
        });

        through.on('data', function (data) {
          body += data;
        });

        through.on('end', function () {
          assert.deepEqual(attributes, { testing: true, passing: 'hopefully' });
          assert.deepEqual(body, 'content');
          complete();
        });

        readable.pipe(through);
      });
    });
  });
});
<|endoftext|>


<commit_before>/*
Name:           geoip2ws - test.js
Description:    Maxmind GeoIP2 Web Services for node.js
Author:         Franklin van de Meent (https://frankl.in)
Source & docs:  https://github.com/fvdm/nodejs-geoip2ws
Feedback:       https://github.com/fvdm/nodejs-geoip2ws/issues
License:        Unlicense (public domain, see LICENSE file)
*/

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

var geo;

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

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

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

  geo = app (config);

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

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

// Test success
doTest.add ('lookup', function (test) {
  geo ('74.125.206.100', function (err, data) {
    var names = data && data.city && data.city.names;

    test (err)
      .isObject ('fail', 'data', data)
      .isObject ('fail', 'data.city', data && data.city)
      .isObject ('fail', 'data.city.names', names)
      .isString ('fail', 'data.city.names.en', names && names.en)
      .done ();
  });
});

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

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

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

doTest.add ('Error: request timeout', function (test) {
  var tmpConfig = config;
  var tmp;

  tmpConfig.requestTimeout = 1;
  tmp = app (tmpConfig);

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

// Start the tests
doTest.run ();
<commit_msg>Test: on timeout err.error is an Error<commit_after>/*
Name:           geoip2ws - test.js
Description:    Maxmind GeoIP2 Web Services for node.js
Author:         Franklin van de Meent (https://frankl.in)
Source & docs:  https://github.com/fvdm/nodejs-geoip2ws
Feedback:       https://github.com/fvdm/nodejs-geoip2ws/issues
License:        Unlicense (public domain, see LICENSE file)
*/

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

var geo;

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

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

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

  geo = app (config);

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

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

// Test success
doTest.add ('lookup', function (test) {
  geo ('74.125.206.100', function (err, data) {
    var names = data && data.city && data.city.names;

    test (err)
      .isObject ('fail', 'data', data)
      .isObject ('fail', 'data.city', data && data.city)
      .isObject ('fail', 'data.city.names', names)
      .isString ('fail', 'data.city.names.en', names && names.en)
      .done ();
  });
});

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

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

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

doTest.add ('Error: request timeout', function (test) {
  var tmpConfig = config;
  var tmp;

  tmpConfig.requestTimeout = 1;
  tmp = app (tmpConfig);

  tmp ('74.125.206.100', function (err) {
    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')
      .done ();
  });
});

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


<commit_before>var gulp    = require('gulp'),
    jshint  = require('gulp-jshint'),
    stylish = require('jshint-stylish'),
    concat  = require('gulp-concat'),
    rename  = require('gulp-rename'),
    uglify  = require('gulp-uglify');

gulp.task('js-hint', function() {
  gulp.src('src/*.js')
      .pipe(jshint({laxcomma: true}))
      .pipe(jshint.reporter(stylish));
});

gulp.task('js-compile_src-pro', function() {
  gulp.src('src/*.js')
      .pipe(concat('main.js'))
      .pipe(uglify())
      .pipe(gulp.dest('./build'))
});

gulp.task('js-compile_src-dev', function() {
  gulp.src('src/*.js')
      .pipe(concat('main.dev.js'))
      .pipe(gulp.dest('./build'))
});

gulp.task('js-compile_vendor', function() {
  gulp.src('vendor/*.js')
      .pipe(concat('vendor.js'))
      .pipe(uglify())
      .pipe(gulp.dest('./build'))
});

gulp.task('watch', function() {
gulp.watch('src/*.js', ['js-hint'
                       ,'js-compile_src-dev'
                       ,'js-compile_src-pro'
                       ,'js-compile_vendor']);
});

gulp.task('default', ['js-hint'
                     ,'js-compile_src-dev'
                     ,'js-compile_src-pro'
                     ,'js-compile_vendor'
                     ,'watch']);

<commit_msg>Testing merge<commit_after>// This comment is a test
var gulp    = require('gulp'),
    jshint  = require('gulp-jshint'),
    stylish = require('jshint-stylish'),
    concat  = require('gulp-concat'),
    rename  = require('gulp-rename'),
    uglify  = require('gulp-uglify');

gulp.task('js-hint', function() {
  gulp.src('src/*.js')
      .pipe(jshint({laxcomma: true}))
      .pipe(jshint.reporter(stylish));
});

gulp.task('js-compile_src-pro', function() {
  gulp.src('src/*.js')
      .pipe(concat('main.js'))
      .pipe(uglify())
      .pipe(gulp.dest('./build'))
});

gulp.task('js-compile_src-dev', function() {
  gulp.src('src/*.js')
      .pipe(concat('main.dev.js'))
      .pipe(gulp.dest('./build'))
});

gulp.task('js-compile_vendor', function() {
  gulp.src('vendor/*.js')
      .pipe(concat('vendor.js'))
      .pipe(uglify())
      .pipe(gulp.dest('./build'))
});

gulp.task('watch', function() {
gulp.watch('src/*.js', ['js-hint'
                       ,'js-compile_src-dev'
                       ,'js-compile_src-pro'
                       ,'js-compile_vendor']);
});

gulp.task('default', ['js-hint'
                     ,'js-compile_src-dev'
                     ,'js-compile_src-pro'
                     ,'js-compile_vendor'
                     ,'watch']);

<|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-13 20:58:02<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 t = parse("*#foo > elem[ class ~= bar i][class$=bAz i]:not([id*=2])")({
	name: "elem",
	attribs: {class:"bar baz"},
	parent: {
		name: "elem",
		attribs: {id: "foo"}
	}
});
console.log("result:", !!t)<commit_msg>Added missing require<commit_after>var parse = require("./");

var t = parse("doo, *#foo > elem.bar[class$=bAz i]:not([ id *= \"2\" ])")({
	name: "elem",
	attribs: {class:"bar baz"},
	parent: {
		name: "elem",
		attribs: {id: "foo"}
	}
});
console.log("result:", !!t)<|endoftext|>


<commit_before>var test = require('tape');
var shimmedKeys = require('./index.js');
var is = require('is');
var keys = require('./shim.js');
var forEach = require('foreach');
var indexOf = require('indexof');

var obj = {
	"str": "boz",
	"obj": {},
	"arr": [],
	"bool": true,
	"num": 42,
	"aNull": null,
	"undef": undefined
};
var objKeys = ['str', 'obj', 'arr', 'bool', 'num', 'aNull', 'undef'];

test('exports a function', function (t) {
	if (Object.keys) {
		t.equal(Object.keys, shimmedKeys, 'Object.keys is supported and exported');
	} else {
		t.equal(keys, shimmedKeys, 'Object.keys is not supported; shim is exported');
	}
	t.end();
});

test('working with actual shim', function (t) {
	t.notEqual(Object.keys, keys, 'keys shim is not native Object.keys');
	t.end();
});

test('works with an object literal', function (t) {
	var theKeys = keys(obj);
	t.equal(is.array(theKeys), true, 'returns an array');
	t.deepEqual(theKeys, objKeys, 'Object has expected keys');
	t.end();
});

test('works with an array', function (t) {
	var arr = [1, 2, 3];
	var theKeys = keys(arr);
	t.equal(is.array(theKeys), true, 'returns an array');
	t.deepEqual(theKeys, ['0', '1', '2'], 'Array has expected keys');
	t.end();
});

test('works with a function', function (t) {
	var foo = function () {};
	foo.a = true;

	t.doesNotThrow(function () { return keys(foo); }, 'does not throw an error');
	t.deepEqual(keys(foo), ['a'], 'returns expected keys');
	t.end();
});

test('returns names which are own properties', function (t) {
	forEach(keys(obj), function (name) {
		t.equal(obj.hasOwnProperty(name), true, name + ' should be returned');
	});
	t.end();
});

test('returns names which are enumerable', function (t) {
	var k, loopedValues = [];
	for (k in obj) {
		loopedValues.push(k);
	}
	forEach(keys(obj), function (name) {
		t.notEqual(indexOf(loopedValues, name), -1, name + ' is not enumerable');
	});
	t.end();
});

test('throws an error for a non-object', function (t) {
	t.throws(
		function () { return keys(42); },
		new TypeError('Object.keys called on a non-object'),
		'throws on a non-object'
	);
	t.end();
});

test('works with an object instance', function (t) {
	var Prototype = function () {};
	Prototype.prototype.foo = true;
	var obj = new Prototype();
	obj.bar = true;
	var theKeys = keys(obj);
	t.equal(is.array(theKeys), true, 'returns an array');
	t.deepEqual(theKeys, ['bar'], 'Instance has expected keys');
	t.end();
});

test('works in iOS 5 mobile Safari', function (t) {
	var Foo = function () {};
	Foo.a = function () {};

	// the bug is keys(Foo) => ['a', 'prototype'] instead of ['a']
	t.deepEqual(keys(Foo), ['a'], 'has expected keys');
	t.end();
});

<commit_msg>Adding an IE < 9 test per #3<commit_after>var test = require('tape');
var shimmedKeys = require('./index.js');
var is = require('is');
var keys = require('./shim.js');
var forEach = require('foreach');
var indexOf = require('indexof');

var obj = {
	"str": "boz",
	"obj": {},
	"arr": [],
	"bool": true,
	"num": 42,
	"aNull": null,
	"undef": undefined
};
var objKeys = ['str', 'obj', 'arr', 'bool', 'num', 'aNull', 'undef'];

test('exports a function', function (t) {
	if (Object.keys) {
		t.equal(Object.keys, shimmedKeys, 'Object.keys is supported and exported');
	} else {
		t.equal(keys, shimmedKeys, 'Object.keys is not supported; shim is exported');
	}
	t.end();
});

test('working with actual shim', function (t) {
	t.notEqual(Object.keys, keys, 'keys shim is not native Object.keys');
	t.end();
});

test('works with an object literal', function (t) {
	var theKeys = keys(obj);
	t.equal(is.array(theKeys), true, 'returns an array');
	t.deepEqual(theKeys, objKeys, 'Object has expected keys');
	t.end();
});

test('works with an array', function (t) {
	var arr = [1, 2, 3];
	var theKeys = keys(arr);
	t.equal(is.array(theKeys), true, 'returns an array');
	t.deepEqual(theKeys, ['0', '1', '2'], 'Array has expected keys');
	t.end();
});

test('works with a function', function (t) {
	var foo = function () {};
	foo.a = true;

	t.doesNotThrow(function () { return keys(foo); }, 'does not throw an error');
	t.deepEqual(keys(foo), ['a'], 'returns expected keys');
	t.end();
});

test('returns names which are own properties', function (t) {
	forEach(keys(obj), function (name) {
		t.equal(obj.hasOwnProperty(name), true, name + ' should be returned');
	});
	t.end();
});

test('returns names which are enumerable', function (t) {
	var k, loopedValues = [];
	for (k in obj) {
		loopedValues.push(k);
	}
	forEach(keys(obj), function (name) {
		t.notEqual(indexOf(loopedValues, name), -1, name + ' is not enumerable');
	});
	t.end();
});

test('throws an error for a non-object', function (t) {
	t.throws(
		function () { return keys(42); },
		new TypeError('Object.keys called on a non-object'),
		'throws on a non-object'
	);
	t.end();
});

test('works with an object instance', function (t) {
	var Prototype = function () {};
	Prototype.prototype.foo = true;
	var obj = new Prototype();
	obj.bar = true;
	var theKeys = keys(obj);
	t.equal(is.array(theKeys), true, 'returns an array');
	t.deepEqual(theKeys, ['bar'], 'Instance has expected keys');
	t.end();
});

test('works in iOS 5 mobile Safari', function (t) {
	var Foo = function () {};
	Foo.a = function () {};

	// the bug is keys(Foo) => ['a', 'prototype'] instead of ['a']
	t.deepEqual(keys(Foo), ['a'], 'has expected keys');
	t.end();
});

test('works in environments with the dontEnum bug (IE < 9)', function (t) {
	var Foo = function () {};
	Foo.a = function () {};

	// the bug is keys(Foo) => ['a', 'constructor'] instead of ['a']
	t.deepEqual(keys(Foo), ['a'], 'has expected keys');
	t.end();
});

<|endoftext|>


<commit_before>var MetroHash64  = require('./index').MetroHash64;
var MetroHash128 = require('./index').MetroHash128;
var expect       = require('chai').expect;

const TESTVECTOR_S = '012345678901234567890123456789012345678901234567890123456789012';
const TESTVECTOR_B = new Buffer(TESTVECTOR_S);

const TESTS = [
  { cls : MetroHash64,            expected : '6B753DAE06704BAD' },
  { cls : MetroHash64,  seed : 0, expected : '6B753DAE06704BAD' },
  { cls : MetroHash64,  seed : 1, expected : '3B0D481CF4B9B8DF' },
  { cls : MetroHash128,           expected : 'C77CE2BFA4ED9F9B0548B2AC5074A297' },
  { cls : MetroHash128, seed : 0, expected : 'C77CE2BFA4ED9F9B0548B2AC5074A297' },
  { cls : MetroHash128, seed : 1, expected : '45A3CDB838199D7FBDD68D867A14ECEF' },
];

describe('Instantiation and method calling', function() {

  it('new MetroHash64() should work', function() {
    expect(function() { new MetroHash64(); }).to.not.throw();
  });

  it('MetroHash64() should work', function() {
    expect(function() { MetroHash64(); }).to.not.throw();
  });

  it('new MetroHash128() should work', function() {
    expect(function() { new MetroHash128(); }).to.not.throw();
  });

  it('MetroHash128() should work', function() {
    expect(function() { MetroHash128(); }).to.not.throw();
  });

  it('MetroHash64() should allow chaining', function() {
    expect(function() {
      new MetroHash64().update(TESTVECTOR_B).digest().toString('hex');
    }).to.not.throw();
  });

  it('MetroHash128() should allow chaining', function() {
    expect(function() {
      new MetroHash128().update(TESTVECTOR_B).digest().toString('hex');
    }).to.not.throw();
  });

});

describe('Test vectors', function() {

  TESTS.forEach(function(test) {
    var suffix = test.seed !== undefined ? ', ' + test.seed + ')' : ')';

    it('new ' + test.cls.name + '(String' + suffix, function() {
      var instance = new test.cls(test.seed);
      instance.update(TESTVECTOR_S);
      expect(instance.digest().toString('hex').toUpperCase()).to.equal(test.expected);
    });

    it(test.cls.name + '(String' + suffix, function() {
      var instance = test.cls(test.seed);
      instance.update(TESTVECTOR_S);
      expect(instance.digest().toString('hex').toUpperCase()).to.equal(test.expected);
    });

    it('new ' + test.cls.name + '(Buffer' + suffix, function() {
      var instance = new test.cls(test.seed);
      instance.update(TESTVECTOR_B);
      expect(instance.digest().toString('hex').toUpperCase()).to.equal(test.expected);
    });

    it(test.cls.name + '(Buffer' + suffix, function() {
      var instance = test.cls(test.seed);
      instance.update(TESTVECTOR_B);
      expect(instance.digest().toString('hex').toUpperCase()).to.equal(test.expected);
    });

  });

})
<commit_msg>Added incremental tests<commit_after>var MetroHash64  = require('./index').MetroHash64;
var MetroHash128 = require('./index').MetroHash128;
var expect       = require('chai').expect;

const TESTVECTOR_S = '012345678901234567890123456789012345678901234567890123456789012';
const TESTVECTOR_B = new Buffer(TESTVECTOR_S);

const TESTS = [
  { cls : MetroHash64,            expected : '6B753DAE06704BAD' },
  { cls : MetroHash64,  seed : 0, expected : '6B753DAE06704BAD' },
  { cls : MetroHash64,  seed : 1, expected : '3B0D481CF4B9B8DF' },
  { cls : MetroHash128,           expected : 'C77CE2BFA4ED9F9B0548B2AC5074A297' },
  { cls : MetroHash128, seed : 0, expected : 'C77CE2BFA4ED9F9B0548B2AC5074A297' },
  { cls : MetroHash128, seed : 1, expected : '45A3CDB838199D7FBDD68D867A14ECEF' },
];

describe('Instantiation and method calling', function() {

  it('new MetroHash64() should work', function() {
    expect(function() { new MetroHash64(); }).to.not.throw();
  });

  it('MetroHash64() should work', function() {
    expect(function() { MetroHash64(); }).to.not.throw();
  });

  it('new MetroHash128() should work', function() {
    expect(function() { new MetroHash128(); }).to.not.throw();
  });

  it('MetroHash128() should work', function() {
    expect(function() { MetroHash128(); }).to.not.throw();
  });

  it('MetroHash64() should allow chaining', function() {
    expect(function() {
      new MetroHash64().update(TESTVECTOR_B).digest().toString('hex');
    }).to.not.throw();
  });

  it('MetroHash128() should allow chaining', function() {
    expect(function() {
      new MetroHash128().update(TESTVECTOR_B).digest().toString('hex');
    }).to.not.throw();
  });

});

describe('Test vectors', function() {

  TESTS.forEach(function(test) {
    var suffix = test.seed !== undefined ? ', ' + test.seed + ')' : ')';

    it('new ' + test.cls.name + '(String' + suffix, function() {
      var instance = new test.cls(test.seed);
      instance.update(TESTVECTOR_S);
      expect(instance.digest().toString('hex').toUpperCase()).to.equal(test.expected);
    });

    it(test.cls.name + '(String' + suffix, function() {
      var instance = test.cls(test.seed);
      instance.update(TESTVECTOR_S);
      expect(instance.digest().toString('hex').toUpperCase()).to.equal(test.expected);
    });

    it('new ' + test.cls.name + '(Buffer' + suffix, function() {
      var instance = new test.cls(test.seed);
      instance.update(TESTVECTOR_B);
      expect(instance.digest().toString('hex').toUpperCase()).to.equal(test.expected);
    });

    it(test.cls.name + '(Buffer' + suffix, function() {
      var instance = test.cls(test.seed);
      instance.update(TESTVECTOR_B);
      expect(instance.digest().toString('hex').toUpperCase()).to.equal(test.expected);
    });

    it(test.cls.name + '(String' + suffix + ' incremental', function() {
      var instance = test.cls(test.seed);
      TESTVECTOR_S.split('').forEach(function(c) {
        instance.update(c);
      });
      expect(instance.digest().toString('hex').toUpperCase()).to.equal(test.expected);
    });

    it(test.cls.name + '(Buffer' + suffix + ' incremental', function() {
      var instance = test.cls(test.seed);
      for (var i = 0; i < TESTVECTOR_B.length; i++) {
        instance.update(TESTVECTOR_B.slice(i, i + 1));
      }
      expect(instance.digest().toString('hex').toUpperCase()).to.equal(test.expected);
    });

  });

});
<|endoftext|>


<commit_before>/*
Name:           geoip2ws - test.js
Description:    Maxmind GeoIP2 Web Services for node.js
Author:         Franklin van de Meent (https://frankl.in)
Source & docs:  https://github.com/fvdm/nodejs-geoip2ws
Feedback:       https://github.com/fvdm/nodejs-geoip2ws/issues
License:        Unlicense (public domain, see LICENSE file)
*/

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

var geo;

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

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

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

  geo = app (config);

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

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

// Test success
doTest.add ('lookup - arguments', function (test) {
  geo ('74.125.206.100', function (err, data) {
    var names = data && data.city && data.city.names;
    var dataIP = data && data.traits && data.traits.ip_address;
    var dataSub = data && data.most_specific_subdivision.iso_code;

    test (err)
      .isObject ('fail', 'data', data)
      .isObject ('fail', 'data.city', data && data.city)
      .isObject ('fail', 'data.city.names', names)
      .isExactly ('fail', 'data.city.names.en', names && names.en, 'Mountain View')
      .isExactly ('fail', 'data.traits.ip_address', dataIP, '74.125.206.100')
      .isExactly ('fail', 'data.most_specific_subdivision', dataSub, 'CA')

doTest.add ('lookup - object', function (test) {
  var obj = {
    ip: '74.125.206.100',
    service: config.service
  };

  geo (obj, function (err, data) {
    var names = data && data.city && data.city.names;
    var dataIP = data && data.traits && data.traits.ip_address;
    var dataSub = data && data.most_specific_subdivision.iso_code;

    test (err)
      .isObject ('fail', 'data', data)
      .isObject ('fail', 'data.city', data && data.city)
      .isObject ('fail', 'data.city.names', names)
      .isExactly ('fail', 'data.city.names.en', names && names.en, 'Mountain View')
      .isExactly ('fail', 'data.traits.ip_address', dataIP, '74.125.206.100')
      .isExactly ('fail', 'data.most_specific_subdivision', dataSub, 'CA')
      .done ();
  });
});
      .done ();
  });
});

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

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

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

doTest.add ('Setup with arguments', function (test) {
  geo = app (config.userId, config.licenseKey, config.service, config.timeout);

  geo ('74.125.206.100', function (err, data) {
    var names = data && data.city && data.city.names;
    var dataIP = data && data.traits && data.traits.ip_address;
    var dataSub = data && data.most_specific_subdivision.iso_code;

    test (err)
      .isObject ('fail', 'data', data)
      .isObject ('fail', 'data.city', data && data.city)
      .isObject ('fail', 'data.city.names', names)
      .isExactly ('fail', 'data.city.names.en', names && names.en, 'Mountain View')
      .isExactly ('fail', 'data.traits.ip_address', dataIP, '74.125.206.100')
      .isExactly ('fail', 'data.most_specific_subdivision', dataSub, 'CA')
      .done ();
  });
});

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

  tmp ('74.125.206.100', 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 ();
  });
});

// Start the tests
doTest.run ();
<commit_msg>Test(tests): Add lookup data.subdivisions array test<commit_after>/*
Name:           geoip2ws - test.js
Description:    Maxmind GeoIP2 Web Services for node.js
Author:         Franklin van de Meent (https://frankl.in)
Source & docs:  https://github.com/fvdm/nodejs-geoip2ws
Feedback:       https://github.com/fvdm/nodejs-geoip2ws/issues
License:        Unlicense (public domain, see LICENSE file)
*/

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

var geo;

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

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

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

  geo = app (config);

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

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

// Test success
doTest.add ('lookup - arguments', function (test) {
  geo ('74.125.206.100', function (err, data) {
    var names = data && data.city && data.city.names;
    var dataIP = data && data.traits && data.traits.ip_address;
    var dataSub = data && data.most_specific_subdivision.iso_code;

    test (err)
      .isObject ('fail', 'data', data)
      .isObject ('fail', 'data.city', data && data.city)
      .isObject ('fail', 'data.city.names', names)
      .isExactly ('fail', 'data.city.names.en', names && names.en, 'Mountain View')
      .isExactly ('fail', 'data.traits.ip_address', dataIP, '74.125.206.100')
      .isExactly ('fail', 'data.most_specific_subdivision', dataSub, 'CA')
      .done ();
  });
});

doTest.add ('lookup - object', function (test) {
  var obj = {
    ip: '74.125.206.100',
    service: config.service
  };

  geo (obj, function (err, data) {
    var names = data && data.city && data.city.names;
    var dataIP = data && data.traits && data.traits.ip_address;
    var dataSub = data && data.most_specific_subdivision.iso_code;

    test (err)
      .isObject ('fail', 'data', data)
      .isObject ('fail', 'data.city', data && data.city)
      .isObject ('fail', 'data.city.names', names)
      .isExactly ('fail', 'data.city.names.en', names && names.en, 'Mountain View')
      .isExactly ('fail', 'data.traits.ip_address', dataIP, '74.125.206.100')
      .isExactly ('fail', 'data.most_specific_subdivision', dataSub, 'CA')
      .done ();
  });
});

// Satellite IPs have no geo location
doTest.add ('lookup - data.subdivisions array', function (test) {
  geo ('95.107.128.1', function (err, data) {
    var dataIP = data && data.traits && data.traits.ip_address;

    test (err)
      .isArray ('fail', 'data.subdivisions', data.subdivisions)
      .isEmpty ('fail', 'data.subdivisions', data.subdivisions)
      .isExactly ('fail', 'data.traits.ip_address', dataIP, '95.107.128.1')
      .done ();
  });
});

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

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

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

doTest.add ('Setup with arguments', function (test) {
  geo = app (config.userId, config.licenseKey, config.service, config.timeout);

  geo ('74.125.206.100', function (err, data) {
    var names = data && data.city && data.city.names;
    var dataIP = data && data.traits && data.traits.ip_address;
    var dataSub = data && data.most_specific_subdivision.iso_code;

    test (err)
      .isObject ('fail', 'data', data)
      .isObject ('fail', 'data.city', data && data.city)
      .isObject ('fail', 'data.city.names', names)
      .isExactly ('fail', 'data.city.names.en', names && names.en, 'Mountain View')
      .isExactly ('fail', 'data.traits.ip_address', dataIP, '74.125.206.100')
      .isExactly ('fail', 'data.most_specific_subdivision', dataSub, 'CA')
      .done ();
  });
});

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

  tmp ('74.125.206.100', 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 ();
  });
});

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


<commit_before>import test from 'ava';
import fn from './';

test('should return an array', t => {
	t.is(Array.isArray(fn.all), true);
	t.end();
});

test('should return a random string from the list', t => {
	t.is(typeof fn(), 'string');
	t.is(fn.all.indexOf(fn()) !== -1, true);
	t.end();
});
<commit_msg>Adjust tests to newer AVA version<commit_after>import test from 'ava';
import fn from './';

test.cb('should return an array', t => {
	t.is(Array.isArray(fn.all), true);
	t.end();
});

test.cb('should return a random string from the list', t => {
	t.is(typeof fn(), 'string');
	t.is(fn.all.indexOf(fn()) !== -1, true);
	t.end();
});
<|endoftext|>


<commit_before>var assert = require('assert');
var blocked = require('blocked')
  , forloop = require('./index.js');

var count = 20000;

var blockingFunc = function(i, c) {
	var a = Array(1000).join(c);
}

describe('blocking', function() {
	it('for loop', function(done) {
		var blockErr = null;

		blocked(function(ms){
  			blockErr = new Error("Blocked " + ms + "ms");
			done();
		});
		setTimeout(function() {
			for (var i = 0; i < count; i++) {
				blockingFunc(i, 'b');
			}
			setTimeout(function() {
				if (!blockErr) {
					done("Did not block");
				}
			}, 100);
		}, 100);
	});
});

describe('non-blocking', function() {
	it('forloop', function(done) {
		var blockErr = null;

		blocked(function(ms){
  			blockErr = new Error("Blocked " + ms + "ms");
			done(blockErr);
		});

		forloop(0,
			count,
			1,
			function(i) {
				blockingFunc(i, 'n');
			},
			function() {
				if (!blockErr) {
					done();
				}
			}
        	);
	});
});
<commit_msg>test cases for increment<commit_after>var assert = require('assert');
var blocked = require('blocked')
  , forloop = require('./index.js');

var count = 20000;

var blockingFunc = function(i, c) {
  var a = Array(1000).join(c);
}

describe('blocking', function() {
  it('for loop', function(done) {
    var blockErr = null;

    blocked(function(ms){
        blockErr = new Error("Blocked " + ms + "ms");
      done();
    });
    setTimeout(function() {
      for (var i = 0; i < count; i++) {
        blockingFunc(i, 'b');
      }
      setTimeout(function() {
        if (!blockErr) {
          done("Did not block");
        }
      }, 100);
    }, 100);
  });
});

describe('non-blocking', function() {
  it('forloop', function(done) {
    var blockErr = null;

    blocked(function(ms){
        blockErr = new Error("Blocked " + ms + "ms");
      done(blockErr);
    });

    forloop(0,
      count,
      1,
      function(i) {
        blockingFunc(i, 'n');
      },
      function() {
        if (!blockErr) {
          done();
        }
      }
          );
  });
});

describe('increment', function() {
  it('by 1', function(done) {
    var sum = (count * (count + 1)) / 2;
    forloop(0, count, 1,
      function(i) {
        sum -= (i + 1);
      },
      function() {
        assert.equal(sum, 0);
        done();
      }
          );
  });

  it('by -1', function(done) {
    var sum = (count * (count + 1)) / 2;
    forloop(count, 0, -1,
      function(i) {
        sum -= i;
      },
      function() {
        assert.equal(sum, 0);
        done();
      }
          );
  });

  it('by 10', function(done) {
    var sum = count / 10;
    var tally = 0;
    forloop(0, count, 10,
      function(i) {
        tally++;
      },
      function() {
        assert.equal(sum, tally);
        done();
      }
          );
  });

  it('default value', function(done) {
    var sum = (count * (count + 1)) / 2;
    forloop(0, count,
      function(i) {
        sum -= (i + 1);
      },
      function() {
        assert.equal(sum, 0);
        done();
      }
          );
  });
});
<|endoftext|>