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

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

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

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

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


<commit_before>'use strict';
var F = require('./lib/index.js');
var o = new F({a:"pass", usage:"sdf"});
process.stdout.write(o.opts.a);
<commit_msg>updated test.js<commit_after>'use strict';
var F = require('./lib/index.js');
var o = new F({a:"pass", usage:"sdf"});
o.getOpts();
<|endoftext|>


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

  var assume = require('assume')
    , htmlfile = require('./');

  it('is exported as a function', function () {
    assume(htmlfile).is.a('function');
  });

  describe('.supported', function () {
    it('is a boolean', function () {
      assume(htmlfile.supported).is.a('boolean');
    });

    it('is false, as this is node.js', function () {
      assume(htmlfile.supported).is.false();
    });
  });
});
<commit_msg>[test] Polyfill ActiveXObject<commit_after>describe('htmlfile', function () {
  'use strict';

  function ActiveXObject(type) {
    this.type = type;
    this.data = [];
    this.body = '';
  }

  ActiveXObject.prototype.open = function () { return this.data.push('open'); };
  ActiveXObject.prototype.close = function () { return this.data.push('close'); };
  ActiveXObject.prototype.write = function (data) { this.body += data; };

  //
  // Really minimum viable ActiveXObject polyfill for a HTMLfiles. This allows
  // us to check if everything works as intended.
  //
  global.ActiveXObject = ActiveXObject;

  var calls = 0;
  global.CollectGarbage = function () { calls++; };

  var assume = require('assume')
    , htmlfile = require('./');

  it('is exported as a function', function () {
    assume(htmlfile).is.a('function');
  });

  it('opens and closes the htmlfile', function () {
    var html = htmlfile();

    assume(html.data[0]).equals('open');
    assume(html.data[1]).equals('close');
  });

  it('adds the supplied domain', function () {
    var html = htmlfile('foo.com');

    assume(html.body).to.include('foo.com');
    assume(html.body).to.include('document.domain=');
  });

  it('only adds the domain if it can find one', function () {
    var html = htmlfile();

    assume(html.body).does.not.include('foo.com');
    assume(html.body).does.not.include('document.domain=');
  });

  describe('.supported', function () {
    it('is a boolean', function () {
      assume(htmlfile.supported).is.a('boolean');
    });

    it('is true, as this is node.js & we polyfilled it', function () {
      assume(htmlfile.supported).is.true();
    });
  });

  describe('#destroy', function () {
    it('calls the CollectGarbage method', function () {
      assume(calls).equals(0);
      htmlfile.destroy();
      assume(calls).equals(1);
    });
  });
});
<|endoftext|>


<commit_before>
var test      = require('tap').test
  , split     = require('./')
  , callback  = require('callback-stream')
  , strcb     = callback.bind(null, { decodeStrings: false })
  , objcb     = callback.bind(null, { objectMode: true })

test('split two lines on end', function(t) {
  t.plan(1)

  var input = split()

  input.pipe(strcb(function(err, list) {
    t.deepEqual(list, ['hello', 'world'])
  }))

  input.end('hello\nworld')
})

test('split two lines on two writes', function(t) {
  t.plan(1)

  var input = split()

  input.pipe(strcb(function(err, list) {
    t.deepEqual(list, ['hello', 'world'])
  }))

  input.write('hello')
  input.write('\nworld')
  input.end()
})

test('accumulate multiple writes', function(t) {
  t.plan(1)

  var input = split()

  input.pipe(strcb(function(err, list) {
    t.deepEqual(list, ['helloworld'])
  }))

  input.write('hello')
  input.write('world')
  input.end()
})

test('split using a custom string matcher', function(t) {
  t.plan(1)

  var input = split('~')

  input.pipe(strcb(function(err, list) {
    t.deepEqual(list, ['hello', 'world'])
  }))

  input.end('hello~world')
})

test('split using a custom regexp matcher', function(t) {
  t.plan(1)

  var input = split(/~/)

  input.pipe(strcb(function(err, list) {
    t.deepEqual(list, ['hello', 'world'])
  }))

  input.end('hello~world')
})

test('support an option argument', function(t) {
  t.plan(2)

  var input = split({ highWatermark: 2 })

  input.pipe(strcb(function(err, list) {
    t.notOk(err, 'no errors')
    t.deepEqual(list, ['hello', 'world'])
  }))

  input.end('hello\nworld')
})

test('support a mapper function', function(t) {
  t.plan(2)

  var a = { a: '42' }
    , b = { b: '24' }
  var input = split(JSON.parse)

  input.pipe(objcb(function(err, list) {
    t.notOk(err, 'no errors')
    t.deepEqual(list, [a, b])
  }))

  input.write(JSON.stringify(a))
  input.write('\n')
  input.end(JSON.stringify(b))
})

test('split lines windows-style', function(t) {
  t.plan(1)

  var input = split()

  input.pipe(strcb(function(err, list) {
    t.deepEqual(list, ['hello', 'world'])
  }))

  input.end('hello\r\nworld')
})

test('splits a buffer', function(t) {
  t.plan(1)

  var input = split()

  input.pipe(strcb(function(err, list) {
    t.deepEqual(list, ['hello', 'world'])
  }))

  input.end(new Buffer('hello\nworld'))
})

test('do not end on undefined', function(t) {
  t.plan(1)

  var input = split(function(line) {})

  input.pipe(strcb(function(err, list) {
    t.deepEqual(list, [])
  }))

  input.end(new Buffer('hello\nworld'))
})

test('has destroy method', function(t) {
  t.plan(1)

  var input = split(function(line) {})

  input.on('close', function() {
    t.ok(true, 'close emitted')
    t.end()
  })

  input.destroy()
})<commit_msg>Add tests for two argument constructor.<commit_after>
var test      = require('tap').test
  , split     = require('./')
  , callback  = require('callback-stream')
  , strcb     = callback.bind(null, { decodeStrings: false })
  , objcb     = callback.bind(null, { objectMode: true })

test('split two lines on end', function(t) {
  t.plan(1)

  var input = split()

  input.pipe(strcb(function(err, list) {
    t.deepEqual(list, ['hello', 'world'])
  }))

  input.end('hello\nworld')
})

test('split two lines on two writes', function(t) {
  t.plan(1)

  var input = split()

  input.pipe(strcb(function(err, list) {
    t.deepEqual(list, ['hello', 'world'])
  }))

  input.write('hello')
  input.write('\nworld')
  input.end()
})

test('accumulate multiple writes', function(t) {
  t.plan(1)

  var input = split()

  input.pipe(strcb(function(err, list) {
    t.deepEqual(list, ['helloworld'])
  }))

  input.write('hello')
  input.write('world')
  input.end()
})

test('split using a custom string matcher', function(t) {
  t.plan(1)

  var input = split('~')

  input.pipe(strcb(function(err, list) {
    t.deepEqual(list, ['hello', 'world'])
  }))

  input.end('hello~world')
})

test('split using a custom regexp matcher', function(t) {
  t.plan(1)

  var input = split(/~/)

  input.pipe(strcb(function(err, list) {
    t.deepEqual(list, ['hello', 'world'])
  }))

  input.end('hello~world')
})

test('support an option argument', function(t) {
  t.plan(2)

  var input = split({ highWatermark: 2 })

  input.pipe(strcb(function(err, list) {
    t.notOk(err, 'no errors')
    t.deepEqual(list, ['hello', 'world'])
  }))

  input.end('hello\nworld')
})

test('support a mapper function', function(t) {
  t.plan(2)

  var a = { a: '42' }
    , b = { b: '24' }
  var input = split(JSON.parse)

  input.pipe(objcb(function(err, list) {
    t.notOk(err, 'no errors')
    t.deepEqual(list, [a, b])
  }))

  input.write(JSON.stringify(a))
  input.write('\n')
  input.end(JSON.stringify(b))
})

test('split lines windows-style', function(t) {
  t.plan(1)

  var input = split()

  input.pipe(strcb(function(err, list) {
    t.deepEqual(list, ['hello', 'world'])
  }))

  input.end('hello\r\nworld')
})

test('splits a buffer', function(t) {
  t.plan(1)

  var input = split()

  input.pipe(strcb(function(err, list) {
    t.deepEqual(list, ['hello', 'world'])
  }))

  input.end(new Buffer('hello\nworld'))
})

test('do not end on undefined', function(t) {
  t.plan(1)

  var input = split(function(line) {})

  input.pipe(strcb(function(err, list) {
    t.deepEqual(list, [])
  }))

  input.end(new Buffer('hello\nworld'))
})

test('has destroy method', function(t) {
  t.plan(1)

  var input = split(function(line) {})

  input.on('close', function() {
    t.ok(true, 'close emitted')
    t.end()
  })

  input.destroy()
})

test('support custom matcher and mapper', function(t) {
  t.plan(2)

  var a = { a: '42' }
    , b = { b: '24' }
  var input = split("~", JSON.parse)

  input.pipe(objcb(function(err, list) {
    t.notOk(err, 'no errors')
    t.deepEqual(list, [a, b])
  }))

  input.write(JSON.stringify(a))
  input.write('~')
  input.end(JSON.stringify(b))
})

test('support custom matcher and options', function(t) {
  t.plan(2)

  var input = split("~", { highWatermark: 2 })

  input.pipe(strcb(function(err, list) {
    t.notOk(err, 'no errors')
    t.deepEqual(list, ['hello', 'world'])
  }))

  input.end('hello~world')
})

test('support mapper and options', function(t) {
  t.plan(2)

  var a = { a: '42' }
    , b = { b: '24' }
  var input = split(JSON.parse, { highWaterMark: 2 })

  input.pipe(objcb(function(err, list) {
    t.notOk(err, 'no errors')
    t.deepEqual(list, [a, b])
  }))

  input.write(JSON.stringify(a))
  input.write('\n')
  input.end(JSON.stringify(b))
})
<|endoftext|>


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

// Setup
// $ EUROPEANA_KEY=abc123 npm test
var europeana = app (
  process.env.EUROPEANA_APIKEY || null,
  process.env.EUROPEANA_TIMEOUT || 5000
);

doTest.add ('Module', function () {
  doTest.test ()
    .isFunction ('fail', 'exports', app)
    .isFunction ('fail', 'module', europeana)
    .done ();
});

doTest.add ('search', function () {
  var props = {
    query: 'who:"laurent de la hyre"'
  };

  europeana ('search', props, function (err, data) {
    doTest.test (err)
      .isObject ('fail', 'data', data)
      .isNotEmpty ('warn', 'data', data)
      .done ();
  });
});

doTest.add ('record', function () {
  var record = '9200365/BibliographicResource_1000055039444';
  var props = {
    profile: 'params'
  };

  europeana ('record/' + record, props, function (err, data) {
    doTest.test (err)
      .isObject ('fail', 'data', data)
      .isNotEmpty ('warn', 'data', data)
      .done ();
  });
});

doTest.add ('translateQuery', function () {
  var props = {
    languageCodes: 'nl,en,hu',
    term: 'painting'
  };

  europeana ('translateQuery', props, function (err, data) {
    doTest.test (err)
      .isObject ('fail', 'data', data)
      .isNotEmpty ('warn', 'data', data)
      .isArray ('warn', 'data.translations', data && data.translations)
      .done ();
  });
});

/*
// Suggestions in unavailable
// http://labs.europeana.eu/api/suggestions
doTest.add ('suggestions', function () {
  var props = {
    query: 'laurent de la hyre',
    rows: 10
  };

  app ('suggestions', props, function (err, data) {
    doTest.test (err)
      .isObject ('fail', 'data', data)
      .done ();
  });
});
*/

// Start the tests
doTest.run ();
<commit_msg>Test: added providers tests<commit_after>var doTest = require ('dotest');
var app = require ('./');

// Setup
// $ EUROPEANA_KEY=abc123 npm test
var europeana = app (
  process.env.EUROPEANA_APIKEY || null,
  process.env.EUROPEANA_TIMEOUT || 5000
);

doTest.add ('Module', function () {
  doTest.test ()
    .isFunction ('fail', 'exports', app)
    .isFunction ('fail', 'module', europeana)
    .done ();
});

doTest.add ('search', function () {
  var props = {
    query: 'who:"laurent de la hyre"'
  };

  europeana ('search', props, function (err, data) {
    doTest.test (err)
      .isObject ('fail', 'data', data)
      .isNotEmpty ('warn', 'data', data)
      .done ();
  });
});

doTest.add ('record', function () {
  var record = '9200365/BibliographicResource_1000055039444';
  var props = {
    profile: 'params'
  };

  europeana ('record/' + record, props, function (err, data) {
    doTest.test (err)
      .isObject ('fail', 'data', data)
      .isNotEmpty ('warn', 'data', data)
      .done ();
  });
});

