<commit_before>var
  should = require('should'),
  EventEmitter = require('events'),
  proxyquire = require('proxyquire');

describe('plugin implementation', function () {
  var
    Plugin,
    plugin,
    emitter,
    setPort,
    fakeId = 'Verbal Kint',
    destination,
    linkedChannel,
    messageSent,
    notification;

  before(function () {
    // stubbing socket.io
    Plugin = proxyquire('../lib/index', {
      'socket.io': portNumber => {
        emitter = new EventEmitter();

        setPort = portNumber;

        emitter.id = fakeId;
        emitter.set = () => {};
        emitter.to = () => {
          return {
            emit: (channel, payload) => {
              messageSent = payload;
              destination = channel;
            }
          };
        };

        emitter.sockets = { connected: {} };
        emitter.sockets.connected[fakeId] = {
          join: channel => { linkedChannel = channel; },
          leave: channel => { linkedChannel = channel; },
          emit: (event, payload) => { notification = {event, payload}; }
        };

        return emitter;
      }
    });
  });

  beforeEach(function () {
    setPort = -1;
    destination = null;
    messageSent = null;
    linkedChannel = null;
    notification = null;
    plugin = new Plugin();
  });

  describe('#general', function () {
    it('should expose an init function', function () {
      should(plugin.init).be.a.Function();
    });

    it('should expose a hooks object', function () {
      var hooks = require('../lib/config/hooks');
      should(plugin.hooks).match(hooks);
    });
  });

  describe('#init', function () {
    var
      config = {port: 1234},
      context = {foo: 'bar'};

    it('should throw an error if no "config" argument has been provided', function (done) {
      try {
        plugin.init(undefined, {}, true);
        done(new Error('Expected a throw, but nothing happened'));
      }
      catch (e) {
        done();
      }
    });

    it('should fallback to dummy-mode if no port configuration has been provided', function () {
      var ret = plugin.init({}, {}, false);

      should(ret).be.false();
      should(plugin.isDummy).be.true();
    });

    it('should set internal properties correctly', function () {
      var
        ret = plugin.init(config, context, true);

      should(ret).be.eql(plugin);
      should(plugin.isDummy).be.true();
      should(plugin.config).be.eql(config);
      should(plugin.context).be.eql(context);
      should(setPort).be.eql(-1);
    });

    it('should start a socket.io broker if not in dummy mode', function () {
      var ret = plugin.init(config, context, false);

      should(ret).be.eql(plugin);
      should(plugin.isDummy).be.false();
      should(plugin.config).be.eql(config);
      should(plugin.context).be.eql(context);
      should(setPort).be.eql(1234);
    });

    it('should manage new connections on a "connection" event', function (done) {
      var
        stubSocket = { thisIsNot: 'aSocket' };

      this.timeout(50);

      plugin.newConnection = socket => {
        should(socket).be.eql(stubSocket);
        done();
      };

      plugin.init(config, context, false);
      emitter.emit('connection', stubSocket);
    });

    it('should fallback to dummy-mode if the broker is unable to start', function (done) {
      this.timeout(50);

      plugin.init(config, context, false);
      emitter.emit('error', 'fake error');
      process.nextTick(() => {
        should(plugin.isDummy).be.true();
        done();
      });
    });
  });

  describe('#broadcast', function () {
    var
      channel = 'foobar',
      payload = {foo: 'bar'};

    beforeEach(function () {
      plugin.init({port: 1234}, {}, false);
    });

    it('should do nothing if in dummy mode', function () {
      plugin.isDummy = true;
      plugin.broadcast({channel,payload});
      should(messageSent).be.null();
      should(destination).be.null();
    });

    it('should broadcast a message correctly', function () {
      plugin.broadcast({channel,payload});
      should(messageSent).be.eql(payload);
      should(destination).be.eql(channel);
    });
  });

  describe('#notify', function () {
    var
      channel = 'foobar',
      payload = {foo: 'bar'};

    beforeEach(function () {
      plugin.init({port: 1234}, {}, false);
    });

    it('should do nothing if in dummy mode', function () {
      plugin.isDummy = true;
      plugin.notify({id: fakeId,channel,payload});
      should(notification).be.null();
    });

    it('should notify a client correctly', function () {
      plugin.notify({id: fakeId, channel, payload});
      should(notification).not.be.null();
      should(notification.payload).be.eql(payload);
      should(notification.event).be.eql(channel);
    });
  });

  describe('#joinChannel', function () {
    beforeEach(function () {
      plugin.init({port: 1234}, {}, false);
    });

    it('should do nothing if in dummy mode', function () {
      plugin.isDummy = true;
      plugin.joinChannel({id: fakeId, channel: 'foo'});
      should(linkedChannel).be.null();
    });

    it('should link an id with a channel', function () {
      plugin.joinChannel({id: fakeId, channel: 'foo'});
      should(linkedChannel).be.eql('foo');
    });

    it('should do nothing if the id is unknown', function () {
      plugin.joinChannel({id: 'some other id', channel: 'foo'});
      should(linkedChannel).be.null();
    });
  });

  describe('#leaveChannel', function () {
    beforeEach(function () {
      plugin.init({port: 1234}, {}, false);
    });

    it('should do nothing if in dummy mode', function () {
      plugin.isDummy = true;
      plugin.leaveChannel({id: fakeId, channel: 'foo'});
      should(linkedChannel).be.null();
    });

    it('should link an id with a channel', function () {
      plugin.leaveChannel({id: fakeId, channel: 'foo'});
      should(linkedChannel).be.eql('foo');
    });

    it('should do nothing if the id is unknown', function () {
      plugin.leaveChannel({id: 'some other id', channel: 'foo'});
      should(linkedChannel).be.null();
    });
  });

  describe('#newConnection', function () {
    // some heavy stubbing here...
    var
      connection = {foo: 'bar'},
      fakeRequestId = 'fakeRequestId',
      serializedResponse = {bar: 'foo'},
      connected,
      executed,
      disconnected,
      response = {
        toJson: () => {
          return serializedResponse;
        }
      },
      context = {
        RequestObject: function (foo) {
          foo.requestId = fakeRequestId;
          return foo;
        },
        getRouter: () => {
          return {
            newConnection: (protocol, id) => {
              if (!id) {
                return Promise.rejected(new Error('rejected'));
              }

              should(protocol).be.eql(plugin.protocol);
              should(id).be.eql(emitter.id);
              connected = true;
              return Promise.resolve(connection);
            },
            execute: (request, conn, cb) => {
              should(conn).be.eql(connection);
              executed = true;

              if (request.errorMe) {
                return cb('errorMe', response);
              }

              cb(null, response);
            },
            removeConnection: () => {
              disconnected = true;
            }
          };
        }
      };

    beforeEach(function () {
      plugin.init({port: 1234, room: 'foo'}, context, false);
      connected = executed = disconnected = false;
    });

    it('should do nothing if in dummy mode', function () {
      plugin.isDummy = true;

      should(plugin.newConnection(emitter)).be.false();
      should(connected).be.false();
    });

    it('should initialize a new connection', function () {
      plugin.newConnection(emitter);
      should(connected).be.true();
    });

    it('should listen to incoming requests and forward them to Kuzzle', function (done) {
      var payload = {fake: 'data'};
      this.timeout(100);
      plugin.newConnection(emitter);

      setTimeout(() => {
        emitter.emit(plugin.config.room, payload);

        setTimeout(() => {
          should(connected).be.true();
          should(executed).be.true();
          should(disconnected).be.false();
          should(messageSent).be.eql(serializedResponse);
          should(destination).be.eql(fakeRequestId);
          done();
        }, 40);
      }, 20);
    });

    it('should forward an error to clients if Kuzzle throws one', function (done) {
      var payload = {errorMe: true};
      this.timeout(100);
      plugin.newConnection(emitter);

      setTimeout(() => {
        emitter.emit(plugin.config.room, payload);

        setTimeout(() => {
          should(connected).be.true();
          should(executed).be.true();
          should(disconnected).be.false();
          should(messageSent).be.eql(serializedResponse);
          should(destination).be.eql(fakeRequestId);
          done();
        }, 20);
      }, 20);
    });

    it('should handle client disconnections', function (done) {
      this.timeout(100);
      plugin.newConnection(emitter);

      setTimeout(() => {
        emitter.emit('disconnect', {});

        setTimeout(() => {
          should(connected).be.true();
          should(executed).be.false();
          should(disconnected).be.true();
          should(messageSent).be.null();
          should(destination).be.null();
          done();
        }, 20);
      }, 20);
    });

    it('should handle client socket errors', function (done) {
      this.timeout(100);
      plugin.newConnection(emitter);

      setTimeout(() => {
        emitter.emit('error', {});

        setTimeout(() => {
          should(connected).be.true();
          should(executed).be.false();
          should(disconnected).be.true();
          should(messageSent).be.null();
          should(destination).be.null();
          done();
        }, 20);
      }, 20);
    });
  });
});
<commit_msg>Fixed tests<commit_after>var
  should = require('should'),
  EventEmitter = require('events'),
  proxyquire = require('proxyquire');

