<commit_before>'use strict';

/* deps: mocha */
var assert = require('assert');

var Composer = require('../');
var noop = require('../lib/noop');
var composer;

describe('composer', function() {
  beforeEach(function() {
    composer = new Composer();
  });

  it('should throw an error when a name is not given for a task', function(done) {
    try {
      composer.task();
      done(new Error('Expected an error to be thrown'));
    } catch (err) {
      assert(err);
      assert.equal(err.message, 'expected `name` to be a string');
      done();
    }
  });

  it('should register a task', function() {
    var fn = function(done) {
      done();
    };
    composer.task('default', fn);
    assert.equal(typeof composer.tasks.default, 'object');
    assert.equal(composer.tasks.default.fn, fn);
  });

  it('should return a task by name', function() {
    var fn = function(done) {
      done();
    };
    composer.task('default', fn);
    var task = composer.task('default');
    assert.equal(typeof task, 'object');
    assert.equal(task.fn, fn);
  });

  it('should register a task with an array of named dependencies', function() {
    composer.task('default', ['foo', 'bar'], function(done) {
      done();
    });
    assert.equal(typeof composer.tasks.default, 'object');
    assert.deepEqual(composer.tasks.default.deps, ['foo', 'bar']);
  });

  it('should register a task with an array of function dependencies', function() {
    function baz(cb) { cb(); };
    baz.taskName = 'Baz';

    var deps = [
      'foo',
      function bar(cb) { cb(); },
      baz,
      function(cb) { cb(); }
    ];
    composer.task('default', deps, function(done) {
      done();
    });
    assert.equal(typeof composer.tasks.default, 'object');
    assert.deepEqual(composer.tasks.default.deps, ['foo', 'bar', 'Baz', '[anonymous (1)]']);
  });

  it('should register a task with a list of strings as dependencies', function() {
    composer.task('default', 'foo', 'bar', function(done) {
      done();
    });
    assert.equal(typeof composer.tasks.default, 'object');
    assert.deepEqual(composer.tasks.default.deps, ['foo', 'bar']);
  });

  it('should register a task as a noop function when only dependencies are given', function() {
    composer.task('default', ['foo', 'bar']);
    assert.equal(typeof composer.tasks.default, 'object');
    assert.equal(composer.tasks.default.fn, noop);
  });

  it('should register a task with options as the second argument', function() {
    composer.task('default', {flow: 'parallel'}, ['foo', 'bar']);
    assert.equal(typeof composer.tasks.default, 'object');
    assert.equal(composer.tasks.default.fn, noop);
  });

  it('should run a task', function(done) {
    var count = 0;
    composer.task('default', function(cb) {
      count++;
      cb();
    });

    composer.build('default', function(err) {
      if (err) return done(err);
      assert.equal(count, 1);
      done();
    });
  });

  it('should run the `default` task when no task is given', function(done) {
    var count = 0;
    composer.task('default', function(cb) {
      count++;
      cb();
    });

    composer.build(function(err) {
      if (err) return done(err);
      assert.equal(count, 1);
      done();
    });
  });

  it('should throw an error when a task with unregistered dependencies is built', function(done) {
    var count = 0;
    composer.task('default', ['foo', 'bar'], function(cb) {
      count++;
      cb();
    });

    composer.build('default', function(err) {
      if (!err) return done(new Error('Expected an error to be thrown.'));
      assert.equal(count, 0);
      done();
    });
  });

  it('should throw an error when a task with globbed dependencies cannot be found', function(done) {
    var count = 0;
    composer.task('default', ['a-*'], function(cb) {
      count++;
      cb();
    });

    composer.build('default', function(err) {
      if (!err) return done(new Error('Expected an error to be thrown.'));
      assert.equal(count, 0);
      done();
    });
  });

  it('should throw an error when `.build` is called without a callback function.', function() {
    try {
      composer.build('default');
      throw new Error('Expected an error to be thrown.');
    } catch (err) {
    }
  });

  it('should emit task events', function(done) {
    var events = [];
    composer.on('task:starting', function(task, run) {
      events.push('starting.' + task.name);
    });
    composer.on('task:finished', function(task, run) {
      events.push('finished.' + task.name);
    });
    composer.on('task:error', function(err) {
      events.push('error.' + err.task.name);
    });

    composer.task('foo', function(cb) {
      cb();
    });
    composer.task('bar', ['foo'], function(cb) {
      cb();
    });
    composer.task('default', ['bar']);
    composer.build('default', function(err) {
      if (err) return done(err);
      assert.deepEqual(events, ['starting.default', 'starting.bar', 'starting.foo', 'finished.foo', 'finished.bar', 'finished.default']);
      done();
    });
  });

  it('should emit an error event when an error is passed back in a task', function(done) {
    composer.on('task:error', function(err) {
      assert(err);
      assert.equal(err.message, 'This is an error');
    });
    composer.task('default', function(cb) {
      return cb(new Error('This is an error'));
    });
    composer.build('default', function(err) {
      if (err) return done();
      done(new Error('Expected an error'));
    });
  });

  it('should emit an error event when an error is thrown in a task', function(done) {
    var errors = 0;
    composer.on('task:error', function(err) {
      errors++;
      assert(err);
      assert.equal(err.message, 'This is an error');
    });
    composer.task('default', function() {
      throw new Error('This is an error');
    });
    composer.build('default', function(err) {
      assert.equal(errors, 1);
      if (err) return done();
      done(new Error('Expected an error'));
    });
  });

  it('should emit build events', function(done) {
    var events = [];
    composer.on('starting', function(app, run) {
      events.push('starting.' + app._appname);
    });
    composer.on('finished', function(app, run) {
      events.push('finished.' + app._appname);
    });
    composer.on('error', function(err) {
      events.push('error.' + err.app._appname);
    });

    composer.task('foo', function(cb) {
      cb();
    });
    composer.task('bar', ['foo'], function(cb) {
      cb();
    });
    composer.task('default', ['bar']);
    composer.build('default', function(err) {
      if (err) return done(err);
      assert.deepEqual(events, ['starting.composer', 'finished.composer']);
      done();
    });
  });

  it('should emit a build error event when an error is passed back in a task', function(done) {
    composer.on('error', function(err) {
      assert(err);
      assert.equal(err.message, 'This is an error');
    });
    composer.task('default', function(cb) {
      return cb(new Error('This is an error'));
    });
    composer.build('default', function(err) {
      if (err) return done();
      done(new Error('Expected an error'));
    });
  });

  it('should emit a build error event when an error is thrown in a task', function(done) {
    var errors = 0;
    composer.on('error', function(err) {
      errors++;
      assert(err);
      assert.equal(err.message, 'This is an error');
    });
    composer.task('default', function() {
      throw new Error('This is an error');
    });
    composer.build('default', function(err) {
      assert.equal(errors, 1);
      if (err) return done();
      done(new Error('Expected an error'));
    });
  });

  it('should run dependencies before running the dependent task.', function(done) {
    var seq = [];
    composer.task('foo', function(cb) {
      seq.push('foo');
      cb();
    });
    composer.task('bar', function(cb) {
      seq.push('bar');
      cb();
    });
    composer.task('default', ['foo', 'bar'], function(cb) {
      seq.push('default');
      cb();
    });

    composer.build('default', function(err) {
      if (err) return done(err);
      assert.deepEqual(seq, ['foo', 'bar', 'default']);
      done();
    });
  });

  it('should run globbed dependencies before running the dependent task.', function(done) {
    var seq = [];
    composer.task('a-foo', function(cb) {
      seq.push('a-foo');
      cb();
    });
    composer.task('a-bar', function(cb) {
      seq.push('a-bar');
      cb();
    });
    composer.task('b-foo', function(cb) {
      seq.push('b-foo');
      cb();
    });
    composer.task('b-bar', function(cb) {
      seq.push('b-bar');
      cb();
    });
    composer.task('default', ['a-*'], function(cb) {
      seq.push('default');
      cb();
    });

    composer.build(function(err) {
      if (err) return done(err);
      assert.deepEqual(seq, ['a-foo', 'a-bar', 'default']);
      done();
    });
  });

  it('should get the current task name from `this`', function(done) {
    var results = [];
    var fn = function(cb) {
      results.push(this.name);
      cb();
    };
    var tasks = [];
    for (var i = 0; i < 10; i++) {
      tasks.push('task-' + i);
      composer.task('task-' + i, fn);
    }
    composer.build(tasks, function(err) {
      if (err) return done(err);
      assert.equal(results.length, 10);
      assert.deepEqual(results, ['task-0', 'task-1', 'task-2', 'task-3', 'task-4', 'task-5', 'task-6', 'task-7', 'task-8', 'task-9']);
      done();
    });
  });

  it('should get the build history after a build', function(done) {
    var results = [];
    var fn = function(cb) {
      results.push(this.name);
      cb();
    };
    var tasks = [];
    for (var i = 0; i < 10; i++) {
      tasks.push('task-' + i);
      composer.task('task-' + i, fn);
    }
    composer.build(tasks, function(err) {
      if (err) return done(err);
      assert(composer.buildHistory.length > 0);
      assert.equal(results.length, 10);
      assert.deepEqual(results, ['task-0', 'task-1', 'task-2', 'task-3', 'task-4', 'task-5', 'task-6', 'task-7', 'task-8', 'task-9']);
      done();
    });
  });
});
<commit_msg>add tests for custom inspect function<commit_after>'use strict';

/* deps: mocha */
var assert = require('assert');

var Composer = require('../');
var noop = require('../lib/noop');
var composer;