doTest.add ('translateQuery', function () {
  var props = {
    languageCodes: 'nl,en,hu',
    term: 'painting'
  };

  europeana ('translateQuery', props, function (err, data) {
    doTest.test (err)
      .isObject ('fail', 'data', data)
      .isNotEmpty ('warn', 'data', data)
      .isArray ('warn', 'data.translations', data && data.translations)
      .done ();
  });
});

doTest.add ('providers normal', function () {
  europeana ('providers', function (err, data) {
    doTest.test (err)
      .isObject ('fail', 'data', data)
      .isNotEmpty ('warn', 'data', data)
      .isArray ('warn', 'data.items', data && data.items)
      .done ();
  });
});

doTest.add ('providers params', function () {
  var params = {
    pagesize: 3
  };

  europeana ('providers', params, function (err, data) {
    doTest.test (err)
      .isObject ('fail', 'data', data)
      .isNotEmpty ('warn', 'data', data)
      .isArray ('warn', 'data.items', data && data.items)
      .isExactly ('warn', 'data.items.length', data && data.items && data.items.length, 3)
      .done ();
  });
});

/*
// Suggestions in unavailable
// http://labs.europeana.eu/api/suggestions
doTest.add ('suggestions', function () {
  var props = {
    query: 'laurent de la hyre',
    rows: 10
  };

  app ('suggestions', props, function (err, data) {
    doTest.test (err)
      .isObject ('fail', 'data', data)
      .done ();
  });
});
*/

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


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

test(function getter (t) {
	var f1 = {foo: {bar: 1}};
	t.assert(dotProp.get(f1) === f1);
	t.assert(dotProp.get(f1, 'foo') === f1.foo);
	t.assert(dotProp.get({foo: 1}, 'foo') === 1);
	t.assert(dotProp.get({foo: null}, 'foo') === null);
	t.assert(dotProp.get({foo: undefined}, 'foo') === undefined);
	t.assert(dotProp.get({foo: {bar: true}}, 'foo.bar') === true);
	t.assert(dotProp.get({foo: {bar: {baz: true}}}, 'foo.bar.baz') === true);
	t.assert(dotProp.get({foo: {bar: {baz: null}}}, 'foo.bar.baz') === null);
	t.assert(dotProp.get({foo: {bar: 'a'}}, 'foo.fake.fake2') === undefined);
	t.end();
});

test(function setter (t) {
	var f1 = {};

	function func() {
	  return 'test';
	}

	dotProp.set(f1, 'foo', 2);
	t.assert(f1.foo === 2);

	f1 = {foo: {bar: 1}};
	dotProp.set(f1, 'foo.bar', 2);
	t.assert(f1.foo.bar === 2);

	dotProp.set(f1, 'foo.bar.baz', 3);
	t.assert(f1.foo.bar.baz === 3);

	dotProp.set(f1, 'foo.bar', 'test');
	t.assert(f1.foo.bar === 'test');

	dotProp.set(f1, 'foo.bar', null);
	t.assert(f1.foo.bar === null);

	dotProp.set(f1, 'foo.bar', false);
	t.assert(f1.foo.bar === false);

	dotProp.set(f1, 'foo.bar', undefined);
	t.assert(f1.foo.bar === undefined);

	dotProp.set(f1, 'foo.fake.fake2', 'fake');
	t.assert(f1.foo.fake.fake2 === 'fake');

	dotProp.set(f1, 'foo.function', func);
	t.assert(f1.foo.function === func);

	t.end();
});
<commit_msg>minor tweaks<commit_after>'use strict';
var test = require('ava');
var dotProp = require('./');

test(function getter(t) {
	var f1 = {foo: {bar: 1}};
	t.assert(dotProp.get(f1) === f1);
	t.assert(dotProp.get(f1, 'foo') === f1.foo);
	t.assert(dotProp.get({foo: 1}, 'foo') === 1);
	t.assert(dotProp.get({foo: null}, 'foo') === null);
	t.assert(dotProp.get({foo: undefined}, 'foo') === undefined);
	t.assert(dotProp.get({foo: {bar: true}}, 'foo.bar') === true);
	t.assert(dotProp.get({foo: {bar: {baz: true}}}, 'foo.bar.baz') === true);
	t.assert(dotProp.get({foo: {bar: {baz: null}}}, 'foo.bar.baz') === null);
	t.assert(dotProp.get({foo: {bar: 'a'}}, 'foo.fake.fake2') === undefined);
	t.end();
});