describe('plugin implementation', function () {
  var
    Plugin,
    plugin,
    emitter,
    setPort,
    fakeId = 'Verbal Kint',
    destination,
    linkedChannel,
    messageSent,
    notification;

  before(function () {
    // stubbing socket.io
    Plugin = proxyquire('../lib/index', {
      'socket.io': portNumber => {
        emitter = new EventEmitter();

        setPort = portNumber;

        emitter.id = fakeId;
        emitter.set = () => {};
        emitter.to = () => {
          return {
            emit: (channel, payload) => {
              messageSent = payload;
              destination = channel;
            }
          };
        };

        emitter.sockets = { connected: {} };
        emitter.sockets.connected[fakeId] = {
          join: channel => { linkedChannel = channel; },
          leave: channel => { linkedChannel = channel; },
          emit: (event, payload) => { notification = {event, payload}; }
        };

        return emitter;
      }
    });
  });

  beforeEach(function () {
    setPort = -1;
    destination = null;
    messageSent = null;
    linkedChannel = null;
    notification = null;
    plugin = new Plugin();
  });

  describe('#general', function () {
    it('should expose an init function', function () {
      should(plugin.init).be.a.Function();
    });

    it('should expose a hooks object', function () {
      var hooks = require('../lib/config/hooks');
      should(plugin.hooks).match(hooks);
    });
  });

  describe('#init', function () {
    var
      config = {port: 1234},
      context = {foo: 'bar'};

    it('should throw an error if no "config" argument has been provided', function (done) {
      try {
        plugin.init(undefined, {}, true);
        done(new Error('Expected a throw, but nothing happened'));
      }
      catch (e) {
        done();
      }
    });

    it('should fallback to dummy-mode if no port configuration has been provided', function () {
      var ret = plugin.init({}, {}, false);

      should(ret).be.false();
      should(plugin.isDummy).be.true();
    });

    it('should set internal properties correctly', function () {
      var
        ret = plugin.init(config, context, true);

      should(ret).be.eql(plugin);
      should(plugin.isDummy).be.true();
      should(plugin.config).be.eql(config);
      should(plugin.context).be.eql(context);
      should(setPort).be.eql(-1);
    });

    it('should start a socket.io broker if not in dummy mode', function () {
      var ret = plugin.init(config, context, false);

      should(ret).be.eql(plugin);
      should(plugin.isDummy).be.false();
      should(plugin.config).be.eql(config);
      should(plugin.context).be.eql(context);
      should(setPort).be.eql(1234);
    });

    it('should manage new connections on a "connection" event', function (done) {
      var
        stubSocket = { thisIsNot: 'aSocket' };

      this.timeout(50);

      plugin.newConnection = socket => {
        should(socket).be.eql(stubSocket);
        done();
      };

      plugin.init(config, context, false);
      emitter.emit('connection', stubSocket);
    });

    it('should fallback to dummy-mode if the broker is unable to start', function (done) {
      this.timeout(50);

      plugin.init(config, context, false);
      emitter.emit('error', 'fake error');
      process.nextTick(() => {
        should(plugin.isDummy).be.true();
        done();
      });
    });
  });

  describe('#broadcast', function () {
    var
      channel = 'foobar',
      payload = {foo: 'bar'};

    beforeEach(function () {
      plugin.init({port: 1234}, {}, false);
    });

    it('should do nothing if in dummy mode', function () {
      plugin.isDummy = true;
      plugin.broadcast({channel,payload});
      should(messageSent).be.null();
      should(destination).be.null();
    });

    it('should broadcast a message correctly', function () {
      plugin.broadcast({channel,payload});
      should(messageSent).be.eql(payload);
      should(destination).be.eql(channel);
    });
  });

  describe('#notify', function () {
    var
      channel = 'foobar',
      payload = {foo: 'bar'};

    beforeEach(function () {
      plugin.init({port: 1234}, {}, false);
    });

    it('should do nothing if in dummy mode', function () {
      plugin.isDummy = true;
      plugin.notify({id: fakeId,channel,payload});
      should(notification).be.null();
    });

    it('should notify a client correctly', function () {
      plugin.notify({id: fakeId, channel, payload});
      should(notification).not.be.null();
      should(notification.payload).be.eql(payload);
      should(notification.event).be.eql(channel);
    });
  });

  describe('#joinChannel', function () {
    beforeEach(function () {
      plugin.init({port: 1234}, {}, false);
    });

    it('should do nothing if in dummy mode', function () {
      plugin.isDummy = true;
      plugin.joinChannel({id: fakeId, channel: 'foo'});
      should(linkedChannel).be.null();
    });

    it('should link an id with a channel', function () {
      plugin.joinChannel({id: fakeId, channel: 'foo'});
      should(linkedChannel).be.eql('foo');
    });

    it('should do nothing if the id is unknown', function () {
      plugin.joinChannel({id: 'some other id', channel: 'foo'});
      should(linkedChannel).be.null();
    });
  });

  describe('#leaveChannel', function () {
    beforeEach(function () {
      plugin.init({port: 1234}, {}, false);
    });

    it('should do nothing if in dummy mode', function () {
      plugin.isDummy = true;
      plugin.leaveChannel({id: fakeId, channel: 'foo'});
      should(linkedChannel).be.null();
    });

    it('should link an id with a channel', function () {
      plugin.leaveChannel({id: fakeId, channel: 'foo'});
      should(linkedChannel).be.eql('foo');
    });

    it('should do nothing if the id is unknown', function () {
      plugin.leaveChannel({id: 'some other id', channel: 'foo'});
      should(linkedChannel).be.null();
    });
  });

  describe('#newConnection', function () {
    // some heavy stubbing here...
    var
      connection = {foo: 'bar'},
      fakeRequestId = 'fakeRequestId',
      serializedResponse = {bar: 'foo'},
      connected,
      executed,
      disconnected,
      response = {
        toJson: () => {
          return serializedResponse;
        }
      },
      context = {
        RequestObject: function (foo) {
          foo.requestId = fakeRequestId;
          return foo;
        },
        getRouter: () => {
          return {
            newConnection: (protocol, id) => {
              if (!id) {
                return Promise.rejected(new Error('rejected'));
              }

              should(protocol).be.eql(plugin.protocol);
              should(id).be.eql(emitter.id);
              connected = true;
              return Promise.resolve(connection);
            },
            execute: (request, conn, cb) => {
              should(conn).be.eql(connection);
              executed = true;

              if (request.errorMe) {
                return cb('errorMe', response);
              }

              cb(null, response);
            },
            removeConnection: () => {
              disconnected = true;
            }
          };
        }
      };

    beforeEach(function () {
      plugin.init({port: 1234, room: 'foo'}, context, false);
      connected = executed = disconnected = false;
    });

    it('should do nothing if in dummy mode', function () {
      plugin.isDummy = true;

      should(plugin.newConnection(emitter)).be.false();
      should(connected).be.false();
    });

    it('should initialize a new connection', function () {
      plugin.newConnection(emitter);
      should(connected).be.true();
    });

    it('should listen to incoming requests and forward them to Kuzzle', function (done) {
      var payload = {fake: 'data'};
      this.timeout(100);
      plugin.newConnection(emitter);

      setTimeout(() => {
        emitter.emit(plugin.config.room, payload);

        setTimeout(() => {
          should(connected).be.true();
          should(executed).be.true();
          should(disconnected).be.false();
          should(messageSent).be.eql(response);
          should(destination).be.eql(fakeRequestId);
          done();
        }, 40);
      }, 20);
    });

    it('should forward an error to clients if Kuzzle throws one', function (done) {
      var payload = {errorMe: true};
      this.timeout(100);
      plugin.newConnection(emitter);

      setTimeout(() => {
        emitter.emit(plugin.config.room, payload);

        setTimeout(() => {
          should(connected).be.true();
          should(executed).be.true();
          should(disconnected).be.false();
          should(messageSent).be.eql(response);
          should(destination).be.eql(fakeRequestId);
          done();
        }, 20);
      }, 20);
    });

    it('should handle client disconnections', function (done) {
      this.timeout(100);
      plugin.newConnection(emitter);

      setTimeout(() => {
        emitter.emit('disconnect', {});

        setTimeout(() => {
          should(connected).be.true();
          should(executed).be.false();
          should(disconnected).be.true();
          should(messageSent).be.null();
          should(destination).be.null();
          done();
        }, 20);
      }, 20);
    });

    it('should handle client socket errors', function (done) {
      this.timeout(100);
      plugin.newConnection(emitter);

      setTimeout(() => {
        emitter.emit('error', {});

        setTimeout(() => {
          should(connected).be.true();
          should(executed).be.false();
          should(disconnected).be.true();
          should(messageSent).be.null();
          should(destination).be.null();
          done();
        }, 20);
      }, 20);
    });
  });
});
<|endoftext|>


<commit_before>var assert = require('chai').assert;
var CipherService = require('../');

describe('CipherFactory', function () {
  it('Should properly export', function () {
    assert.isObject(CipherService);
    assert.isFunction(CipherService.create);
    assert.isFunction(CipherService.JWT);
  });
});
<commit_msg>Add test for index<commit_after>var assert = require('chai').assert;
var CipherService = require('../');
var JWTCipher = require('../lib/JwtCipher');

describe('CipherFactory', function () {
  it('Should properly export', function () {
    assert.isObject(CipherService);
    assert.isFunction(CipherService.create);
    assert.isFunction(CipherService.JWT);
  });

  it('Should properly create JWT cipher', function () {
    var cipher = CipherService.create('jwt');
    assert.instanceOf(cipher, JWTCipher);
  });
});
<|endoftext|>


<commit_before>//data.js

/*
 * contains initial data for testing
 * and functions for accessing/writing
 * data
 */

var GiftCard = function () {
    this.id = 0;
    this.firstName = "";
    this.lastName = "";
    this.notes = "";
    this.balance = 0;
    this.email = "";
    this.phone = "";
    this.transactions = [];
    this.created = Date();
    this.modified = Date();
};

GiftCard.prototype.toString = function () {
    return "<(id: " + this.id + ") " + this.firstName + " " + this.lastName + ", $" + this.balance + ">";
}

GiftCard.prototype.addTransaction = function(tx)
{
    var newBalance = this.balance + tx.amt;
    if(newBalance< 0)
        return false;
    this.balance = newBalance;
    this.transactions.push(tx);
    this.modified = Date();

    return true;

};

var Transaction = function(amt, type)
{
    this.amt = amt;
    this.type = type;
    this.created = Date();

}

var data = {};

data.counter = 0;