describe('composer', function() {
  beforeEach(function() {
    composer = new Composer();
  });

  it('should throw an error when a name is not given for a task', function(done) {
    try {
      composer.task();
      done(new Error('Expected an error to be thrown'));
    } catch (err) {
      assert(err);
      assert.equal(err.message, 'expected `name` to be a string');
      done();
    }
  });

  it('should register a task', function() {
    var fn = function(done) {
      done();
    };
    composer.task('default', fn);
    assert.equal(typeof composer.tasks.default, 'object');
    assert.equal(composer.tasks.default.fn, fn);
  });

  it('should return a task by name', function() {
    var fn = function(done) {
      done();
    };
    composer.task('default', fn);
    var task = composer.task('default');
    assert.equal(typeof task, 'object');
    assert.equal(task.fn, fn);
  });

  it('should register a task with an array of named dependencies', function() {
    composer.task('default', ['foo', 'bar'], function(done) {
      done();
    });
    assert.equal(typeof composer.tasks.default, 'object');
    assert.deepEqual(composer.tasks.default.deps, ['foo', 'bar']);
  });

  it('should register a task with an array of function dependencies', function() {
    function baz(cb) { cb(); };
    baz.taskName = 'Baz';

    var deps = [
      'foo',
      function bar(cb) { cb(); },
      baz,
      function(cb) { cb(); }
    ];
    composer.task('default', deps, function(done) {
      done();
    });
    assert.equal(typeof composer.tasks.default, 'object');
    assert.deepEqual(composer.tasks.default.deps, ['foo', 'bar', 'Baz', '[anonymous (1)]']);
  });

  it('should register a task with a list of strings as dependencies', function() {
    composer.task('default', 'foo', 'bar', function(done) {
      done();
    });
    assert.equal(typeof composer.tasks.default, 'object');
    assert.deepEqual(composer.tasks.default.deps, ['foo', 'bar']);
  });

  it('should register a task as a noop function when only dependencies are given', function() {
    composer.task('default', ['foo', 'bar']);
    assert.equal(typeof composer.tasks.default, 'object');
    assert.equal(composer.tasks.default.fn, noop);
  });

  it('should register a task with options as the second argument', function() {
    composer.task('default', {flow: 'parallel'}, ['foo', 'bar']);
    assert.equal(typeof composer.tasks.default, 'object');
    assert.equal(composer.tasks.default.fn, noop);
  });

  it('should run a task', function(done) {
    var count = 0;
    composer.task('default', function(cb) {
      count++;
      cb();
    });

    composer.build('default', function(err) {
      if (err) return done(err);
      assert.equal(count, 1);
      done();
    });
  });

  it('should run the `default` task when no task is given', function(done) {
    var count = 0;
    composer.task('default', function(cb) {
      count++;
      cb();
    });

    composer.build(function(err) {
      if (err) return done(err);
      assert.equal(count, 1);
      done();
    });
  });

  it('should throw an error when a task with unregistered dependencies is built', function(done) {
    var count = 0;
    composer.task('default', ['foo', 'bar'], function(cb) {
      count++;
      cb();
    });

    composer.build('default', function(err) {
      if (!err) return done(new Error('Expected an error to be thrown.'));
      assert.equal(count, 0);
      done();
    });
  });

  it('should throw an error when a task with globbed dependencies cannot be found', function(done) {
    var count = 0;
    composer.task('default', ['a-*'], function(cb) {
      count++;
      cb();
    });

    composer.build('default', function(err) {
      if (!err) return done(new Error('Expected an error to be thrown.'));
      assert.equal(count, 0);
      done();
    });
  });

  it('should throw an error when `.build` is called without a callback function.', function() {
    try {
      composer.build('default');
      throw new Error('Expected an error to be thrown.');
    } catch (err) {
    }
  });

  it('should emit task events', function(done) {
    var events = [];
    composer.on('task:starting', function(task, run) {
      events.push('starting.' + task.name);
    });
    composer.on('task:finished', function(task, run) {
      events.push('finished.' + task.name);
    });
    composer.on('task:error', function(err) {
      events.push('error.' + err.task.name);
    });

    composer.task('foo', function(cb) {
      cb();
    });
    composer.task('bar', ['foo'], function(cb) {
      cb();
    });
    composer.task('default', ['bar']);
    composer.build('default', function(err) {
      if (err) return done(err);
      assert.deepEqual(events, ['starting.default', 'starting.bar', 'starting.foo', 'finished.foo', 'finished.bar', 'finished.default']);
      done();
    });
  });

  it('should emit an error event when an error is passed back in a task', function(done) {
    composer.on('task:error', function(err) {
      assert(err);
      assert.equal(err.message, 'This is an error');
    });
    composer.task('default', function(cb) {
      return cb(new Error('This is an error'));
    });
    composer.build('default', function(err) {
      if (err) return done();
      done(new Error('Expected an error'));
    });
  });

  it('should emit an error event when an error is thrown in a task', function(done) {
    var errors = 0;
    composer.on('task:error', function(err) {
      errors++;
      assert(err);
      assert.equal(err.message, 'This is an error');
    });
    composer.task('default', function() {
      throw new Error('This is an error');
    });
    composer.build('default', function(err) {
      assert.equal(errors, 1);
      if (err) return done();
      done(new Error('Expected an error'));
    });
  });

  it('should emit build events', function(done) {
    var events = [];
    composer.on('starting', function(app, run) {
      events.push('starting.' + app._appname);
    });
    composer.on('finished', function(app, run) {
      events.push('finished.' + app._appname);
    });
    composer.on('error', function(err) {
      events.push('error.' + err.app._appname);
    });

    composer.task('foo', function(cb) {
      cb();
    });
    composer.task('bar', ['foo'], function(cb) {
      cb();
    });
    composer.task('default', ['bar']);
    composer.build('default', function(err) {
      if (err) return done(err);
      assert.deepEqual(events, ['starting.composer', 'finished.composer']);
      done();
    });
  });

  it('should emit a build error event when an error is passed back in a task', function(done) {
    composer.on('error', function(err) {
      assert(err);
      assert.equal(err.message, 'This is an error');
    });
    composer.task('default', function(cb) {
      return cb(new Error('This is an error'));
    });
    composer.build('default', function(err) {
      if (err) return done();
      done(new Error('Expected an error'));
    });
  });

  it('should emit a build error event when an error is thrown in a task', function(done) {
    var errors = 0;
    composer.on('error', function(err) {
      errors++;
      assert(err);
      assert.equal(err.message, 'This is an error');
    });
    composer.task('default', function() {
      throw new Error('This is an error');
    });
    composer.build('default', function(err) {
      assert.equal(errors, 1);
      if (err) return done();
      done(new Error('Expected an error'));
    });
  });

  it('should run dependencies before running the dependent task.', function(done) {
    var seq = [];
    composer.task('foo', function(cb) {
      seq.push('foo');
      cb();
    });
    composer.task('bar', function(cb) {
      seq.push('bar');
      cb();
    });
    composer.task('default', ['foo', 'bar'], function(cb) {
      seq.push('default');
      cb();
    });

    composer.build('default', function(err) {
      if (err) return done(err);
      assert.deepEqual(seq, ['foo', 'bar', 'default']);
      done();
    });
  });

  it('should add inspect function to tasks.', function() {
    composer.task('foo', function(cb) {
      cb();
    });
    composer.task('bar', function(cb) {
      cb();
    });
    composer.task('default', ['foo', 'bar'], function(cb) {
      cb();
    });
    assert.equal(composer.tasks.foo.inspect(), '<Task "foo" deps: []>');
    assert.equal(composer.tasks.bar.inspect(), '<Task "bar" deps: []>');
    assert.equal(composer.tasks.default.inspect(), '<Task "default" deps: [foo, bar]>');
  });

  it('should add custom inspect function to tasks.', function() {
    composer.options = {
      inspectFn: function(task) {
        return '<Task "' + task.name + '"' + (task.options.deps.length ? ' [' + task.options.deps.join(', ') + ']' : '') + '>';
      }
    };
    composer.task('foo', function(cb) {
      cb();
    });
    composer.task('bar', function(cb) {
      cb();
    });
    composer.task('default', ['foo', 'bar'], function(cb) {
      cb();
    });
    assert.equal(composer.tasks.foo.inspect(), '<Task "foo">');
    assert.equal(composer.tasks.bar.inspect(), '<Task "bar">');
    assert.equal(composer.tasks.default.inspect(), '<Task "default" [foo, bar]>');
  });

  it('should disable inspect function on tasks.', function() {
    composer.options = {
      inspectFn: false
    };

    composer.task('foo', function(cb) {
      cb();
    });
    composer.task('bar', function(cb) {
      cb();
    });
    composer.task('default', ['foo', 'bar'], function(cb) {
      cb();
    });
    assert.equal(typeof composer.tasks.foo.inspect, 'undefined');
    assert.equal(typeof composer.tasks.bar.inspect, 'undefined');
    assert.equal(typeof composer.tasks.default.inspect, 'undefined');
  });

  it('should run globbed dependencies before running the dependent task.', function(done) {
    var seq = [];
    composer.task('a-foo', function(cb) {
      seq.push('a-foo');
      cb();
    });
    composer.task('a-bar', function(cb) {
      seq.push('a-bar');
      cb();
    });
    composer.task('b-foo', function(cb) {
      seq.push('b-foo');
      cb();
    });
    composer.task('b-bar', function(cb) {
      seq.push('b-bar');
      cb();
    });
    composer.task('default', ['a-*'], function(cb) {
      seq.push('default');
      cb();
    });

    composer.build(function(err) {
      if (err) return done(err);
      assert.deepEqual(seq, ['a-foo', 'a-bar', 'default']);
      done();
    });
  });

  it('should get the current task name from `this`', function(done) {
    var results = [];
    var fn = function(cb) {
      results.push(this.name);
      cb();
    };
    var tasks = [];
    for (var i = 0; i < 10; i++) {
      tasks.push('task-' + i);
      composer.task('task-' + i, fn);
    }
    composer.build(tasks, function(err) {
      if (err) return done(err);
      assert.equal(results.length, 10);
      assert.deepEqual(results, ['task-0', 'task-1', 'task-2', 'task-3', 'task-4', 'task-5', 'task-6', 'task-7', 'task-8', 'task-9']);
      done();
    });
  });

  it('should get the build history after a build', function(done) {
    var results = [];
    var fn = function(cb) {
      results.push(this.name);
      cb();
    };
    var tasks = [];
    for (var i = 0; i < 10; i++) {
      tasks.push('task-' + i);
      composer.task('task-' + i, fn);
    }
    composer.build(tasks, function(err) {
      if (err) return done(err);
      assert(composer.buildHistory.length > 0);
      assert.equal(results.length, 10);
      assert.deepEqual(results, ['task-0', 'task-1', 'task-2', 'task-3', 'task-4', 'task-5', 'task-6', 'task-7', 'task-8', 'task-9']);
      done();
    });
  });
});
<|endoftext|>


<commit_before>var fs = require('fs');

var test = require('tape');
var streamStats = require('stream-stats');
var isStream = require('isstream');