test(function setter(t) {
	var f1 = {};

	function func() {
		return 'test';
	}

	dotProp.set(f1, 'foo', 2);
	t.assert(f1.foo === 2);

	f1 = {foo: {bar: 1}};
	dotProp.set(f1, 'foo.bar', 2);
	t.assert(f1.foo.bar === 2);

	dotProp.set(f1, 'foo.bar.baz', 3);
	t.assert(f1.foo.bar.baz === 3);

	dotProp.set(f1, 'foo.bar', 'test');
	t.assert(f1.foo.bar === 'test');

	dotProp.set(f1, 'foo.bar', null);
	t.assert(f1.foo.bar === null);

	dotProp.set(f1, 'foo.bar', false);
	t.assert(f1.foo.bar === false);

	dotProp.set(f1, 'foo.bar', undefined);
	t.assert(f1.foo.bar === undefined);

	dotProp.set(f1, 'foo.fake.fake2', 'fake');
	t.assert(f1.foo.fake.fake2 === 'fake');

	dotProp.set(f1, 'foo.function', func);
	t.assert(f1.foo.function === func);

	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-24 00:32: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>🤖(fix): 2017-6-13 20:49:30<commit_after>const test = require('ava');
const random = require('./helpers/random');
const all = require('./products');

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

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


<commit_before>const fs = require('fs')
const test = require('flip-tape') // eslint-disable-line
const jsonFile = require('jsonfile')
const execSync = require('child_process').execSync
const path = require('path')
const parallel = require('run-parallel')

var testDirYrn
var testPkgPathYrn
var testDirNpm
var testPkgPathNpm

'Behaves like NPM regarding `package.json`'.test(t => {
  t.plan(5)
  prepareDirs()

  '`yrn` runs'.doesNotThrow(x => execSync('./bin.js help'))

  run(['yrn'], 'install --save-dev tape')
  { let newPkg = readPkg(testPkgPathYrn)
    'devDependency was added'.ok(newPkg.devDependencies.tape)
  }

  run(['yrn'], 'uninstall --save-dev tape')
  { let newPkg = readPkg(testPkgPathYrn)
    'devDependency was removed'.notOk(newPkg.devDependencies.tape)
  }

  run(['yrn'], 'install --save tape')
  { let newPgks = readPkg(testPkgPathYrn)
    'dependency was added'.ok(newPgks.dependencies.tape)
  }

  run(['yrn'], 'uninstall --save tape')
  { let newPgks = readPkg(testPkgPathYrn)
    'dependency was removed'.notOk(newPgks.dependencies.tape)
  }
  removeDirs()
})

'Behaves like NPM regarding `node_modules` and Yarns files'.test(t => {
  t.plan(3)
  prepareDirs()
  run(['yrn', 'npm'], 'install tape')
  run(['yrn', 'npm'], 'install standard')

  'previous packages got restored'.deepEqual(
    getDirectories(testDirYrn + '/node_modules'),
    getDirectories(testDirNpm + '/node_modules')
  )

  // yarn and npm create .bin content differently
  /*
  'previous symlinks got restored'.deepEqual(
    fs.readdirSync(testDirYrn + '/node_modules/.bin'),
    fs.readdirSync(testDirNpm + '/node_modules/.bin')
  )
  */

  '`yarn.lock` got removed'.notOk(
    fs.existsSync(testDirYrn + '/yarn.lock')
  )

  '`.yarn-integrity` got removed'.notOk(
    fs.existsSync(testDirYrn + '/node_modules/.yarn-integrity')
  )

  removeDirs()
})

'Installs saved dependencies like NPM'.test(t => {
  t.plan(1)
  prepareDirs()
  let testPkg = {
    license: 'MIT',
    description: '-',
    repository: '-',
    dependencies: { tape: '4.x' },
    devDependencies: { standard: '8.x' }
  }
  jsonFile.writeFileSync(testPkgPathYrn, testPkg)
  jsonFile.writeFileSync(testPkgPathNpm, testPkg)

  run(['yrn', 'npm'], 'install')

  '`yrn install`'.deepEqual(
    getDirectories(testDirYrn + '/node_modules'),
    getDirectories(testDirNpm + '/node_modules')
  )
  removeDirs()
})

'`yrn` is faster than NPM'.test(t => {
  t.plan(1)
  prepareDirs()

  let start
  let totalYrn
  let totalNpm

  parallel([done => {
    start = new Date().getTime()
    run(['yrn'], 'install choo webtorrent')
    run(['yrn'], 'install tape standard')
    run(['yrn'], 'install signalhub webrtc-swarm')
    totalYrn = new Date().getTime() - start
    done()
  }, done => {
    start = new Date().getTime()
    run(['npm'], 'install choo webtorrent')
    run(['npm'], 'install tape standard')
    run(['npm'], 'install signalhub webrtc-swarm')
    totalNpm = new Date().getTime() - start
    done()
  }], x => {
    t.ok(totalYrn < totalNpm, 'installing 6 pkgs over 3 runs')
    t.comment('`yrn` runs: ' + totalYrn + 'ms; NPM runs: ' + totalNpm + 'ms')
    removeDirs()
  })
})

function prepareDirs () {
  testDirYrn = fs.mkdtempSync('./test-')
  testPkgPathYrn = testDirYrn + '/package.json'
  testDirNpm = fs.mkdtempSync('./test-')
  testPkgPathNpm = testDirNpm + '/package.json'
  let testPkg = { license: 'MIT', description: '-', repository: '-' }
  jsonFile.writeFileSync(testPkgPathYrn, testPkg)
  jsonFile.writeFileSync(testPkgPathNpm, testPkg)
}

function removeDirs () {
  execSync('rm -rf ' + testDirYrn)
  execSync('rm -rf ' + testDirNpm)
}

function run (bin, cmd) {
  var runYrn = bin.includes('yrn')
  var runNpm = bin.includes('npm')
  if (runYrn) execSync('cd ' + testDirYrn + ' && ' + './../bin.js ' + cmd)
  if (runNpm) execSync('cd ' + testDirNpm + ' && ' + 'npm ' + cmd)
}

function readPkg (path, raw) {
  return raw
    ? fs.readFileSync(path, {encoding: 'utf8'})
    : jsonFile.readFileSync(path)
}

function getDirectories (dir) {
  return fs.readdirSync(dir).filter(file => {
    return fs.statSync(path.join(dir, file)).isDirectory()
  })
}
<commit_msg>allow every version<commit_after>const fs = require('fs')
const test = require('flip-tape') // eslint-disable-line
const jsonFile = require('jsonfile')
const execSync = require('child_process').execSync
const path = require('path')
const parallel = require('run-parallel')

var testDirYrn
var testPkgPathYrn
var testDirNpm
var testPkgPathNpm

'Behaves like NPM regarding `package.json`'.test(t => {
  t.plan(5)
  prepareDirs()

  '`yrn` runs'.doesNotThrow(x => execSync('./bin.js help'))

  run(['yrn'], 'install --save-dev tape')
  { let newPkg = readPkg(testPkgPathYrn)
    'devDependency was added'.ok(newPkg.devDependencies.tape)
  }

  run(['yrn'], 'uninstall --save-dev tape')
  { let newPkg = readPkg(testPkgPathYrn)
    'devDependency was removed'.notOk(newPkg.devDependencies.tape)
  }

  run(['yrn'], 'install --save tape')
  { let newPgks = readPkg(testPkgPathYrn)
    'dependency was added'.ok(newPgks.dependencies.tape)
  }

  run(['yrn'], 'uninstall --save tape')
  { let newPgks = readPkg(testPkgPathYrn)
    'dependency was removed'.notOk(newPgks.dependencies.tape)
  }
  removeDirs()
})

'Behaves like NPM regarding `node_modules` and Yarns files'.test(t => {
  t.plan(3)
  prepareDirs()
  run(['yrn', 'npm'], 'install tape')
  run(['yrn', 'npm'], 'install standard')

  'previous packages got restored'.deepEqual(
    getDirectories(testDirYrn + '/node_modules'),
    getDirectories(testDirNpm + '/node_modules')
  )

  // yarn and npm create .bin content differently
  /*
  'previous symlinks got restored'.deepEqual(
    fs.readdirSync(testDirYrn + '/node_modules/.bin'),
    fs.readdirSync(testDirNpm + '/node_modules/.bin')
  )
  */

  '`yarn.lock` got removed'.notOk(
    fs.existsSync(testDirYrn + '/yarn.lock')
  )

  '`.yarn-integrity` got removed'.notOk(
    fs.existsSync(testDirYrn + '/node_modules/.yarn-integrity')
  )

  removeDirs()
})

'Installs saved dependencies like NPM'.test(t => {
  t.plan(1)
  prepareDirs()
  let testPkg = {
    license: 'MIT',
    description: '-',
    repository: '-',
    dependencies: { tape: '*' },
    devDependencies: { standard: '*' }
  }
  jsonFile.writeFileSync(testPkgPathYrn, testPkg)
  jsonFile.writeFileSync(testPkgPathNpm, testPkg)

  run(['yrn', 'npm'], 'install')

  '`yrn install`'.deepEqual(
    getDirectories(testDirYrn + '/node_modules'),
    getDirectories(testDirNpm + '/node_modules')
  )
  removeDirs()
})

'`yrn` is faster than NPM'.test(t => {
  t.plan(1)
  prepareDirs()

  let start
  let totalYrn
  let totalNpm

  parallel([done => {
    start = new Date().getTime()
    run(['yrn'], 'install choo webtorrent')
    run(['yrn'], 'install tape standard')
    run(['yrn'], 'install signalhub webrtc-swarm')
    totalYrn = new Date().getTime() - start
    done()
  }, done => {
    start = new Date().getTime()
    run(['npm'], 'install choo webtorrent')
    run(['npm'], 'install tape standard')
    run(['npm'], 'install signalhub webrtc-swarm')
    totalNpm = new Date().getTime() - start
    done()
  }], x => {
    t.ok(totalYrn < totalNpm, 'installing 6 pkgs over 3 runs')
    t.comment('`yrn` runs: ' + totalYrn + 'ms; NPM runs: ' + totalNpm + 'ms')
    removeDirs()
  })
})

function prepareDirs () {
  testDirYrn = fs.mkdtempSync('./test-')
  testPkgPathYrn = testDirYrn + '/package.json'
  testDirNpm = fs.mkdtempSync('./test-')
  testPkgPathNpm = testDirNpm + '/package.json'
  let testPkg = { license: 'MIT', description: '-', repository: '-' }
  jsonFile.writeFileSync(testPkgPathYrn, testPkg)
  jsonFile.writeFileSync(testPkgPathNpm, testPkg)
}

function removeDirs () {
  execSync('rm -rf ' + testDirYrn)
  execSync('rm -rf ' + testDirNpm)
}

function run (bin, cmd) {
  var runYrn = bin.includes('yrn')
  var runNpm = bin.includes('npm')
  if (runYrn) execSync('cd ' + testDirYrn + ' && ' + './../bin.js ' + cmd)
  if (runNpm) execSync('cd ' + testDirNpm + ' && ' + 'npm ' + cmd)
}

function readPkg (path, raw) {
  return raw
    ? fs.readFileSync(path, {encoding: 'utf8'})
    : jsonFile.readFileSync(path)
}

function getDirectories (dir) {
  return fs.readdirSync(dir).filter(file => {
    return fs.statSync(path.join(dir, file)).isDirectory()
  })
}
<|endoftext|>


<commit_before>var ws = require("nodejs-websocket")
 var connections = [];
 var currentID = 0;

 function removeConnection(id){
	for (var i = 0; i < connections.length; i++){
		if (connections[i].id == id)
			connections.splice(i,i);
	}
 }

 function sendMessage(message){
	for (var i = 0; i < connections.length; i++){
		connections[i].sendText(message)
	}
 }
// Scream server example: "hi" -> "HI!!!"
var server = ws.createServer(function (conn) {
	console.log("New connection")
	conn.on("text", function (str) {
		console.log("Received "+str)
		var json = {id : conn.id, event: 'Message Recieved', value: str}
		sendMessage(JSON.stringify(json));
	})
	conn.on("close", function (code, reason) {
		removeConnection(conn.id);
	})
	conn.on('uncaughtException', function (code, reason) {
		removeConnection(conn.id);
	})
	conn.on('error', function (err) {
		console.log(err);
		conn.close();
	})
	conn.id = currentID;
	currentID++;
	connections.push(conn);
}).listen(8001)<commit_msg>Add Server JSON connection<commit_after>var ws = require("nodejs-websocket")
 var connections = [];
 var currentID = 0;

 function removeConnection(id){
	for (var i = 0; i < connections.length; i++){
		if (connections[i].id == id)
			connections.splice(i,i);
	}
 }

 function sendMessage(message){
	for (var i = 0; i < connections.length; i++){
		connections[i].sendText(message)
	}
 }
// Scream server example: "hi" -> "HI!!!"
var server = ws.createServer(function (conn) {
	console.log("New connection")
	conn.on("text", function (str) {
		console.log("Received "+str)
		var json = {id : conn.id, event: 'Message Recieved', x: str.split(":")[0], y: str.split(":")[1]}
		sendMessage(JSON.stringify(json));
	})
	conn.on("close", function (code, reason) {
		removeConnection(conn.id);
	})
	conn.on('uncaughtException', function (code, reason) {
		removeConnection(conn.id);
	})
	conn.on('error', function (err) {
		console.log(err);
		conn.close();
	})
	conn.id = currentID;
	currentID++;
	connections.push(conn);
}).listen(8001)<|endoftext|>


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

var pack = require('./lib/util/pack.js');
var typedarray = require('./lib/util/typedarray.js');
var Spec = require('./lib/amf/spec.js');

test('int roundtrip', function (t) {
  var pointer = 0;
  var startVal = Math.floor(Math.random() * Spec.MAX_INT);
  console.log(startVal);

  var stream = '';
  var writeByte = function (byte) {
    stream += pack('c', byte);
  };

  var readByte = function () {
    var value = stream.substr(pointer, 1);
    pointer += value.length;
    return value.charCodeAt(0);
  };

// type marker
  writeByte(0x04);

  if (startVal < Spec.MIN_INT || startVal > Spec.MAX_INT) {
    throw new Error('Integer out of range: ' + startVal);
  }

  if (startVal < 0 || startVal >= Spec.MIN_4_BYTE_INT) {
    writeByte((startVal >> 22) | 0x80);
    writeByte((startVal >> 15) | 0x80);
    writeByte((startVal >> 8) | 0x80);
    writeByte(startVal);
  } else if (startVal >= Spec.MIN_3_BYTE_INT) {
    writeByte((startVal >> 14) | 0x80);
    writeByte((startVal >> 7) | 0x80);
    writeByte(startVal & 0x7f);
  } else if (startVal >= Spec.MIN_2_BYTE_INT) {
    writeByte((startVal >> 7) | 0x80);
    writeByte(startVal & 0x7f);
  } else {
    writeByte(startVal);
  }

  var marker = readByte();
  var count = 1;
  var endVal = 0;
  var byte = readByte();

  while (((byte & 0x80) != 0) && count < 4) {
    endVal <<= 7;
    endVal |= (byte & 0x7F);
    byte = readByte();
    count++;
  }

  if (count < 4) {
    endVal <<= 7;
    endVal |= byte;
  } else {
    // Use all 8 bits from the 4th byte
    endVal <<= 8;
    endVal |= byte;
  }

  if ((endVal & 0x18000000) == 0x18000000) {
    endVal ^= 0x1fffffff;
    endVal *= -1;
    endVal -= 1;
  } else {
    if ((endVal & 0x10000000) == 0x10000000) {
      // remove the signed flag
      endVal &= 0x0fffffff;
    }
  }

  t.plan(1);

  t.equal(startVal, endVal);
});

function endianness() {
  var u16array = new Uint16Array([0x1234]),
      u8array = new Uint8Array(u16array.buffer);
  return u8array[0] === 0x12;
}

test('test endianness script', function (t) {
  t.plan(1);

  t.doesNotThrow(function () {
    console.log(endianness());
  });
});<commit_msg>Fixed stupid oversight<commit_after>var test = require('tape');

var pack = require('./lib/util/pack.js');
var typedarray = require('./lib/util/typedarray.js');
var Spec = require('./lib/amf/spec.js');

test('int roundtrip', function (t) {
  var pointer = 0;
  var startVal = Math.floor(Math.random() * Spec.MAX_INT);
  console.log(startVal);

  var stream = '';
  var writeByte = function (byte) {
    stream += pack('c', byte);
  };

  var readByte = function () {
    var value = stream.substr(pointer, 1);
    pointer += value.length;
    return value.charCodeAt(0);
  };

// type marker
  writeByte(0x04);

  if (startVal < Spec.MIN_INT || startVal > Spec.MAX_INT) {
    throw new Error('Integer out of range: ' + startVal);
  }

  if (startVal < 0 || startVal >= Spec.MIN_4_BYTE_INT) {
    writeByte((startVal >> 22) | 0x80);
    writeByte((startVal >> 15) | 0x80);
    writeByte((startVal >> 8) | 0x80);
    writeByte(startVal);
  } else if (startVal >= Spec.MIN_3_BYTE_INT) {
    writeByte((startVal >> 14) | 0x80);
    writeByte((startVal >> 7) | 0x80);
    writeByte(startVal & 0x7f);
  } else if (startVal >= Spec.MIN_2_BYTE_INT) {
    writeByte((startVal >> 7) | 0x80);
    writeByte(startVal & 0x7f);
  } else {
    writeByte(startVal);
  }

  var marker = readByte();
  var count = 1;
  var endVal = 0;
  var byte = readByte();

  while (((byte & 0x80) != 0) && count < 4) {
    endVal <<= 7;
    endVal |= (byte & 0x7F);
    byte = readByte();
    count++;
  }

  if (count < 4) {
    endVal <<= 7;
    endVal |= byte;
  } else {
    // Use all 8 bits from the 4th byte
    endVal <<= 8;
    endVal |= byte;
  }

  if ((endVal & 0x18000000) == 0x18000000) {
    endVal ^= 0x1fffffff;
    endVal *= -1;
    endVal -= 1;
  } else {
    if ((endVal & 0x10000000) == 0x10000000) {
      // remove the signed flag
      endVal &= 0x0fffffff;
    }
  }

  t.plan(1);

  t.equal(startVal, endVal);
});

function endianness() {
  var u16array = new typedarray.Uint16Array([0x1234]),
      u8array = new typedarray.Uint8Array(u16array.buffer);
  return u8array[0] === 0x12;
}

test('test endianness script', function (t) {
  t.plan(1);

  t.doesNotThrow(function () {
    console.log(endianness());
  });
});<|endoftext|>


<commit_before>
var Joi = require('joi');

var baseSchema = require('./schemes/baseSchema');

var peer1 = require('./objects/valid/peer/peer1.json');
var user1 = require('./objects/valid/user/user1.json');

var validate = function (object, schema) {
    return new Promise(function (resolve, reject) {
        Joi.validate(object, schema, function (err, res) {
            if (err) {
                reject(err);
            } else {
                resolve(res);
            }
        })
    });
};

var arr = [
    validate(peer1, baseSchema),
    validate(user1, baseSchema),
];

Promise.all(arr)
    .then(function (res) {
        console.log('all good');
    })
    .catch(console.log);<commit_msg>Недподхваченные изменения<commit_after>
var Joi = require('joi');

var baseSchema = require('./schemes/baseSchema');

var peer1 = require('./objects/valid/peer/peer1.json');
var user1 = require('./objects/valid/user/user1.json');

var validate = function (object, schema) {
    return new Promise(function (resolve, reject) {
        Joi.validate(object, schema, function (err, res) {
            if (err) {
                reject(err);
            } else {
                resolve(res);
            }
        })
    });
};

var arr = [
    validate(peer1, baseSchema),
    validate(user1, baseSchema)
];

Promise.all(arr)
    .then(function (res) {
        console.log('all good');
    })
    .catch(console.log);<|endoftext|>


<commit_before>'use strict';

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

test('truco features', function(t) {
  t.deepEqual(truco('Lorem Ipsum Dolor Sit', 5), 'Lorem…', 'truncate');
  t.deepEqual(truco('Lorem Ipsum Dolor Sit', 5, '...'), 'Lorem...', 'custom ellipsis');
  t.deepEqual(truco('Lorem Ipsum', 150), 'Lorem Ipsum', 'do not append ellipsis if doesn\'t need to')
  t.end();
});
<commit_msg>Added `invert` test suite.<commit_after>'use strict';

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

test('truco features', function(t) {
  t.deepEqual(truco('Lorem Ipsum'), 'Lorem Ipsum', 'should not add ellipsis if limit was not specified');
  t.deepEqual(truco('Lorem Ipsum Dolor Sit', 5), 'Lorem…', 'truncate on specified limit');
  t.deepEqual(truco('Lorem Ipsum Dolor Sit', 5, {ellipsis: '...'}), 'Lorem...', 'custom ellipsis');
  t.deepEqual(truco('Lorem Ipsum', 150), 'Lorem Ipsum', 'do not append ellipsis if doesn\'t need to')
  t.end();
});

test('invert', function(t) {
  t.deepEqual(truco('Lorem Ipsum', 5, {moonwalk: true}), '…Ipsum', 'truncate on specified limit');
  t.deepEqual(truco('Lorem Ipsum Dolor Sit', 3, {moonwalk: true, ellipsis: '...'}), '...Sit', 'custom ellipsis');
  t.deepEqual(truco('Lorem Ipsum', 150, {moonwalk: true}), 'Lorem Ipsum', 'do not append ellipsis if doesn\'t need to');
  t.end();
});
<|endoftext|>


<commit_before>var fs = require("fs");
var assert = require("assert");
var mask = require("./mask");

function readToArrayBuffer (path, callback) {
  var rs = fs.createReadStream(path);
  rs.on("readable", function () {
    var buffer = rs.read();
    var ab = new ArrayBuffer(buffer.length);
    var u8 = new Uint8Array(ab);
    for (var i = 0; i < buffer.length; i++) {
      u8[i] = buffer[i];
    };
    callback(ab);
  });
};

describe("mask.Mask", function () {
  describe("#from_pbm()", function () {
    it("exists", function () {
      assert.notEqual(mask.Mask.from_pbm, undefined);
    });
    it("reads test-data/bullet-ascii.pbm.", function (done) {
      readToArrayBuffer("test-data/bullet-ascii.pbm", function (ab) {
        mask.Mask.from_pbm(ab, function (mask) {
          done();
        });
      });
    });
  });
});
<commit_msg>more tests + abstraction<commit_after>var fs = require("fs");
var assert = require("assert");
var mask = require("./mask");

function readToArrayBuffer (path, callback) {
  var rs = fs.createReadStream(path);
  rs.on("readable", function () {
    var buffer = rs.read();
    var ab = new ArrayBuffer(buffer.length);
    var u8 = new Uint8Array(ab);
    for (var i = 0; i < buffer.length; i++) {
      u8[i] = buffer[i];
    };
    callback(ab);
  });
};

describe("mask.Mask", function () {
  describe("#from_pbm()", function () {
    it("exists", function () {
      assert.notEqual(mask.Mask.from_pbm, undefined);
    });
    function assert_reads (path) {
      it("reads " + path + ".", function (done) {
        readToArrayBuffer(path, function (ab) {
          mask.Mask.from_pbm(ab, function (mask) {
            done();
          });
        });
      });
    };
    assert_reads("test-data/bullet-ascii.pbm");
    assert_reads("test-data/frame-ascii.pbm");
    assert_reads("test-data/bullet-binary.pbm");
    assert_reads("test-data/frame-binary.pbm");
  });
});
<|endoftext|>


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

test('kinks', function(t){
  var hourglass = {
        "type": "Polygon",
        "coordinates": [
          [
            [
              -45.703125,
              -3.381823735328289
            ],
            [
              -54.9755859375,
              -3.9519408561575946
            ],
            [
              -47.9443359375,
              -13.539200668930802
            ],
            [
              -54.58007812499999,
              -13.752724664396975
            ],
            [
              -45.703125,
              -3.381823735328289
            ]
          ]
        ]
      }

  var hourglassKinks = kinks(hourglass)
  t.ok(hourglassKinks, 'get self intersection from hourglass polygon')
  t.equal(hourglass.features.length, 1)
})<commit_msg>add triple test<commit_after>var test = require('tape')
var kinks = require('./')

test('kinks', function(t){
  var hourglass = {
        "type": "Polygon",
        "coordinates": [
          [
            [
              -45.703125,
              -3.381823735328289
            ],
            [
              -54.9755859375,
              -3.9519408561575946
            ],
            [
              -47.9443359375,
              -13.539200668930802
            ],
            [
              -54.58007812499999,
              -13.752724664396975
            ],
            [
              -45.703125,
              -3.381823735328289
            ]
          ]
        ]
      }

  var hourglassKinks = kinks(hourglass)
  t.ok(hourglassKinks, 'get self intersection from hourglass polygon')
  t.equal(hourglassKinks.features.length, 1)

  var triple = {
        "type": "Polygon",
        "coordinates": [
          [
            [
              -44.384765625,
              1.0106897682409128
            ],
            [
              -53.4375,
              0.4833927027896987
            ],
            [
              -43.154296875,
              -6.402648405963884
            ],
            [
              -53.173828125,
              -6.708253968671543
            ],
            [
              -43.857421875,
              -13.752724664396975
            ],
            [
              -54.09667968749999,
              -14.944784875088372
            ],
            [
              -53.3935546875,
              -11.867350911459308
            ],
            [
              -44.384765625,
              1.0106897682409128
            ]
          ]
        ]
      }
    }

  var tripleKinks = kinks(triple)
  t.ok(tripleKinks, 'get self intersection from hourglass polygon')
  t.equal(tripleKinks.features.length, 3)
})<|endoftext|>


<commit_before>'use strict';
var equal = require('buffer-equal');
var test = require('ava');
var stdin = require('./');

test('should get stdin', function (t) {
	t.plan(1);

	stdin(function (data) {
		t.assert(equal(data, new Buffer('unicorns\n')));
		t.assert(data.toString().trim() === 'unicorns');
	});
});
<commit_msg>fix test plan<commit_after>'use strict';
var equal = require('buffer-equal');
var test = require('ava');
var stdin = require('./');

test('should get stdin', function (t) {
	t.plan(2);

	stdin(function (data) {
		t.assert(equal(data, new Buffer('unicorns\n')));
		t.assert(data.toString().trim() === 'unicorns');
	});
});
<|endoftext|>


<commit_before>/*
Name:         overheid.io - test.js
Description:  Access overheid.io endpoints like OpenKvK, RDW and BAG with node.js
Author:       Franklin van de Meent (https://frankl.in)
Source code:  https://github.com/fvdm/nodejs-overheid.io
Feedback:     https://github.com/fvdm/nodejs-overheid.io/issues
License:      Unlicense (Public Domain) - see LICENSE file
              (https://github.com/fvdm/nodejs-overheid.io/raw/master/LICENSE)
*/

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

// Setup
var config = {
  apikey: process.env.OVIO_APIKEY || null,
  timeout: process.env.OVIO_TIMEOUT || 5000,
  dataset: 'voertuiggegevens'
};

var ovio = app (config);

// Tests
dotest.add ('Module', function (test) {
  test()
    .isFunction ('fail', 'exports', app)
    .isFunction ('fail', 'interface', ovio)
    .done();
});

dotest.add ('config.timeout', function (test) {
  ovio ({
    path: '4-TFL-24',
    params: {
      fields: ['eerstekleur']
    },
    timeout: 1,
    callback: function (err) {
      var error = err && err.error;

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

dotest.add ('no result', function (test) {
  ovio ({
    path: 'error.test',
    callback: function (err) {
      test()
        .isError ('fail', 'err', err)
        .isExactly ('fail', 'err.message', err && err.message, 'no result')
        .done();
    }
  });
});

dotest.add ('item', function (test) {
  ovio ({
    path: '4-TFL-24',
    callback: function (err, data) {
      test (err)
        .isNotEmpty ('fail', 'data', data)
        .isObject ('fail', 'data', data)
        .isExactly ('fail', 'data.kenteken', data && data.kenteken, '4-TFL-24')
        .isString ('fail', 'data.eerstekleur', data && data.eerstekleur)
        .done();
    }
  });
});

dotest.add ('list', function (test) {
  ovio ({
    params: {
      query: '*X*',
      queryFields: ['handelsbenaming'],
      filters: { merk: 'bmw' },
      fields: ['eerstekleur', 'vermogen']
    },
    callback: function (err, data) {
      var embedded = data && data._embedded;

      test (err)
        .isObject ('fail', 'data', data)
        .isCondition ('fail', 'data.totalItemCount', data && data.totalItemCount, '>=', 1)
        .isObject ('fail', 'data._embedded', embedded)
        .isArray ('fail', 'data._embedded.kenteken', embedded && embedded.kenteken)
        .isNotEmpty ('warn', 'data._embedded.kenteken', embedded && embedded.kenteken)
        .done();
    }
  });
});

dotest.add ('Error: invalid response', function (test) {
  ovio ({
    params: {
      fields: ''
    },
    callback: function (err, data) {
      test()
        .isError ('fail', 'err', err)
        .isExactly ('fail', 'err.message', err && err.message, 'invalid response')
        .isUndefined ('fail', 'data', data)
        .isCondition ('warn', 'err.code', err && err.code, '>=', 300)
        .done();
    }
  });
});

dotest.add ('Error: API error', function (test) {
  var tmp = app ({
    dataset: 'voertuiggegevens'
  });

  tmp ({
    params: {
      filters: { merk: 'bmw' }
    },
    callback: function (err, data) {
      test()
        .isError ('fail', 'err', err)
        .isExactly ('fail', 'err.message', err && err.message, 'API error')
        .isString ('fail', 'err.error', err && err.error)
        .isNotEmpty ('fail', 'err.error', err && err.error)
        .isCondition ('fail', 'err.code', err && err.code, '>=', 300)
        .isUndefined ('fail', 'data', data)
        .done();
    }
  });
});

// Start the tests
dotest.run();
<commit_msg>Test(main): Check err isNull on normal requests<commit_after>/*
Name:         overheid.io - test.js
Description:  Access overheid.io endpoints like OpenKvK, RDW and BAG with node.js
Author:       Franklin van de Meent (https://frankl.in)
Source code:  https://github.com/fvdm/nodejs-overheid.io
Feedback:     https://github.com/fvdm/nodejs-overheid.io/issues
License:      Unlicense (Public Domain) - see LICENSE file
              (https://github.com/fvdm/nodejs-overheid.io/raw/master/LICENSE)
*/

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

// Setup
var config = {
  apikey: process.env.OVIO_APIKEY || null,
  timeout: process.env.OVIO_TIMEOUT || 5000,
  dataset: 'voertuiggegevens'
};

var ovio = app (config);

// Tests
dotest.add ('Module', function (test) {
  test()
    .isFunction ('fail', 'exports', app)
    .isFunction ('fail', 'interface', ovio)
    .done();
});

dotest.add ('config.timeout', function (test) {
  ovio ({
    path: '4-TFL-24',
    params: {
      fields: ['eerstekleur']
    },
    timeout: 1,
    callback: function (err) {
      var error = err && err.error;

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

dotest.add ('no result', function (test) {
  ovio ({
    path: 'error.test',
    callback: function (err) {
      test()
        .isError ('fail', 'err', err)
        .isExactly ('fail', 'err.message', err && err.message, 'no result')
        .done();
    }
  });
});

dotest.add ('item', function (test) {
  ovio ({
    path: '4-TFL-24',
    callback: function (err, data) {
      test (err)
        .isNull ('fail', 'err', err)
        .isNotEmpty ('fail', 'data', data)
        .isObject ('fail', 'data', data)
        .isExactly ('fail', 'data.kenteken', data && data.kenteken, '4-TFL-24')
        .isString ('fail', 'data.eerstekleur', data && data.eerstekleur)
        .done();
    }
  });
});

dotest.add ('list', function (test) {
  ovio ({
    params: {
      query: '*X*',
      queryFields: ['handelsbenaming'],
      filters: { merk: 'bmw' },
      fields: ['eerstekleur', 'vermogen']
    },
    callback: function (err, data) {
      var embedded = data && data._embedded;

      test (err)
        .isNull ('fail', 'err', err)
        .isObject ('fail', 'data', data)
        .isCondition ('fail', 'data.totalItemCount', data && data.totalItemCount, '>=', 1)
        .isObject ('fail', 'data._embedded', embedded)
        .isArray ('fail', 'data._embedded.kenteken', embedded && embedded.kenteken)
        .isNotEmpty ('warn', 'data._embedded.kenteken', embedded && embedded.kenteken)
        .done();
    }
  });
});

dotest.add ('Error: invalid response', function (test) {
  ovio ({
    params: {
      fields: ''
    },
    callback: function (err, data) {
      test()
        .isError ('fail', 'err', err)
        .isExactly ('fail', 'err.message', err && err.message, 'invalid response')
        .isUndefined ('fail', 'data', data)
        .isCondition ('warn', 'err.code', err && err.code, '>=', 300)
        .done();
    }
  });
});

dotest.add ('Error: API error', function (test) {
  var tmp = app ({
    dataset: 'voertuiggegevens'
  });

  tmp ({
    params: {
      filters: { merk: 'bmw' }
    },
    callback: function (err, data) {
      test()
        .isError ('fail', 'err', err)
        .isExactly ('fail', 'err.message', err && err.message, 'API error')
        .isString ('fail', 'err.error', err && err.error)
        .isNotEmpty ('fail', 'err.error', err && err.error)
        .isCondition ('fail', 'err.code', err && err.code, '>=', 300)
        .isUndefined ('fail', 'data', data)
        .done();
    }
  });
});

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


<commit_before>import test from 'ava';

import wrap from './index';

test('doesn\'t do anything on succesful promise', async t => {
	t.plan(2);
	const fn = wrap(async(req, res, next) => {
		return next(null);
	});
	const p = fn(null, null, err => t.falsy(err));
	t.notThrows(p);
	return p;
});

test('calls next with an error on failed promise', t => {
	t.plan(2);
	const fn = wrap(async() => {
		throw new Error();
	});
	const p = fn(null, null, err => t.truthy(err));
	t.notThrows(p);
	return p;
});
<commit_msg>test: simplify tests<commit_after>import test from 'ava';

import wrap from './index';

test('doesn\'t do anything on succesful promise', async t => {
	t.plan(2);
	const fn = wrap(async(req, res, next) => {
		return next(null);
	});
	t.notThrows(fn(null, null, err => t.falsy(err)));
});

test('calls next with an error on failed promise', async t => {
	t.plan(2);
	const fakeErr = new Error('hi');
	const fn = wrap(async() => {
		throw fakeErr;
	});
	t.notThrows(fn(null, null, err => t.is(err, fakeErr)));
});
<|endoftext|>


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

var Gagarin = require('./lib/gagarin');
var path = require('path');
var fs = require('fs');
var pathToApp = path.resolve('./tests/example');
var program = require('commander');
var helpers = require('./lib/helpers');

program
  .option('-g, --grep <pattern>', 'only run tests matching <pattern>')
  .option('-w, --webdriver <url>', 'webdriver url [default: http://127.0.0.1:9515]', 'http://127.0.0.1:9515')
  .option('-B, --skip-build', 'do not build, just run the tests')
  .option('-o, --build-only', 'just build, do not run the tests')
  .option('-V, --verbose', 'run with verbose mode with logs from client/server', false)

program.parse(process.argv);

var gagarin = new Gagarin({
  pathToApp     : pathToApp,
  webdriver     : program.webdriver,
  reporter      : 'spec',
  timeout       : 6000,
  grep          : program.grep,
  skipBuild     : program.skipBuild,
  buildOnly     : program.buildOnly,
  muteBuild     : !program.verbose,
  verbose       : program.verbose,
});

fs.readdirSync(path.join(__dirname, 'tests', 'specs')).forEach(function (file) {
  gagarin.addFile(path.join(__dirname, 'tests', 'specs', file));
});

gagarin.run(function (failedCount) {
  if (failedCount > 0) {
    process.exit(1);
  }
  process.exit(0);
});
<commit_msg>In our tests use --verbose by default<commit_after>#!/usr/bin/env node

var Gagarin = require('./lib/gagarin');
var path = require('path');
var fs = require('fs');
var pathToApp = path.resolve('./tests/example');
var program = require('commander');
var helpers = require('./lib/helpers');

program
  .option('-g, --grep <pattern>', 'only run tests matching <pattern>')
  .option('-w, --webdriver <url>', 'webdriver url [default: http://127.0.0.1:9515]', 'http://127.0.0.1:9515')
  .option('-B, --skip-build', 'do not build, just run the tests')
  .option('-o, --build-only', 'just build, do not run the tests')
  .option('-V, --verbose', 'run with verbose mode with logs from client/server', false)

program.parse(process.argv);

var gagarin = new Gagarin({
  pathToApp     : pathToApp,
  webdriver     : program.webdriver,
  reporter      : 'spec',
  timeout       : 6000,
  grep          : program.grep,
  skipBuild     : program.skipBuild,
  buildOnly     : program.buildOnly,
  muteBuild     : !program.verbose,
  //verbose       : program.verbose,
  verbose       : true,
});

fs.readdirSync(path.join(__dirname, 'tests', 'specs')).forEach(function (file) {
  gagarin.addFile(path.join(__dirname, 'tests', 'specs', file));
});

gagarin.run(function (failedCount) {
  if (failedCount > 0) {
    process.exit(1);
  }
  process.exit(0);
});
<|endoftext|>


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

describe('Tiny Binary Format', function() {
  var Tile;

  beforeEach(function() {
    Tile = new BinaryFormat([
      { length: 8, name: 'type' },
      { length: 8, name: 'height' },
      { length: 1, name: 'veg' }
    ]);
  });

  it('should be a function', function() {
    assert.equal(typeof BinaryFormat, 'function');
  });

  it('should return an object', function() {
    assert.equal(typeof Tile, 'object');
  });

  it('the object should have the correct prototype', function() {
    assert.equal(Tile instanceof BinaryFormat, true);
  });

  describe('#pack', function() {
    var testCases;

    beforeEach(function() {
      testCases = [
        { input: [14, 31, 1], expected: 7231 },
        { input: [0,  79, 0], expected: 158 },
        { input: [8,  60, 1], expected: 4217 },
        { input: [46, 18, 0], expected: 23588 },
        { input: [18, 32, 1], expected: 9281 }
      ];
    });

    it('should be a function', function() {
      assert.equal(typeof Tile.pack, 'function');
    });

    it('should return a number', function() {
      testCases.forEach(function(test) {
        assert.equal(typeof Tile.pack.apply(Tile, test.input), 'number');
      });
    });

    it('should return the correct numbers', function() {
      testCases.forEach(function(test) {
        assert.equal(Tile.pack.apply(Tile, test.input), test.expected);
      });
    });
  });

  describe('#unpack', function() {
    var testCases;

    beforeEach(function() {
      testCases = [
        { input: [26, 2, 0] },
        { input: [125, 5, 1] },
        { input: [3, 99, 1] },
        { input: [88, 99, 1] }
      ];
    });

    it('should be a function', function() {
      assert.equal(typeof Tile.unpack, 'function');
    });

    it('should return an object', function() {
      testCases.forEach(function(test) {
        assert.equal(typeof Tile.unpack.apply(Tile, test.input), 'object');
      });
    });

    it('should be reversible', function() {
      testCases.forEach(function(test) {
        var packed = Tile.pack.apply(Tile, test.input);
        assert.deepEqual(Tile.unpack(packed), {
          type: test.input[0],
          height: test.input[1],
          veg: test.input[2]
        });
      });
    });
  });

  describe('#unpackArray', function() {
    var testCases;

    beforeEach(function() {
      testCases = [
        { input: [53, 49, 1] },
        { input: [111, 31, 0] },
        { input: [9, 5, 1] },
        { input: [16, 9, 0] }
      ];
    });

    it('should be a function', function() {
      assert.equal(typeof Tile.unpackArray, 'function');
    });

    it('should return an array', function() {
      testCases.forEach(function(test) {
        var unpacked = Tile.unpackArray.apply(Tile, test.input);
        assert.equal(unpacked instanceof Array, true);
      });
    });

    it('should be reversible', function() {
      testCases.forEach(function(test) {
        var packed = Tile.pack.apply(Tile, test.input);
        assert.deepEqual(Tile.unpackArray(packed), test.input);
      });
    });
  });
});
<commit_msg>adds unit tests to prevent #3 from happening again<commit_after>var assert = require('assert'),
    BinaryFormat = require('./');

describe('Tiny Binary Format', function() {
  var Tile;

  beforeEach(function() {
    Tile = new BinaryFormat([
      { length: 8, name: 'type' },
      { length: 8, name: 'height' },
      { length: 1, name: 'veg' }
    ]);
  });

  it('should be a function', function() {
    assert.equal(typeof BinaryFormat, 'function');
  });

  it('should return an object', function() {
    assert.equal(typeof Tile, 'object');
  });

  it('the object should have the correct prototype', function() {
    assert.equal(Tile instanceof BinaryFormat, true);
  });

  describe('#pack', function() {
    var testCases;

    beforeEach(function() {
      testCases = [
        { input: [14, 31, 1], expected: 7231 },
        { input: [0,  79, 0], expected: 158 },
        { input: [8,  60, 1], expected: 4217 },
        { input: [46, 18, 0], expected: 23588 },
        { input: [18, 32, 1], expected: 9281 }
      ];
    });

    it('should be a function', function() {
      assert.equal(typeof Tile.pack, 'function');
    });

    it('should return a number', function() {
      testCases.forEach(function(test) {
        assert.equal(typeof Tile.pack.apply(Tile, test.input), 'number');
      });
    });

    it('should return the correct numbers', function() {
      testCases.forEach(function(test) {
        assert.equal(Tile.pack.apply(Tile, test.input), test.expected);
      });
    });
  });

  describe('#unpack', function() {
    var testCases;

    beforeEach(function() {
      testCases = [
        { input: [26, 2, 0] },
        { input: [125, 5, 1] },
        { input: [3, 99, 1] },
        { input: [88, 99, 1] }
      ];
    });

    it('should be a function', function() {
      assert.equal(typeof Tile.unpack, 'function');
    });

    it('should return an object', function() {
      testCases.forEach(function(test) {
        var unpacked = Tile.unpack.apply(Tile, test.input);
        assert.equal(typeof unpacked, 'object');
        assert.equal(unpacked instanceof Array, false);
      });
    });

    it('should be reversible', function() {
      testCases.forEach(function(test) {
        var packed = Tile.pack.apply(Tile, test.input);
        assert.deepEqual(Tile.unpack(packed), {
          type: test.input[0],
          height: test.input[1],
          veg: test.input[2]
        });
      });
    });
  });

  describe('#unpackArray', function() {
    var testCases;

    beforeEach(function() {
      testCases = [
        { input: [53, 49, 1] },
        { input: [111, 31, 0] },
        { input: [9, 5, 1] },
        { input: [16, 9, 0] }
      ];
    });

    it('should be a function', function() {
      assert.equal(typeof Tile.unpackArray, 'function');
    });

    it('should return an array', function() {
      testCases.forEach(function(test) {
        var unpacked = Tile.unpackArray.apply(Tile, test.input);
        assert.equal(unpacked instanceof Array, true);
      });
    });

    it('should be reversible', function() {
      testCases.forEach(function(test) {
        var packed = Tile.pack.apply(Tile, test.input);
        assert.deepEqual(Tile.unpackArray(packed), test.input);
      });
    });
  });
});
<|endoftext|>


<commit_before>let assert = require('assert');
let parser = require('./index.js');

const cases = {
    case1: `a=b`,
    result1: {term: {a: "b"}},
    case2: `(a=-1)`,
    result2: {term: {a: -1}},
    case3: `(Keywords=-9214364837600034816 and Severity="INFO")`,
    result3: {
        "bool": {
            "filter": [
                {
                    "term": {
                        "Keywords": -9214364837600034816
                    }
                },
                {
                    "term": {
                        "Severity": "INFO"
                    }
                }
            ]
        }
    },
    case4: `a≈'b'`,
    result4: {match: {a: "b"}},
    case5: `((a="b" and (a="b" AND a="b")) or a="b")`,
    result5: {"bool":{"should":[{"bool":{"filter":[{"term":{"a":"b"}},{"term":{"a":"b"}},{"term":{"a":"b"}}]}},{"term":{"a":"b"}}]}},
    case6: `system_platform in ["linux", "window"] `,
    result6: {"terms":{"system_platform":["linux","window"]}},
    case7: `system_platform Like "linu*" `,
    result7: {"wildcard":{"system_platform":"linu*"}},
    case8: `(a=b * a>=4) * (a=b * a>=4)`,
    result8: {"bool":{"must":[{"bool":{"filter":[{"term":{"a":"b"}},{"range":{"a":{"gte":"4"}}}]}},{"bool":{"filter":[{"term":{"a":"b"}},{"range":{"a":{"gte":"4"}}}]}}]}},
    case9: `~ a=b`,
    result9: {
        "bool": {
            "must_not": [
                {
                    "term": {
                        "a": "b"
                    }

                }
            ]
        }
    }
};

describe('Test Suite', function () {

    describe('1.Simple YMember Test', function () {
        it(``, function () {
            assert.equal(JSON.stringify(cases.result1), JSON.stringify(parser.parse(cases.case1)));
        });
    });

    describe('2.Negative Number Test', function () {
        it(``, function () {
            assert.equal(JSON.stringify(cases.result2), JSON.stringify(parser.parse(cases.case2)));
        });
    });

    describe('3.And Test', function () {
        it(``, function () {
            assert.equal(JSON.stringify(cases.result3), JSON.stringify(parser.parse(cases.case3)));
        });
    });

    describe('4.Approximate Test', function () {
        it(``, function () {
            assert.equal(JSON.stringify(cases.result4), JSON.stringify(parser.parse(cases.case4)));
        });
    });

    describe('5.Complex Brackets Test', function () {
        it(``, function () {
            assert.equal(JSON.stringify(cases.result5), JSON.stringify(parser.parse(cases.case5)));
        });
    });

    describe('6.In Test', function () {
        it(``, function () {
            assert.equal(JSON.stringify(cases.result6), JSON.stringify(parser.parse(cases.case6)));
        });
    });

    describe('7.Like Test', function () {
        it(``, function () {
            assert.equal(JSON.stringify(cases.result7), JSON.stringify(parser.parse(cases.case7)));
        });
    });

    describe('8.Complex And Test', function () {
        it(``, function () {
            assert.equal(JSON.stringify(cases.result8), JSON.stringify(parser.parse(cases.case8)));
        });
    });

    describe('9.Not Test', function () {
        it(``, function () {
            assert.equal(JSON.stringify(cases.result9), JSON.stringify(parser.parse(cases.case9)));
        });
    });
});<commit_msg>add special char test<commit_after>let assert = require('assert');
let parser = require('./index.js');

const cases = {
    case1: `a=b`,
    result1: {term: {a: "b"}},
    case2: `(a=-1)`,
    result2: {term: {a: -1}},
    case3: `(Keywords=-9214364837600034816 and Severity="INFO")`,
    result3: {
        "bool": {
            "filter": [
                {
                    "term": {
                        "Keywords": -9214364837600034816
                    }
                },
                {
                    "term": {
                        "Severity": "INFO"
                    }
                }
            ]
        }
    },
    case4: `a≈'b'`,
    result4: {match: {a: "b"}},
    case5: `((a="b" and (a="b" AND a="b")) or a="b")`,
    result5: {"bool":{"should":[{"bool":{"filter":[{"term":{"a":"b"}},{"term":{"a":"b"}},{"term":{"a":"b"}}]}},{"term":{"a":"b"}}]}},
    case6: `system_platform in ["linux", "window"] `,
    result6: {"terms":{"system_platform":["linux","window"]}},
    case7: `system_platform Like "linu*" `,
    result7: {"wildcard":{"system_platform":"linu*"}},
    case8: `(a=b * a>=4) * (a=b * a>=4)`,
    result8: {"bool":{"must":[{"bool":{"filter":[{"term":{"a":"b"}},{"range":{"a":{"gte":"4"}}}]}},{"bool":{"filter":[{"term":{"a":"b"}},{"range":{"a":{"gte":"4"}}}]}}]}},
    case9: `~ a=b`,
    result9: {
        "bool": {
            "must_not": [
                {
                    "term": {
                        "a": "b"
                    }

                }
            ]
        }
    },
    case10: `a='10.201.81-&24'`,
    result10: {term: {a: "10.201.81-&24"}}
};

describe('Test Suite', function () {

    describe('1.Simple YMember Test', function () {
        it(``, function () {
            assert.equal(JSON.stringify(cases.result1), JSON.stringify(parser.parse(cases.case1)));
        });
    });

    describe('2.Negative Number Test', function () {
        it(``, function () {
            assert.equal(JSON.stringify(cases.result2), JSON.stringify(parser.parse(cases.case2)));
        });
    });

    describe('3.And Test', function () {
        it(``, function () {
            assert.equal(JSON.stringify(cases.result3), JSON.stringify(parser.parse(cases.case3)));
        });
    });

    describe('4.Approximate Test', function () {
        it(``, function () {
            assert.equal(JSON.stringify(cases.result4), JSON.stringify(parser.parse(cases.case4)));
        });
    });

    describe('5.Complex Brackets Test', function () {
        it(``, function () {
            assert.equal(JSON.stringify(cases.result5), JSON.stringify(parser.parse(cases.case5)));
        });
    });

    describe('6.In Test', function () {
        it(``, function () {
            assert.equal(JSON.stringify(cases.result6), JSON.stringify(parser.parse(cases.case6)));
        });
    });

    describe('7.Like Test', function () {
        it(``, function () {
            assert.equal(JSON.stringify(cases.result7), JSON.stringify(parser.parse(cases.case7)));
        });
    });

    describe('8.Complex And Test', function () {
        it(``, function () {
            assert.equal(JSON.stringify(cases.result8), JSON.stringify(parser.parse(cases.case8)));
        });
    });

    describe('9.Not Test', function () {
        it(``, function () {
            assert.equal(JSON.stringify(cases.result9), JSON.stringify(parser.parse(cases.case9)));
        });
    });

    describe('10.Special Char Test', function () {
        it(``, function () {
            assert.equal(JSON.stringify(cases.result10), JSON.stringify(parser.parse(cases.case10)));
        });
    });
});<|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 fs          = require('fs')
var rawData     = fs.read('emojis.json').toString()
var buildFailed = false
var passed      = function() { console.log("\x1B[92mPASSED\x1B[0m\n") }
var failed      = function() {
  console.log("\x1B[91mFAILED\x1B[0m\n")
  buildFailed = true
}
var reveal = function() {
  if(buildFailed) {
    console.log(":cry: \x1B[91mNo good, something failed.\x1B[0m :boom:\n")
    phantom.exit(buildFailed)
  } else {
    console.log(":sparkles: \x1B[96mWho's awesome? You're awesome!\x1B[0m :+1:\n")
    phantom.exit()
  }
}

//
console.log("\nTEST: Correct JSON format")

try {
  var data = JSON.parse(fs.read('emojis.json'))
  var keys = Object.keys(data)
  keys.splice(keys.indexOf('keys'), 1)
  passed()
} catch(e) {
  console.log('Invalid JSON format. See the CONTRIBUTING doc for reference.')
  failed()
  reveal()
}

//
console.log("TEST: Correct number of emojis")

if(keys.length !== 862) {
  console.log("There are 862 emojis, but emojis.json has " + keys.length + " entries.")
  failed()
} else {
  passed()
}

//
console.log("TEST: Ordered keys are up to date")

if(data.keys.length !== 862) {
  console.log("There are 862 emojis, but keys contains " + data.keys.length + " emojis.")
  failed()
} else {
  passed()
}

//
console.log("TEST: No duplicated entries")

var arr = []
var dups = []

keys.forEach(function(key) {
  if(arr.indexOf(key) < 0) {
    arr.push(key)
  } else {
    dups.push(key)
  }
})

if(dups.length > 0) {
  dups.forEach(function(key) {
    console.log('There is more than one "' + key + '" in emojis.json.')
  })
  failed()
} else {
  passed()
}

//
console.log("TEST: No unnecessary keywords")

var unnecessities = []
var unnecessitiesInKeywords = []

keys.forEach(function(key) {
  data[key]["keywords"].forEach(function(keyword) {
    if(key.match(keyword)) {
      unnecessities.push([key, keyword])
    }

    var otherKeywords = data[key]["keywords"].slice()
    otherKeywords.splice(data[key]["keywords"].indexOf(keyword), 1)
    otherKeywords.forEach(function(otherKeyword) {
      if(otherKeyword.match(keyword)) {
        unnecessitiesInKeywords.push([otherKeyword, keyword, key])
      }
    })
  })
})

if(unnecessities.length > 0 || unnecessitiesInKeywords.length > 0) {
  unnecessities.forEach(function(arr) {
    console.log('"' + arr[1] + '" is unnecessary as it is already part of "' + arr[0] + '" and will be matched.')
  })
  unnecessitiesInKeywords.forEach(function(arr) {
    console.log('"' + arr[1] + '" is unnecessary as a "' + arr[2] + '" already has a keyword "' + arr[0] + '".')
  })

  failed()
} else {
  passed()
}

//
console.log("TEST: Line format")

var offenses = []
var lines = rawData.replace(/^{\n([\s\S]*)\n}\n$/, '$1').split("\n")
var baseRegex = '^    "keywords": \\["[\\w- ]+"(, "[\\w- ]+")*\\]'
var contentRegex = new RegExp(baseRegex + ',$')
var lastLineRegex = new RegExp(baseRegex + '$')
lines.forEach(function(line, index) {
  if(line.match(/keywords/) && !line.match(contentRegex)) {
    offenses.push(index + 2)
  }
})

if(offenses.length > 0) {
  offenses.forEach(function(lineNo) {
    console.log('Line ' + lineNo + ' has the wrong format.')
  })

  failed()
} else {
  passed()
}

reveal()
<commit_msg>updated number of emoji in tests<commit_after>var fs          = require('fs')
var rawData     = fs.read('emojis.json').toString()
var buildFailed = false
var passed      = function() { console.log("\x1B[92mPASSED\x1B[0m\n") }
var failed      = function() {
  console.log("\x1B[91mFAILED\x1B[0m\n")
  buildFailed = true
}
var reveal = function() {
  if(buildFailed) {
    console.log(":cry: \x1B[91mNo good, something failed.\x1B[0m :boom:\n")
    phantom.exit(buildFailed)
  } else {
    console.log(":sparkles: \x1B[96mWho's awesome? You're awesome!\x1B[0m :+1:\n")
    phantom.exit()
  }
}

//
console.log("\nTEST: Correct JSON format")

try {
  var data = JSON.parse(fs.read('emojis.json'))
  var keys = Object.keys(data)
  keys.splice(keys.indexOf('keys'), 1)
  passed()
} catch(e) {
  console.log('Invalid JSON format. See the CONTRIBUTING doc for reference.')
  failed()
  reveal()
}

//
console.log("TEST: Correct number of emojis")

if(keys.length !== 883) {
  console.log("There are 862 emojis, but emojis.json has " + keys.length + " entries.")
  failed()
} else {
  passed()
}

//
console.log("TEST: Ordered keys are up to date")

if(data.keys.length !== 862) {
  console.log("There are 862 emojis, but keys contains " + data.keys.length + " emojis.")
  failed()
} else {
  passed()
}

//
console.log("TEST: No duplicated entries")

var arr = []
var dups = []

keys.forEach(function(key) {
  if(arr.indexOf(key) < 0) {
    arr.push(key)
  } else {
    dups.push(key)
  }
})

if(dups.length > 0) {
  dups.forEach(function(key) {
    console.log('There is more than one "' + key + '" in emojis.json.')
  })
  failed()
} else {
  passed()
}

//
console.log("TEST: No unnecessary keywords")

var unnecessities = []
var unnecessitiesInKeywords = []

keys.forEach(function(key) {
  data[key]["keywords"].forEach(function(keyword) {
    if(key.match(keyword)) {
      unnecessities.push([key, keyword])
    }

    var otherKeywords = data[key]["keywords"].slice()
    otherKeywords.splice(data[key]["keywords"].indexOf(keyword), 1)
    otherKeywords.forEach(function(otherKeyword) {
      if(otherKeyword.match(keyword)) {
        unnecessitiesInKeywords.push([otherKeyword, keyword, key])
      }
    })
  })
})

if(unnecessities.length > 0 || unnecessitiesInKeywords.length > 0) {
  unnecessities.forEach(function(arr) {
    console.log('"' + arr[1] + '" is unnecessary as it is already part of "' + arr[0] + '" and will be matched.')
  })
  unnecessitiesInKeywords.forEach(function(arr) {
    console.log('"' + arr[1] + '" is unnecessary as a "' + arr[2] + '" already has a keyword "' + arr[0] + '".')
  })

  failed()
} else {
  passed()
}

//
console.log("TEST: Line format")

var offenses = []
var lines = rawData.replace(/^{\n([\s\S]*)\n}\n$/, '$1').split("\n")
var baseRegex = '^    "keywords": \\["[\\w- ]+"(, "[\\w- ]+")*\\]'
var contentRegex = new RegExp(baseRegex + ',$')
var lastLineRegex = new RegExp(baseRegex + '$')
lines.forEach(function(line, index) {
  if(line.match(/keywords/) && !line.match(contentRegex)) {
    offenses.push(index + 2)
  }
})

if(offenses.length > 0) {
  offenses.forEach(function(lineNo) {
    console.log('Line ' + lineNo + ' has the wrong format.')
  })

  failed()
} else {
  passed()
}

reveal()
<|endoftext|>


<commit_before>var sys = require("sys"),
my_http = require("http"),
path = require("path"),
url = require("url");

my_http.createServer(function(request,response){
    var my_path = url.parse(request.url).pathme;
    var full_path = path.join(process.cwd(),my_path);
    path.exists(full_path, function(exists){
	      if(!exists){
	          response.writeHeader(404, {"Content-Type": "text/plain"});
	          response.write("404 Not Found\n");
	          response.end();
	      }
	      else{
	          //T
	      }
    });
})

my_http.createServer(function(request,response){
    var my_path = url.parse(request.url).pathname;
    load_file(my_path,response);
}).listen(8080);
<commit_msg>imported firebase and initialized db connection<commit_after>var sys = require("sys"),
my_http = require("http"),
path = require("path"),
url = require("url");

var Firebase = require("Firebase")

my_http.createServer(function(request,response){
    var my_path = url.parse(request.url).pathme;
    var full_path = path.join(process.cwd(),my_path);
    path.exists(full_path, function(exists){
	      if(!exists){
	          response.writeHeader(404, {"Content-Type": "text/plain"});
	          response.write("404 Not Found\n");
	          response.end();
	      }
	      else{
	          //opens firebase connection (not sure if we need it right here,
	          //just for reference's sake)
	          var fb = new Firebase("https://improvplusplus.firebaseio.com")

	      }
    });
})

my_http.createServer(function(request,response){
    var my_path = url.parse(request.url).pathname;
    load_file(my_path,response);
}).listen(8080);
<|endoftext|>


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

console.log('  ' + Object.keys(figures).map(x => figures[x]).join('  ') + '\n');

test('returns a figure', t => {
	t.true(figures.tick === '✔' || figures.tick === '√');
	t.end();
});
<commit_msg>update tests for latest AVA version<commit_after>import test from 'ava';
import figures from './';

console.log('  ' + Object.keys(figures).map(x => figures[x]).join('  ') + '\n');

test('returns a figure', t => {
	t.true(figures.tick === '✔' || figures.tick === '√');
});
<|endoftext|>


<commit_before>import test from 'ava';

const objc = require('./src/index.js');

test('string creation', t => {
  const NSString = objc.NSString;
  let string = NSString.stringWithString_('Hello World');
  t.is(String(string), 'Hello World');
});

test('primitive return values', t => {
  const NSString = objc.NSString;
  let string = NSString.stringWithString_('I am the doctor');
  let length = string.length();
  t.is(length, 15);
  t.is(typeof length, 'number');
});

test('load constant w/out bundle', t => {
  objc.import('AppKit');
  let NSFontAttributeName = objc.constant('NSFontAttributeName');

  t.is(NSFontAttributeName, 'NSFont');
});

test('load constant w/ bundle', t => {
  objc.import('AppKit');
  let NSFontAttributeName = objc.constant('NSFontAttributeName', 'AppKit');

  t.is(NSFontAttributeName, 'NSFont');
});

test('load constant w/ full bundle name', t => {
  objc.import('AppKit');
  let NSFontAttributeName = objc.constant('NSFontAttributeName', 'com.apple.AppKit');

  t.is(NSFontAttributeName, 'NSFont');
});

test('get username using NSProcessInfo, convert to javascript string and compare the value to the username given by `os.userInfo()`', t => {
  const NSProcessInfo = objc.NSProcessInfo;
  const os = require('os');

  let processInfo = NSProcessInfo.processInfo();
  let username = processInfo.userName();

  t.is(String(username), os.userInfo().username);
});

test('primitive argument types', t => {
  const NSNumber = objc.NSNumber;

  let number = NSNumber.numberWithInt_(5);

  t.is(Number(number), 5);
});

test('inout parameters 1 (^@)', t => {
  const NSFileManager = objc.NSFileManager;
  let fm = NSFileManager.defaultManager();

  const filepath = '/Library/Caches/randomfilenamethatsurelydoesntexust.hey';
  fm.createFileAtPath_contents_attributes_(filepath, null, null);

  let error1 = objc.ref(null);
  let success1 = fm.removeItemAtPath_error_(filepath, error1);

  t.is(success1, true);
  t.is(typeof objc.deref(error1), 'undefined');

  let error2 = objc.ref(null);
  let success2 = fm.removeItemAtPath_error_(filepath, error2);

  t.is(success2, false);
  t.is(typeof objc.deref(error2), 'object');
});

test('inout parameters 2 (^@)', t => {
  const NSDictionary = objc.NSDictionary;
  const NSAppleScript = objc.NSAppleScript;
  let source = 'telll application "Safari" to get URL of current tab of window 1';

  let script = NSAppleScript.alloc().initWithSource_(source);

  let error = objc.ref(null);
  let success = script.compileAndReturnError_(error);

  t.is(success, false);
  t.is(objc.deref(error).isKindOfClass_(NSDictionary), true);
});

test('Automatic array conversion (JS array -> NSArray)', t => {
  let NSArray = objc.NSArray;

  let inputArray = ['I', 'am', 'the', 'doctor'];
  let array = NSArray.arrayWithArray_(inputArray);

  inputArray.forEach((object, index) => {
    let str1 = String(object);
    let str2 = String(array.objectAtIndex_(index));
    t.is(str1, str2);
  });
});

test('Iterate over a NSArray', t => {
  let NSArray = objc.NSArray;

  let inputArray = ['hey', 'missy', 'you', 'so', 'fine'];
  let array = NSArray.arrayWithArray_(inputArray);

  for (let element of array) {
    let index = inputArray.indexOf(String(element));
    inputArray.splice(index, 1);
  }

  t.is(inputArray.length, 0);
});
<commit_msg>Added a test for calling methods that contain underscores<commit_after>import test from 'ava';

const objc = require('./src/index.js');

test('string creation', t => {
  const NSString = objc.NSString;
  let string = NSString.stringWithString_('Hello World');
  t.is(String(string), 'Hello World');
});

test('primitive return values', t => {
  const NSString = objc.NSString;
  let string = NSString.stringWithString_('I am the doctor');
  let length = string.length();
  t.is(length, 15);
  t.is(typeof length, 'number');
});

test('load constant w/out bundle', t => {
  objc.import('AppKit');
  let NSFontAttributeName = objc.constant('NSFontAttributeName');

  t.is(NSFontAttributeName, 'NSFont');
});

test('load constant w/ bundle', t => {
  objc.import('AppKit');
  let NSFontAttributeName = objc.constant('NSFontAttributeName', 'AppKit');

  t.is(NSFontAttributeName, 'NSFont');
});

test('load constant w/ full bundle name', t => {
  objc.import('AppKit');
  let NSFontAttributeName = objc.constant('NSFontAttributeName', 'com.apple.AppKit');

  t.is(NSFontAttributeName, 'NSFont');
});

test('get username using NSProcessInfo, convert to javascript string and compare the value to the username given by `os.userInfo()`', t => {
  const NSProcessInfo = objc.NSProcessInfo;
  const os = require('os');

  let processInfo = NSProcessInfo.processInfo();
  let username = processInfo.userName();

  t.is(String(username), os.userInfo().username);
});

test('primitive argument types', t => {
  const NSNumber = objc.NSNumber;

  let number = NSNumber.numberWithInt_(5);

  t.is(Number(number), 5);
});

test('inout parameters 1 (^@)', t => {
  const NSFileManager = objc.NSFileManager;
  let fm = NSFileManager.defaultManager();

  const filepath = '/Library/Caches/randomfilenamethatsurelydoesntexust.hey';
  fm.createFileAtPath_contents_attributes_(filepath, null, null);

  let error1 = objc.ref(null);
  let success1 = fm.removeItemAtPath_error_(filepath, error1);

  t.is(success1, true);
  t.is(typeof objc.deref(error1), 'undefined');

  let error2 = objc.ref(null);
  let success2 = fm.removeItemAtPath_error_(filepath, error2);

  t.is(success2, false);
  t.is(typeof objc.deref(error2), 'object');
});

test('inout parameters 2 (^@)', t => {
  const NSDictionary = objc.NSDictionary;
  const NSAppleScript = objc.NSAppleScript;
  let source = 'telll application "Safari" to get URL of current tab of window 1';

  let script = NSAppleScript.alloc().initWithSource_(source);

  let error = objc.ref(null);
  let success = script.compileAndReturnError_(error);

  t.is(success, false);
  t.is(objc.deref(error).isKindOfClass_(NSDictionary), true);
});

test('Automatic array conversion (JS array -> NSArray)', t => {
  let NSArray = objc.NSArray;

  let inputArray = ['I', 'am', 'the', 'doctor'];
  let array = NSArray.arrayWithArray_(inputArray);

  inputArray.forEach((object, index) => {
    let str1 = String(object);
    let str2 = String(array.objectAtIndex_(index));
    t.is(str1, str2);
  });
});

test('Iterate over a NSArray', t => {
  let NSArray = objc.NSArray;

  let inputArray = ['hey', 'missy', 'you', 'so', 'fine'];
  let array = NSArray.arrayWithArray_(inputArray);

  for (let element of array) {
    let index = inputArray.indexOf(String(element));
    inputArray.splice(index, 1);
  }

  t.is(inputArray.length, 0);
});

test('Test calling methods that contain underscores', t => {
  let NSDate = objc.NSDate;

  let now = NSDate.date();
  let web_RFC1123DateString = now._web_RFC1123DateString(); // eslint-disable-line camelcase

  t.is(typeof web_RFC1123DateString, 'object'); // eslint-disable-line camelcase
  t.is(web_RFC1123DateString.isKindOfClass_('NSString'), true); // eslint-disable-line camelcase
});
<|endoftext|>


<commit_before>var postcss = require('postcss');
var expect  = require('chai').expect;

var plugin = require('./');

var errorString = '/* ERROR: Unable to calculate transparency stop lengths. Please use explicit stop values. */\n';

var test = function (input, output, opts, done) {
    if (typeof opts === 'function' && done === undefined) {
        done = opts;
        opts = {};
    }
    postcss([ plugin(opts) ]).process(input).then(function (result) {
        expect(result.css).to.eql(output);
        expect(result.warnings()).to.be.empty;
        done();
    }).catch(function (error) {
        done(error);
    });
};

var testProperty = function (prop, gradType, input, output, opts, done) {
    var prefix = '.test{ ' + prop + ':' + gradType + '-gradient( ';
    var suffix = ' ); }';
    input = prefix + input + suffix;
    output = prefix + output + suffix;
    return test(input, output, opts, done);
};

var testGradient = function (input, output, opts, done) {
    return testProperty('background-image', 'linear', input, output, opts, done);
};

/* global describe, it */
describe('postcss-gradient-transparency-fix', function () {

    it('ignores non-gradient transparent values', function (done) {
        test('a{ background:transparent }', 'a{ background:transparent }', done);
    });

    it('corrects single rgb() value', function (done) {
        testGradient('rgb(255,0,0), transparent',
                     'rgb(255,0,0), rgba(255, 0, 0, 0)', done);
    });

    it('corrects single rgba() value', function (done) {
        testGradient('rgba(120, 0, 200, 0.5), transparent',
                     'rgba(120, 0, 200, 0.5), rgba(120, 0, 200, 0)', done);
    });

    it('corrects single hsl() value', function (done) {
        testGradient('hsl(204, 30%, 70%), transparent',
                     'hsl(204, 30%, 70%), hsla(204, 30%, 70%, 0)', done);
    });

    it('corrects single hsla() value', function (done) {
        testGradient('hsla(123,50%,50%,0.7), transparent',
                     'hsla(123,50%,50%,0.7), hsla(123, 50%, 50%, 0)', done);
    });

    it('corrects 3-digit hex value', function (done) {
        testGradient('#fed, transparent',
                     '#fed, rgba(255, 238, 221, 0)', done);
    });

    it('corrects 6-digit hex value', function (done) {
        testGradient('#5adCab,transparent',
                     '#5adCab,rgba(90, 220, 171, 0)', done);
    });

    it('corrects 8-digit hex value', function (done) {
        testGradient('#fee1600d, transparent',
                     '#fee1600d, rgba(254, 225, 96, 0)', done);
    });

    it('corrects named colours', function (done) {
        testGradient('papayawhip, transparent',
                     'papayawhip, rgba(255, 239, 213, 0)', done);
    });

    it('handles any order', function (done) {
        testGradient('transparent,  blue',
                     'rgba(0, 0, 255, 0),  blue', done);
    });

    it('maintains stop positions', function (done) {
        testGradient('transparent 30%, blue',
                     'rgba(0, 0, 255, 0) 30%,  blue', done);
    });

    it('generates two colour stops when transparent is between two colours', function (done) {
        testGradient('#f00, transparent 50%, #0f0',
                     '#f00, rgba(255, 0, 0, 0) 50%, rgba(0, 255, 0, 0) 50%, #0f0', done);
    });

    it('calculates missing stop lengths when possible', function (done) {
        testGradient('#f00, transparent, #0f0',
                     '#f00, rgba(255, 0, 0, 0) 50%, rgba(0, 255, 0, 0) 50%, #0f0', done);
        testGradient('#f00 30%, transparent, #0f0',
                     '#f00 30%, rgba(255, 0, 0, 0) 65%, rgba(0, 255, 0, 0) 65%, #0f0', done);
        testGradient('#f00 20px, transparent, #0f0 50px',
                     '#f00 20px, rgba(255, 0, 0, 0) 45px, rgba(0, 255, 0, 0) 45px, #0f0 50px', done);
    });

    it('generates an error when missing stop lengths can\'t be calculated', function (done) {
        testGradient(              '#f00 20px, transparent, #0f0',
                     errorString + '#f00 20px, transparent, #0f0', done);
    });

    it('works with linear-gradient angles', function (done) {
        testGradient('to right, transparent, #ff0',
                     'to right, rgba(255, 255, 0, 0), #ff0', done);
        testGradient('27deg, #ff0, transparent',
                     '27deg, #ff0, rgba(255, 255, 0, 0)', done);
    });

    it('works with radial-gradient syntax', function (done) {
        testProperty('background-image', 'radial', 'transparent, #ff0',
                                         'rgba(255, 255, 0, 0), #ff0', done);
        testProperty('background-image', 'radial', 'farthest-side at 20% 30%, #ff0, transparent',
                                         'farthest-side at 20% 30%, #ff0, rgba(255, 255, 0, 0)', done);
    });

    it('works with repeating gradients', function (done) {
        testProperty('background-image', 'repeating-linear', 'transparent, #ff0',
                                                             'rgba(255, 255, 0, 0), #ff0', done);
        testProperty('background-image', 'repeating-radial', '#ff0, transparent',
                                                             '#ff0, rgba(255, 255, 0, 0)', done);
    });

    it('works with conic-gradient syntax', function (done) {
        testProperty('background-image', 'conic', 'transparent, #ff0',
                                                  'rgba(255, 255, 0, 0), #ff0', done);
    });

    it('works on properties other than background-image', function (done) {
        testProperty('background',   'linear', 'transparent, #ff0',
                                               'rgba(255, 255, 0, 0), #ff0', done);
        testProperty('border-image', 'linear', 'transparent, #ff0',
                                               'rgba(255, 255, 0, 0), #ff0', done);
    });

});
<commit_msg>Thought of some more tests<commit_after>var postcss = require('postcss');
var expect  = require('chai').expect;

var plugin = require('./');

var errorString = '/* ERROR: Unable to calculate transparency stop lengths. Please use explicit stop values. */\n';

var test = function (input, output, opts, done) {
    if (typeof opts === 'function' && done === undefined) {
        done = opts;
        opts = {};
    }
    postcss([ plugin(opts) ]).process(input).then(function (result) {
        expect(result.css).to.eql(output);
        expect(result.warnings()).to.be.empty;
        done();
    }).catch(function (error) {
        done(error);
    });
};

var testProperty = function (prop, gradType, input, output, opts, done) {
    var prefix = '.test{ ' + prop + ':' + gradType + '-gradient( ';
    var suffix = ' ); }';
    input = prefix + input + suffix;
    output = prefix + output + suffix;
    return test(input, output, opts, done);
};

var testGradient = function (input, output, opts, done) {
    return testProperty('background-image', 'linear', input, output, opts, done);
};

/* global describe, it */
describe('postcss-gradient-transparency-fix', function () {

    it('ignores non-gradient transparent values', function (done) {
        test('a{ background:transparent }', 'a{ background:transparent }', done);
    });

    it('corrects single rgb() value', function (done) {
        testGradient('rgb(255,0,0), transparent',
                     'rgb(255,0,0), rgba(255, 0, 0, 0)', done);
    });

    it('corrects single rgba() value', function (done) {
        testGradient('rgba(120, 0, 200, 0.5), transparent',
                     'rgba(120, 0, 200, 0.5), rgba(120, 0, 200, 0)', done);
    });

    it('corrects single hsl() value', function (done) {
        testGradient('hsl(204, 30%, 70%), transparent',
                     'hsl(204, 30%, 70%), hsla(204, 30%, 70%, 0)', done);
    });

    it('corrects single hsla() value', function (done) {
        testGradient('hsla(123,50%,50%,0.7), transparent',
                     'hsla(123,50%,50%,0.7), hsla(123, 50%, 50%, 0)', done);
    });

    it('corrects 3-digit hex value', function (done) {
        testGradient('#fed, transparent',
                     '#fed, rgba(255, 238, 221, 0)', done);
    });

    it('corrects 6-digit hex value', function (done) {
        testGradient('#5adCab,transparent',
                     '#5adCab,rgba(90, 220, 171, 0)', done);
    });

    it('corrects 8-digit hex value', function (done) {
        testGradient('#fee1600d, transparent',
                     '#fee1600d, rgba(254, 225, 96, 0)', done);
    });

    it('corrects named colours', function (done) {
        testGradient('papayawhip, transparent',
                     'papayawhip, rgba(255, 239, 213, 0)', done);
    });

    it('handles any order', function (done) {
        testGradient('transparent,  blue',
                     'rgba(0, 0, 255, 0),  blue', done);
    });

    it('maintains stop positions', function (done) {
        testGradient('transparent 30%, blue',
                     'rgba(0, 0, 255, 0) 30%,  blue', done);
    });

    it('generates two colour stops when transparent is between two colours', function (done) {
        testGradient('#f00, transparent 50%, #0f0',
                     '#f00, rgba(255, 0, 0, 0) 50%, rgba(0, 255, 0, 0) 50%, #0f0', done);
    });

    it('calculates missing stop lengths when possible', function (done) {
        testGradient('#f00, transparent, #0f0',
                     '#f00, rgba(255, 0, 0, 0) 50%, rgba(0, 255, 0, 0) 50%, #0f0', done);
        testGradient('#f00 30%, transparent, #0f0',
                     '#f00 30%, rgba(255, 0, 0, 0) 65%, rgba(0, 255, 0, 0) 65%, #0f0', done);
        testGradient('#f00 20px, transparent, #0f0 50px',
                     '#f00 20px, rgba(255, 0, 0, 0) 45px, rgba(0, 255, 0, 0) 45px, #0f0 50px', done);
    });

    it('generates an error when missing stop lengths can\'t be calculated', function (done) {
        testGradient(              '#f00 20px, transparent, #0f0',
                     errorString + '#f00 20px, transparent, #0f0', done);
    });

    it('handles multiple transparent values in a single gradient', function (done) {
        testGradient('#f00, transparent, #0f0, transparent, #00f',
                     '#f00, rgba(255, 0, 0, 0) 25%, rgba(0, 255, 0, 0) 25%, #0f0, rgba(0, 255, 0, 0) 75%, rgba(0, 0, 255, 0) 75%, #00f', done);
    });

    it('handles consecutive transparent values', function (done) {
        testGradient('#f00, transparent, transparent, #0f0',
                     '#f00, rgba(255, 0, 0, 0) 33%, rgba(0, 255, 0, 0) 67%, #0f0', done);
        testGradient('#f00, transparent 25%, transparent 73%, #0f0',
                     '#f00, rgba(255, 0, 0, 0) 25%, rgba(0, 255, 0, 0) 73%, #0f0', done);
        testGradient('transparent, transparent, #0f0',
                     'rgba(0, 255, 0, 0) 0%, rgba(0, 255, 0, 0) 50%, #0f0', done);
    });

    it('handles multiple gradients', function (done) {
        testGradient('transparent, blue), linear-gradient(red, transparent',
                     'rgba(0, 0, 255, 0),  blue), linear-gradient(red, rgba(255, 0, 0, 0))', done);
    });

    it('ignores non-gradient multiple background values', function (done) {
        testProperty('background', 'linear',
            'transparent, blue), transparent, url(http://example.com/transparent.png)',
            'rgba(0, 0, 255, 0), blue), transparent, url(http://example.com/transparent.png)', done);
    });

    it('works with linear-gradient angles', function (done) {
        testGradient('to right, transparent, #ff0',
                     'to right, rgba(255, 255, 0, 0), #ff0', done);
        testGradient('27deg, #ff0, transparent',
                     '27deg, #ff0, rgba(255, 255, 0, 0)', done);
    });

    it('works with radial-gradient syntax', function (done) {
        testProperty('background-image', 'radial', 'transparent, #ff0',
                                         'rgba(255, 255, 0, 0), #ff0', done);
        testProperty('background-image', 'radial', 'farthest-side at 20% 30%, #ff0, transparent',
                                         'farthest-side at 20% 30%, #ff0, rgba(255, 255, 0, 0)', done);
    });

    it('works with repeating gradients', function (done) {
        testProperty('background-image', 'repeating-linear', 'transparent, #ff0',
                                                             'rgba(255, 255, 0, 0), #ff0', done);
        testProperty('background-image', 'repeating-radial', '#ff0, transparent',
                                                             '#ff0, rgba(255, 255, 0, 0)', done);
    });

    it('works with conic-gradient syntax', function (done) {
        testProperty('background-image', 'conic', 'transparent, #ff0',
                                                  'rgba(255, 255, 0, 0), #ff0', done);
    });

    it('works on properties other than background-image', function (done) {
        testProperty('background',   'linear', 'transparent, #ff0',
                                               'rgba(255, 255, 0, 0), #ff0', done);
        testProperty('border-image', 'linear', 'transparent, #ff0',
                                               'rgba(255, 255, 0, 0), #ff0', done);
    });

});
<|endoftext|>


<commit_before>var assert = require('assert')
var mminch = require('./index')

console.log('testing api...');

assert( typeof mminch == 'function', 'mminch is not a function'  );
assert( typeof mminch() == 'object', 'mminch did not return a string'  );

console.log('testing conversions mm to inches...');

assert.equal(mminch('1').toInch(), '3/64')
assert.equal(mminch('1.5').toInch(), '1/32')
assert.equal(mminch('2').toInch(), '5/64')
assert.equal(mminch('2.5').toInch(), '3/32')
assert.equal(mminch('3').toInch(), '1/8')
assert.equal(mminch('8').toInch(), '5/16')
assert.equal(mminch('25.4').toInch(), '1')
assert.equal(mminch('26').toInch(), '1 1/32')
assert.equal(mminch('100').toInch(), '3 15/16')

console.log('testing conversions inches to mm...');

assert.equal(mminch('3/64').toMM(), '1')
assert.equal(mminch('1/32').toMM(), '1.5')
assert.equal(mminch('5/64').toMM(), '2')
assert.equal(mminch('3/32').toMM(), '2.5')
assert.equal(mminch('1/8').toMM(), '3')
assert.equal(mminch('5/16').toMM(), '8')
assert.equal(mminch('1').toMM(), '25.4')
assert.equal(mminch('1 1/32').toMM(), '26')
assert.equal(mminch('3 15/16').toMM(), '100')

console.log('testing passed!');
<commit_msg>Correct tests<commit_after>var assert = require('assert')
var mminch = require('./index')

console.log('testing api...')

assert( typeof mminch === 'function', 'mminch is not a function')
assert( typeof mminch() === 'object', 'mminch did not return a string')

console.log('testing conversions mm to inches...')

assert.equal(mminch('1').toInch(), '3/64')
assert.equal(mminch('1.5').toInch(), '1/16')
assert.equal(mminch('2').toInch(), '5/64')
assert.equal(mminch('2.5').toInch(), '3/32')
assert.equal(mminch('3').toInch(), '1/8')
assert.equal(mminch('8').toInch(), '5/16')
assert.equal(mminch('25.4').toInch(), '1')
assert.equal(mminch('26').toInch(), '1 1/32')
assert.equal(mminch('100').toInch(), '3 15/16')

console.log('testing conversions inches to mm...')

assert.equal(mminch('3/64').toMM(), '1')
assert.equal(mminch('1/16').toMM(), '1.5')
assert.equal(mminch('5/64').toMM(), '2')
assert.equal(mminch('3/32').toMM(), '2.5')
assert.equal(mminch('1/8').toMM(), '3')
assert.equal(mminch('5/16').toMM(), '8')
assert.equal(mminch('1').toMM(), '25.4')
assert.equal(mminch('1 1/32').toMM(), '26')
assert.equal(mminch('3 15/16').toMM(), '100')

console.log('testing passed!')

<|endoftext|>