data.findAll = function()
{
    return testData;
};

data.findByName = function(name)
{
    for (var i=0; i < testData.length; i++){
    var namecat = testData[i].firstName + " " + testData[i].lastName
    if(namecat == name){
        console.log(testData[i]);
        return testData[i];

//        var tempbal = 0;
//        tempbal = tempbal + testData[i].balance;

    }
}
//    console.log(tempbal);
//    return tempbal;

};

data.findByPhone = function(phone)
{
  for (var i=0; i < testData.length; i++){
    var phonecat = testData[i].phone;
    if(namecat == phone){
        console.log(testData[i]);
        return testData[i];
}
  }
};

data.search = function(query)
{
    // version 1
    //check query against name, email, phone
}

data.save = function(gc)
{
    //save the card to the DB, return the saved object
};

data.createCard = function(name, amt)
{
    data.counter += 1;
    var card = new GiftCard();
    card.id = data.counter;
    card.firstName = name.split(" ")[0];
    card.lastName = name.split(" ")[1];
    card.addTransaction(new Transaction(amt, "card-purchase"));
    return card;
};

var testData =
[
    data.createCard("Kai Williams", 10),
    data.createCard("Ryan Sobeck", 5),
    data.createCard("Filiz C.", 20),
    data.createCard("Austen Cortese", 10),
    data.createCard("Robby Lucia", 30)
];

//for (var i=0; i < testData.length; i++){
//    console.log(testData[i]);
//};

//console.log(data);

data.findByName("Robby Lucia");

//console.log(testData[1].firstName);<commit_msg>search functions print result to test.html<commit_after>//data.js

/*
 * contains initial data for testing
 * and functions for accessing/writing
 * data
 */

var GiftCard = function () {
    this.id = 0;
    this.firstName = "";
    this.lastName = "";
    this.notes = "";
    this.balance = 0;
    this.email = "";
    this.phone = "";
    this.transactions = [];
    this.created = Date();
    this.modified = Date();
};

GiftCard.prototype.toString = function () {
    return "<(id: " + this.id + ") " + this.firstName + " " + this.lastName + ", $" + this.balance + ">";
}

GiftCard.prototype.addTransaction = function(tx)
{
    var newBalance = this.balance + tx.amt;
    if(newBalance< 0)
        return false;
    this.balance = newBalance;
    this.transactions.push(tx);
    this.modified = Date();

    return true;

};

var Transaction = function(amt, type)
{
    this.amt = amt;
    this.type = type;
    this.created = Date();

}

var data = {};

data.counter = 0;

data.findAll = function()
{
	console.log(testData);
    $("#main").html(testData.toString());
    return testData;

};

data.findByName = function(name)
{
    for (var i=0; i < testData.length; i++){
    var namecat = testData[i].firstName + " " + testData[i].lastName
	    if(namecat == name){
	        console.log(testData[i]);
	        return  $("#main").html("name" + testData[i].toString());
	    }
	}

};
/*
data.findByName = function(name){
	var show = _.findWhere(testData,{name: name});
	 console.log(show);
	 return show;
};
data.findByPhone = function(phone){
	var show = _.findWhere(testData.shows, {phone: phone});
	 console.log(show);
	 return show;
};

*/
data.findByPhone = function(phone)
{
	var phoneCat=phone.replace(/-|\s/g,"");
		console.log(phoneCat);
  for (var i=0; i < testData.length; i++){
    if(phoneCat == testData[i].phone){

        console.log(testData[i]);
        return  $("#main").append("phone number" + testData[i].toString());
	}
  }
};

data.search = function(query)
{
    // version 1
    //check query against name, email, phone
}

data.save = function(gc)
{
    //save the card to the DB, return the saved object
};

data.createCard = function(name, amt, phone)
{
    data.counter += 1;
    var card = new GiftCard();
    card.id = data.counter;
    card.firstName = name.split(" ")[0];
    card.lastName = name.split(" ")[1];
    card.phone = phone;
    card.addTransaction(new Transaction(amt, "card-purchase"));

    return card;
};

var testData =
[
    data.createCard("Kai Williams", 10, 5555555555),
    data.createCard("Ryan Sobeck", 5, 8888888888),
    data.createCard("Filiz C.", 20, 9999999999),
    data.createCard("Austen Cortese", 10, 2222222222),
    data.createCard("Robby Lucia", 30, 4444444444)
];

data.findByName("Kai Williams");
data.findByPhone("222 2-222222");
data.findAll();

<|endoftext|>


<commit_before>var proxyquire = require('proxyquire');
var assert = require('assert');
var _range = require('lodash.range');
var es = require('event-stream');
var mongodb = require('mongodb');
var ReadPreference = require('mongodb-read-preference');
var sample = require('../');
var ReservoirSampler = require('../lib/reservoir-sampler');
var NativeSampler = require('../lib/native-sampler');
var runner = require('mongodb-runner');

var debug = require('debug')('mongodb-collection-sample:test');

var getSampler = function(version, fn) {
  proxyquire('../lib', {
    'get-mongodb-version': function(opts, cb) {
      process.nextTick(function() {
        cb(null, version);
      });
    }
  }).getSampler({}, 'pets', {}, fn);
};

var runnerOpts = {
  topology: 'replicaset'
};

before(function(done) {
  this.timeout(20000);
  debug('launching local replicaset.');
  runner(runnerOpts, done);
});

after(function(done) {
  this.timeout(10000);
  debug('stopping replicaset.');
  runner.stop(runnerOpts, done);
});

describe('mongodb-collection-sample', function() {
  before(function(done) {
    // output the current version for debug purpose
    mongodb.MongoClient.connect('mongodb://localhost:27017/test', function(err, db) {
      assert.ifError(err);
      db.admin().serverInfo(function(err2, info) {
        assert.ifError(err2);
        debug('running tests with MongoDB version %s.', info.version);
        db.close();
        done();
      });
    });
  });

  describe('polyfill', function() {
    it('should use reservoir sampling if version is 3.1.5', function(done) {
      getSampler('3.1.5', function(err, src) {
        assert.ifError(err);
        assert(src instanceof ReservoirSampler);
        done();
      });
    });

    it('should use native sampling if version is 3.1.6', function(done) {
      getSampler('3.1.6', function(err, src) {
        assert.ifError(err);
        assert(src instanceof NativeSampler);
        done();
      });
    });

    it('should use native sampling if version is 3.1.7', function(done) {
      getSampler('3.1.7', function(err, src) {
        assert.ifError(err);
        assert(src instanceof NativeSampler);
        done();
      });
    });
  });

  describe('Reservoir Sampler chunk sampling', function() {
    var db;

    before(function(done) {
      this.timeout(10000);
      mongodb.MongoClient.connect('mongodb://localhost:27017/test', function(err, _db) {
        if (err) {
          return done(err);
        }
        db = _db;

        var docs = _range(0, 15000).map(function(i) {
          return {
            _id: 'needle_' + i,
            is_even: i % 2
          };
        });
        db.collection('haystack').insert(docs, done);
      });
    });

    after(function(done) {
      if (!db) {
        return done();
      }
      db.dropCollection('haystack', done);
    });

    it('should use `_id: -1` as the default sort', function(done) {
      getSampler('3.1.5', function(err, src) {
        assert.ifError(err);
        assert.deepEqual(src.sort, {
          _id: -1
        });
        done();
      });
    });

    it('should have the test.haystack collection with 15000 docs', function(done) {
      db.collection('haystack').count(function(err, res) {
        assert.ifError(err);
        assert.equal(res, 15000);
        done();
      });
    });

    it('should sample 10000 docs in several chunks', function(done) {
      var seen = 0;
      sample(db, 'haystack', {
        size: 10000,
        chunkSize: 1234
      })
        .pipe(es.through(function(doc) {
          seen++;
          this.emit('data', doc);
        }, function() {
          this.emit('end');
          assert.equal(seen, 10000);
          done();
        }));
    });
  });

  describe('functional', function() {
    var db;

    before(function(done) {
      mongodb.MongoClient.connect('mongodb://localhost:27017/test', function(err, _db) {
        if (err) {
          return done(err);
        }
        db = _db;

        var docs = _range(0, 1000).map(function(i) {
          return {
            _id: 'needle_' + i,
            is_even: i % 2
          };
        });
        db.collection('haystack').insert(docs, done);
      });
    });

    after(function(done) {
      if (!db) {
        return done();
      }
      db.dropCollection('haystack', done);
    });

    it('should should default the sample size to `5`', function(done) {
      var seen = 0;
      sample(db, 'haystack')
        .pipe(es.through(function(doc) {
          seen++;
          this.emit('data', doc);
        }, function() {
          this.emit('end');
          assert.equal(seen, 5);
          done();
        }));
    });

    it('should allow specifying a query', function(done) {
      var docs = [];
      var options = {
        size: 10,
        query: {
          is_even: 1
        }
      };
      sample(db, 'haystack', options)
        .pipe(es.through(function(doc) {
          docs.push(doc);
          this.emit('data', doc);
        }, function() {
          this.emit('end');
          assert.equal(docs.filter(function(d) {
            return d.is_even === 1;
          }).length, options.size);
          done();
        }));
    });

    it('should get a sample of 10 documents', function(done) {
      var seen = 0;
      sample(db, 'haystack')
        .pipe(es.through(function(doc) {
          seen++;
          this.emit('data', doc);
        }, function() {
          this.emit('end');
          assert.equal(seen, 5);
          done();
        }));
    });

    it('should return as many documents as possible if '
      + 'the requested sample size is larger than the '
      + 'collection size', function(done) {
      var seen = 0;
      sample(db, 'haystack', {
        size: 2000
      })
        .pipe(es.through(function(doc) {
          seen++;
          this.emit('data', doc);
        }, function() {
          this.emit('end');
          assert.equal(seen, 1000);
          done();
        }));
    });
  });

  describe('topology', function() {
    this.timeout(30000);

    var dbPrim;
    var dbSec;
    var options = {
      readPreference: ReadPreference.nearest
    };

    before(function(done) {
      mongodb.MongoClient.connect('mongodb://localhost:27017/test', function(err, _dbPrim) {
        if (err) {
          return done(err);
        }
        dbPrim = _dbPrim;
        var docs = _range(0, 100).map(function(i) {
          return {
            _id: 'needle_' + i,
            is_even: i % 2
          };
        });
        dbPrim.collection('haystack').insert(docs, {w: 3}, function() {
          mongodb.MongoClient.connect('mongodb://localhost:27018/test', function(errInsert, _dbSec) {
            if (errInsert) {
              return done(errInsert);
            }
            dbSec = _dbSec;
            dbSec.collection('haystack', options).count(function(errCount, res) {
              assert.ifError(errCount);
              assert.equal(res, 100);
              done();
            });
          });
        });
      });
    });

    after(function(done) {
      if (!dbPrim) {
        return done();
      }
      dbPrim.dropCollection('haystack', function() {
        dbPrim.close();
        dbSec.close();
        done();
      });
    });

    it('should sample correctly when connected to a secondary node', function(done) {
      var opts = {
        size: 5,
        query: {}
      };
      // Get a stream of sample documents from the collection and make sure
      // 5 documents have been returned.
      var count = 0;
      var stream = sample(dbSec, 'haystack', opts);
      stream.on('error', function(err2) {
        done(err2);
      });
      stream.on('data', function() {
        count++;
      });
      stream.on('end', function() {
        assert.equal(count, opts.size);
        done();
      });
    });
  });
});
<commit_msg>increased timeout for before/after mocha hooks.<commit_after>var proxyquire = require('proxyquire');
var assert = require('assert');
var _range = require('lodash.range');
var es = require('event-stream');
var mongodb = require('mongodb');
var ReadPreference = require('mongodb-read-preference');
var sample = require('../');
var ReservoirSampler = require('../lib/reservoir-sampler');
var NativeSampler = require('../lib/native-sampler');
var runner = require('mongodb-runner');