var checkUsage = require('../lib/checkUsage');
var ogrChild = require('../lib/ogrChild');
var splitOGRJSON = require('../lib/splitOGRJSON');
var makeBulkSeparator = require('../lib/makeBulkSeparator');
var formatAddress = require('../lib/formatAddress');
var esLoader = require('../lib/esLoader');
var transformerTemplate = require('../lib/transformerTemplate');

test('Check Usage', function(t){
  t.plan(6);

  var program = {
    shapefile: 'someshape',
    host: 'localhost',
    port: 9200,
    transformer: './transformers/default'
  }

  var first = checkUsage(program)
  t.equal(first.messages.length, 3);
  t.equal(first.err, 0);

  var second = checkUsage({port:9201});
  t.equal(second.messages.length, 1);
  t.equal(second.err, 1);

  var third = checkUsage({port:NaN})
  t.equal(third.messages.length, 2);
  t.equal(third.err, 1);
});

test('ogriChild module', function(t){
  t.plan(3);

  var shp = 'test/data/t.shp';
  var child = ogrChild(shp);
  var errInChild = 0;

  t.ok(child, 'ogrChild process is created');
  t.ok(isStream(child.stdout), 'the child process has stdout');

  child.stderr.once('data',function(){
    errInChild = 1;
  });

  child.stderr.once('end',function(){
    t.notOk(errInChild, 'ogr2ogr doesn\'t emit an error');
  });
});

test('splitOGRJSON module', function(t){
  t.plan(1);

  var json = 'test/data/t.json';
  var stats = streamStats('splitOGR',{store:1});

  fs.createReadStream(json)
    .pipe(splitOGRJSON())
    .pipe(stats)
    .sink();

  stats.on('end', function(){
    var result = stats.getResult();
    var validJSON = 1;
    result.chunks.forEach(function(v){
      try{
        JSON.parse(v.chunk.toString())
      }catch(e){
        validJSON = 0;
      }
    });
    t.ok(validJSON, 'splitOGRJSON yields valid JSON chunks');
  })
});

test('makeBulkSeparator module', function(t){
  t.plan(3);
  var sep = makeBulkSeparator('ind','typ');
  var sepObj = JSON.parse(sep.slice(0,sep.length-1));
  var expectedSep = {index:{_index:'ind',_type:'typ'}}
  t.deepEqual(sepObj, expectedSep, 'Bulk separator on standard input');

  var mtSep = makeBulkSeparator();
  var mtObj = JSON.parse(mtSep.slice(0,mtSep.length-1));
  var expectedMT = {index:{}};
  t.deepEqual(mtObj, expectedMT, 'Bulk separator on empty input');

  try{
    makeBulkSeparator(null, 'failing');
  }catch(e){
    t.pass('Bulk separator with a type and no index fails');
  }
});

test('formatAddress module', function(t){
  t.plan(2);

  var add1 = '123 fake st. San Francisco, CA, 12345';
  var add2 = '221B Baker St. Arg, AZ, 67876';

  t.equal(formatAddress('123 fake st.', 'San Francisco', 'CA', 12345), add1, 'Standard format')
  t.equal(formatAddress('  221B Baker St.', 'Arg  ', 'AZ', '67876'), add2, 'Trim strings');
});

test('esLoader module', function(t){
  t.plan(2);
  try{
    esLoader.connect();
  }catch(e){
    t.pass('Connect fails without host/port')
  }
  t.ok(isStream.isWritable(esLoader.load()),'esLoader.load returns a write stream');
});

test('transformerTemplate module', function(t){
  t.plan(3);
  var trans = transformerTemplate('123 fake st.','Springfield','Oregon',19992);

  t.equal(typeof trans, 'function', 'template returns a function');
  t.ok(isStream.isDuplex(trans()), 'The produced transformer generates a transform stream');

  try{
    transformerTemplate();
  }catch(e){
    t.pass('Calling the template without all arguments throws an error');
  }
});

/*test('Transformers', function(t){

  fs.readdir('transformers/',function(err,transformers){
    t.plan(1);
   console.log(transformers);
  });
  /*var transform = require('transformers/default');
  var json = 'test/data/t.json';
  var stats = streamStats('ogrToTransform');

  fs.createReadStream(json)
    .pipe(splitOGRJSON())
    .pipe(
    .pipe(stats)
    .sink();

});*/
<commit_msg>Reworking template tests to delve deeper<commit_after>var fs = require('fs');
var path = require('path');

var test = require('tape');
var streamStats = require('stream-stats');
var isStream = require('isstream');

var checkUsage = require('../lib/checkUsage');
var ogrChild = require('../lib/ogrChild');
var splitOGRJSON = require('../lib/splitOGRJSON');
var makeBulkSeparator = require('../lib/makeBulkSeparator');
var formatAddress = require('../lib/formatAddress');
var esLoader = require('../lib/esLoader');
var transformerTemplate = require('../lib/transformerTemplate');

test('Check Usage', function(t){
  t.plan(6);

  var program = {
    shapefile: 'someshape',
    host: 'localhost',
    port: 9200,
    transformer: './transformers/default'
  }

  var first = checkUsage(program)
  t.equal(first.messages.length, 3);
  t.equal(first.err, 0);

  var second = checkUsage({port:9201});
  t.equal(second.messages.length, 1);
  t.equal(second.err, 1);

  var third = checkUsage({port:NaN})
  t.equal(third.messages.length, 2);
  t.equal(third.err, 1);
});

test('ogriChild module', function(t){
  t.plan(3);

  var shp = 'test/data/t.shp';
  var child = ogrChild(shp);
  var errInChild = 0;

  t.ok(child, 'ogrChild process is created');
  t.ok(isStream(child.stdout), 'the child process has stdout');

  child.stderr.once('data',function(){
    errInChild = 1;
  });

  child.stderr.once('end',function(){
    t.notOk(errInChild, 'ogr2ogr doesn\'t emit an error');
  });
});

test('splitOGRJSON module', function(t){
  t.plan(1);

  var json = 'test/data/t.json';
  var stats = streamStats('splitOGR',{store:1});

  fs.createReadStream(json)
    .pipe(splitOGRJSON())
    .pipe(stats)
    .sink();

  stats.on('end', function(){
    var result = stats.getResult();
    var validJSON = 1;
    result.chunks.forEach(function(v){
      try{
        JSON.parse(v.chunk.toString())
      }catch(e){
        validJSON = 0;
      }
    });
    t.ok(validJSON, 'splitOGRJSON yields valid JSON chunks');
  })
});

test('makeBulkSeparator module', function(t){
  t.plan(3);
  var sep = makeBulkSeparator('ind','typ');
  var sepObj = JSON.parse(sep.slice(0,sep.length-1));
  var expectedSep = {index:{_index:'ind',_type:'typ'}}
  t.deepEqual(sepObj, expectedSep, 'Bulk separator on standard input');

  var mtSep = makeBulkSeparator();
  var mtObj = JSON.parse(mtSep.slice(0,mtSep.length-1));
  var expectedMT = {index:{}};
  t.deepEqual(mtObj, expectedMT, 'Bulk separator on empty input');

  try{
    makeBulkSeparator(null, 'failing');
  }catch(e){
    t.pass('Bulk separator with a type and no index fails');
  }
});

test('formatAddress module', function(t){
  t.plan(2);

  var add1 = '123 fake st. San Francisco, CA, 12345';
  var add2 = '221B Baker St. Arg, AZ, 67876';

  t.equal(formatAddress('123 fake st.', 'San Francisco', 'CA', 12345), add1, 'Standard format')
  t.equal(formatAddress('  221B Baker St.', 'Arg  ', 'AZ', '67876'), add2, 'Trim strings');
});

test('esLoader module', function(t){
  t.plan(2);
  try{
    esLoader.connect();
  }catch(e){
    t.pass('Connect fails without host/port')
  }
  t.ok(isStream.isWritable(esLoader.load()),'esLoader.load returns a write stream');
});

test('transformerTemplate module', function(t){
  t.plan(5);
  var trans = transformerTemplate('123 fake st.','Springfield','Oregon',19992);

  t.equal(typeof trans, 'function', 'template returns a function');
  t.ok(isStream.isDuplex(trans()), 'The produced transformer generates a transform stream');

  var stats = streamStats('transTemplate',{store:1});

  var preSufTest = trans('start','finish');

  preSufTest.pipe(stats).sink();
  stats.on('end',function(){
    var result = stats.getResult();
    var output = result.chunks[0].chunk.toString();
    t.ok(/^start/.match(output), 'prefix applied properly');
    t.ok(/finish$/.match(output), 'suffix applied properly');
  });
  preSufTest.end('{}')

  try{
    transformerTemplate();
  }catch(e){
    t.pass('Calling the template without all arguments throws an error');
  }
});

/*test('Transformers', function(t){

  fs.readdir('transformers/',function(err,transformers){
    t.plan(transformers.length);

    var sample = 'test/data/sample.json';
    var bulkMatch = {index:{_index:'address',_type:'point'}}
    var bulkMetadata =  makeBulkSeparator('address', 'point');

    transformers.forEach(function(transFile){
      var transformer = require(path.join('transformers', transFile));
      var stats = streamStats(transFile, {store:1});

      fs.createReadStream()
        .pipe(splitOGRJSON())
        .pipe(transformer(bulkMetadata, '\n'))
        .pipe(stats)
        .sink();

      stats.once('end', function(){
        var result = stats.getResult();
        var output = result.chunks[0].chunk.toString().split('\n')
      });
    });

  });

});*/
<|endoftext|>


<commit_before><commit_msg>Revert "When used on resource there are no button settings, so it needs check"<commit_after><|endoftext|>


<commit_before>var assert = require('chai').assert;
var happen = require('happen');
var Vue = require('vue');
var insertCss = require('insert-css');
var $ = require('jquery');
var browser = require('bowser').browser;
var autoprefixer = require('autoprefixer-core');

var View = require('../src/index');

function wait(done) {
    Vue.nextTick(function() {
        done();
    });
}

describe('view', function() {
    before(function () {
        insertCss(autoprefixer.process('* {transition: none !important;}').css);
    });

    var view, $el;
    beforeEach(function(done) {
        view = new View({visible: true});
        $el = $(view.el);
        wait(done);
    });
    afterEach(function() {
        view.destroy();
    });

    describe('widget initialization', function() {
        it('should render widget into root element', function() {
            assert.equal($(document.body).find('.nps-Survey').length, 1);
        });
        it('should be visible', function() {
            assert.isTrue(view.visible);
        });
        it('should show first screen', function() {
            assert.match($el.text(), /How likely are you to recommend/);
        });
        it('should display powered by message', function() {
            assert.match($el.text(), /Powered by/);
        });
    });

    describe('not powered by', function() {
        it('should not display powered by message', function(done) {
            view.poweredBy = false;
            wait(function() {
                assert.notMatch($(view.el).text(), /Powered by/);
                done();
            });
        });
    });

    describe('rating screen', function() {
        it('should not display submit', function() {
            assert.lengthOf($el.find('.nps-Survey-submit'), 0);
        });
        it('should move to next step', function(done) {
            happen.click($el.find('.nps-Scale .nps-Scale-value')[5]);

            wait(function() {
                assert.equal(view.state, 'feedback');
                done();
            });
        });
        it('should not display feedback form', function() {
            assert.lengthOf($el.find('.nps-Feedback-textContainer'), 0);
        });
        it('should close window', function(done) {
            happen.click($el.find('.nps-Dialog-close')[0]);
            wait(function() {
                assert.isFalse(view.visible);
                done();
            });
        });
        it('should submit correct rating', function() {
            happen.click($el.find('.nps-Scale .nps-Scale-value')[5]);
            assert.equal(view.rating, 5);
        });
        it('should emit dismiss event', function(done) {
            var called = false;
            view.on('dismiss', function() {
                called = true;
            });
            happen.click($el.find('.nps-Dialog-close')[0]);
            wait(function() {
                assert.isTrue(called);
                done();
            });
        });
    });

    describe('feedback screen', function() {
        beforeEach(function(done) {
            happen.click($el.find('.nps-Scale .nps-Scale-value')[5]);
            wait(done);
        });
        it('should display button', function() {
            assert.equal($el.find('.nps-Survey-submit').length, 1);
        });
        it('should show feedback form', function() {
            assert.lengthOf($el.find('.nps-Feedback-text'), 1);
        });
        it('should close window', function(done) {
            happen.click($el.find('.nps-Dialog-close')[0]);
            wait(function() {
                assert.isFalse(view.visible);
                done();
            });
        });
        it('should emit dismiss event', function(done) {
            var called = false;
            view.on('dismiss', function() {
                called = true;
            });
            happen.click($el.find('.nps-Dialog-close')[0]);
            wait(function() {
                assert.isTrue(called);
                done();
            });
        });
        it('should emit submit event', function(done) {
            happen.click($el.find('.nps-Scale .nps-Scale-value')[5]);

            var called = false;
            view.on('submit', function() {
                called = true;
            });

            wait(function() {
                happen.click($el.find('.nps-Survey-submit')[0]);
                wait(function() {
                    assert.isTrue(called);
                    done();
                });
            });
        });
    });

    describe('written feedback', function() {
        beforeEach(function(done) {
            view.rating = 10;
            view.state = 'feedback';
            wait(done);
        });

        it('should submit empty feedback', function(done) {
            var called = false;
            view.on('submit', function() {
                called = true;
            });
            wait(function() {
                happen.click($el.find('.nps-Survey-submit')[0]);
                wait(function() {
                    assert.isTrue(called);
                    assert.equal(view.feedback, '');
                    done();
                });
            });
        });

        it('should set feedback', function(done) {
            $el.find('.nps-Feedback-text').val('Rubish');
            happen.once($el.find('.nps-Feedback-text')[0], {type: 'input'});
            wait(function() {
                assert.equal(view.feedback, 'Rubish');
                done();
            });
        });

        if (!browser.msie || browser.version >= 10) {
            it('should not set placeholder by default', function() {
                var placeholder = $el.find('.nps-Feedback-text').attr('placeholder');
                assert.isUndefined(placeholder);
            });
        }

        it('should go to thanks screen', function(done) {
            $el.find('.nps-Feedback-text').val('Rubish');
            happen.keyup($el.find('.nps-Feedback-text')[0]);
            wait(function() {
                happen.click($el.find('.nps-Survey-submit')[0]);
                wait(function() {
                    assert.match($el.text(),
                        /Thank you for your feedback/);
                    done();
                });
            });
        });
        it('should close window on submit', function(done) {
            happen.click($el.find('.nps-Survey-submit')[0]);
            setTimeout(function() {
                assert.isFalse(view.visible);
                done();
            }, 800 /* wait */ + 500 /* animation */ + 100 /* buffer */);
        });
    });

    describe('thanks screen', function() {
        beforeEach(function(done) {
            view.state = 'thanks';
            wait(done);
        });
        it('should display thanks message', function() {
            assert.match($el.text(), /Thank you/);
        });
    });

    describe('filled screen', function() {
        beforeEach(function(done) {
            view.state = 'filled';
            wait(done);
        });
        it('should display filled message', function() {
            assert.match($el.text(), /filled the survey/);
        });
    });

    describe('translations', function() {
        it('should use en as default', function() {
            assert.match($(view.el).text(), /How likely/);
        });
        it('should translate to cs', function(done) {
            view.language = 'cs';
            wait(function() {
                assert.match($(view.el).text(), /Doporučili byste/);
                done();
            });
        });
        it('should handle cz alias', function(done) {
            view.language = 'cz';
            wait(function() {
                assert.match($(view.el).text(), /Doporučili byste/);
                done();
            });
        });
        it('should handle invalid language', function(done) {
            view.language = 'xx';
            wait(function() {
                assert.match($(view.el).text(), /How likely/);
                done();
            });
        });
    });

    describe('positioning', function() {
        it('should use tr as default', function() {
            assert.equal(view.position, 'cr');
        });
    });

    describe('custom translation', function() {
        if (!browser.msie || browser.version >= 10) {
            it('should show custom placeholder', function(done) {
                view.translation = {
                    DETAILS: 'What the fuck?'
                };
                view.rating = 10;
                view.state = 'feedback';
                wait(function() {
                    assert.equal($el.find('.nps-Feedback-text').attr('placeholder'), 'What the fuck?');
                    done();
                });
            });
        }

        it('should show custom message', function(done) {
            view.translation = {
                HOW_LIKELY: 'Doporucil bys vole?'
            };
            wait(function() {
                assert.match($el.text(), /Doporucil bys vole?/);
                done();
            });
        });

        it('should handle null', function(done) {
            view.translation = null;
            view.rating = 10;
            wait(function() {
                assert.match($(view.el).text(), /How likely/);
                done();
            });
        });

        it('should handle undefined', function(done) {
            view.translation = undefined;
            view.rating = 10;
            wait(function() {
                assert.match($(view.el).text(), /How likely/);
                done();
            });
        });

        if (!browser.msie || browser.version >= 10) {
            describe.skip('conditional followup', function() {
                // Conditional followup not used any more.
                // Keeping test in case we re-introduce the functionality
                // in more general sense.
                beforeEach(function() {
                    view.translation = {
                        FOLLOWUP_DETRACTOR: 'Proc?',
                        FOLLOWUP_PASSIVE: 'Co muzeme zlepsit?',
                        FOLLOWUP_PROMOTER: 'Co muzeme zhorsit?'
                    };
                });
                it('should show detractor followup', function(done) {
                    view.rating = 0;
                    wait(function() {
                        assert.equal($el.find('.nps-Feedback-text').attr('placeholder'), 'Proc?');
                        done();
                    });
                });
                it('should show passive followup', function(done) {
                    view.rating = 7;
                    wait(function() {
                        assert.equal($el.find('.nps-Feedback-text').attr('placeholder'), 'Co muzeme zlepsit?');
                        done();
                    });
                });
                it('should show promoter followup', function(done) {
                    view.rating = 10;
                    wait(function() {
                        assert.equal($el.find('.nps-Feedback-text').attr('placeholder'), 'Co muzeme zhorsit?');
                        done();
                    });
                });
            });
        }
    });

    describe('service name', function() {
        it('should show default service name', function() {
            assert.include($el.text(), 'How likely are you to recommend us to your friends and colleagues?');
            assert.include($el.html(), 'How likely are you to recommend us to your friends and colleagues?');
        });
        it('should show custom service name', function(done) {
            view.serviceName = 'Google';
            wait(function () {
                assert.include($el.text(), 'How likely are you to recommend Google to your friends and colleagues?');
                assert.include($el.html(), 'How likely are you to recommend <b>Google</b> to your friends and colleagues?');
                done();
            });
        });
        it('should handle empty space', function(done) {
            view.serviceName = '';
            wait(function () {
                assert.include($el.text(), 'How likely are you to recommend us to your friends and colleagues?');
                done();
            });
        });
        it('should trim to empty space', function(done) {
            view.serviceName = ' ';
            wait(function () {
                assert.include($el.text(), 'How likely are you to recommend us to your friends and colleagues?');
                done();
            });
        });
        it('should escape service name', function(done) {
            view.serviceName = '<script>alert("aaa")</script>';
            wait(function () {
                assert.include($el.text(), '<script>alert("aaa")</script>');
                done();
            });
        });
    });

});
<commit_msg>remove redundant select rating<commit_after>var assert = require('chai').assert;
var happen = require('happen');
var Vue = require('vue');
var insertCss = require('insert-css');
var $ = require('jquery');
var browser = require('bowser').browser;
var autoprefixer = require('autoprefixer-core');

var View = require('../src/index');

function wait(done) {
    Vue.nextTick(function() {
        done();
    });
}