var debug = require('debug')('mongodb-collection-sample:test');

var getSampler = function(version, fn) {
  proxyquire('../lib', {
    'get-mongodb-version': function(opts, cb) {
      process.nextTick(function() {
        cb(null, version);
      });
    }
  }).getSampler({}, 'pets', {}, fn);
};

var runnerOpts = {
  topology: 'replicaset'
};

before(function(done) {
  this.timeout(40000);
  debug('launching local replicaset.');
  runner(runnerOpts, done);
});

after(function(done) {
  this.timeout(20000);
  debug('stopping replicaset.');
  runner.stop(runnerOpts, done);
});

describe('mongodb-collection-sample', function() {
  before(function(done) {
    // output the current version for debug purpose
    mongodb.MongoClient.connect('mongodb://localhost:27017/test', function(err, db) {
      assert.ifError(err);
      db.admin().serverInfo(function(err2, info) {
        assert.ifError(err2);
        debug('running tests with MongoDB version %s.', info.version);
        db.close();
        done();
      });
    });
  });

  describe('polyfill', function() {
    it('should use reservoir sampling if version is 3.1.5', function(done) {
      getSampler('3.1.5', function(err, src) {
        assert.ifError(err);
        assert(src instanceof ReservoirSampler);
        done();
      });
    });

    it('should use native sampling if version is 3.1.6', function(done) {
      getSampler('3.1.6', function(err, src) {
        assert.ifError(err);
        assert(src instanceof NativeSampler);
        done();
      });
    });

    it('should use native sampling if version is 3.1.7', function(done) {
      getSampler('3.1.7', function(err, src) {
        assert.ifError(err);
        assert(src instanceof NativeSampler);
        done();
      });
    });
  });

  describe('Reservoir Sampler chunk sampling', function() {
    var db;

    before(function(done) {
      this.timeout(10000);
      mongodb.MongoClient.connect('mongodb://localhost:27017/test', function(err, _db) {
        if (err) {
          return done(err);
        }
        db = _db;

        var docs = _range(0, 15000).map(function(i) {
          return {
            _id: 'needle_' + i,
            is_even: i % 2
          };
        });
        db.collection('haystack').insert(docs, done);
      });
    });

    after(function(done) {
      if (!db) {
        return done();
      }
      db.dropCollection('haystack', done);
    });

    it('should use `_id: -1` as the default sort', function(done) {
      getSampler('3.1.5', function(err, src) {
        assert.ifError(err);
        assert.deepEqual(src.sort, {
          _id: -1
        });
        done();
      });
    });

    it('should have the test.haystack collection with 15000 docs', function(done) {
      db.collection('haystack').count(function(err, res) {
        assert.ifError(err);
        assert.equal(res, 15000);
        done();
      });
    });

    it('should sample 10000 docs in several chunks', function(done) {
      var seen = 0;
      sample(db, 'haystack', {
        size: 10000,
        chunkSize: 1234
      })
        .pipe(es.through(function(doc) {
          seen++;
          this.emit('data', doc);
        }, function() {
          this.emit('end');
          assert.equal(seen, 10000);
          done();
        }));
    });
  });

  describe('functional', function() {
    var db;

    before(function(done) {
      mongodb.MongoClient.connect('mongodb://localhost:27017/test', function(err, _db) {
        if (err) {
          return done(err);
        }
        db = _db;

        var docs = _range(0, 1000).map(function(i) {
          return {
            _id: 'needle_' + i,
            is_even: i % 2
          };
        });
        db.collection('haystack').insert(docs, done);
      });
    });

    after(function(done) {
      if (!db) {
        return done();
      }
      db.dropCollection('haystack', done);
    });

    it('should should default the sample size to `5`', function(done) {
      var seen = 0;
      sample(db, 'haystack')
        .pipe(es.through(function(doc) {
          seen++;
          this.emit('data', doc);
        }, function() {
          this.emit('end');
          assert.equal(seen, 5);
          done();
        }));
    });

    it('should allow specifying a query', function(done) {
      var docs = [];
      var options = {
        size: 10,
        query: {
          is_even: 1
        }
      };
      sample(db, 'haystack', options)
        .pipe(es.through(function(doc) {
          docs.push(doc);
          this.emit('data', doc);
        }, function() {
          this.emit('end');
          assert.equal(docs.filter(function(d) {
            return d.is_even === 1;
          }).length, options.size);
          done();
        }));
    });

    it('should get a sample of 10 documents', function(done) {
      var seen = 0;
      sample(db, 'haystack')
        .pipe(es.through(function(doc) {
          seen++;
          this.emit('data', doc);
        }, function() {
          this.emit('end');
          assert.equal(seen, 5);
          done();
        }));
    });

    it('should return as many documents as possible if '
      + 'the requested sample size is larger than the '
      + 'collection size', function(done) {
      var seen = 0;
      sample(db, 'haystack', {
        size: 2000
      })
        .pipe(es.through(function(doc) {
          seen++;
          this.emit('data', doc);
        }, function() {
          this.emit('end');
          assert.equal(seen, 1000);
          done();
        }));
    });
  });

  describe('topology', function() {
    this.timeout(30000);

    var dbPrim;
    var dbSec;
    var options = {
      readPreference: ReadPreference.nearest
    };

    before(function(done) {
      mongodb.MongoClient.connect('mongodb://localhost:27017/test', function(err, _dbPrim) {
        if (err) {
          return done(err);
        }
        dbPrim = _dbPrim;
        var docs = _range(0, 100).map(function(i) {
          return {
            _id: 'needle_' + i,
            is_even: i % 2
          };
        });
        dbPrim.collection('haystack').insert(docs, {w: 3}, function() {
          mongodb.MongoClient.connect('mongodb://localhost:27018/test', function(errInsert, _dbSec) {
            if (errInsert) {
              return done(errInsert);
            }
            dbSec = _dbSec;
            dbSec.collection('haystack', options).count(function(errCount, res) {
              assert.ifError(errCount);
              assert.equal(res, 100);
              done();
            });
          });
        });
      });
    });

    after(function(done) {
      if (!dbPrim) {
        return done();
      }
      dbPrim.dropCollection('haystack', function() {
        dbPrim.close();
        dbSec.close();
        done();
      });
    });

    it('should sample correctly when connected to a secondary node', function(done) {
      var opts = {
        size: 5,
        query: {}
      };
      // Get a stream of sample documents from the collection and make sure
      // 5 documents have been returned.
      var count = 0;
      var stream = sample(dbSec, 'haystack', opts);
      stream.on('error', function(err2) {
        done(err2);
      });
      stream.on('data', function() {
        count++;
      });
      stream.on('end', function() {
        assert.equal(count, opts.size);
        done();
      });
    });
  });
});
<|endoftext|>


<commit_before>const assert = require("assert");
const adapterTests = require("@feathersjs/adapter-tests");
const errors = require("@feathersjs/errors");
const feathers = require("@feathersjs/feathers");

const solr = require("../lib");
const Client = require("../lib").Client;
const options = {
  Model: new Client("http://localhost:8983/solr/techproducts"),
  paginate: {},
  events: ["testing"]
};

const app = feathers().use("techproducts", new solr(options));
const service = app.service("techproducts");

const tests = [
  ".options",
  ".events",
  "._get",
  "._find",
  "._create",
  "._update",
  "._patch",
  "._remove",
  ".get",
  ".get + $select",
  ".get + id + query",
  ".get + NotFound",
  ".get + id + query id",
  ".find",
  ".remove",
  ".remove + $select",
  ".remove + id + query",
  ".remove + multi",
  ".remove + id + query id",
  ".update",
  ".update + $select",
  ".update + id + query",
  ".update + NotFound",
  ".update + id + query id",
  ".patch",
  ".patch + $select",
  ".patch + id + query",
  ".patch multiple",
  ".patch multi query",
  ".patch + NotFound",
  ".patch + id + query id",
  ".create",
  ".create + $select",
  ".create multi",
  "internal .find",
  "internal .get",
  "internal .create",
  "internal .update",
  "internal .patch",
  "internal .remove",
  ".find + equal",
  ".find + equal multiple",
  ".find + $sort",
  ".find + $sort + string",
  ".find + $limit",
  ".find + $limit 0",
  ".find + $skip",
  ".find + $select",
  ".find + $or",
  ".find + $in",
  ".find + $nin",
  ".find + $lt",
  ".find + $lte",
  ".find + $gt",
  ".find + $gte",
  ".find + $ne",
  ".find + $gt + $lt + $sort",
  // ".find + $or nested + $sort",
  ".find + paginate",
  ".find + paginate + $limit + $skip",
  ".find + paginate + $limit 0",
  ".find + paginate + params"
];
const testSuite = adapterTests(tests);

describe("Feathers Solr Service", () => {
  beforeEach(done => setTimeout(done, 50));

  before(async function() {
    await service.Model.post("schema/fields", {
      "add-field": {
        name: "name",
        type: "text_general",
        multiValued: false,
        indexed: true,
        stored: true
      }
    });
    await service.Model.post("schema/fields", {
      "add-field": {
        name: "age",
        type: "pint",
        multiValued: false,
        indexed: true,
        stored: true
      }
    });
    await service.Model.post("schema/fields", {
      "add-field": {
        name: "created",
        type: "boolean",
        multiValued: false,
        indexed: true,
        stored: true
      }
    });
  });

  it("is CommonJS compatible", () =>
    assert.strictEqual(typeof require("../lib"), "function"));

  describe("Whitelisted params", () => {
    it("should accept $search", async () => {
      const result = await service.find({ query: { $search: true } });
      assert.ok(Array.isArray(result), "result is array");
    });
    it("should accept $suggest", async () => {
      const result = await service.find({ query: { $suggest: true } });
      assert.ok(Array.isArray(result), "result is array");
    });
    it("should accept $params", async () => {
      const result = await service.find({ query: { $params: true } });
      assert.ok(Array.isArray(result), "result is array");
    });
    it("should accept $facet", async () => {
      const result = await service.find({ query: { $facet: true } });
      assert.ok(Array.isArray(result), "result is array");
    });
    it("should accept $populate", async () => {
      const result = await service.find({ query: { $populate: true } });
      assert.ok(Array.isArray(result), "result is array");
    });
  });

  describe("Prepare Adapter Tests", () => {
    it(".delete multi ", async () => {
      service.options.multi = ["remove"];
      await service.remove(null, { query: { id: "*" } });
      service.options.multi = false;
      const result = await service.find({});
      assert.ok(Array.isArray(result), "data is an array");
      assert.ok(result.length == 0, "data is empty");
    });

    it("has fields name", async () => {
      const response = await service.Model.get("schema/fields/name");
      assert.ok(response.field.name == "name", "field name exists");
    });

    it("has fields age", async () => {
      const response = await service.Model.get("schema/fields/age");
      assert.ok(response.field.name == "age", "field age exists");
    });

    it("has fields created", async () => {
      const response = await service.Model.get("schema/fields/created");
      assert.ok(response.field.name == "created", "field created exists");
    });
  });
  testSuite(app, errors, "techproducts");
});
<commit_msg>Refactor<commit_after>const assert = require("assert");
const adapterTests = require("@feathersjs/adapter-tests");
const errors = require("@feathersjs/errors");
const feathers = require("@feathersjs/feathers");

const solr = require("../lib");
const Client = require("../lib").Client;
const options = {
  Model: new Client("http://localhost:8983/solr/techproducts"),
  paginate: {},
  events: ["testing"]
};

const app = feathers().use("techproducts", new solr(options));
const service = app.service("techproducts");

const tests = [
  ".options",
  ".events",
  "._get",
  "._find",
  "._create",
  "._update",
  "._patch",
  "._remove",
  ".get",
  ".get + $select",
  ".get + id + query",
  ".get + NotFound",
  ".get + id + query id",
  ".find",
  ".remove",
  ".remove + $select",
  ".remove + id + query",
  ".remove + multi",
  ".remove + id + query id",
  ".update",
  ".update + $select",
  ".update + id + query",
  ".update + NotFound",
  ".update + id + query id",
  ".patch",
  ".patch + $select",
  ".patch + id + query",
  ".patch multiple",
  ".patch multi query",
  ".patch + NotFound",
  ".patch + id + query id",
  ".create",
  ".create + $select",
  ".create multi",
  "internal .find",
  "internal .get",
  "internal .create",
  "internal .update",
  "internal .patch",
  "internal .remove",
  ".find + equal",
  ".find + equal multiple",
  ".find + $sort",
  ".find + $sort + string",
  ".find + $limit",
  ".find + $limit 0",
  ".find + $skip",
  ".find + $select",
  ".find + $or",
  ".find + $in",
  ".find + $nin",
  ".find + $lt",
  ".find + $lte",
  ".find + $gt",
  ".find + $gte",
  ".find + $ne",
  ".find + $gt + $lt + $sort",
  // ".find + $or nested + $sort",
  ".find + paginate",
  ".find + paginate + $limit + $skip",
  ".find + paginate + $limit 0",
  ".find + paginate + params"
];
const testSuite = adapterTests(tests);

describe("Feathers Solr Service", () => {
  // beforeEach(done => setTimeout(done, 10));

  before(async function() {
    await service.Model.post("schema/fields", {
      "add-field": {
        name: "name",
        type: "text_general",
        multiValued: false,
        indexed: true,
        stored: true
      }
    });
    await service.Model.post("schema/fields", {
      "add-field": {
        name: "age",
        type: "pint",
        multiValued: false,
        indexed: true,
        stored: true
      }
    });
    await service.Model.post("schema/fields", {
      "add-field": {
        name: "created",
        type: "boolean",
        multiValued: false,
        indexed: true,
        stored: true
      }
    });
  });

  it("is CommonJS compatible", () =>
    assert.strictEqual(typeof require("../lib"), "function"));

  describe("Whitelisted params", () => {
    it("should accept $search", async () => {
      const result = await service.find({ query: { $search: true } });
      assert.ok(Array.isArray(result), "result is array");
    });
    it("should accept $suggest", async () => {
      const result = await service.find({ query: { $suggest: true } });
      assert.ok(Array.isArray(result), "result is array");
    });
    it("should accept $params", async () => {
      const result = await service.find({ query: { $params: true } });
      assert.ok(Array.isArray(result), "result is array");
    });
    it("should accept $facet", async () => {
      const result = await service.find({ query: { $facet: true } });
      assert.ok(Array.isArray(result), "result is array");
    });
    it("should accept $populate", async () => {
      const result = await service.find({ query: { $populate: true } });
      assert.ok(Array.isArray(result), "result is array");
    });
  });

  describe("Prepare Adapter Tests", () => {
    it(".delete multi ", async () => {
      service.options.multi = ["remove"];
      await service.remove(null, { query: { id: "*" } });
      service.options.multi = false;
      const result = await service.find({});
      assert.ok(Array.isArray(result), "data is an array");
      assert.ok(result.length == 0, "data is empty");
    });

    it("has fields name", async () => {
      const response = await service.Model.get("schema/fields/name");
      assert.ok(response.field.name == "name", "field name exists");
    });

    it("has fields age", async () => {
      const response = await service.Model.get("schema/fields/age");
      assert.ok(response.field.name == "age", "field age exists");
    });

    it("has fields created", async () => {
      const response = await service.Model.get("schema/fields/created");
      assert.ok(response.field.name == "created", "field created exists");
    });
  });
  testSuite(app, errors, "techproducts");
});
<|endoftext|>


<commit_before>import path from 'path'
import fs from 'fs'
import { transformFileSync } from 'babel-core'
import plugin from '../src'

function trim(str) {
  return str.replace(/^\s+|\s+$/, '');
}

describe('babel-plugin-styled-components', () => {
  const fixturesDir = path.join(__dirname, 'fixtures')
  fs.readdirSync(fixturesDir).sort().map((caseName) => {
    it(`should ${caseName.replace(/^\d*-/, '').split('-').join(' ')}`, () => {
      const fixtureDir = path.join(fixturesDir, caseName)
      const beforePath = path.join(fixtureDir, 'before.js');
      const before = transformFileSync(beforePath).code

      const after = fs.readFileSync(
          path.join(fixtureDir, 'after.js')
      ).toString()

      expect(trim(before)).toEqual(trim(after))
    })
  })
})
<commit_msg>Keep tests from breaking with .DS_Store<commit_after>import path from 'path'
import fs from 'fs'
import { transformFileSync } from 'babel-core'
import plugin from '../src'

function trim(str) {
  return str.replace(/^\s+|\s+$/, '');
}

describe('babel-plugin-styled-components', () => {
  const fixturesDir = path.join(__dirname, 'fixtures')
  fs.readdirSync(fixturesDir).sort().map((caseName) => {
    if (caseName === '.DS_Store') return
    it(`should ${caseName.replace(/^\d*-/, '').split('-').join(' ')}`, () => {
      const fixtureDir = path.join(fixturesDir, caseName)
      const beforePath = path.join(fixtureDir, 'before.js');
      const before = transformFileSync(beforePath).code

      const after = fs.readFileSync(
          path.join(fixtureDir, 'after.js')
      ).toString()

      expect(trim(before)).toEqual(trim(after))
    })
  })
})
<|endoftext|>


<commit_before>var should = require('chai').should(),
    assert = require('better-assert'),
    parser = require('../');