describe('view', function() {
    before(function () {
        insertCss(autoprefixer.process('* {transition: none !important;}').css);
    });

    var view, $el;
    beforeEach(function(done) {
        view = new View({visible: true});
        $el = $(view.el);
        wait(done);
    });
    afterEach(function() {
        view.destroy();
    });

    describe('widget initialization', function() {
        it('should render widget into root element', function() {
            assert.equal($(document.body).find('.nps-Survey').length, 1);
        });
        it('should be visible', function() {
            assert.isTrue(view.visible);
        });
        it('should show first screen', function() {
            assert.match($el.text(), /How likely are you to recommend/);
        });
        it('should display powered by message', function() {
            assert.match($el.text(), /Powered by/);
        });
    });

    describe('not powered by', function() {
        it('should not display powered by message', function(done) {
            view.poweredBy = false;
            wait(function() {
                assert.notMatch($(view.el).text(), /Powered by/);
                done();
            });
        });
    });

    describe('rating screen', function() {
        it('should not display submit', function() {
            assert.lengthOf($el.find('.nps-Survey-submit'), 0);
        });
        it('should move to next step', function(done) {
            happen.click($el.find('.nps-Scale .nps-Scale-value')[5]);

            wait(function() {
                assert.equal(view.state, 'feedback');
                done();
            });
        });
        it('should not display feedback form', function() {
            assert.lengthOf($el.find('.nps-Feedback-textContainer'), 0);
        });
        it('should close window', function(done) {
            happen.click($el.find('.nps-Dialog-close')[0]);
            wait(function() {
                assert.isFalse(view.visible);
                done();
            });
        });
        it('should submit correct rating', function() {
            happen.click($el.find('.nps-Scale .nps-Scale-value')[5]);
            assert.equal(view.rating, 5);
        });
        it('should emit dismiss event', function(done) {
            var called = false;
            view.on('dismiss', function() {
                called = true;
            });
            happen.click($el.find('.nps-Dialog-close')[0]);
            wait(function() {
                assert.isTrue(called);
                done();
            });
        });
    });

    describe('feedback screen', function() {
        beforeEach(function(done) {
            happen.click($el.find('.nps-Scale .nps-Scale-value')[5]);
            wait(done);
        });
        it('should display button', function() {
            assert.equal($el.find('.nps-Survey-submit').length, 1);
        });
        it('should show feedback form', function() {
            assert.lengthOf($el.find('.nps-Feedback-text'), 1);
        });
        it('should close window', function(done) {
            happen.click($el.find('.nps-Dialog-close')[0]);
            wait(function() {
                assert.isFalse(view.visible);
                done();
            });
        });
        it('should emit dismiss event', function(done) {
            var called = false;
            view.on('dismiss', function() {
                called = true;
            });
            happen.click($el.find('.nps-Dialog-close')[0]);
            wait(function() {
                assert.isTrue(called);
                done();
            });
        });
        it('should emit submit event', function(done) {
            var called = false;
            view.on('submit', function() {
                called = true;
            });

            happen.click($el.find('.nps-Survey-submit')[0]);
            wait(function() {
                assert.isTrue(called);
                done();
            });
        });
    });

    describe('written feedback', function() {
        beforeEach(function(done) {
            view.rating = 10;
            view.state = 'feedback';
            wait(done);
        });

        it('should submit empty feedback', function(done) {
            var called = false;
            view.on('submit', function() {
                called = true;
            });
            wait(function() {
                happen.click($el.find('.nps-Survey-submit')[0]);
                wait(function() {
                    assert.isTrue(called);
                    assert.equal(view.feedback, '');
                    done();
                });
            });
        });

        it('should set feedback', function(done) {
            $el.find('.nps-Feedback-text').val('Rubish');
            happen.once($el.find('.nps-Feedback-text')[0], {type: 'input'});
            wait(function() {
                assert.equal(view.feedback, 'Rubish');
                done();
            });
        });

        if (!browser.msie || browser.version >= 10) {
            it('should not set placeholder by default', function() {
                var placeholder = $el.find('.nps-Feedback-text').attr('placeholder');
                assert.isUndefined(placeholder);
            });
        }

        it('should go to thanks screen', function(done) {
            $el.find('.nps-Feedback-text').val('Rubish');
            happen.keyup($el.find('.nps-Feedback-text')[0]);
            wait(function() {
                happen.click($el.find('.nps-Survey-submit')[0]);
                wait(function() {
                    assert.match($el.text(),
                        /Thank you for your feedback/);
                    done();
                });
            });
        });
        it('should close window on submit', function(done) {
            happen.click($el.find('.nps-Survey-submit')[0]);
            setTimeout(function() {
                assert.isFalse(view.visible);
                done();
            }, 800 /* wait */ + 500 /* animation */ + 100 /* buffer */);
        });
    });

    describe('thanks screen', function() {
        beforeEach(function(done) {
            view.state = 'thanks';
            wait(done);
        });
        it('should display thanks message', function() {
            assert.match($el.text(), /Thank you/);
        });
    });

    describe('filled screen', function() {
        beforeEach(function(done) {
            view.state = 'filled';
            wait(done);
        });
        it('should display filled message', function() {
            assert.match($el.text(), /filled the survey/);
        });
    });

    describe('translations', function() {
        it('should use en as default', function() {
            assert.match($(view.el).text(), /How likely/);
        });
        it('should translate to cs', function(done) {
            view.language = 'cs';
            wait(function() {
                assert.match($(view.el).text(), /Doporučili byste/);
                done();
            });
        });
        it('should handle cz alias', function(done) {
            view.language = 'cz';
            wait(function() {
                assert.match($(view.el).text(), /Doporučili byste/);
                done();
            });
        });
        it('should handle invalid language', function(done) {
            view.language = 'xx';
            wait(function() {
                assert.match($(view.el).text(), /How likely/);
                done();
            });
        });
    });

    describe('positioning', function() {
        it('should use tr as default', function() {
            assert.equal(view.position, 'cr');
        });
    });

    describe('custom translation', function() {
        if (!browser.msie || browser.version >= 10) {
            it('should show custom placeholder', function(done) {
                view.translation = {
                    DETAILS: 'What the fuck?'
                };
                view.rating = 10;
                view.state = 'feedback';
                wait(function() {
                    assert.equal($el.find('.nps-Feedback-text').attr('placeholder'), 'What the fuck?');
                    done();
                });
            });
        }

        it('should show custom message', function(done) {
            view.translation = {
                HOW_LIKELY: 'Doporucil bys vole?'
            };
            wait(function() {
                assert.match($el.text(), /Doporucil bys vole?/);
                done();
            });
        });

        it('should handle null', function(done) {
            view.translation = null;
            view.rating = 10;
            wait(function() {
                assert.match($(view.el).text(), /How likely/);
                done();
            });
        });

        it('should handle undefined', function(done) {
            view.translation = undefined;
            view.rating = 10;
            wait(function() {
                assert.match($(view.el).text(), /How likely/);
                done();
            });
        });

        if (!browser.msie || browser.version >= 10) {
            describe.skip('conditional followup', function() {
                // Conditional followup not used any more.
                // Keeping test in case we re-introduce the functionality
                // in more general sense.
                beforeEach(function() {
                    view.translation = {
                        FOLLOWUP_DETRACTOR: 'Proc?',
                        FOLLOWUP_PASSIVE: 'Co muzeme zlepsit?',
                        FOLLOWUP_PROMOTER: 'Co muzeme zhorsit?'
                    };
                });
                it('should show detractor followup', function(done) {
                    view.rating = 0;
                    wait(function() {
                        assert.equal($el.find('.nps-Feedback-text').attr('placeholder'), 'Proc?');
                        done();
                    });
                });
                it('should show passive followup', function(done) {
                    view.rating = 7;
                    wait(function() {
                        assert.equal($el.find('.nps-Feedback-text').attr('placeholder'), 'Co muzeme zlepsit?');
                        done();
                    });
                });
                it('should show promoter followup', function(done) {
                    view.rating = 10;
                    wait(function() {
                        assert.equal($el.find('.nps-Feedback-text').attr('placeholder'), 'Co muzeme zhorsit?');
                        done();
                    });
                });
            });
        }
    });

    describe('service name', function() {
        it('should show default service name', function() {
            assert.include($el.text(), 'How likely are you to recommend us to your friends and colleagues?');
            assert.include($el.html(), 'How likely are you to recommend us to your friends and colleagues?');
        });
        it('should show custom service name', function(done) {
            view.serviceName = 'Google';
            wait(function () {
                assert.include($el.text(), 'How likely are you to recommend Google to your friends and colleagues?');
                assert.include($el.html(), 'How likely are you to recommend <b>Google</b> to your friends and colleagues?');
                done();
            });
        });
        it('should handle empty space', function(done) {
            view.serviceName = '';
            wait(function () {
                assert.include($el.text(), 'How likely are you to recommend us to your friends and colleagues?');
                done();
            });
        });
        it('should trim to empty space', function(done) {
            view.serviceName = ' ';
            wait(function () {
                assert.include($el.text(), 'How likely are you to recommend us to your friends and colleagues?');
                done();
            });
        });
        it('should escape service name', function(done) {
            view.serviceName = '<script>alert("aaa")</script>';
            wait(function () {
                assert.include($el.text(), '<script>alert("aaa")</script>');
                done();
            });
        });
    });

});
<|endoftext|>


<commit_before>/* global require, describe, it */
'use strict';

// MODULES //

var matrix = require( 'dstructs-matrix' );

var // Expectation library:
	chai = require( 'chai' ),

	// Module to be tested:
	isEven = require( './../lib' );

// VARIABLES //

var expect = chai.expect,
	assert = chai.assert;

// TESTS //