describe('index.test.js', function () {

    it('should support git://*', function () {
      var url = 'git://github.com/jamesor/mongoose-versioner';
      parser(url).should.equal('github.com/jamesor/mongoose-versioner');
    });

    it('should support git://*.git', function () {
      var url = 'git://github.com/treygriffith/cellar.git';
      parser(url).should.equal('github.com/treygriffith/cellar');
    });

    it('should support https://*', function () {
      var url = 'https://github.com/Empeeric/i18n-node';
      parser(url).should.equal('github.com/Empeeric/i18n-node');
    });

    it('should support https://*.git', function () {
      var url = 'https://jpillora@github.com/banchee/tranquil.git';
      parser(url).should.equal('github.com/banchee/tranquil');
    });

    it('should return undefined on failure', function () {
      var url = 'git://github.com/justgord/.git';
      assert(parser(url) == null);
    });

    it('should parse git@gist urls', function () {
      var url = 'git@gist.github.com:3135914.git';
      parser(url).should.equal('gist.github.com/3135914');
    });

    it('should parse https://gist urls', function () {
      var url = 'https://gist.github.com/3135914.git';
      parser(url).should.equal('gist.github.com/3135914');
    });

    it('should parse git@github urls', function () {
      var url = 'git@github.com:AdoHe/ImageServer.git';
      parser(url).should.equal('github.com/AdoHe/ImageServer');
    });

    it('should parse company specific git@* urls', function () {
      var url = 'git@dev.sh.westudio.com:framework/Tunnel.git';
      parser(url).should.equal('dev.sh.westudio.com/framework/Tunnel');
    });
});
<commit_msg>add travis ci support....<commit_after>var should = require('chai').should(),
    assert = require('better-assert'),
    parser = require('../');

describe('index.test.js', function () {

    it('should support git://*', function () {
      var url = 'git://github.com/jamesor/mongoose-versioner';
      parser(url).should.equal('github.com/jamesor/mongoose-versioner');
    });

    it('should support git://*.git', function () {
      var url = 'git://github.com/treygriffith/cellar.git';
      parser(url).should.equal('github.com/treygriffith/cellar');
    });

    it('should support https://*', function () {
      var url = 'https://github.com/Empeeric/i18n-node';
      parser(url).should.equal('github.com/Empeeric/i18n-node');
    });

    it('should parse https://*.git', function () {
      var url = 'https://jpillora@github.com/banchee/tranquil.git';
      parser(url).should.equal('github.com/banchee/tranquil');
    });

    it('should return undefined on failure', function () {
      var url = 'git://github.com/justgord/.git';
      assert(parser(url) == null);
    });

    it('should parse git@gist urls', function () {
      var url = 'git@gist.github.com:3135914.git';
      parser(url).should.equal('gist.github.com/3135914');
    });

    it('should parse https://gist urls', function () {
      var url = 'https://gist.github.com/3135914.git';
      parser(url).should.equal('gist.github.com/3135914');
    });

    it('should parse git@github urls', function () {
      var url = 'git@github.com:AdoHe/ImageServer.git';
      parser(url).should.equal('github.com/AdoHe/ImageServer');
    });

    it('should parse company specific git@* urls', function () {
      var url = 'git@dev.sh.westudio.com:framework/Tunnel.git';
      parser(url).should.equal('dev.sh.westudio.com/framework/Tunnel');
    });
});
<|endoftext|>


<commit_before>/* eslint-env node, mocha */
import fs from 'fs';
import postcssSyntax from 'postcss-scss';
import { expect } from 'chai';

import cssSelectorExtract, { process, processSync } from '../js/index';

/** @test {cssSelectorExtract} */
describe(`cssSelectorExtract`, () => {
  const css = fs.readFileSync(`test/css/test.css`, { encoding: `utf8` });
  const scss = fs.readFileSync(`test/css/test.scss`, { encoding: `utf8` });
  const scssSyntaxTest = fs.readFileSync(`test/css/scss-syntax-test.scss`, { encoding: `utf8` });

  it(`should be a function`, () => {
    expect(typeof cssSelectorExtract).to.equal(`object`);
  });

  /** @test {process} */
  describe(`process()`, () => {
    it(`should be a function`, () => {
      expect(typeof process).to.equal(`function`);
    });

    it(`CSS: correct way to extract default selector - should return filtered selector`, () => {
      const referenceCss = fs.readFileSync(`test/css/reference/test1.css`, { encoding: `utf8` });
      const filters = [`.test-selector`];
      return process({ css, filters })
        .then((extractCss) => {
          expect(extractCss.trim()).to.equal(referenceCss.trim());
        });
    });

    it(`CSS: correct way to extract nested selector - should return filtered selector`, () => { // eslint-disable-line max-len
      const referenceCss = fs.readFileSync(`test/css/reference/test2.css`, { encoding: `utf8` });
      const filters = [`.nest .nested-test-selector`];
      return process({ css, filters })
        .then((extractCss) => {
          expect(extractCss.trim()).to.equal(referenceCss.trim());
        });
    });

    it(`CSS: wrong way to extract nested selector - should return empty string`, () => {
      const filters = [`.nested-test-selector`];
      return process({ css, filters })
        .then((extractCss) => {
          expect(extractCss.trim()).to.equal(``);
        });
    });

    it(`CSS: correct way to extract @media nested selector - should return filtered selector`, () => { // eslint-disable-line max-len
      const referenceCss = fs.readFileSync(`test/css/reference/test3.css`, { encoding: `utf8` });
      const filters = [`.nested-in-media-query`];
      return process({ css, filters })
        .then((extractCss) => {
          expect(extractCss.trim()).to.equal(referenceCss.trim());
        });
    });

    it(`CSS: selector replacement - should return replaced selector`, () => {
      const referenceCss = fs.readFileSync(`test/css/reference/test4.css`, { encoding: `utf8` });
      const filters = [{
        selector: `.test-selector`,
        replacement: `.test-selector-replaced`,
      }];
      return process({ css, filters })
        .then((extractCss) => {
          expect(extractCss.trim()).to.equal(referenceCss.trim());
        });
    });

    it(`SCSS: wrong way to extract nested selector - should return empty string`, () => {
      const filters = [`.nested-test-selector`];
      return process({ css: scss, filters, postcssSyntax })
        .then((extractCss) => {
          expect(extractCss.trim()).to.equal(``);
        });
    });

    it(`SCSS: extract multiple instances of a selector with nested child selectors - should return the selectors with all nested selectors`, () => { // eslint-disable-line max-len
      const referenceScss = fs.readFileSync(`test/css/reference/test5.scss`, { encoding: `utf8` });
      const filters = [
        `.nest`,
        `.commma-nest-test`,
        {
          selector: `.replace-nest-test`,
          replacement: `.replaced-nest-test`,
        },
        {
          selector: `.replace-nested-test-selector`,
          replacement: `.replaced-nested-test-selector`,
        },
      ];
      return process({ css: scss, filters, postcssSyntax })
        .then((extractCss) => {
          expect(extractCss.trim()).to.equal(referenceScss.trim());
        });
    });

    it(`SCSS: correct way to extract @media nested selector - should return filtered selector`, () => { // eslint-disable-line max-len
      const referenceScss = fs.readFileSync(`test/css/reference/test6.scss`, { encoding: `utf8` });
      const filters = [`.media-query-in-test-selector`];
      return process({ css: scss, filters, postcssSyntax })
        .then((extractCss) => {
          expect(extractCss.trim()).to.equal(referenceScss.trim());
        });
    });

    it(`SCSS: test SCSS syntax - should finish without errors`, () => {
      const referenceScss = fs.readFileSync(`test/css/reference/test7.scss`, { encoding: `utf8` });
      const filters = [`.none`];
      return process({ css: scssSyntaxTest, filters, postcssSyntax })
        .then((extractCss) => {
          expect(extractCss.trim()).to.equal(referenceScss.trim());
        });
    });

    it(`RegEx: extract selectors using regular expressions`, () => {
      const referenceCss = fs.readFileSync(`test/css/reference/test8.css`, { encoding: `utf8` });
      const filters = [/^\.test-.*/];
      return process({ css, filters })
        .then((extractCss) => {
          expect(extractCss.trim()).to.equal(referenceCss.trim());
        });
    });

    it(`RegEx: extract and replace selectors using regular expressions`, () => {
      const referenceCss = fs.readFileSync(`test/css/reference/test9.css`, { encoding: `utf8` });
      const filters = [{
        selector: /^\.test-(.+)-(.+).*/,
        replacement: `.test__$1--$2`,
      }];
      return process({ css, filters })
        .then((extractCss) => {
          expect(extractCss.trim()).to.equal(referenceCss.trim());
        });
    });

    it(`Bootstrap: extract and replace selectors using regular expressions`, () => {
      const bootstrapCss = fs.readFileSync(`node_modules/bootstrap/scss/_alert.scss`, {
        encoding: `utf8`,
      });
      const referenceCss = fs.readFileSync(`test/css/reference/test10.scss`, { encoding: `utf8` });
      const filters = [
        `.alert`,
        `.close`,
        {
          selector: `.alert-heading`,
          replacement: `.alert__heading`,
        },
        {
          selector: `.alert-link`,
          replacement: `.alert__link`,
        },
        {
          selector: /^\.alert-(.+)/,
          replacement: `.alert--$1`,
        },
      ];
      return process({ css: bootstrapCss, filters, postcssSyntax })
        .then((extractCss) => {
          expect(extractCss.trim()).to.equal(referenceCss.trim());
        });
    });
  });

  /** @test {processSync} */
  describe(`processSync()`, () => {
    it(`should be a function`, () => {
      expect(typeof processSync).to.equal(`function`);
    });
  });
});
<commit_msg>Fix test definition<commit_after>/* eslint-env node, mocha */
import fs from 'fs';
import postcssSyntax from 'postcss-scss';
import { expect } from 'chai';

import cssSelectorExtract, { process, processSync } from '../js/index';

/** @test {cssSelectorExtract} */
describe(`cssSelectorExtract`, () => {
  const css = fs.readFileSync(`test/css/test.css`, { encoding: `utf8` });
  const scss = fs.readFileSync(`test/css/test.scss`, { encoding: `utf8` });
  const scssSyntaxTest = fs.readFileSync(`test/css/scss-syntax-test.scss`, { encoding: `utf8` });

  it(`should be a object`, () => {
    expect(typeof cssSelectorExtract).to.equal(`object`);
  });

  /** @test {process} */
  describe(`process()`, () => {
    it(`should be a function`, () => {
      expect(typeof process).to.equal(`function`);
    });

    it(`CSS: correct way to extract default selector - should return filtered selector`, () => {
      const referenceCss = fs.readFileSync(`test/css/reference/test1.css`, { encoding: `utf8` });
      const filters = [`.test-selector`];
      return process({ css, filters })
        .then((extractCss) => {
          expect(extractCss.trim()).to.equal(referenceCss.trim());
        });
    });

    it(`CSS: correct way to extract nested selector - should return filtered selector`, () => { // eslint-disable-line max-len
      const referenceCss = fs.readFileSync(`test/css/reference/test2.css`, { encoding: `utf8` });
      const filters = [`.nest .nested-test-selector`];
      return process({ css, filters })
        .then((extractCss) => {
          expect(extractCss.trim()).to.equal(referenceCss.trim());
        });
    });

    it(`CSS: wrong way to extract nested selector - should return empty string`, () => {
      const filters = [`.nested-test-selector`];
      return process({ css, filters })
        .then((extractCss) => {
          expect(extractCss.trim()).to.equal(``);
        });
    });

    it(`CSS: correct way to extract @media nested selector - should return filtered selector`, () => { // eslint-disable-line max-len
      const referenceCss = fs.readFileSync(`test/css/reference/test3.css`, { encoding: `utf8` });
      const filters = [`.nested-in-media-query`];
      return process({ css, filters })
        .then((extractCss) => {
          expect(extractCss.trim()).to.equal(referenceCss.trim());
        });
    });

    it(`CSS: selector replacement - should return replaced selector`, () => {
      const referenceCss = fs.readFileSync(`test/css/reference/test4.css`, { encoding: `utf8` });
      const filters = [{
        selector: `.test-selector`,
        replacement: `.test-selector-replaced`,
      }];
      return process({ css, filters })
        .then((extractCss) => {
          expect(extractCss.trim()).to.equal(referenceCss.trim());
        });
    });

    it(`SCSS: wrong way to extract nested selector - should return empty string`, () => {
      const filters = [`.nested-test-selector`];
      return process({ css: scss, filters, postcssSyntax })
        .then((extractCss) => {
          expect(extractCss.trim()).to.equal(``);
        });
    });

    it(`SCSS: extract multiple instances of a selector with nested child selectors - should return the selectors with all nested selectors`, () => { // eslint-disable-line max-len
      const referenceScss = fs.readFileSync(`test/css/reference/test5.scss`, { encoding: `utf8` });
      const filters = [
        `.nest`,
        `.commma-nest-test`,
        {
          selector: `.replace-nest-test`,
          replacement: `.replaced-nest-test`,
        },
        {
          selector: `.replace-nested-test-selector`,
          replacement: `.replaced-nested-test-selector`,
        },
      ];
      return process({ css: scss, filters, postcssSyntax })
        .then((extractCss) => {
          expect(extractCss.trim()).to.equal(referenceScss.trim());
        });
    });

    it(`SCSS: correct way to extract @media nested selector - should return filtered selector`, () => { // eslint-disable-line max-len
      const referenceScss = fs.readFileSync(`test/css/reference/test6.scss`, { encoding: `utf8` });
      const filters = [`.media-query-in-test-selector`];
      return process({ css: scss, filters, postcssSyntax })
        .then((extractCss) => {
          expect(extractCss.trim()).to.equal(referenceScss.trim());
        });
    });

    it(`SCSS: test SCSS syntax - should finish without errors`, () => {
      const referenceScss = fs.readFileSync(`test/css/reference/test7.scss`, { encoding: `utf8` });
      const filters = [`.none`];
      return process({ css: scssSyntaxTest, filters, postcssSyntax })
        .then((extractCss) => {
          expect(extractCss.trim()).to.equal(referenceScss.trim());
        });
    });

    it(`RegEx: extract selectors using regular expressions`, () => {
      const referenceCss = fs.readFileSync(`test/css/reference/test8.css`, { encoding: `utf8` });
      const filters = [/^\.test-.*/];
      return process({ css, filters })
        .then((extractCss) => {
          expect(extractCss.trim()).to.equal(referenceCss.trim());
        });
    });

    it(`RegEx: extract and replace selectors using regular expressions`, () => {
      const referenceCss = fs.readFileSync(`test/css/reference/test9.css`, { encoding: `utf8` });
      const filters = [{
        selector: /^\.test-(.+)-(.+).*/,
        replacement: `.test__$1--$2`,
      }];
      return process({ css, filters })
        .then((extractCss) => {
          expect(extractCss.trim()).to.equal(referenceCss.trim());
        });
    });

    it(`Bootstrap: extract and replace selectors using regular expressions`, () => {
      const bootstrapCss = fs.readFileSync(`node_modules/bootstrap/scss/_alert.scss`, {
        encoding: `utf8`,
      });
      const referenceCss = fs.readFileSync(`test/css/reference/test10.scss`, { encoding: `utf8` });
      const filters = [
        `.alert`,
        `.close`,
        {
          selector: `.alert-heading`,
          replacement: `.alert__heading`,
        },
        {
          selector: `.alert-link`,
          replacement: `.alert__link`,
        },
        {
          selector: /^\.alert-(.+)/,
          replacement: `.alert--$1`,
        },
      ];
      return process({ css: bootstrapCss, filters, postcssSyntax })
        .then((extractCss) => {
          expect(extractCss.trim()).to.equal(referenceCss.trim());
        });
    });
  });

  /** @test {processSync} */
  describe(`processSync()`, () => {
    it(`should be a function`, () => {
      expect(typeof processSync).to.equal(`function`);
    });
  });
});
<|endoftext|>


<commit_before>/* eslint no-loop-func: 0 */

var path = require('path');
var gulp = require('gulp');
var rename = require('gulp-rename');
var run = require('../');
var util = require('./util');

describe('gulp-run', function gulpRunTestCase() {
  var inputFileName = path.join(__dirname, '_resource/input.txt');

  // it('includes `node_modules/.bin` on the PATH', function includeNodeModulesTest(done) {
  //   var nodeModulesPath = path.join(__dirname, '..', '..', '.bin');
  //
  //   run('echo $PATH', { verbosity: 0 }).exec()
  //     .pipe(util.compare(new RegExp('^' + nodeModulesPath)))
  //     .on('finish', done)
  //   ;
  // });

  // it('lets you set the initial cwd of the command', function cwdTest(done) {
  //   run('pwd', { cwd: '/', verbosity: 0 }).exec()
  //     .pipe(util.compare('/\n'))
  //     .on('finish', done)
  //   ;
  // });

  // describe.skip('verbosity levels', function verbosityTestCase() {
  //   var colors = require('gulp-util').colors;
  //   var output = '';
  //   var stdoutWrite = process.stdout.write;
  //
  //   before(function handleBefore() {
  //     process.stdout.write = function write(chunk, enc, callback) {
  //       output += chunk.toString(enc);
  //
  //       if (typeof callback === 'function') {
  //         process.nextTick(callback);
  //       }
  //     };
  //   });
  //
  //   after(function handleAfter() {
  //     process.stdout.write = stdoutWrite;
  //   });
  //
  //   beforeEach(function handleBeforeEach() {
  //     output = '';
  //   });
  //
  //   it('verbosity 0 never prints', function neverPrintTest(done) {
  //     (new run.Command('echo "testing verbosity:0"', { verbosity: 0 }))
  //       .exec(function handleExec() {
  //         output.should.match(/^$/);
  //
  //         done();
  //       })
  //     ;
  //   });
  //
  //   it('verbosity 1 prints stderr when the command is done', function stdErrPrintTest(done) {
  //     (new run.Command('echo "testing verbosity:1"', { verbosity: 1 }))
  //       .exec(function handleExec() {
  //         output = colors.stripColor(output);
  //         output.should.match(/\$ echo "testing verbosity:1" # Silenced\s*\n/);
  //
  //         done();
  //       })
  //     ;
  //   });
  //
  //   it(
  //     'verbosity 2 prints stderr and stdout when the command is done',
  //     function stdErrAndStdOutTest(done) {
  //       (new run.Command('echo "testing verbosity:2"', { verbosity: 2 }))
  //         .exec(function handleExec() {
  //           output = colors.stripColor(output);
  //           output.should.match(/\$ echo "testing verbosity:2"\s*\ntesting verbosity:2/);
  //
  //           done();
  //         })
  //       ;
  //     }
  //   );
  //
  //   it('verbosity 3 prints stderr and stdout in real time', function printAllTest(done) {
  //     (new run.Command('echo "testing verbosity:3"', { verbosity: 3 }))
  //       .exec(function handleExec() {
  //         output = colors.stripColor(output);
  //         output.should.match(/\$ echo "testing verbosity:3"\s*\ntesting verbosity:3/);
  //
  //         done();
  //       })
  //     ;
  //   });
  // });

  describe('in a vinyl pipeline', function vinylPipelineTestCase() {
    // it('works with buffers', function bufferTest(done) {
    //   // use awk to extract the even lines of a file
    //   gulp.src(inputFileName, { buffer: true })
    //     .pipe(run('awk "NR % 2 == 0"', {
    //       verbosity: 0
    //     }))
    //     .pipe(util.compare('2\n4\n6\n8\n10\n12\n'))
    //     .on('finish', done)
    //   ;
    // });

    // it('works with streams', function streamTest(done) {
    //   // use awk to extract the even lines of a file
    //   gulp.src(inputFileName, { buffer: false })
    //     .pipe(run('awk "NR % 2 == 0"', {
    //       verbosity: 0
    //     }))
    //     .pipe(util.compare('2\n4\n6\n8\n10\n12\n'))
    //     .on('finish', done)
    //   ;
    // });

    it('supports command templates, i.e. `echo <%= file.path %>`', function templateTest(done) {
      gulp.src(inputFileName)
        .pipe(run('echo <%= file.path %>', {
          verbosity: 0
        }))
        .pipe(util.compare(inputFileName + '\n'))
        .on('finish', done)
      ;
    });

    it('emits an `error` event on a failed command', function errorTest(done) {
      gulp.src(inputFileName)
        .pipe(run('exit 1', { verbosity: 0 }))
        .on('error', util.noop(done))
      ;
    });

    it('maintains metadata of incoming file', function metaDataTest(done) {
      gulp.src(inputFileName)
        .pipe(util.inspect(function handleInspect(file) {
          file.custom = 'custom metadata';
        }))
        .pipe(run('cat', {
          verbosity: 0
        }))
        .pipe(util.inspect(function captureInspect(file) {
          file.custom.should.equal('custom metadata');
        }))
        .on('finish', done)
      ;
    });
  });

  describe('direct execution (`.exec`)', function execTestCase() {
    it('is asynchronous (this test sleeps for 1s)', function asyncTest(done) {
      var semaphore = new util.Semaphore(2, done);
      var startTime = process.hrtime()[0];
      var index;

      for (index = 0; index < 2; index += 1) {
        run('sleep 1', { verbosity: 0 })
          .exec(function handleExec() {
            var delta = process.hrtime()[0] - startTime;
            delta.should.equal(1);
            semaphore.done();
          })
        ;
      }
    });

    it('returns a vinyl stream wrapping stdout', function wrappingStdOutTest(done) {
      run('echo Hello World', { verbosity: 0 })
        .exec()
        .pipe(util.compare('Hello World\n'))
        .on('finish', done)
      ;
    });

    it('emits an `error` event on a failed command', function emitErrorTest(done) {
      run('exit 1', { verbosity: 0 })
        .exec()
        .on('error', util.noop(done))
      ;
    });

    it('closes the stream when done', function streamCloseTest(done) {
      run('echo Hello World', { verbosity: 0 })
        .exec()
        .on('finish', done)
      ;
    });
  });

  describe('issues', function issuesTestCase() {
    it('#18 - file names and paths', function issue18(done) {
      run('echo hello world', { cwd: './', verbosity: 0 }).exec()
        .pipe(rename('dest.txt'))
        .on('finish', done)
      ;
    });

    it('#35 - no callback if command not found', function commandNotFoundTest(done) {
      run('nonexistant', { verbosity: 0 })
        .exec()
        .on('error', function handleError() {
          done();
        })
      ;
    });
  });
});
<commit_msg>Isolate travis ci error<commit_after>/* eslint no-loop-func: 0 */