describe( 'compute-iseven', function tests() {

	it( 'should throw an error if provided an invalid input type', function test() {
		var values = [
				'5',
				{},
				true,
				null,
				undefined,
				NaN,
				function(){}
			];

		for ( var i = 0; i < values.length; i++ ) {
			expect( badValue( values[i] ) ).to.throw( TypeError );
		}

		function badValue( value ) {
			return function() {
				isEven( value );
			};
		}
	});

	it( 'should export a function', function test() {
		expect( isEven ).to.be.a( 'function' );
	});

	it( 'should throw an error if `options` is not an object', function test() {
		var values = [
			'5',
			5,
			true,
			undefined,
			null,
			NaN,
			[],
			function(){}
		];

		for ( var i = 0; i < values.length; i++ ) {
			expect( badValue( values[ i ] ) ).to.throw( TypeError );
		}

		function badValue( value ) {
			return function() {
				isEven( [1,2,3,4,5], value );
			};
		}
	});

	it( 'should throw an error if provided an accessor which is not a function', function test() {
		var values = [
			'5',
			5,
			true,
			undefined,
			null,
			NaN,
			[],
			{}
		];

		for ( var i = 0; i < values.length; i++ ) {
			expect( badValue( values[ i ] ) ).to.throw( TypeError );
		}

		function badValue( value ) {
			return function() {
				isEven( [1,2,3,4,5], {'accessor': value} );
			};
		}
	});

	it( 'should throw an error if provided a copy option which is not a boolean', function test() {
		var values = [
			'5',
			5,
			function(){},
			undefined,
			null,
			NaN,
			[],
			{}
		];

		for ( var i = 0; i < values.length; i++ ) {
			expect( badValue( values[ i ] ) ).to.throw( TypeError );
		}

		function badValue( value ) {
			return function() {
				isEven( [1,2,3,4,5], {'copy': value} );
			};
		}
	});

	it( 'should check whether a single number is even', function test() {

		assert.ok( isEven( 2 ) === 1 );
		assert.ok( isEven( 3 ) === 0 );

	});

	it( 'should check whether elements in array are even numbers', function test() {
		var data, expected, results;

		data = [ 2, 4, 5, 3, 8, 2 ];
		expected = [ 1, 1, 0, 0, 1, 1 ];

		results = isEven( data );

		assert.strictEqual( results.length, expected.length );
		assert.deepEqual( results, expected );
	});

	it( 'should check whether elements in a matrix are even numbers', function test() {
		var data, expected, results;

		data = matrix( new Int8Array( [ 2, 4, 5, 3] ), [2,2] );
		results = isEven( data );

		expected = '1,1;0,0';

		assert.strictEqual( results.toString(), expected );
	});

	it( 'should check whether elements in array are even numbers using an accessor', function test() {
		var data, expected, actual;

		data = [
			{'x':2},
			{'x':4},
			{'x':5},
			{'x':3},
			{'x':8},
			{'x':2}
		];

		actual = isEven( data, {'accessor': getValue} );
		expected = [ 1, 1, 0, 0, 1, 1 ];

		assert.deepEqual( actual, expected );

		function getValue( d ) {
			return d.x;
		}
	});

	it( 'should check whether elements in array are even and mutate the input array', function test() {
		var data, expected, results;

		data = [ 2, 4, 5, 3, 8, 2 ];
		expected = [ 1, 1, 0, 0, 1, 1 ];

		results = isEven( data, {'copy': false} );

		assert.strictEqual( results.length, expected.length );
		assert.deepEqual( results, expected );
		assert.ok( results === data );
	});

	it( 'should check whether elements in a matrix are even and mutate the input array', function test() {
		var data, expected, results;

		data = matrix( new Int8Array( [ 2, 4, 5, 3] ), [2,2] );
		expected = matrix( new Int8Array( [1, 1, 0, 0] ), [2,2] );

		results = isEven( data, {'copy': false} );

		assert.strictEqual( results.length, expected.length );
		assert.deepEqual( results, expected );
		assert.ok( results === data );
	});

	it( 'should check whether elements in array are even using an accessor and mutate the input array', function test() {
		var data, expected, actual;

		data = [
			{'x':2},
			{'x':4},
			{'x':5},
			{'x':3},
			{'x':8},
			{'x':2}
		];

		actual = isEven( data, {'accessor': getValue, 'copy':false} );
		expected = [ 1, 1, 0, 0, 1, 1 ];
		assert.ok( actual === data );

		assert.deepEqual( actual, expected );

		function getValue( d ) {
			return d.x;
		}
	});

	it( 'should return null if provided an empty array', function test() {
		assert.isNull( isEven( [] ) );
	});

});
<commit_msg>[FIX] change test since strings are array-like<commit_after>/* global require, describe, it */
'use strict';

// MODULES //

var matrix = require( 'dstructs-matrix' );

var // Expectation library:
	chai = require( 'chai' ),

	// Module to be tested:
	isEven = require( './../lib' );

// VARIABLES //

var expect = chai.expect,
	assert = chai.assert;

// TESTS //

describe( 'compute-iseven', function tests() {

	it( 'should throw an error if provided an invalid input type', function test() {
		var values = [
				// '5', // Strings are Array-like
				{},
				true,
				null,
				undefined,
				NaN,
				function(){}
			];

		for ( var i = 0; i < values.length; i++ ) {
			expect( badValue( values[i] ) ).to.throw( TypeError );
		}

		function badValue( value ) {
			return function() {
				isEven( value );
			};
		}
	});

	it( 'should export a function', function test() {
		expect( isEven ).to.be.a( 'function' );
	});

	it( 'should throw an error if `options` is not an object', function test() {
		var values = [
			'5',
			5,
			true,
			undefined,
			null,
			NaN,
			[],
			function(){}
		];

		for ( var i = 0; i < values.length; i++ ) {
			expect( badValue( values[ i ] ) ).to.throw( TypeError );
		}

		function badValue( value ) {
			return function() {
				isEven( [1,2,3,4,5], value );
			};
		}
	});

	it( 'should throw an error if provided an accessor which is not a function', function test() {
		var values = [
			'5',
			5,
			true,
			undefined,
			null,
			NaN,
			[],
			{}
		];

		for ( var i = 0; i < values.length; i++ ) {
			expect( badValue( values[ i ] ) ).to.throw( TypeError );
		}

		function badValue( value ) {
			return function() {
				isEven( [1,2,3,4,5], {'accessor': value} );
			};
		}
	});

	it( 'should throw an error if provided a copy option which is not a boolean', function test() {
		var values = [
			'5',
			5,
			function(){},
			undefined,
			null,
			NaN,
			[],
			{}
		];

		for ( var i = 0; i < values.length; i++ ) {
			expect( badValue( values[ i ] ) ).to.throw( TypeError );
		}

		function badValue( value ) {
			return function() {
				isEven( [1,2,3,4,5], {'copy': value} );
			};
		}
	});

	it( 'should check whether a single number is even', function test() {

		assert.ok( isEven( 2 ) === 1 );
		assert.ok( isEven( 3 ) === 0 );

	});

	it( 'should check whether elements in array are even numbers', function test() {
		var data, expected, results;

		data = [ 2, 4, 5, 3, 8, 2 ];
		expected = [ 1, 1, 0, 0, 1, 1 ];

		results = isEven( data );

		assert.strictEqual( results.length, expected.length );
		assert.deepEqual( results, expected );
	});

	it( 'should check whether elements in a matrix are even numbers', function test() {
		var data, expected, results;

		data = matrix( new Int8Array( [ 2, 4, 5, 3] ), [2,2] );
		results = isEven( data );

		expected = '1,1;0,0';

		assert.strictEqual( results.toString(), expected );
	});

	it( 'should check whether elements in array are even numbers using an accessor', function test() {
		var data, expected, actual;

		data = [
			{'x':2},
			{'x':4},
			{'x':5},
			{'x':3},
			{'x':8},
			{'x':2}
		];

		actual = isEven( data, {'accessor': getValue} );
		expected = [ 1, 1, 0, 0, 1, 1 ];

		assert.deepEqual( actual, expected );

		function getValue( d ) {
			return d.x;
		}
	});

	it( 'should check whether elements in array are even and mutate the input array', function test() {
		var data, expected, results;

		data = [ 2, 4, 5, 3, 8, 2 ];
		expected = [ 1, 1, 0, 0, 1, 1 ];

		results = isEven( data, {'copy': false} );

		assert.strictEqual( results.length, expected.length );
		assert.deepEqual( results, expected );
		assert.ok( results === data );
	});

	it( 'should check whether elements in a matrix are even and mutate the input array', function test() {
		var data, expected, results;

		data = matrix( new Int8Array( [ 2, 4, 5, 3] ), [2,2] );
		expected = matrix( new Int8Array( [1, 1, 0, 0] ), [2,2] );

		results = isEven( data, {'copy': false} );

		assert.strictEqual( results.length, expected.length );
		assert.deepEqual( results, expected );
		assert.ok( results === data );
	});

	it( 'should check whether elements in array are even using an accessor and mutate the input array', function test() {
		var data, expected, actual;

		data = [
			{'x':2},
			{'x':4},
			{'x':5},
			{'x':3},
			{'x':8},
			{'x':2}
		];

		actual = isEven( data, {'accessor': getValue, 'copy':false} );
		expected = [ 1, 1, 0, 0, 1, 1 ];
		assert.ok( actual === data );

		assert.deepEqual( actual, expected );

		function getValue( d ) {
			return d.x;
		}
	});

	it( 'should return null if provided an empty array', function test() {
		assert.isNull( isEven( [] ) );
	});

});
<|endoftext|>


<commit_before>/**
 * @file Th component
 * @author liangxiaojun(liangxiaojun@derbysoft.com)
 */

import React, {Component} from 'react';
import PropTypes from 'prop-types';
import classNames from 'classnames';

import ThSortIcon from '../_ThSortingIcon';

import HorizontalAlign from '../_statics/HorizontalAlign';
import SortingType from '../_statics/SortingType';

import Util from '../_vendors/Util';

class Th extends Component {

    static Align = HorizontalAlign;
    static SortingType = SortingType;

    constructor(props, ...restArgs) {
        super(props, ...restArgs);
    }

    /**
     * handle th content render
     * @returns {*}
     */
    handleRender = () => {

        const {colIndex, data, renderer} = this.props;

        switch (typeof renderer) {
            case 'function':
                return renderer(data, colIndex);
            default:
                return renderer;
        }

    };

    /**
     * handle th click and trigger sorting callback
     */
    handleClick = () => {

        const {sortable, onSortChange} = this.props;

        if (!sortable || !onSortChange) {
            return;
        }

        const {sorting, defaultSortingType, sortingProp} = this.props,
            result = {};

        if (sorting && sorting.prop === sortingProp) {
            result.prop = sorting.prop;
            if (!sorting.type) {
                result.type = defaultSortingType;
            } else if (sorting.type === defaultSortingType) {
                result.type = -defaultSortingType;
            } else {
                result.type = SortingType.DEFAULT;
            }
        } else {
            result.prop = sortingProp;
            result.type = defaultSortingType;
        }

        onSortChange && onSortChange(result);

    };