var path = require('path');
var gulp = require('gulp');
var rename = require('gulp-rename');
var run = require('../');
var util = require('./util');

describe('gulp-run', function gulpRunTestCase() {
  var inputFileName = path.join(__dirname, '_resource/input.txt');

  // it('includes `node_modules/.bin` on the PATH', function includeNodeModulesTest(done) {
  //   var nodeModulesPath = path.join(__dirname, '..', '..', '.bin');
  //
  //   run('echo $PATH', { verbosity: 0 }).exec()
  //     .pipe(util.compare(new RegExp('^' + nodeModulesPath)))
  //     .on('finish', done)
  //   ;
  // });

  // it('lets you set the initial cwd of the command', function cwdTest(done) {
  //   run('pwd', { cwd: '/', verbosity: 0 }).exec()
  //     .pipe(util.compare('/\n'))
  //     .on('finish', done)
  //   ;
  // });

  // describe.skip('verbosity levels', function verbosityTestCase() {
  //   var colors = require('gulp-util').colors;
  //   var output = '';
  //   var stdoutWrite = process.stdout.write;
  //
  //   before(function handleBefore() {
  //     process.stdout.write = function write(chunk, enc, callback) {
  //       output += chunk.toString(enc);
  //
  //       if (typeof callback === 'function') {
  //         process.nextTick(callback);
  //       }
  //     };
  //   });
  //
  //   after(function handleAfter() {
  //     process.stdout.write = stdoutWrite;
  //   });
  //
  //   beforeEach(function handleBeforeEach() {
  //     output = '';
  //   });
  //
  //   it('verbosity 0 never prints', function neverPrintTest(done) {
  //     (new run.Command('echo "testing verbosity:0"', { verbosity: 0 }))
  //       .exec(function handleExec() {
  //         output.should.match(/^$/);
  //
  //         done();
  //       })
  //     ;
  //   });
  //
  //   it('verbosity 1 prints stderr when the command is done', function stdErrPrintTest(done) {
  //     (new run.Command('echo "testing verbosity:1"', { verbosity: 1 }))
  //       .exec(function handleExec() {
  //         output = colors.stripColor(output);
  //         output.should.match(/\$ echo "testing verbosity:1" # Silenced\s*\n/);
  //
  //         done();
  //       })
  //     ;
  //   });
  //
  //   it(
  //     'verbosity 2 prints stderr and stdout when the command is done',
  //     function stdErrAndStdOutTest(done) {
  //       (new run.Command('echo "testing verbosity:2"', { verbosity: 2 }))
  //         .exec(function handleExec() {
  //           output = colors.stripColor(output);
  //           output.should.match(/\$ echo "testing verbosity:2"\s*\ntesting verbosity:2/);
  //
  //           done();
  //         })
  //       ;
  //     }
  //   );
  //
  //   it('verbosity 3 prints stderr and stdout in real time', function printAllTest(done) {
  //     (new run.Command('echo "testing verbosity:3"', { verbosity: 3 }))
  //       .exec(function handleExec() {
  //         output = colors.stripColor(output);
  //         output.should.match(/\$ echo "testing verbosity:3"\s*\ntesting verbosity:3/);
  //
  //         done();
  //       })
  //     ;
  //   });
  // });

  describe('in a vinyl pipeline', function vinylPipelineTestCase() {
    // it('works with buffers', function bufferTest(done) {
    //   // use awk to extract the even lines of a file
    //   gulp.src(inputFileName, { buffer: true })
    //     .pipe(run('awk "NR % 2 == 0"', {
    //       verbosity: 0
    //     }))
    //     .pipe(util.compare('2\n4\n6\n8\n10\n12\n'))
    //     .on('finish', done)
    //   ;
    // });

    // it('works with streams', function streamTest(done) {
    //   // use awk to extract the even lines of a file
    //   gulp.src(inputFileName, { buffer: false })
    //     .pipe(run('awk "NR % 2 == 0"', {
    //       verbosity: 0
    //     }))
    //     .pipe(util.compare('2\n4\n6\n8\n10\n12\n'))
    //     .on('finish', done)
    //   ;
    // });

    // it('supports command templates, i.e. `echo <%= file.path %>`', function templateTest(done) {
    //   gulp.src(inputFileName)
    //     .pipe(run('echo <%= file.path %>', {
    //       verbosity: 0
    //     }))
    //     .pipe(util.compare(inputFileName + '\n'))
    //     .on('finish', done)
    //   ;
    // });

    it('emits an `error` event on a failed command', function errorTest(done) {
      gulp.src(inputFileName)
        .pipe(run('exit 1', { verbosity: 0 }))
        .on('error', util.noop(done))
      ;
    });

    it('maintains metadata of incoming file', function metaDataTest(done) {
      gulp.src(inputFileName)
        .pipe(util.inspect(function handleInspect(file) {
          file.custom = 'custom metadata';
        }))
        .pipe(run('cat', {
          verbosity: 0
        }))
        .pipe(util.inspect(function captureInspect(file) {
          file.custom.should.equal('custom metadata');
        }))
        .on('finish', done)
      ;
    });
  });

  describe('direct execution (`.exec`)', function execTestCase() {
    it('is asynchronous (this test sleeps for 1s)', function asyncTest(done) {
      var semaphore = new util.Semaphore(2, done);
      var startTime = process.hrtime()[0];
      var index;

      for (index = 0; index < 2; index += 1) {
        run('sleep 1', { verbosity: 0 })
          .exec(function handleExec() {
            var delta = process.hrtime()[0] - startTime;
            delta.should.equal(1);
            semaphore.done();
          })
        ;
      }
    });

    it('returns a vinyl stream wrapping stdout', function wrappingStdOutTest(done) {
      run('echo Hello World', { verbosity: 0 })
        .exec()
        .pipe(util.compare('Hello World\n'))
        .on('finish', done)
      ;
    });

    it('emits an `error` event on a failed command', function emitErrorTest(done) {
      run('exit 1', { verbosity: 0 })
        .exec()
        .on('error', util.noop(done))
      ;
    });

    it('closes the stream when done', function streamCloseTest(done) {
      run('echo Hello World', { verbosity: 0 })
        .exec()
        .on('finish', done)
      ;
    });
  });

  describe('issues', function issuesTestCase() {
    it('#18 - file names and paths', function issue18(done) {
      run('echo hello world', { cwd: './', verbosity: 0 }).exec()
        .pipe(rename('dest.txt'))
        .on('finish', done)
      ;
    });

    it('#35 - no callback if command not found', function commandNotFoundTest(done) {
      run('nonexistant', { verbosity: 0 })
        .exec()
        .on('error', function handleError() {
          done();
        })
      ;
    });
  });
});
<|endoftext|>