    render() {

        const {
            className, style, renderer, align, rowSpan, colSpan, noWrap,
            sortable, sortingProp, sorting, sortingAscIconCls, sortingDescIconCls
        } = this.props;

        return (
            <th className={classNames({
                [`align-${align}`]: align && align !== HorizontalAlign.LEFT,
                sortable: sortable,
                sorting: sortable && sortingProp && sorting && sorting.prop && sorting.prop === sortingProp,
                'no-wrap': sortable || noWrap,
                [className]: className
            })}
                style={style}
                title={typeof renderer === 'string' ? renderer : null}
                rowSpan={rowSpan}
                colSpan={colSpan}
                onClick={this.handleClick}>

                        {this.handleRender()}

                    {
                        sortable ?
                            <ThSortIcon sorting={sorting}
                                        sortingProp={sortingProp}
                                        sortingAscIconCls={sortingAscIconCls}
                                        sortingDescIconCls={sortingDescIconCls}/>
                            :
                            null
                    }

        );

    }
}

Th.propTypes = {

    className: PropTypes.string,
    style: PropTypes.object,

    renderer: PropTypes.oneOfType([PropTypes.string, PropTypes.func]),
    align: PropTypes.oneOf(Util.enumerateValue(HorizontalAlign)),
    colIndex: PropTypes.number,
    data: PropTypes.array,
    noWrap: PropTypes.bool,
    rowSpan: PropTypes.number,
    colSpan: PropTypes.number,

    /**
     * sorting
     */
    sorting: PropTypes.shape({
        prop: PropTypes.string,
        type: PropTypes.oneOf(Util.enumerateValue(SortingType))
    }),
    defaultSortingType: PropTypes.oneOf(Util.enumerateValue(SortingType)),
    sortingAscIconCls: PropTypes.string,
    sortingDescIconCls: PropTypes.string,
    sortable: PropTypes.bool,
    sortingProp: PropTypes.string,

    onSortChange: PropTypes.func

};

Th.defaultProps = {

    colIndex: 0,

    noWrap: false,

    defaultSortingType: SortingType.ASC,
    sortingAscIconCls: 'fas fa-sort-up',
    sortingDescIconCls: 'fas fa-sort-down',
    sortable: false

};

export default Th;
<commit_msg>update Th<commit_after>/**
 * @file Th component
 * @author liangxiaojun(liangxiaojun@derbysoft.com)
 */

import React, {Component} from 'react';
import PropTypes from 'prop-types';
import classNames from 'classnames';

import ThSortIcon from '../_ThSortingIcon';

import HorizontalAlign from '../_statics/HorizontalAlign';
import SortingType from '../_statics/SortingType';

import Util from '../_vendors/Util';

class Th extends Component {

    static Align = HorizontalAlign;
    static SortingType = SortingType;

    constructor(props, ...restArgs) {
        super(props, ...restArgs);
    }

    /**
     * handle th content render
     * @returns {*}
     */
    handleRender = () => {

        const {colIndex, data, renderer} = this.props;

        switch (typeof renderer) {
            case 'function':
                return renderer(data, colIndex);
            default:
                return renderer;
        }

    };

    /**
     * handle th click and trigger sorting callback
     */
    handleClick = () => {

        const {sortable, onSortChange} = this.props;

        if (!sortable || !onSortChange) {
            return;
        }

        const {sorting, defaultSortingType, sortingProp} = this.props;
        let result = {};

        if (sorting && sorting.prop === sortingProp) {
            result.prop = sorting.prop;
            if (!sorting.type) {
                result.type = defaultSortingType;
            } else if (sorting.type === defaultSortingType) {
                result.type = -defaultSortingType;
            } else {
                result = null;
            }
        } else {
            result.prop = sortingProp;
            result.type = defaultSortingType;
        }

        onSortChange && onSortChange(result);

    };

    render() {

        const {
            className, style, renderer, align, rowSpan, colSpan, noWrap,
            sortable, sortingProp, sorting, sortingAscIconCls, sortingDescIconCls
        } = this.props;

        return (
            <th className={classNames({
                [`align-${align}`]: align && align !== HorizontalAlign.LEFT,
                sortable: sortable,
                sorting: sortable && sortingProp && sorting && sorting.prop && sorting.prop === sortingProp,
                'no-wrap': sortable || noWrap,
                [className]: className
            })}
                style={style}
                title={typeof renderer === 'string' ? renderer : null}
                rowSpan={rowSpan}
                colSpan={colSpan}
                onClick={this.handleClick}>

                        {this.handleRender()}

                    {
                        sortable ?
                            <ThSortIcon sorting={sorting}
                                        sortingProp={sortingProp}
                                        sortingAscIconCls={sortingAscIconCls}
                                        sortingDescIconCls={sortingDescIconCls}/>
                            :
                            null
                    }

        );

    }
}

Th.propTypes = {

    className: PropTypes.string,
    style: PropTypes.object,

    renderer: PropTypes.oneOfType([PropTypes.string, PropTypes.func]),
    align: PropTypes.oneOf(Util.enumerateValue(HorizontalAlign)),
    colIndex: PropTypes.number,
    data: PropTypes.array,
    noWrap: PropTypes.bool,
    rowSpan: PropTypes.number,
    colSpan: PropTypes.number,

    /**
     * sorting
     */
    sorting: PropTypes.shape({
        prop: PropTypes.string,
        type: PropTypes.oneOf(Util.enumerateValue(SortingType))
    }),
    defaultSortingType: PropTypes.oneOf(Util.enumerateValue(SortingType)),
    sortingAscIconCls: PropTypes.string,
    sortingDescIconCls: PropTypes.string,
    sortable: PropTypes.bool,
    sortingProp: PropTypes.string,

    onSortChange: PropTypes.func

};

Th.defaultProps = {

    colIndex: 0,

    noWrap: false,

    defaultSortingType: SortingType.ASC,
    sortingAscIconCls: 'fas fa-sort-up',
    sortingDescIconCls: 'fas fa-sort-down',
    sortable: false

};

export default Th;
<|endoftext|>


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

it('should pass the a11y validation', function (cb) {
	var stream = axeCore();

	stream.on('data', function (results) {
		assert.equal(0, results.violation.length);

	});

	stream.on('end', cb);

	stream.write(new gutil.File({
		base: __dirname,
		path: __dirname + '/test/fixtures/working.html'
	}));

	stream.end();
});

it('should not pass the a11y validation', function (cb) {
	var stream = axeCore();

	stream.on('data', function (results) {
		assert.not.equal(0, results.violation.length);
	});

	stream.on('end', cb);

	stream.write(new gutil.File({
		base: __dirname,
		path: __dirname + '/test/fixtures/broken.html'
	}));

	stream.end();
});
<commit_msg>test(test.js): it creates buffers with the files content<commit_after>'use strict';
var assert = require('assert');
var gutil = require('gulp-util');
var axeCore = require('../');

it('should pass the a11y validation', function (cb) {
	var stream = axeCore();

	stream.on('data', function (results) {
		assert.equal(0, results.violation.length);

	});

	stream.on('end', cb);

	stream.write(new gutil.File({
		base: __dirname,
		path: __dirname + '/test/working.html',
		contents: new Buffer('
Label for this text field.<input type="text" id="has-label">
')
	}));

	stream.end();
});

it('should not pass the a11y validation', function (cb) {
	var stream = axeCore();

	stream.on('data', function (results) {
		assert.not.equal(0, results.violation.length);
	});

	stream.on('end', cb);

	stream.write(new gutil.File({
		base: __dirname,
		path: __dirname + '/test/broken.html',
		contents: new Buffer('

Not a label
<input type="text" id="no-label">
Not an alt

')
	}));

	stream.end();
});
<|endoftext|>


<commit_before>"use strict"
var test = require("tape")

var path = require("path")
var getPixels = typeof window === "undefined" ?
  require("../node-pixels.js") :
  require("../dom-pixels.js")

function test_image(t, img) {
  img = img.transpose(1, 0, 2)
  t.equals(img.shape[0], 16)
  t.equals(img.shape[1], 8)
  t.equals(img.get(0, 0, 0), 0)
  t.equals(img.get(0, 0, 1), 0)
  t.equals(img.get(0, 0, 2), 0)
  t.equals(img.get(1, 0, 0), 0xff)
  t.equals(img.get(1, 0, 1), 0)
  t.equals(img.get(1, 0, 2), 0)
  t.equals(img.get(2, 0, 0), 0xff)
  t.equals(img.get(2, 0, 1), 0xff)
  t.equals(img.get(2, 0, 2), 0)
  t.equals(img.get(3, 0, 0), 0xff)
  t.equals(img.get(3, 0, 1), 0)
  t.equals(img.get(3, 0, 2), 0xff)
  t.equals(img.get(0, 1, 0), 0)
  t.equals(img.get(0, 1, 1), 0xff)
  t.equals(img.get(0, 1, 2), 0)
  t.equals(img.get(1, 1, 0), 0)
  t.equals(img.get(1, 1, 1), 0xff)
  t.equals(img.get(1, 1, 2), 0xff)
  t.equals(img.get(0, 2, 0), 0)
  t.equals(img.get(0, 2, 1), 0)
  t.equals(img.get(0, 2, 2), 0xff)

  for(var i=4; i<8; ++i) {
    for(var j=0; j<16; ++j) {
      t.equals(img.get(j, i, 0), 0xff)
      t.equals(img.get(j, i, 1), 0xff)
      t.equals(img.get(j, i, 2), 0xff)
    }
  }
}

test("get-pixels", function(t) {
  getPixels(path.join(__dirname, "lena.png"), function(err, pixels) {
    if(err) {
      t.assert(false)
    } else {
      t.equals(pixels.shape.join(","), "512,512,4")
    }
    t.end()
  })
})

test("get-pixels-png", function(t) {
  getPixels(path.join(__dirname, "test_pattern.png"), function(err, pixels) {
    if(err) {
      t.error(err, "failed to parse png")
      t.end()
      return
    }
    test_image(t, pixels)
    t.end()
  })
})

test("get-pixels-ppm", function(t) {
  getPixels(path.join(__dirname, "test_pattern.ppm"), function(err, pixels) {
    if(err) {
      t.error(err, "failed to parse ppm")
      t.end()
      return
    }
    test_image(t, pixels)
    t.end()
  })
})

test("get-pixels-jpg", function(t) {
  //FIXME: This fails because JPEG is a lossy format
  getPixels(path.join(__dirname, "test_pattern.jpg"), function(err, pixels) {
    if(err) {
      t.error(err, "failed to parse jpg")
      t.end()
      return
    }
    test_image(t, pixels)
    t.end()
  })
})

test("get-pixels-gif", function(t) {
  getPixels(path.join(__dirname, "test_pattern.gif"), function(err, pixels) {
    if(err) {
      t.error(err, "failed to parse gif")
      t.end()
      return
    }
    test_image(t, pixels)
    t.end()
  })
})

test("get-pixels-bmp", function(t) {
  getPixels(path.join(__dirname, "test_pattern.bmp"), function(err, pixels) {
    if(err) {
      t.error(err, "failed to parse bmp")
      t.end()
      return
    }
    test_image(t, pixels)
    t.end()
  })
})<commit_msg>fix test cases for gif<commit_after>"use strict"
var test = require("tape")

var path = require("path")
var getPixels = typeof window === "undefined" ?
  require("../node-pixels.js") :
  require("../dom-pixels.js")

function test_image(t, img) {
  img = img.transpose(1, 0, 2)
  t.equals(img.shape[0], 16)
  t.equals(img.shape[1], 8)
  t.equals(img.get(0, 0, 0), 0)
  t.equals(img.get(0, 0, 1), 0)
  t.equals(img.get(0, 0, 2), 0)
  t.equals(img.get(1, 0, 0), 0xff)
  t.equals(img.get(1, 0, 1), 0)
  t.equals(img.get(1, 0, 2), 0)
  t.equals(img.get(2, 0, 0), 0xff)
  t.equals(img.get(2, 0, 1), 0xff)
  t.equals(img.get(2, 0, 2), 0)
  t.equals(img.get(3, 0, 0), 0xff)
  t.equals(img.get(3, 0, 1), 0)
  t.equals(img.get(3, 0, 2), 0xff)
  t.equals(img.get(0, 1, 0), 0)
  t.equals(img.get(0, 1, 1), 0xff)
  t.equals(img.get(0, 1, 2), 0)
  t.equals(img.get(1, 1, 0), 0)
  t.equals(img.get(1, 1, 1), 0xff)
  t.equals(img.get(1, 1, 2), 0xff)
  t.equals(img.get(0, 2, 0), 0)
  t.equals(img.get(0, 2, 1), 0)
  t.equals(img.get(0, 2, 2), 0xff)

  for(var i=4; i<8; ++i) {
    for(var j=0; j<16; ++j) {
      t.equals(img.get(j, i, 0), 0xff)
      t.equals(img.get(j, i, 1), 0xff)
      t.equals(img.get(j, i, 2), 0xff)
    }
  }
}

test("get-pixels", function(t) {
  getPixels(path.join(__dirname, "lena.png"), function(err, pixels) {
    if(err) {
      t.assert(false)
    } else {
      t.equals(pixels.shape.join(","), "512,512,4")
    }
    t.end()
  })
})

test("get-pixels-png", function(t) {
  getPixels(path.join(__dirname, "test_pattern.png"), function(err, pixels) {
    if(err) {
      t.error(err, "failed to parse png")
      t.end()
      return
    }
    test_image(t, pixels)
    t.end()
  })
})

test("get-pixels-ppm", function(t) {
  getPixels(path.join(__dirname, "test_pattern.ppm"), function(err, pixels) {
    if(err) {
      t.error(err, "failed to parse ppm")
      t.end()
      return
    }
    test_image(t, pixels)
    t.end()
  })
})

test("get-pixels-jpg", function(t) {
  //FIXME: This fails because JPEG is a lossy format
  getPixels(path.join(__dirname, "test_pattern.jpg"), function(err, pixels) {
    if(err) {
      t.error(err, "failed to parse jpg")
      t.end()
      return
    }
    test_image(t, pixels)
    t.end()
  })
})

test("get-pixels-gif", function(t) {
  getPixels(path.join(__dirname, "test_pattern.gif"), function(err, pixels) {
    if(err) {
      t.error(err, "failed to parse gif")
      t.end()
      return
    }
    test_image(t, pixels.pick(0))
    t.end()
  })
})

test("get-pixels-bmp", function(t) {
  getPixels(path.join(__dirname, "test_pattern.bmp"), function(err, pixels) {
    if(err) {
      t.error(err, "failed to parse bmp")
      t.end()
      return
    }
    test_image(t, pixels)
    t.end()
  })
})<|endoftext|>


<commit_before>/*global after, describe, it */
'use strict';

var assert = require('assert');
var fs = require('fs');
var Imagemin = require('../');
var path = require('path');
var rm = require('rimraf');

describe('Imagemin()', function () {
    after(function (cb) {
        rm(path.join(__dirname, 'tmp'), cb);
    });

    it('should optimize a GIF', function (cb) {
        var imagemin = new Imagemin();

        imagemin
            .src(path.join(__dirname, 'fixtures/test.gif'))
            .dest(path.join(__dirname, 'tmp/test.gif'))
            .use(Imagemin.gifsicle())
            .optimize(function () {
                assert(fs.statSync(imagemin.dest()).size < fs.statSync(imagemin.src()).size);
                assert(fs.statSync(imagemin.dest()).size > 0);
                cb();
            });
    });

    it('should optimize a JPG', function (cb) {
        var imagemin = new Imagemin();

        imagemin
            .src(path.join(__dirname, 'fixtures/test.jpg'))
            .dest(path.join(__dirname, 'tmp/test.jpg'))
            .use(Imagemin.jpegtran())
            .optimize(function () {
                assert(fs.statSync(imagemin.dest()).size < fs.statSync(imagemin.src()).size);
                assert(fs.statSync(imagemin.dest()).size > 0);
                cb();
            });
    });

    it('should optimize a PNG', function (cb) {
        var imagemin = new Imagemin();

        imagemin
            .src(path.join(__dirname, 'fixtures/test.png'))
            .dest(path.join(__dirname, 'tmp/test.png'))
            .use(Imagemin.optipng())
            .optimize(function () {
                assert(fs.statSync(imagemin.dest()).size < fs.statSync(imagemin.src()).size);
                assert(fs.statSync(imagemin.dest()).size > 0);
                cb();
            });
    });

    it('should optimize a SVG', function (cb) {
        var imagemin = new Imagemin();

        imagemin
            .src(path.join(__dirname, 'fixtures/test.svg'))
            .dest(path.join(__dirname, 'tmp/test.svg'))
            .use(Imagemin.svgo())
            .optimize(function () {
                assert(fs.statSync(imagemin.dest()).size < fs.statSync(imagemin.src()).size);
                assert(fs.statSync(imagemin.dest()).size > 0);
                cb();
            });
    });

    it('should optimize a image using Buffer', function (cb) {
        var buf = fs.readFileSync(path.join(__dirname, 'fixtures/test.jpg'));
        var imagemin = new Imagemin();

        imagemin
            .src(buf)
            .use(Imagemin.jpegtran())
            .optimize(function (err, file) {
                assert(file.contents.length < buf.length);
                cb();
            });
    });

    it('should output error on corrupt images', function (cb) {
        var imagemin = new Imagemin();

        imagemin
            .src(path.join(__dirname, 'fixtures/test-corrupt.jpg'))
            .dest(path.join(__dirname, 'tmp/test-corrupt.jpg'))
            .use(Imagemin.jpegtran())
            .optimize(function (err) {
                assert(err);
                cb();
            });
    });

    it('should ignore directories', function (cb) {
        var imagemin = new Imagemin();

        imagemin
            .src(path.join(__dirname, 'fixtures/test'))
            .use(Imagemin.jpegtran())
            .optimize(function (err) {
                assert(!err);
                cb();
            });
    });
});
<commit_msg>Use ava for testing<commit_after>'use strict';

var fs = require('fs');
var Imagemin = require('../');
var path = require('path');
var test = require('ava');

test('optimize a GIF', function (t) {
    t.plan(5);

    var imagemin = new Imagemin()
        .src(path.join(__dirname, 'fixtures/test.gif'))
        .dest(path.join(__dirname, 'tmp/test.gif'))
        .use(Imagemin.gifsicle());

    imagemin.optimize(function (err) {
        t.assert(!err);

        fs.stat(imagemin.dest(), function (err, a) {
            t.assert(!err);
            t.assert(a.size > 0);

            fs.stat(imagemin.src(), function (err, b) {
                t.assert(!err);
                t.assert(a.size < b.size);
            });
        });
    });
});

test('optimize a JPG', function (t) {
    t.plan(5);

    var imagemin = new Imagemin()
        .src(path.join(__dirname, 'fixtures/test.jpg'))
        .dest(path.join(__dirname, 'tmp/test.jpg'))
        .use(Imagemin.jpegtran());

    imagemin.optimize(function (err) {
        t.assert(!err);

        fs.stat(imagemin.dest(), function (err, a) {
            t.assert(!err);
            t.assert(a.size > 0);

            fs.stat(imagemin.src(), function (err, b) {
                t.assert(!err);
                t.assert(a.size < b.size);
            });
        });
    });
});

test('optimize a PNG', function (t) {
    t.plan(5);

    var imagemin = new Imagemin()
        .src(path.join(__dirname, 'fixtures/test.png'))
        .dest(path.join(__dirname, 'tmp/test.png'))
        .use(Imagemin.optipng());

    imagemin.optimize(function (err) {
        t.assert(!err);

        fs.stat(imagemin.dest(), function (err, a) {
            t.assert(!err);
            t.assert(a.size > 0);

            fs.stat(imagemin.src(), function (err, b) {
                t.assert(!err);
                t.assert(a.size < b.size);
            });
        });
    });
});

test('optimize a SVG', function (t) {
    t.plan(5);

    var imagemin = new Imagemin()
        .src(path.join(__dirname, 'fixtures/test.svg'))
        .dest(path.join(__dirname, 'tmp/test.svg'))
        .use(Imagemin.svgo());

    imagemin.optimize(function (err) {
        t.assert(!err);

        fs.stat(imagemin.dest(), function (err, a) {
            t.assert(!err);
            t.assert(a.size > 0);

            fs.stat(imagemin.src(), function (err, b) {
                t.assert(!err);
                t.assert(a.size < b.size);
            });
        });
    });
});

test('output error on corrupt images', function (t) {
    t.plan(1);

    var imagemin = new Imagemin()
        .src(path.join(__dirname, 'fixtures/test-corrupt.jpg'))
        .dest(path.join(__dirname, 'tmp/test-corrupt.jpg'))
        .use(Imagemin.jpegtran());

    imagemin.optimize(function (err) {
        t.assert(err);
    });
});
<|endoftext|>