<commit_before>const buildArray = require('build-array');
const test = require('ava');

const { default: find, series } = require('../packages/find');
const getIttr = require('../packages/test-get-ittr');
const schedule = require('../packages/test-scheduler')();
const timeout = require('../packages/test-timeout');

test(
  'fulfill [] find',
  schedule(async t => {
    const then = timeout(4);
    const input = [1, 2, 3, 4];
    const order = [];

    const output = await find(input.map(Number), async (v, i) => {
      await then(v);
      order.push(i);
      return v === 2;
    });

    t.deepEqual(output, 2);
    t.notDeepEqual(order, buildArray(order.length).map((v, i) => i));
  })
);

test(
  'fulfill @@Iterator find',
  schedule(async t => {
    const then = timeout(4);
    const order = [];

    const output = await find(getIttr(), async (v, i) => {
      await then(`${v}${v}`);
      order.push(i);
      return i === 2;
    });

    t.deepEqual(output, 'c');
    t.notDeepEqual(order, buildArray(order.length).map((v, i) => i));
  })
);

test(
  'fulfill {} find',
  schedule(async t => {
    const then = timeout(4);
    const order = [];

    const output = await find(
      {
        a: 1,
        b: 2,
        c: 3,
        d: 4
      },
      async (v, i) => {
        await then(v);
        order.push(v);
        return v === 2;
      }
    );

    t.notDeepEqual(order, buildArray(order.length).map((v, i) => i + 1));
    t.deepEqual(output, {
      key: 'b',
      value: 2
    });
  })
);

test(
  'fail [] find',
  schedule(async t => {
    t.throws(
      find([1, 2, 3, 4], async (v, i) => {
        if (i > 2) {
          throw new Error('expected error');
        }

        return false;
      })
    );
  })
);

test(
  'fail @@Iterator find',
  schedule(
    async t =>
      t.throws(
        find(getIttr(), async (v, i) => {
          if (i > 2) {
            throw new Error('expected error');
          }

          return false;
        })
      )
  )
);

test(
  'fail {} find',
  schedule(
    async t =>
      t.throws(
        find(
          {
            a: 1,
            b: 2,
            c: 3,
            d: 4
          },
          async (v, i) => {
            if (i === 'c') {
              throw new Error('expected error');
            }

            return false;
          }
        )
      )
  )
);

test(
  'fulfill [] findSeries',
  schedule(async t => {
    const then = timeout(4);
    const input = [1, 2, 3, 4];
    const order = [];

    const output = await series(input.map(Number), async (v, i) => {
      await then(v);
      order.push(i);
      return v === 2;
    });

    t.deepEqual(output, 2);
    t.deepEqual(order, buildArray(order.length).map((v, i) => i));
  })
);

test(
  'fulfill @@Iterator findSeries',
  schedule(async t => {
    const then = timeout(4);
    const order = [];

    const output = await series(getIttr(), async (v, i) => {
      await then(`${v}${v}`);
      order.push(i);
      return i === 2;
    });

    t.deepEqual(output, 'c');
    t.deepEqual(order, buildArray(order.length).map((v, i) => i));
  })
);

test(
  'fulfill {} findSeries',
  schedule(async t => {
    const then = timeout(4);
    const order = [];

    const output = await series(
      {
        a: 1,
        b: 2,
        c: 3,
        d: 4
      },
      async (v, i) => {
        await then(v);
        order.push(v);
        return v === 2;
      }
    );

    t.deepEqual(order, buildArray(order.length).map((v, i) => i + 1));
    t.deepEqual(output, {
      key: 'b',
      value: 2
    });
  })
);

test(
  'fail [] findSeries',
  schedule(
    async t =>
      t.throws(
        series([1, 2, 3, 4], async (v, i) => {
          if (i > 2) {
            throw new Error('expected error');
          }

          return false;
        })
      )
  )
);

test(
  'fail @@Iterator findSeries',
  schedule(
    async t =>
      t.throws(
        series(getIttr(), async (v, i) => {
          if (i > 2) {
            throw new Error('expected error');
          }

          return false;
        })
      )
  )
);

test(
  'fail {} findSeries',
  schedule(
    async t =>
      t.throws(
        series(
          {
            a: 1,
            b: 2,
            c: 3,
            d: 4
          },
          async (v, i) => {
            if (i === 'c') {
              throw new Error('expected error');
            }

            return false;
          }
        )
      )
  )
);
<commit_msg>fix find<commit_after>const buildArray = require('build-array');
const test = require('ava');

const { default: find, series } = require('../packages/find');
const getIttr = require('../packages/test-get-ittr');
const schedule = require('../packages/test-scheduler')();
const timeout = require('../packages/test-timeout');

test(
  'fulfill [] find',
  schedule(async t => {
    const then = timeout(4);
    const input = [1, 2, 3, 4];
    const order = [];

    const output = await find(input.map(Number), async (v, i) => {
      await then(v);
      order.push(i);
      return v === 2;
    });

    t.deepEqual(output, 2);
    t.notDeepEqual(order, buildArray(order.length).map((v, i) => i));
  })
);

test(
  'fulfill @@Iterator find',
  schedule(async t => {
    const then = timeout(4);
    const order = [];

    const output = await find(getIttr(), async (v, i) => {
      await then(`${v}${v}`);
      order.push(i);
      return i === 2;
    });

    t.deepEqual(output, 'c');
    t.notDeepEqual(order, buildArray(order.length).map((v, i) => i));
  })
);

test(
  'fulfill {} find',
  schedule(async t => {
    const then = timeout(4);
    const order = [];

    const output = await find(
      {
        a: 1,
        b: 2,
        c: 3,
        d: 4
      },
      async (v, i) => {
        await then(v);
        order.push(v);
        return v === 2;
      }
    );

    t.notDeepEqual(order, buildArray(order.length).map((v, i) => i + 1));
    t.deepEqual(output, {
      key: 'b',
      value: 2
    });
  })
);

test(
  'fail [] find',
  schedule(async t =>
    t.throws(
      find([1, 2, 3, 4], async (v, i) => {
        if (i > 2) {
          throw new Error('expected error');
        }

        return false;
      })
    )
  )
);

test(
  'fail @@Iterator find',
  schedule(
    async t =>
      t.throws(
        find(getIttr(), async (v, i) => {
          if (i > 2) {
            throw new Error('expected error');
          }

          return false;
        })
      )
  )
);

test(
  'fail {} find',
  schedule(
    async t =>
      t.throws(
        find(
          {
            a: 1,
            b: 2,
            c: 3,
            d: 4
          },
          async (v, i) => {
            if (i === 'c') {
              throw new Error('expected error');
            }

            return false;
          }
        )
      )
  )
);

test(
  'fulfill [] findSeries',
  schedule(async t => {
    const then = timeout(4);
    const input = [1, 2, 3, 4];
    const order = [];

    const output = await series(input.map(Number), async (v, i) => {
      await then(v);
      order.push(i);
      return v === 2;
    });

    t.deepEqual(output, 2);
    t.deepEqual(order, buildArray(order.length).map((v, i) => i));
  })
);

test(
  'fulfill @@Iterator findSeries',
  schedule(async t => {
    const then = timeout(4);
    const order = [];

    const output = await series(getIttr(), async (v, i) => {
      await then(`${v}${v}`);
      order.push(i);
      return i === 2;
    });

    t.deepEqual(output, 'c');
    t.deepEqual(order, buildArray(order.length).map((v, i) => i));
  })
);

test(
  'fulfill {} findSeries',
  schedule(async t => {
    const then = timeout(4);
    const order = [];

    const output = await series(
      {
        a: 1,
        b: 2,
        c: 3,
        d: 4
      },
      async (v, i) => {
        await then(v);
        order.push(v);
        return v === 2;
      }
    );

    t.deepEqual(order, buildArray(order.length).map((v, i) => i + 1));
    t.deepEqual(output, {
      key: 'b',
      value: 2
    });
  })
);

test(
  'fail [] findSeries',
  schedule(
    async t =>
      t.throws(
        series([1, 2, 3, 4], async (v, i) => {
          if (i > 2) {
            throw new Error('expected error');
          }

          return false;
        })
      )
  )
);

test(
  'fail @@Iterator findSeries',
  schedule(
    async t =>
      t.throws(
        series(getIttr(), async (v, i) => {
          if (i > 2) {
            throw new Error('expected error');
          }

          return false;
        })
      )
  )
);

test(
  'fail {} findSeries',
  schedule(
    async t =>
      t.throws(
        series(
          {
            a: 1,
            b: 2,
            c: 3,
            d: 4
          },
          async (v, i) => {
            if (i === 'c') {
              throw new Error('expected error');
            }

            return false;
          }
        )
      )
  )
);
<|endoftext|>


<commit_before>'use strict';

var should = require('should');
var gutil = require('gulp-util');
var path = require('path');
var fs = require('fs');
var sass = require('../index');
var assert = require('assert');

var createVinyl = function createVinyl(filename, contents) {
  var base = path.join(__dirname, 'scss');
  var filePath = path.join(base, filename);

  return new gutil.File({
    'cwd': __dirname,
    'base': base,
    'path': filePath,
    'contents': contents || fs.readFileSync(filePath)
  });
};

describe('gulp-sass -- async compile', function() {
  it('should pass file when it isNull()', function(done) {
    var stream = sass();
    var emptyFile = {
      'isNull': function () {
        return true;
      }
    };
    stream.on('data', function(data) {
      data.should.equal(emptyFile);
      done();
    });
    stream.write(emptyFile);
  });

  it('should emit error when file isStream()', function (done) {
    var stream = sass();
    var streamFile = {
      'isNull': function () {
        return false;
      },
      'isStream': function () {
        return true;
      }
    };
    stream.on('error', function(err) {
      err.message.should.equal('Streaming not supported');
      done();
    });
    stream.write(streamFile);
  });

  it('should compile a single sass file', function(done) {
    var sassFile = createVinyl('mixins.scss');
    var stream = sass();
    stream.on('data', function(cssFile) {
      should.exist(cssFile);
      should.exist(cssFile.path);
      should.exist(cssFile.relative);
      should.exist(cssFile.contents);
      String(cssFile.contents).should.equal(
        fs.readFileSync(path.join(__dirname, 'expected/mixins.css'), 'utf8')
      );
      done();
    });
    stream.write(sassFile);
  });

  it('should compile multiple sass files', function(done) {
    var files = [
      createVinyl('mixins.scss'),
      createVinyl('variables.scss')
    ];
    var stream = sass();
    var mustSee = files.length;
    var expectedPath = 'expected/mixins.css';

    stream.on('data', function(cssFile) {
      should.exist(cssFile);
      should.exist(cssFile.path);
      should.exist(cssFile.relative);
      should.exist(cssFile.contents);
      if (cssFile.path.indexOf('variables') !== -1) {
        expectedPath = 'expected/variables.css';
      }
      String(cssFile.contents).should.equal(
        fs.readFileSync(path.join(__dirname, expectedPath), 'utf8')
      );
      mustSee--;
      if (mustSee <= 0) {
        done();
      }
    });

    files.forEach(function (file) {
      stream.write(file);
    });
  });

  it('should compile files with partials in another folder', function(done) {
    var sassFile = createVinyl('inheritance.scss');
    var stream = sass();
    stream.on('data', function(cssFile) {
      should.exist(cssFile);
      should.exist(cssFile.path);
      should.exist(cssFile.relative);
      should.exist(cssFile.contents);
      String(cssFile.contents).should.equal(
        fs.readFileSync(path.join(__dirname, 'expected/inheritance.css'), 'utf8')
      );
      done();
    });
    stream.write(sassFile);
  });

  it('should handle sass errors', function(done) {
    var errorFile = createVinyl('error.scss');
    var stream = sass();

    stream.on('error', function(err) {
      err.message.indexOf('property "font" must be followed by a \':\'').should.not.equal(-1);
      done();
    });
    stream.write(errorFile);
  });

  it('should work with gulp-sourcemaps', function(done) {
    var sassFile = createVinyl('inheritance.scss');

    // Expected sources are relative to file.base
    var expectedSources = [
      'includes/_cats.scss',
      '../../stdin'
    ];

    var stream;

    sassFile.sourceMap = '{' +
      '"version": 3,' +
      '"file": "scss/subdir/multilevelimport.scss",' +
      '"names": [],' +
      '"mappings": "",' +
      '"sources": [ "scss/subdir/multilevelimport.scss" ],' +
      '"sourcesContent": [ "@import ../inheritance;" ]' +
    '}';

    stream = sass();
    stream.on('data', function(cssFile) {
      should.exist(cssFile.sourceMap);
      assert.deepEqual(cssFile.sourceMap.sources, expectedSources);
      done();
    });
    stream.write(sassFile);
  });
});

describe('gulp-sass -- sync compile', function() {
  it('should pass file when it isNull()', function(done) {
    var stream = sass.sync();
    var emptyFile = {
      'isNull': function () {
        return true;
      }
    };
    stream.on('data', function(data) {
      data.should.equal(emptyFile);
      done();
    });
    stream.write(emptyFile);
  });

  it('should emit error when file isStream()', function (done) {
    var stream = sass.sync();
    var streamFile = {
      'isNull': function () {
        return false;
      },
      'isStream': function () {
        return true;
      }
    };
    stream.on('error', function(err) {
      err.message.should.equal('Streaming not supported');
      done();
    });
    stream.write(streamFile);
  });

  it('should compile a single sass file', function(done) {
    var sassFile = createVinyl('mixins.scss');
    var stream = sass.sync();
    stream.on('data', function(cssFile) {
      should.exist(cssFile);
      should.exist(cssFile.path);
      should.exist(cssFile.relative);
      should.exist(cssFile.contents);
      String(cssFile.contents).should.equal(
        fs.readFileSync(path.join(__dirname, 'expected/mixins.css'), 'utf8')
      );
      done();
    });
    stream.write(sassFile);
  });

  it('should compile multiple sass files', function(done) {
    var files = [
      createVinyl('mixins.scss'),
      createVinyl('variables.scss')
    ];
    var stream = sass.sync();
    var mustSee = files.length;
    var expectedPath = 'expected/mixins.css';

    stream.on('data', function(cssFile) {
      should.exist(cssFile);
      should.exist(cssFile.path);
      should.exist(cssFile.relative);
      should.exist(cssFile.contents);
      if (cssFile.path.indexOf('variables') !== -1) {
        expectedPath = 'expected/variables.css';
      }
      String(cssFile.contents).should.equal(
        fs.readFileSync(path.join(__dirname, expectedPath), 'utf8')
      );
      mustSee--;
      if (mustSee <= 0) {
        done();
      }
    });

    files.forEach(function (file) {
      stream.write(file);
    });
  });

  it('should compile files with partials in another folder', function(done) {
    var sassFile = createVinyl('inheritance.scss');
    var stream = sass.sync();
    stream.on('data', function(cssFile) {
      should.exist(cssFile);
      should.exist(cssFile.path);
      should.exist(cssFile.relative);
      should.exist(cssFile.contents);
      String(cssFile.contents).should.equal(
        fs.readFileSync(path.join(__dirname, 'expected/inheritance.css'), 'utf8')
      );
      done();
    });
    stream.write(sassFile);
  });

  it('should handle sass errors', function(done) {
    var errorFile = createVinyl('error.scss');
    var stream = sass.sync();

    stream.on('error', function(err) {
      err.message.indexOf('property "font" must be followed by a \':\'').should.not.equal(-1);
      done();
    });
    stream.write(errorFile);
  });

  it('should work with gulp-sourcemaps', function(done) {
    var sassFile = createVinyl('inheritance.scss');

    // Expected sources are relative to file.base
    var expectedSources = [
      'includes/_cats.scss',
      'inheritance.scss'
    ];

    var stream;

    sassFile.sourceMap = '{' +
      '"version": 3,' +
      '"file": "scss/subdir/multilevelimport.scss",' +
      '"names": [],' +
      '"mappings": "",' +
      '"sources": [ "scss/subdir/multilevelimport.scss" ],' +
      '"sourcesContent": [ "@import ../inheritance;" ]' +
    '}';

    stream = sass.sync();
    stream.on('data', function(cssFile) {
      should.exist(cssFile.sourceMap);
      assert.deepEqual(cssFile.sourceMap.sources, expectedSources);
      done();
    });
    stream.write(sassFile);
  });
});
<commit_msg>Nope, shouldn't be , should be file name<commit_after>'use strict';

var should = require('should');
var gutil = require('gulp-util');
var path = require('path');
var fs = require('fs');
var sass = require('../index');
var assert = require('assert');

var createVinyl = function createVinyl(filename, contents) {
  var base = path.join(__dirname, 'scss');
  var filePath = path.join(base, filename);

  return new gutil.File({
    'cwd': __dirname,
    'base': base,
    'path': filePath,
    'contents': contents || fs.readFileSync(filePath)
  });
};

describe('gulp-sass -- async compile', function() {
  it('should pass file when it isNull()', function(done) {
    var stream = sass();
    var emptyFile = {
      'isNull': function () {
        return true;
      }
    };
    stream.on('data', function(data) {
      data.should.equal(emptyFile);
      done();
    });
    stream.write(emptyFile);
  });

  it('should emit error when file isStream()', function (done) {
    var stream = sass();
    var streamFile = {
      'isNull': function () {
        return false;
      },
      'isStream': function () {
        return true;
      }
    };
    stream.on('error', function(err) {
      err.message.should.equal('Streaming not supported');
      done();
    });
    stream.write(streamFile);
  });

  it('should compile a single sass file', function(done) {
    var sassFile = createVinyl('mixins.scss');
    var stream = sass();
    stream.on('data', function(cssFile) {
      should.exist(cssFile);
      should.exist(cssFile.path);
      should.exist(cssFile.relative);
      should.exist(cssFile.contents);
      String(cssFile.contents).should.equal(
        fs.readFileSync(path.join(__dirname, 'expected/mixins.css'), 'utf8')
      );
      done();
    });
    stream.write(sassFile);
  });

  it('should compile multiple sass files', function(done) {
    var files = [
      createVinyl('mixins.scss'),
      createVinyl('variables.scss')
    ];
    var stream = sass();
    var mustSee = files.length;
    var expectedPath = 'expected/mixins.css';

    stream.on('data', function(cssFile) {
      should.exist(cssFile);
      should.exist(cssFile.path);
      should.exist(cssFile.relative);
      should.exist(cssFile.contents);
      if (cssFile.path.indexOf('variables') !== -1) {
        expectedPath = 'expected/variables.css';
      }
      String(cssFile.contents).should.equal(
        fs.readFileSync(path.join(__dirname, expectedPath), 'utf8')
      );
      mustSee--;
      if (mustSee <= 0) {
        done();
      }
    });

    files.forEach(function (file) {
      stream.write(file);
    });
  });

  it('should compile files with partials in another folder', function(done) {
    var sassFile = createVinyl('inheritance.scss');
    var stream = sass();
    stream.on('data', function(cssFile) {
      should.exist(cssFile);
      should.exist(cssFile.path);
      should.exist(cssFile.relative);
      should.exist(cssFile.contents);
      String(cssFile.contents).should.equal(
        fs.readFileSync(path.join(__dirname, 'expected/inheritance.css'), 'utf8')
      );
      done();
    });
    stream.write(sassFile);
  });

  it('should handle sass errors', function(done) {
    var errorFile = createVinyl('error.scss');
    var stream = sass();

    stream.on('error', function(err) {
      err.message.indexOf('property "font" must be followed by a \':\'').should.not.equal(-1);
      done();
    });
    stream.write(errorFile);
  });

  it('should work with gulp-sourcemaps', function(done) {
    var sassFile = createVinyl('inheritance.scss');

    // Expected sources are relative to file.base
    var expectedSources = [
      'includes/_cats.scss',
      'inheritance.scss'
    ];

    var stream;

    sassFile.sourceMap = '{' +
      '"version": 3,' +
      '"file": "scss/subdir/multilevelimport.scss",' +
      '"names": [],' +
      '"mappings": "",' +
      '"sources": [ "scss/subdir/multilevelimport.scss" ],' +
      '"sourcesContent": [ "@import ../inheritance;" ]' +
    '}';

    stream = sass();
    stream.on('data', function(cssFile) {
      should.exist(cssFile.sourceMap);
      assert.deepEqual(cssFile.sourceMap.sources, expectedSources);
      done();
    });
    stream.write(sassFile);
  });
});

describe('gulp-sass -- sync compile', function() {
  it('should pass file when it isNull()', function(done) {
    var stream = sass.sync();
    var emptyFile = {
      'isNull': function () {
        return true;
      }
    };
    stream.on('data', function(data) {
      data.should.equal(emptyFile);
      done();
    });
    stream.write(emptyFile);
  });

  it('should emit error when file isStream()', function (done) {
    var stream = sass.sync();
    var streamFile = {
      'isNull': function () {
        return false;
      },
      'isStream': function () {
        return true;
      }
    };
    stream.on('error', function(err) {
      err.message.should.equal('Streaming not supported');
      done();
    });
    stream.write(streamFile);
  });

  it('should compile a single sass file', function(done) {
    var sassFile = createVinyl('mixins.scss');
    var stream = sass.sync();
    stream.on('data', function(cssFile) {
      should.exist(cssFile);
      should.exist(cssFile.path);
      should.exist(cssFile.relative);
      should.exist(cssFile.contents);
      String(cssFile.contents).should.equal(
        fs.readFileSync(path.join(__dirname, 'expected/mixins.css'), 'utf8')
      );
      done();
    });
    stream.write(sassFile);
  });

  it('should compile multiple sass files', function(done) {
    var files = [
      createVinyl('mixins.scss'),
      createVinyl('variables.scss')
    ];
    var stream = sass.sync();
    var mustSee = files.length;
    var expectedPath = 'expected/mixins.css';

    stream.on('data', function(cssFile) {
      should.exist(cssFile);
      should.exist(cssFile.path);
      should.exist(cssFile.relative);
      should.exist(cssFile.contents);
      if (cssFile.path.indexOf('variables') !== -1) {
        expectedPath = 'expected/variables.css';
      }
      String(cssFile.contents).should.equal(
        fs.readFileSync(path.join(__dirname, expectedPath), 'utf8')
      );
      mustSee--;
      if (mustSee <= 0) {
        done();
      }
    });

    files.forEach(function (file) {
      stream.write(file);
    });
  });

  it('should compile files with partials in another folder', function(done) {
    var sassFile = createVinyl('inheritance.scss');
    var stream = sass.sync();
    stream.on('data', function(cssFile) {
      should.exist(cssFile);
      should.exist(cssFile.path);
      should.exist(cssFile.relative);
      should.exist(cssFile.contents);
      String(cssFile.contents).should.equal(
        fs.readFileSync(path.join(__dirname, 'expected/inheritance.css'), 'utf8')
      );
      done();
    });
    stream.write(sassFile);
  });

  it('should handle sass errors', function(done) {
    var errorFile = createVinyl('error.scss');
    var stream = sass.sync();

    stream.on('error', function(err) {
      err.message.indexOf('property "font" must be followed by a \':\'').should.not.equal(-1);
      done();
    });
    stream.write(errorFile);
  });

  it('should work with gulp-sourcemaps', function(done) {
    var sassFile = createVinyl('inheritance.scss');

    // Expected sources are relative to file.base
    var expectedSources = [
      'includes/_cats.scss',
      'inheritance.scss'
    ];

    var stream;

    sassFile.sourceMap = '{' +
      '"version": 3,' +
      '"file": "scss/subdir/multilevelimport.scss",' +
      '"names": [],' +
      '"mappings": "",' +
      '"sources": [ "scss/subdir/multilevelimport.scss" ],' +
      '"sourcesContent": [ "@import ../inheritance;" ]' +
    '}';

    stream = sass.sync();
    stream.on('data', function(cssFile) {
      should.exist(cssFile.sourceMap);
      assert.deepEqual(cssFile.sourceMap.sources, expectedSources);
      done();
    });
    stream.write(sassFile);
  });
});
<|endoftext|>


<commit_before>'use strict';

/* global describe, it, after, before, afterEach, beforeEach */

var fs = require('fs');
var rimraf = require('rimraf');
var should = require('should');
var exec = require('exec-chainable');
var gutil = require('gulp-util');
var GGdeploy = require('../');

describe('gulp-git-deploy', function(){
  var repo = 'https://github.com/agualbbus/gulp-git-deploy-test.git';
  var currentBranch;

  before(function(done){
    exec('git rev-parse --abbrev-ref HEAD')
    .then(function(stdout){
      currentBranch = stdout;
      return exec('git checkout testing-branch ');
    })
    .then(function(stdout){
      console.log(stdout);
      done();
    });

  });

  it('should compare branch/origin with branch/local and be the same', function(done){
    var rev = {};
    exec('git rev-list HEAD -1')
    .then(function(stdout){
      rev.a = stdout;
      return GGdeploy({
        name: 'testing-branch',
        reset: false
      });
    })
    .then(function(){
      return exec('git rev-list HEAD -1');
    })
    .then(function(stdout){
      rev.b = stdout;
      rev.a.should.eql(rev.b);
      done();
    });
  });

  it('should compare branch/origin with branch/local and if different should merge', function(done){
    var rev = {};
    exec('git reset HEAD~1 --hard')
    .then(function(stdout){
      console.log(stdout);
      return exec('git rev-list HEAD -1');
    })
    .then(function(stdout){
      rev.a = stdout;
      return GGdeploy({
        name: 'testing-branch',
        reset: false
      });
    })
    .then(function(stdout){
      console.log(stdout);
      return exec('git rev-list HEAD -1');
    })
    .then(function(stdout){
      rev.b = stdout;
      console.log(rev.a, ' ', rev.b);
      rev.a.should.not.eql(rev.b);
      done();
    });
  });

  it('should compare branch/origin with branch/local and if different should merge then should apply callback', function(done){
    var rev = {};
    var cbText = 'I´m a callback';
    var cb ={
      result: null,
      func : function(){return  cbText}
    };

    exec('git reset HEAD~1 --hard')
    .then(function(stdout){
      console.log(stdout);
      return exec('git rev-list HEAD -1');
    })
    .then(function(stdout){
      rev.a = stdout;
      return GGdeploy({
        name: 'testing-branch',
        reset: false,
      }, cb.func);
    })
    .then(function(stdout){
      cb.result = stdout;
      return exec('git rev-list HEAD -1');
    })
    .then(function(stdout){
      rev.b = stdout;
      console.log(rev.a, ' ', rev.b);
      rev.a.should.not.eql(rev.b);
      cb.result.should.eql(cbText);
      done();
    });
  });

  after(function(done){
    exec('git reset --hard')
    .then(function(stdout){
      console.log(stdout);
      return exec('git checkout '+ currentBranch)
    })
    .then(function(stdout){
      console.log(stdout);
      done();
    });
  });

});

//  it('should fetch a tag from remote origin', function(done){
//    git.fetch('origin', '', {cwd: './test/tmp'}, function(){
//      fs.open('./test/tmp/.git/refs/tags/v1.1.1', 'r', function(err, fd) {
//        should.not.exist(err);
//        fs.close(fd, function() {
//          done();
//        });
//      });
//    });
//  });
//
//  afterEach(function(done){
//    rimraf('./test/tmp', function(err){
//      if(err) return done(err);
//      done();
//    });
//  });
<commit_msg>pull origin testing-branch<commit_after>'use strict';

/* global describe, it, after, before, afterEach, beforeEach */

var fs = require('fs');
var rimraf = require('rimraf');
var should = require('should');
var exec = require('exec-chainable');
var gutil = require('gulp-util');
var GGdeploy = require('../');

describe('gulp-git-deploy', function(){
  var currentBranch;

  before(function(done){
    exec('git rev-parse --abbrev-ref HEAD')
    .then(function(stdout){
      console.log(stdout);
      currentBranch = stdout;
      return exec('git pull origin testing-branch');
    })
    .then(function(stdout){
      console.log(stdout);
      return exec('git checkout testing-branch ');
    })
    .then(function(stdout){
      console.log(stdout);
      done();
    });

  });

  it('should compare branch/origin with branch/local and be the same', function(done){
    var rev = {};
    exec('git rev-list HEAD -1')
    .then(function(stdout){
      rev.a = stdout;
      return GGdeploy({
        name: 'testing-branch',
        reset: false
      });
    })
    .then(function(){
      return exec('git rev-list HEAD -1');
    })
    .then(function(stdout){
      rev.b = stdout;
      rev.a.should.eql(rev.b);
      done();
    });
  });

  it('should compare branch/origin with branch/local and if different should merge', function(done){
    var rev = {};
    exec('git reset HEAD~1 --hard')
    .then(function(stdout){
      console.log(stdout);
      return exec('git rev-list HEAD -1');
    })
    .then(function(stdout){
      rev.a = stdout;
      return GGdeploy({
        name: 'testing-branch',
        reset: false
      });
    })
    .then(function(stdout){
      console.log(stdout);
      return exec('git rev-list HEAD -1');
    })
    .then(function(stdout){
      rev.b = stdout;
      console.log(rev.a, ' ', rev.b);
      rev.a.should.not.eql(rev.b);
      done();
    });
  });

  it('should compare branch/origin with branch/local and if different should merge then should apply callback', function(done){
    var rev = {};
    var cbText = 'I´m a callback';
    var cb ={
      result: null,
      func : function(){return  cbText}
    };

    exec('git reset HEAD~1 --hard')
    .then(function(stdout){
      console.log(stdout);
      return exec('git rev-list HEAD -1');
    })
    .then(function(stdout){
      rev.a = stdout;
      return GGdeploy({
        name: 'testing-branch',
        reset: false,
      }, cb.func);
    })
    .then(function(stdout){
      cb.result = stdout;
      return exec('git rev-list HEAD -1');
    })
    .then(function(stdout){
      rev.b = stdout;
      console.log(rev.a, ' ', rev.b);
      rev.a.should.not.eql(rev.b);
      cb.result.should.eql(cbText);
      done();
    });
  });

  after(function(done){
    exec('git reset --hard')
    .then(function(stdout){
      console.log(stdout);
      return exec('git checkout '+ currentBranch)
    })
    .then(function(stdout){
      console.log(stdout);
      done();
    });
  });

});

//  it('should fetch a tag from remote origin', function(done){
//    git.fetch('origin', '', {cwd: './test/tmp'}, function(){
//      fs.open('./test/tmp/.git/refs/tags/v1.1.1', 'r', function(err, fd) {
//        should.not.exist(err);
//        fs.close(fd, function() {
//          done();
//        });
//      });
//    });
//  });
//
//  afterEach(function(done){
//    rimraf('./test/tmp', function(err){
//      if(err) return done(err);
//      done();
//    });
//  });
<|endoftext|>


<commit_before>'use strict';

/* global describe, it, after, before, afterEach, beforeEach */

var fs = require('fs');
var rimraf = require('rimraf');
var should = require('should');
var exec = require('exec-chainable');
var gutil = require('gulp-util');
var GGdeploy = require('../');

describe('gulp-git-deploy', function(){
  var repo = 'https://github.com/agualbbus/gulp-git-deploy-test.git';
  var currentBranch;

  before(function(done){
    exec('git rev-parse --abbrev-ref HEAD')
    .then(function(stdout){
      currentBranch = stdout;
      return exec('git checkout testing-branch ');
    })
    .then(function(stdout){
      done();
    });

  });

  it('should compare branch/origin with branch/local and be the same', function(done){
    var rev = {};
    exec('git rev-list HEAD -1')
    .then(function(stdout){
      rev.a = stdout;
      return GGdeploy({
        name: 'testing-branch',
        reset: false
      });
    })
    .then(function(){
      return exec('git rev-list HEAD -1');
    })
    .then(function(stdout){
      rev.b = stdout;
      rev.a.should.eql(rev.b);
      done();
    });
  });

  it('should compare branch/origin with branch/local and if different should merge', function(done){
    var rev = {};
    exec('git reset HEAD~1 --hard')
    .then(function(stdout){
      console.log(stdout);
      return exec('git rev-list HEAD -1');
    })
    .then(function(stdout){
      rev.a = stdout;
      return GGdeploy({
        name: 'testing-branch',
        reset: false
      });
    })
    .then(function(stdout){
      console.log(stdout);
      return exec('git rev-list HEAD -1');
    })
    .then(function(stdout){
      rev.b = stdout;
      rev.a.should.not.eql(rev.b);
      done();
    });
  });

  after(function(done){
    exec('git reset --hard')
    .then(function(stdout){
      console.log(stdout);
      return exec('git checkout '+ currentBranch)
    })
    .then(function(stdout){
      console.log(stdout);
      done();
    });
  });

});

//  it('should fetch a tag from remote origin', function(done){
//    git.fetch('origin', '', {cwd: './test/tmp'}, function(){
//      fs.open('./test/tmp/.git/refs/tags/v1.1.1', 'r', function(err, fd) {
//        should.not.exist(err);
//        fs.close(fd, function() {
//          done();
//        });
//      });
//    });
//  });
//
//  afterEach(function(done){
//    rimraf('./test/tmp', function(err){
//      if(err) return done(err);
//      done();
//    });
//  });
<commit_msg>bugfix<commit_after>'use strict';

/* global describe, it, after, before, afterEach, beforeEach */

var fs = require('fs');
var rimraf = require('rimraf');
var should = require('should');
var exec = require('exec-chainable');
var gutil = require('gulp-util');
var GGdeploy = require('../');

describe('gulp-git-deploy', function(){
  var repo = 'https://github.com/agualbbus/gulp-git-deploy-test.git';
  var currentBranch;

  before(function(done){
    exec('git rev-parse --abbrev-ref HEAD')
    .then(function(stdout){
      currentBranch = stdout;
      return exec('git checkout testing-branch ');
    })
    .then(function(stdout){
      done();
    });

  });

  it('should compare branch/origin with branch/local and be the same', function(done){
    var rev = {};
    exec('git rev-list HEAD -1')
    .then(function(stdout){
      rev.a = stdout;
      return GGdeploy({
        name: 'testing-branch',
        reset: false
      });
    })
    .then(function(){
      return exec('git rev-list HEAD -1');
    })
    .then(function(stdout){
      rev.b = stdout;
      rev.a.should.eql(rev.b);
      done();
    });
  });

  it('should compare branch/origin with branch/local and if different should merge', function(done){
    var rev = {};
    exec('git reset HEAD~1 --hard')
    .then(function(stdout){
      console.log(stdout);
      return exec('git rev-list HEAD -1');
    })
    .then(function(stdout){
      rev.a = stdout;
      return GGdeploy({
        name: 'testing-branch',
        reset: false
      });
    })
    .then(function(stdout){
      console.log(stdout);
      return exec('git rev-list HEAD -1');
    })
    .then(function(stdout){
      console.log(stdout);
      rev.b = stdout;
      rev.a.should.not.eql(rev.b);
      done();
    });
  });

  after(function(done){
    exec('git reset --hard')
    .then(function(stdout){
      console.log(stdout);
      return exec('git checkout '+ currentBranch)
    })
    .then(function(stdout){
      console.log(stdout);
      done();
    });
  });

});

//  it('should fetch a tag from remote origin', function(done){
//    git.fetch('origin', '', {cwd: './test/tmp'}, function(){
//      fs.open('./test/tmp/.git/refs/tags/v1.1.1', 'r', function(err, fd) {
//        should.not.exist(err);
//        fs.close(fd, function() {
//          done();
//        });
//      });
//    });
//  });
//
//  afterEach(function(done){
//    rimraf('./test/tmp', function(err){
//      if(err) return done(err);
//      done();
//    });
//  });
<|endoftext|>


<commit_before>var shell = require('..');
var child = require('child_process');
var assert = require('assert');

shell.mkdir('-p', 'tmp');
var file = 'tmp/tempscript' + Math.random() + '.js';
var script = 'require(\'../../make.js\');' +
             'target.all=function(){' +
             '  echo("first"); ' +
             '  cp("this_file_doesnt_exist", ".");' +
             '  echo("second");' +
             '}';

shell.ShellString(script).to(file);
child.exec(JSON.stringify(process.execPath) + ' ' + file, function (err, stdout) {
  assert.ok(stdout.match('first'));
  assert.ok(!stdout.match('second')); // Make should die on errors, so this should never get echoed

  shell.exit(123);
});
<commit_msg>test: remove tests for make (deprecated) (#624)<commit_after><|endoftext|>


<commit_before>'use strict';

const fs = require('fs');
const path = require('path');
const http = require('http');
const os = require('os');
const zlib = require('zlib');
const pump = require('pump');
const {promisify} = require('util');
const stream = require('stream');
const {pipeline} = stream;
stream.pipeline = null;

const tar = require('tar-fs');
const gunzip = require('gunzip-maybe');
const pullout = require('pullout');
const tryToCatch = require('try-to-catch');
const {reRequire} = require('mock-require');

const pipe = require('..');
const test = require('tape');

const random = Math.random();

test('check parameters', (t) => {
    t.throws(pipe, /streams could not be empty!/, 'check streams');
    t.throws(pipe.bind(null, []), /callback could not be empty!/, 'check callback');
    t.end();
});

test('file1 | gunzip maybe: error', async (t) => {
    const _pipe = promisify(pipe);
    const file = fs.createReadStream('/hello');

    const [e] = await tryToCatch(_pipe, [file, gunzip()])

    t.equal(e.code, 'ENOENT', 'should return error');
    t.end();
});

test('file1 | file2: pipeline', async (t) => {
    stream.pipeline = pipeline;

    const pipe = promisify(reRequire('..'));
    const file = fs.createReadStream('/hello');

    const [e] = await tryToCatch(pipe, [file, gunzip()])

    stream.pipeline = null;

    t.equal(e.code, 'ENOENT', 'should return error');
    t.end();
});

test('file1 | file2: pipeline for node < 10', async (t) => {
    stream.pipeline = pump;

    const pipe = promisify(reRequire('..'));
    const file = fs.createReadStream('/hello');

    const [e] = await tryToCatch(pipe, [file, gunzip()])

    stream.pipeline = null;

    t.equal(e.code, 'ENOENT', 'should return error');
    t.end();
});

test('file1 | file2: no error', (t) => {
    const tmp = os.tmpdir();
    const name = path.basename(__filename);
    const nameTmp = path.join(tmp, name + random);

    tryPipe(__filename, nameTmp, () => {
        const file1 = fs.readFileSync(__filename, 'utf8');
        const file2 = fs.readFileSync(nameTmp, 'utf8');

        fs.unlinkSync(nameTmp);

        t.equal(file1, file2, 'files equal');
        t.end();
    });
});

test('file1 | file2: write open EACESS', (t) => {
    const name = path.basename(__filename);
    const nameTmp = '/' + name + random;

    tryPipe(__filename, nameTmp, (error) => {
        t.ok(error, error && error.message);
        t.end();
    });
});

test('file1 | file2: write open EACESS: big file', (t) => {
    const name = path.basename(__filename);
    const nameTmp = '/' + name + random;

    tryPipe('/bin/bash', nameTmp, (error) => {
        t.ok(error, error && error.message);
        t.end();
    });
});

test('file1 | file2: read open ENOENT', (t) => {
    const tmp = os.tmpdir();
    const name = path.basename(__filename);
    const nameTmp = path.join(tmp, name + random);

    tryPipe(__filename + random, nameTmp, (error) => {
        t.ok(error, error && error.message);

        t.end();
    });
});

test('file1 | file2: error read EISDIR', (t) => {
    const tmp = os.tmpdir();
    const name = path.basename(__filename);
    const nameTmp = path.join(tmp, name + random);

    tryPipe('/', nameTmp, (error) => {
        fs.unlinkSync(nameTmp);
        t.equal(error.code, 'EISDIR', 'EISDIR: read error');
        t.end();
    });
});

test('file | dir: error write EISDIR', (t) => {
    tryPipe(__filename, '/', (error) => {
        t.equal(error.code, 'EISDIR', 'EISDIR: write error');
        t.end();
    });
});

test('dir1 | dir2: error read/write EISDIR', (t) => {
    tryPipe(__dirname, '/', (error) => {
        t.equal(error.code, 'EISDIR', 'read/write EISDIR');
        t.end();
    });
});

test('file1 | gzip | file2: no errors', (t) => {
    const tmp = os.tmpdir();
    const name = path.basename(__filename);
    const nameTmp = path.join(tmp, name + random);

    const read = fs.createReadStream(__filename);
    const write = fs.createWriteStream(nameTmp);
    const zip = zlib.createGzip();

    pipe([read, zip, write], () => {
        const file1 = fs.readFileSync(__filename, 'utf8');
        const file2 = fs.readFileSync(nameTmp);
        const zip = zlib.gzipSync(file1);

        fs.unlinkSync(nameTmp);

        t.deepEqual(zip, file2, 'file gziped');
        t.end();
    });
});

test('file1 | gzip', (t) => {
    const read = fs.createReadStream(__filename);
    const zip = zlib.createGzip();

    pipe([read, zip], (error) => {
        t.notOk(error, 'no errors');
        t.end();
    });
});

test('file1 | gzip: error ENOENT', (t) => {
    const read = fs.createReadStream(__filename + random);
    const zip = zlib.createGzip();

    pipe([read, zip], (error) => {
        t.ok(error, error.message);
        t.end();
    });
});

test('file1 | gzip: error EISDIR', (t) => {
    const read = fs.createReadStream('/');
    const zip = zlib.createGzip();

    pipe([read, zip], (error) => {
        t.ok(error, error.message);
        t.end();
    });
});

test('file1 | gunzip: error header check', (t) => {
    const read = fs.createReadStream(__filename);
    const gunzip = zlib.createGunzip();

    pipe([read, gunzip], (error) => {
        t.ok(error, error.message);
        t.end();
    });
});

test('file1 | gunzip | untar: error header check', (t) => {
    const read = fs.createReadStream(__filename);
    const gunzip = zlib.createGunzip();
    const tarStream = tar.extract(__dirname);

    pipe([read, gunzip, tarStream], (error) => {
        t.ok(error, error.message);
        t.end();
    });
});

test('file1 | gunzip | untar: error header check: gz', (t) => {
    const read = fs.createReadStream(__dirname + '/fixture/awk.1.gz');
    const gunzip = zlib.createGunzip();
    const tarStream = tar.extract(__dirname);

    pipe([read, gunzip, tarStream], (error) => {
        t.ok(error, error.message);
        t.end();
    });
});

test('tar | gzip | file', (t) => {
    const fixture = path.join(__dirname, 'fixture');
    const to = path.join(os.tmpdir(), `${Math.random()}.tar.gz`);
    const tarStream = tar.pack(fixture, {
        entries: [
            'pipe.txt'
        ]
    });

    const gzip = zlib.createGzip();
    const write = fs.createWriteStream(to);

    pipe([tarStream, gzip, write], () => {
        const toFile = fs.readFileSync(to);

        fs.unlinkSync(to);
        t.ok(toFile.length, 'should pack file');
        t.end();
    });
});

test('tar | gzip | file: error: EACESS', (t) => {
    const fixture = path.join(__dirname, 'fixture');
    const to = path.join(`/${Math.random()}.tar.gz`);
    const tarStream = tar.pack(fixture, {
        entries: [
            'pipe.txt'
        ]
    });

    const gzip = zlib.createGzip();
    const write = fs.createWriteStream(to);

    pipe([tarStream, gzip, write], (error) => {
        t.ok(error);
        t.end();
    });
});

test('put file', (t) => {
    const server = http.createServer((req, res) => {
        const write = fs.createWriteStream('/xxxxxxx');

        pipe([req, write], () => {
            server.close();

            t.pass('should not crash');
            t.end();
        });

        res.end();
    });

    server.listen(() => {
        const {port} = server.address();
        console.log(`server: 127.0.0.1:${port}`);

        const options = {
            method: 'PUT',
            hostname: 'localhost',
            port,
            path: '/',
        };

        const req = http.request(options, () => {
            server.close();
        });

        req.end();
    });
});

test('file1, file2 | response: end false', (t) => {
    const server = http.createServer((req, res) => {
        const read1 = fs.createReadStream(__filename);
        const read2 = fs.createReadStream(__filename);

        pipe([read1, res], {end: false}, () => {
            pipe([read2, res], (error) => {
                t.notOk(error, 'file1, file2 -> response');
            });
        });
    });

    server.listen(() => {
        const {port} = server.address();
        const url = `http://127.0.0.1:${port}`;

        console.log(`server: 127.0.0.1:${port}`);

        http.get(url, (res) => {
            console.log(`request: ${url}`);

            pullout(res, 'string', (error, data) => {
                const file = fs.readFileSync(__filename, 'utf8');
                t.equal(data.length, file.length * 2, 'reponse == file1 + file2');
                t.end();
                server.close();
            });
        }).on('error', (error) => {
            t.ok(error, error.message);
            t.end();
        });
    });

    server.on('error', (error) => {
        t.ok(error, error.message);
        t.end();
    });
});

test('file1, file2 | options: empty object', (t) => {
    const server = http.createServer((req, res) => {
        const read1 = fs.createReadStream(__filename);
        const read2 = fs.createReadStream(__filename);

        pipe([read1, res], {}, () => {
            pipe([read2, res], () => {});
        });
    });

    server.listen(7331, '127.0.0.1', () => {
        console.log('server: 127.0.0.1:7331');

        http.get('http://127.0.0.1:7331', (res) => {
            console.log('request: http://127.0.0.1:7331');

            pullout(res, 'string', (error, data) => {
                const file = fs.readFileSync(__filename, 'utf8');
                t.equal(data.length, file.length, 'reponse == file');
                t.end();
                server.close();
            });
        }).on('error', (error) => {
            t.ok(error, error.message);
            t.end();
        });
    });

    server.on('error', (error) => {
        t.ok(error, error.message);
        t.end();
    });
});

function tryPipe(from, to, fn) {
    const read = fs.createReadStream(from);
    const write = fs.createWriteStream(to);

    pipe([read, write], (error) => {
        const name = checkListenersLeak([read, write]);

        if (name)
            console.error('possible memory leak: ', name);

        fn(error);
    });
}

function checkListenersLeak(streams) {
    let name;
    const events  = ['open', 'error', 'end', 'finish'];
    const regExp  = /^function (onError|onReadError|onWriteError|onReadEnd|onWriteFinish)/;

    streams.some((stream) => {
        events.some((event) => {
            stream.listeners(event).some((fn) => {
                const is = (fn + '').match(regExp);

                if (is)
                    name = is[1];

                return name;
            });

            return name;
        });

        return name;
    });

    return name;
}

<commit_msg>test(pipe) async-await<commit_after>'use strict';

const fs = require('fs');
const path = require('path');
const http = require('http');
const os = require('os');
const zlib = require('zlib');
const pump = require('pump');
const {promisify} = require('util');
const stream = require('stream');
const {pipeline} = stream;
stream.pipeline = null;

const tar = require('tar-fs');
const gunzip = require('gunzip-maybe');
const pullout = require('pullout');
const tryToCatch = require('try-to-catch');
const {reRequire} = require('mock-require');

const pipe = require('..');
const _pipe = promisify(pipe);
const test = require('tape');

const random = Math.random();

test('check parameters', (t) => {
    t.throws(pipe, /streams could not be empty!/, 'check streams');
    t.throws(pipe.bind(null, []), /callback could not be empty!/, 'check callback');
    t.end();
});

test('file1 | gunzip maybe: error', async (t) => {
    const file = fs.createReadStream('/hello');

    const [e] = await tryToCatch(_pipe, [file, gunzip()])

    t.equal(e.code, 'ENOENT', 'should return error');
    t.end();
});

test('file1 | gunzip maybe: error', async (t) => {
    const file = fs.createReadStream('/hello');

    const [e] = await tryToCatch(_pipe, [file, gunzip()])

    t.equal(e.code, 'ENOENT', 'should return error');
    t.end();
});

test('file1 | file2: pipeline', async (t) => {
    stream.pipeline = pipeline;

    const pipe = promisify(reRequire('..'));
    const file = fs.createReadStream('/hello');

    const [e] = await tryToCatch(pipe, [file, gunzip()])

    stream.pipeline = null;

    t.equal(e.code, 'ENOENT', 'should return error');
    t.end();
});

test('file1 | file2: pipeline for node < 10', async (t) => {
    stream.pipeline = pump;

    const pipe = promisify(reRequire('..'));
    const file = fs.createReadStream('/hello');

    const [e] = await tryToCatch(pipe, [file, gunzip()])

    stream.pipeline = null;

    t.equal(e.code, 'ENOENT', 'should return error');
    t.end();
});

test('file1 | file2: no error', async (t) => {
    const tmp = os.tmpdir();
    const name = path.basename(__filename);
    const nameTmp = path.join(tmp, name + random);
    const _tryPipe = promisify(tryPipe);

    await _tryPipe(__filename, nameTmp);

    const file1 = fs.readFileSync(__filename, 'utf8');
    const file2 = fs.readFileSync(nameTmp, 'utf8');

    fs.unlinkSync(nameTmp);

    t.equal(file1, file2, 'files equal');
    t.end();
});

test('file1 | file2: write open EACESS', (t) => {
    const name = path.basename(__filename);
    const nameTmp = '/' + name + random;

    tryPipe(__filename, nameTmp, (error) => {
        t.ok(error, error && error.message);
        t.end();
    });
});

test('file1 | file2: write open EACESS: big file', (t) => {
    const name = path.basename(__filename);
    const nameTmp = '/' + name + random;

    tryPipe('/bin/bash', nameTmp, (error) => {
        t.ok(error, error && error.message);
        t.end();
    });
});

test('file1 | file2: read open ENOENT', (t) => {
    const tmp = os.tmpdir();
    const name = path.basename(__filename);
    const nameTmp = path.join(tmp, name + random);

    tryPipe(__filename + random, nameTmp, (error) => {
        t.ok(error, error && error.message);

        t.end();
    });
});

test('file1 | file2: error read EISDIR', (t) => {
    const tmp = os.tmpdir();
    const name = path.basename(__filename);
    const nameTmp = path.join(tmp, name + random);

    tryPipe('/', nameTmp, (error) => {
        fs.unlinkSync(nameTmp);
        t.equal(error.code, 'EISDIR', 'EISDIR: read error');
        t.end();
    });
});

test('file | dir: error write EISDIR', (t) => {
    tryPipe(__filename, '/', (error) => {
        t.equal(error.code, 'EISDIR', 'EISDIR: write error');
        t.end();
    });
});

test('dir1 | dir2: error read/write EISDIR', (t) => {
    tryPipe(__dirname, '/', (error) => {
        t.equal(error.code, 'EISDIR', 'read/write EISDIR');
        t.end();
    });
});

test('file1 | gzip | file2: no errors', async (t) => {
    const tmp = os.tmpdir();
    const name = path.basename(__filename);
    const nameTmp = path.join(tmp, name + random);

    const read = fs.createReadStream(__filename);
    const write = fs.createWriteStream(nameTmp);
    const zipStream = zlib.createGzip();

    await _pipe([read, zipStream, write]);

    const file1 = fs.readFileSync(__filename, 'utf8');
    const file2 = fs.readFileSync(nameTmp);
    const zip = zlib.gzipSync(file1);

    fs.unlinkSync(nameTmp);

    t.deepEqual(zip, file2, 'file gziped');
    t.end();
});

test('file1 | gzip', (t) => {
    const read = fs.createReadStream(__filename);
    const zip = zlib.createGzip();

    pipe([read, zip], (error) => {
        t.notOk(error, 'no errors');
        t.end();
    });
});

test('file1 | gzip: error ENOENT', (t) => {
    const read = fs.createReadStream(__filename + random);
    const zip = zlib.createGzip();

    pipe([read, zip], (error) => {
        t.ok(error, error.message);
        t.end();
    });
});

test('file1 | gzip: error EISDIR', (t) => {
    const read = fs.createReadStream('/');
    const zip = zlib.createGzip();

    pipe([read, zip], (error) => {
        t.ok(error, error.message);
        t.end();
    });
});

test('file1 | gunzip: error header check', (t) => {
    const read = fs.createReadStream(__filename);
    const gunzip = zlib.createGunzip();

    pipe([read, gunzip], (error) => {
        t.ok(error, error.message);
        t.end();
    });
});

test('file1 | gunzip | untar: error header check', async (t) => {
    const read = fs.createReadStream(__filename);
    const gunzip = zlib.createGunzip();
    const tarStream = tar.extract(__dirname);

    const [error] = await tryToCatch(_pipe, [read, gunzip, tarStream]);

    t.ok(error, error.message);
    t.end();
});

test('file1 | gunzip | untar: error header check: gz', async (t) => {
    const read = fs.createReadStream(__dirname + '/fixture/awk.1.gz');
    const gunzip = zlib.createGunzip();
    const tarStream = tar.extract(__dirname);

    const [error] = await tryToCatch(_pipe, [read, gunzip, tarStream]);

    t.ok(error, error.message);
    t.end();
});

test('tar | gzip | file', (t) => {
    const fixture = path.join(__dirname, 'fixture');
    const to = path.join(os.tmpdir(), `${Math.random()}.tar.gz`);
    const tarStream = tar.pack(fixture, {
        entries: [
            'pipe.txt'
        ]
    });

    const gzip = zlib.createGzip();
    const write = fs.createWriteStream(to);

    pipe([tarStream, gzip, write], () => {
        const toFile = fs.readFileSync(to);

        fs.unlinkSync(to);
        t.ok(toFile.length, 'should pack file');
        t.end();
    });
});

test('tar | gzip | file: error: EACESS', (t) => {
    const fixture = path.join(__dirname, 'fixture');
    const to = path.join(`/${Math.random()}.tar.gz`);
    const tarStream = tar.pack(fixture, {
        entries: [
            'pipe.txt'
        ]
    });

    const gzip = zlib.createGzip();
    const write = fs.createWriteStream(to);

    pipe([tarStream, gzip, write], (error) => {
        t.ok(error);
        t.end();
    });
});

test('put file', (t) => {
    const server = http.createServer((req, res) => {
        const write = fs.createWriteStream('/xxxxxxx');

        pipe([req, write], () => {
            server.close();

            t.pass('should not crash');
            t.end();
        });

        res.end();
    });

    server.listen(() => {
        const {port} = server.address();
        console.log(`server: 127.0.0.1:${port}`);

        const options = {
            method: 'PUT',
            hostname: 'localhost',
            port,
            path: '/',
        };

        const req = http.request(options, () => {
            server.close();
        });

        req.end();
    });
});

test('file1, file2 | response: end false', (t) => {
    const server = http.createServer((req, res) => {
        const read1 = fs.createReadStream(__filename);
        const read2 = fs.createReadStream(__filename);

        pipe([read1, res], {end: false}, () => {
            pipe([read2, res], (error) => {
                t.notOk(error, 'file1, file2 -> response');
            });
        });
    });

    server.listen(() => {
        const {port} = server.address();
        const url = `http://127.0.0.1:${port}`;

        console.log(`server: 127.0.0.1:${port}`);

        http.get(url, (res) => {
            console.log(`request: ${url}`);

            pullout(res, 'string', (error, data) => {
                const file = fs.readFileSync(__filename, 'utf8');
                t.equal(data.length, file.length * 2, 'reponse == file1 + file2');
                t.end();
                server.close();
            });
        }).on('error', (error) => {
            t.ok(error, error.message);
            t.end();
        });
    });

    server.on('error', (error) => {
        t.ok(error, error.message);
        t.end();
    });
});

test('file1, file2 | options: empty object', (t) => {
    const server = http.createServer((req, res) => {
        const read1 = fs.createReadStream(__filename);
        const read2 = fs.createReadStream(__filename);

        pipe([read1, res], {}, () => {
            pipe([read2, res], () => {});
        });
    });

    server.listen(7331, '127.0.0.1', () => {
        console.log('server: 127.0.0.1:7331');

        http.get('http://127.0.0.1:7331', (res) => {
            console.log('request: http://127.0.0.1:7331');

            pullout(res, 'string', (error, data) => {
                const file = fs.readFileSync(__filename, 'utf8');
                t.equal(data.length, file.length, 'reponse == file');
                t.end();
                server.close();
            });
        }).on('error', (error) => {
            t.ok(error, error.message);
            t.end();
        });
    });

    server.on('error', (error) => {
        t.ok(error, error.message);
        t.end();
    });
});

function tryPipe(from, to, fn) {
    const read = fs.createReadStream(from);
    const write = fs.createWriteStream(to);

    pipe([read, write], (error) => {
        const name = checkListenersLeak([read, write]);

        if (name)
            console.error('possible memory leak: ', name);

        fn(error);
    });
}

function checkListenersLeak(streams) {
    let name;
    const events  = ['open', 'error', 'end', 'finish'];
    const regExp  = /^function (onError|onReadError|onWriteError|onReadEnd|onWriteFinish)/;

    streams.some((stream) => {
        events.some((event) => {
            stream.listeners(event).some((fn) => {
                const is = (fn + '').match(regExp);

                if (is)
                    name = is[1];

                return name;
            });

            return name;
        });

        return name;
    });

    return name;
}

<|endoftext|>


<commit_before>(function() {
    'use strict';

    var test        = require('tape'),
        remimitter  = require('..'),

        os          = require('os'),
        path        = require('path'),
        fs          = require('fs');

    test('file: error EACESS', function(t) {
        var rm = remimitter('/bin/ls');

        rm.on('error', function(error) {
            t.equal(error.code, 'EACCES', error.message);
            rm.abort();
        });

        rm.on('end', function() {
            t.end();
        });
    });

    test('folder: error EACESS', function(t) {
        var rm = remimitter('/bin');

        rm.on('error', function(error) {
            t.equal(error.code, 'EACCES', error.message);
            rm.abort();
        });

        rm.on('end', function() {
            t.end();
        });
    });

    test('folder: error SOME_ERROR', function(t) {
        var rm,
            code    = 'SOME_ERROR',
            rmdir   = fs.rmdir,
            name    = path.join(os.tmpdir(), String(Math.random()));

        fs.mkdirSync(name);

        fs.rmdir = function(name, callback) {
            var error   = Error('Some error');
            error.code  = code;

            callback(error);
        };

        rm = remimitter(name);

        rm.on('error', function(error) {
            t.equal(error.code, code, error.message);
            rm.abort();
        });

        rm.on('end', function() {
            fs.rmdir = rmdir;
            fs.rmdirSync(name);
            t.end();
        });
    });
})();
<commit_msg>test(remy) file: no errors<commit_after>(function() {
    'use strict';

    var test        = require('tape'),
        remimitter  = require('..'),

        os          = require('os'),
        path        = require('path'),
        fs          = require('fs');

    test('file: error EACESS', function(t) {
        var rm = remimitter('/bin/ls');

        rm.on('error', function(error) {
            t.equal(error.code, 'EACCES', error.message);
            rm.abort();
        });

        rm.on('end', function() {
            t.end();
        });
    });

    test('folder: error EACESS', function(t) {
        var rm = remimitter('/bin');

        rm.on('error', function(error) {
            t.equal(error.code, 'EACCES', error.message);
            rm.abort();
        });

        rm.on('end', function() {
            t.end();
        });
    });

    test('folder: error SOME_ERROR', function(t) {
        var rm,
            code    = 'SOME_ERROR',
            rmdir   = fs.rmdir,
            name    = path.join(os.tmpdir(), String(Math.random()));

        fs.mkdirSync(name);

        fs.rmdir = function(name, callback) {
            var error   = Error('Some error');
            error.code  = code;

            callback(error);
        };

        rm = remimitter(name);

        rm.on('error', function(error) {
            t.equal(error.code, code, error.message);
            rm.abort();
        });

        rm.on('end', function() {
            fs.rmdir = rmdir;
            fs.rmdirSync(name);
            t.end();
        });
    });

    test('file: no errors', function(t) {
        var rm,
            name = path.join('/tmp', String(Math.random()));

        fs.writeFileSync(name, 'hello world');

        rm = remimitter(name);

        rm.on('end', function() {
            t.end();
        });
    });

})();
<|endoftext|>


<commit_before>// Copyright (c) 2015 Uber Technologies, Inc.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.

'use strict';

var parallel = require('run-parallel');
var Buffer = require('buffer').Buffer;
var extend = require('xtend');
var allocCluster = require('./lib/alloc-cluster.js');
var EndpointHandler = require('../endpoint-handler');
var TChannel = require('../channel.js');

allocCluster.test('request().send() to a server', 2, function t(cluster, assert) {
    var one = cluster.channels[0];
    var two = cluster.channels[1];
    var hostOne = cluster.hosts[0];

    one.handler = EndpointHandler();

    one.handler.register('foo', function foo(req, res, arg2, arg3) {
        assert.ok(Buffer.isBuffer(arg2), 'handler got an arg2 buffer');
        assert.ok(Buffer.isBuffer(arg3), 'handler got an arg3 buffer');
        res.sendOk(arg2, arg3);
    });

    parallel([

        {
            name: 'bufferOp',
            op: Buffer('foo'),
            reqHead: null,
            reqBody: null,
            resHead: '',
            resBody: ''
        },

        {
            name: 'stringOp',
            op: 'foo',
            reqHead: null,
            reqBody: null,
            resHead: '',
            resBody: ''
        },

        {
            name: 'bufferHead',
            op: 'foo',
            reqHead: Buffer('abc'),
            reqBody: null,
            resHead: 'abc',
            resBody: ''
        },

        {
            name: 'stringHead',
            op: 'foo',
            reqHead: 'abc',
            reqBody: null,
            resHead: 'abc',
            resBody: ''
        },

        {
            name: 'objectHead',
            op: 'foo',
            reqHead: JSON.stringify({value: 'abc'}),
            reqBody: null,
            resHead: '{"value":"abc"}',
            resBody: ''
        },

        {
            name: 'nullHead',
            op: 'foo',
            reqHead: null,
            reqBody: null,
            resHead: '',
            resBody: ''
        },

        {
            name: 'undefinedHead',
            op: 'foo',
            reqHead: undefined,
            reqBody: null,
            resHead: '',
            resBody: ''
        },

        {
            name: 'bufferBody',
            op: 'foo',
            reqHead: null,
            reqBody: Buffer('abc'),
            resHead: '',
            resBody: 'abc'
        },

        {
            name: 'stringBody',
            op: 'foo',
            reqHead: null,
            reqBody: 'abc',
            resHead: '',
            resBody: 'abc'
        },

        {
            name: 'objectBody',
            op: 'foo',
            reqHead: null,
            reqBody: JSON.stringify({value: 'abc'}),
            resHead: '',
            resBody: '{"value":"abc"}'
        },

        {
            name: 'nullBody',
            op: 'foo',
            reqHead: null,
            reqBody: null,
            resHead: '',
            resBody: ''
        },

        {
            name: 'undefinedBody',
            op: 'foo',
            reqHead: null,
            reqBody: undefined,
            resHead: '',
            resBody: ''
        },

    ].map(function eachTestCase(testCase) {
        testCase = extend({
            channel: two,
            opts: {host: hostOne},
        }, testCase);
        return sendTest(testCase, assert);
    }), function onResults(err) {
        assert.ifError(err, 'no errors from sending');
        cluster.assertCleanState(assert, {
            channels: [{
                peers: [{
                    connections: [
                        {direction: 'in', inReqs: 0, outReqs: 0}
                    ]
                }]
            }, {
                peers: [{
                    connections: [
                        {direction: 'out', inReqs: 0, outReqs: 0}
                    ]
                }]
            }]
        });
        assert.end();
    });
});

allocCluster.test('request().send() to a pool of servers', 4, function t(cluster, assert) {
    var client = TChannel({
        timeoutFuzz: 0,
        random: randSeq([
            1.0, 0.1, 0.1, 0.1, // .request, chan 1 wins
            0.1, 1.0, 0.1, 0.1, // .request, chan 2 wins
            0.1, 0.1, 1.0, 0.1, // .request, chan 3 wins
            0.1, 0.1, 0.1, 1.0, // .request, chan 4 wins
            1.0, 0.1, 0.1, 0.1, // .request, chan 1 wins
            0.1, 1.0, 0.1, 0.1, // .request, chan 2 wins
            0.1, 0.1, 1.0, 0.1, // .request, chan 3 wins
            0.1, 0.1, 0.1, 1.0  // .request, chan 4 wins
        ])
    });

    var channel = client.makeSubChannel({
        serviceName: 'lol'
    });

    cluster.channels.forEach(function each(chan, i) {
        var chanNum = i + 1;
        chan.handler = EndpointHandler();
        chan.handler.register('foo', function foo(req, res, arg2, arg3) {
            res.sendOk(arg2, arg3 + ' served by ' + chanNum);
        });
        channel.peers.add(chan.hostPort);
    });

    parallel([

        { name: 'msg1', op: 'foo',
          reqHead: '', reqBody: 'msg1',
          resHead: '', resBody: 'msg1 served by 1' },
        { name: 'msg2', op: 'foo',
          reqHead: '', reqBody: 'msg2',
          resHead: '', resBody: 'msg2 served by 2' },
        { name: 'msg3', op: 'foo',
          reqHead: '', reqBody: 'msg3',
          resHead: '', resBody: 'msg3 served by 3' },
        { name: 'msg4', op: 'foo',
          reqHead: '', reqBody: 'msg4',
          resHead: '', resBody: 'msg4 served by 4' },

        { name: 'msg5', op: 'foo',
          reqHead: '', reqBody: 'msg5',
          resHead: '', resBody: 'msg5 served by 1' },
        { name: 'msg6', op: 'foo',
          reqHead: '', reqBody: 'msg6',
          resHead: '', resBody: 'msg6 served by 2' },
        { name: 'msg7', op: 'foo',
          reqHead: '', reqBody: 'msg7',
          resHead: '', resBody: 'msg7 served by 3' },
        { name: 'msg8', op: 'foo',
          reqHead: '', reqBody: 'msg8',
          resHead: '', resBody: 'msg8 served by 4' },

    ].map(function eachTestCase(testCase) {
        return sendTest(extend({
            logger: cluster.logger,
            channel: channel
        }, testCase), assert);
    }), function onResults(err) {
        assert.ifError(err, 'no errors from sending');
        cluster.assertCleanState(assert, {
            channels: cluster.channels.map(function each() {
                return {
                    peers: [{
                        connections: [
                            {direction: 'in', inReqs: 0, outReqs: 0}
                        ]
                    }]
                };
            })
        });
        assert.end();
    });
});

allocCluster.test('request().send() to self', 1, function t(cluster, assert) {
    var one = cluster.channels[0];

    one.handler = EndpointHandler();
    one.handler.register('foo', function foo(req, res, arg2, arg3) {
        assert.ok(Buffer.isBuffer(arg2), 'handler got an arg2 buffer');
        assert.ok(Buffer.isBuffer(arg3), 'handler got an arg3 buffer');
        res.sendOk(arg2, arg3);
    });
    one.handler.register('bar', function bar(req, res, arg2, arg3) {
        assert.ok(Buffer.isBuffer(arg2), 'handler got an arg2 buffer');
        assert.ok(Buffer.isBuffer(arg3), 'handler got an arg3 buffer');
        res.sendNotOk(arg2, arg3);
    });

    parallel([{
        name: 'msg1', op: 'foo',
        reqHead: 'head1', reqBody: 'msg1',
        resHead: 'head1', resBody: 'msg1',
        opts: {
            host: one.hostPort
        }
    },
    {
        name: 'msg2', op: 'bar',
        reqHead: 'head2', reqBody: 'msg2',
        resHead: 'head2', resBody: 'msg2',
        resOk: false,
        opts: {
            host: one.hostPort
        }
    }].map(function eachTestCase(testCase) {
        testCase = extend({
            channel: one
        }, testCase);
        return sendTest(testCase, assert);
    }), function onResults(err) {
        assert.ifError(err, 'no errors from sending');
        cluster.assertCleanState(assert, {
            channels: [{
                peers: []
            }]
        });
        assert.end();
    });
});

allocCluster.test('self send() with error frame', 1, function t(cluster, assert) {
    var one = cluster.channels[0];

    one.handler = EndpointHandler();
    one.handler.register('foo', function foo(req, res) {
        res.sendError('Cancelled', 'bye lol');
    });

    one.request({
        host: one.hostPort
    }).send('foo', '', '', onResponse);

    function onResponse(err) {
        assert.equal(err.message, 'bye lol');
        assert.deepEqual(err, {
            type: 'tchannel.canceled',
            isErrorFrame: true,
            codeName: 'Cancelled',
            errorCode: 2,
            originalId: 0,
            name: 'TchannelCanceledError',
            message: 'bye lol'
        });

        assert.end();
    }
});

function randSeq(seq) {
    var i = 0;
    return function random() {
        var r = seq[i];
        i = (i + 1) % seq.length;
        return r;
    };
}

function sendTest(testCase, assert) {
    return function runSendTest(callback) {
        testCase.channel
            .request(testCase.opts)
            .send(testCase.op, testCase.reqHead, testCase.reqBody, onResult);
        function onResult(err, res, arg2, arg3) {
            var head = arg2;
            var body = arg3;
            assert.ifError(err, testCase.name + ': no result error');
            if (!err) {
                assert.ok(Buffer.isBuffer(head), testCase.name + ': got head buffer');
                assert.ok(Buffer.isBuffer(body), testCase.name + ': got body buffer');
                assert.equal(head ? String(head) : head, testCase.resHead, testCase.name + ': expected head content');
                assert.equal(body ? String(body) : body, testCase.resBody, testCase.name + ': expected body content');
            }

            if ('resOk' in testCase) {
                assert.equal(res.ok, testCase.resOk,
                    testCase.name + ': expected res ok');
            }

            callback();
        }
    };
}
<commit_msg>test/send: be okay with strings<commit_after>// Copyright (c) 2015 Uber Technologies, Inc.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.

'use strict';

var parallel = require('run-parallel');
var Buffer = require('buffer').Buffer;
var extend = require('xtend');
var allocCluster = require('./lib/alloc-cluster.js');
var EndpointHandler = require('../endpoint-handler');
var TChannel = require('../channel.js');

allocCluster.test('request().send() to a server', 2, function t(cluster, assert) {
    var one = cluster.channels[0];
    var two = cluster.channels[1];
    var hostOne = cluster.hosts[0];

    one.handler = EndpointHandler();

    one.handler.register('foo', function foo(req, res, arg2, arg3) {
        assert.ok(Buffer.isBuffer(arg2), 'handler got an arg2 buffer');
        assert.ok(Buffer.isBuffer(arg3), 'handler got an arg3 buffer');
        res.sendOk(arg2, arg3);
    });

    parallel([

        {
            name: 'bufferOp',
            op: Buffer('foo'),
            reqHead: null,
            reqBody: null,
            resHead: '',
            resBody: ''
        },

        {
            name: 'stringOp',
            op: 'foo',
            reqHead: null,
            reqBody: null,
            resHead: '',
            resBody: ''
        },

        {
            name: 'bufferHead',
            op: 'foo',
            reqHead: Buffer('abc'),
            reqBody: null,
            resHead: 'abc',
            resBody: ''
        },

        {
            name: 'stringHead',
            op: 'foo',
            reqHead: 'abc',
            reqBody: null,
            resHead: 'abc',
            resBody: ''
        },

        {
            name: 'objectHead',
            op: 'foo',
            reqHead: JSON.stringify({value: 'abc'}),
            reqBody: null,
            resHead: '{"value":"abc"}',
            resBody: ''
        },

        {
            name: 'nullHead',
            op: 'foo',
            reqHead: null,
            reqBody: null,
            resHead: '',
            resBody: ''
        },

        {
            name: 'undefinedHead',
            op: 'foo',
            reqHead: undefined,
            reqBody: null,
            resHead: '',
            resBody: ''
        },

        {
            name: 'bufferBody',
            op: 'foo',
            reqHead: null,
            reqBody: Buffer('abc'),
            resHead: '',
            resBody: 'abc'
        },

        {
            name: 'stringBody',
            op: 'foo',
            reqHead: null,
            reqBody: 'abc',
            resHead: '',
            resBody: 'abc'
        },

        {
            name: 'objectBody',
            op: 'foo',
            reqHead: null,
            reqBody: JSON.stringify({value: 'abc'}),
            resHead: '',
            resBody: '{"value":"abc"}'
        },

        {
            name: 'nullBody',
            op: 'foo',
            reqHead: null,
            reqBody: null,
            resHead: '',
            resBody: ''
        },

        {
            name: 'undefinedBody',
            op: 'foo',
            reqHead: null,
            reqBody: undefined,
            resHead: '',
            resBody: ''
        },

    ].map(function eachTestCase(testCase) {
        testCase = extend({
            channel: two,
            opts: {host: hostOne},
        }, testCase);
        return sendTest(testCase, assert);
    }), function onResults(err) {
        assert.ifError(err, 'no errors from sending');
        cluster.assertCleanState(assert, {
            channels: [{
                peers: [{
                    connections: [
                        {direction: 'in', inReqs: 0, outReqs: 0}
                    ]
                }]
            }, {
                peers: [{
                    connections: [
                        {direction: 'out', inReqs: 0, outReqs: 0}
                    ]
                }]
            }]
        });
        assert.end();
    });
});

allocCluster.test('request().send() to a pool of servers', 4, function t(cluster, assert) {
    var client = TChannel({
        timeoutFuzz: 0,
        random: randSeq([
            1.0, 0.1, 0.1, 0.1, // .request, chan 1 wins
            0.1, 1.0, 0.1, 0.1, // .request, chan 2 wins
            0.1, 0.1, 1.0, 0.1, // .request, chan 3 wins
            0.1, 0.1, 0.1, 1.0, // .request, chan 4 wins
            1.0, 0.1, 0.1, 0.1, // .request, chan 1 wins
            0.1, 1.0, 0.1, 0.1, // .request, chan 2 wins
            0.1, 0.1, 1.0, 0.1, // .request, chan 3 wins
            0.1, 0.1, 0.1, 1.0  // .request, chan 4 wins
        ])
    });

    var channel = client.makeSubChannel({
        serviceName: 'lol'
    });

    cluster.channels.forEach(function each(chan, i) {
        var chanNum = i + 1;
        chan.handler = EndpointHandler();
        chan.handler.register('foo', function foo(req, res, arg2, arg3) {
            res.sendOk(arg2, arg3 + ' served by ' + chanNum);
        });
        channel.peers.add(chan.hostPort);
    });

    parallel([

        { name: 'msg1', op: 'foo',
          reqHead: '', reqBody: 'msg1',
          resHead: '', resBody: 'msg1 served by 1' },
        { name: 'msg2', op: 'foo',
          reqHead: '', reqBody: 'msg2',
          resHead: '', resBody: 'msg2 served by 2' },
        { name: 'msg3', op: 'foo',
          reqHead: '', reqBody: 'msg3',
          resHead: '', resBody: 'msg3 served by 3' },
        { name: 'msg4', op: 'foo',
          reqHead: '', reqBody: 'msg4',
          resHead: '', resBody: 'msg4 served by 4' },

        { name: 'msg5', op: 'foo',
          reqHead: '', reqBody: 'msg5',
          resHead: '', resBody: 'msg5 served by 1' },
        { name: 'msg6', op: 'foo',
          reqHead: '', reqBody: 'msg6',
          resHead: '', resBody: 'msg6 served by 2' },
        { name: 'msg7', op: 'foo',
          reqHead: '', reqBody: 'msg7',
          resHead: '', resBody: 'msg7 served by 3' },
        { name: 'msg8', op: 'foo',
          reqHead: '', reqBody: 'msg8',
          resHead: '', resBody: 'msg8 served by 4' },

    ].map(function eachTestCase(testCase) {
        return sendTest(extend({
            logger: cluster.logger,
            channel: channel
        }, testCase), assert);
    }), function onResults(err) {
        assert.ifError(err, 'no errors from sending');
        cluster.assertCleanState(assert, {
            channels: cluster.channels.map(function each() {
                return {
                    peers: [{
                        connections: [
                            {direction: 'in', inReqs: 0, outReqs: 0}
                        ]
                    }]
                };
            })
        });
        assert.end();
    });
});

allocCluster.test('request().send() to self', 1, function t(cluster, assert) {
    var one = cluster.channels[0];

    one.handler = EndpointHandler();
    one.handler.register('foo', function foo(req, res, arg2, arg3) {
        assert.ok(typeof arg2 === 'string', 'handler got an arg2 string');
        assert.ok(typeof arg3 === 'string', 'handler got an arg3 string');
        res.sendOk(arg2, arg3);
    });
    one.handler.register('bar', function bar(req, res, arg2, arg3) {
        assert.ok(typeof arg2 === 'string', 'handler got an arg2 string');
        assert.ok(typeof arg3 === 'string', 'handler got an arg3 string');
        res.sendNotOk(arg2, arg3);
    });

    parallel([{
        name: 'msg1', op: 'foo',
        reqHead: 'head1', reqBody: 'msg1',
        resHead: 'head1', resBody: 'msg1',
        opts: {
            host: one.hostPort
        }
    },
    {
        name: 'msg2', op: 'bar',
        reqHead: 'head2', reqBody: 'msg2',
        resHead: 'head2', resBody: 'msg2',
        resOk: false,
        opts: {
            host: one.hostPort
        }
    }].map(function eachTestCase(testCase) {
        testCase = extend({
            channel: one
        }, testCase);
        return sendTest(testCase, assert);
    }), function onResults(err) {
        assert.ifError(err, 'no errors from sending');
        cluster.assertCleanState(assert, {
            channels: [{
                peers: []
            }]
        });
        assert.end();
    });
});

allocCluster.test('self send() with error frame', 1, function t(cluster, assert) {
    var one = cluster.channels[0];

    one.handler = EndpointHandler();
    one.handler.register('foo', function foo(req, res) {
        res.sendError('Cancelled', 'bye lol');
    });

    one.request({
        host: one.hostPort
    }).send('foo', '', '', onResponse);

    function onResponse(err) {
        assert.equal(err.message, 'bye lol');
        assert.deepEqual(err, {
            type: 'tchannel.canceled',
            isErrorFrame: true,
            codeName: 'Cancelled',
            errorCode: 2,
            originalId: 0,
            name: 'TchannelCanceledError',
            message: 'bye lol'
        });

        assert.end();
    }
});

function randSeq(seq) {
    var i = 0;
    return function random() {
        var r = seq[i];
        i = (i + 1) % seq.length;
        return r;
    };
}

function sendTest(testCase, assert) {
    return function runSendTest(callback) {
        testCase.channel
            .request(testCase.opts)
            .send(testCase.op, testCase.reqHead, testCase.reqBody, onResult);
        function onResult(err, res, arg2, arg3) {
            var head = arg2;
            var body = arg3;
            assert.ifError(err, testCase.name + ': no result error');
            if (!err) {
                assert.ok(typeof head === 'string' || Buffer.isBuffer(head), testCase.name + ': got head buffer or string');
                assert.ok(typeof body === 'string' || Buffer.isBuffer(body), testCase.name + ': got body buffer or string');
                assert.equal(head ? String(head) : head, testCase.resHead, testCase.name + ': expected head content');
                assert.equal(body ? String(body) : body, testCase.resBody, testCase.name + ': expected body content');
            }

            if ('resOk' in testCase) {
                assert.equal(res.ok, testCase.resOk,
                    testCase.name + ': expected res ok');
            }

            callback();
        }
    };
}
<|endoftext|>


<commit_before>'use strict';

let nodeTestingServer = require('node-testing-server').nodeTestingServer;

// Settings for node testing server
nodeTestingServer.config = {
    hostname: 'localhost',
    port: 8001,
    logsEnabled: 0,
    pages: {
        '/test.html': `

First

Second

Third

Fourth

Fifth

Sixth

Seventh

Eighth

Ninth

Tenth

`
    }
}

describe('protractor-numerator tests', function () {
    // Selectors for tests
    let selectorLinkCSS = '.items li';
    let selectorLinkXPath = '//li[ancestor::*[@class="items"]]';

    beforeAll(function () {
        // Turn off Angular synchronization
        browser.ignoreSynchronization = true;
        // Output some information about current tests process
        console.log(`==> Tests running at: ${process.cwd()}`);
        console.log(`==> With argv: ${process.argv}`);

        // Start node testing server
        nodeTestingServer.start();
    });

    beforeEach(function () {
        browser.get(`http://${nodeTestingServer.config.hostname}:${nodeTestingServer.config.port}/test.html`);
    });

    afterAll(function () {
        // Stop node testing server
        nodeTestingServer.stop();
    });

    it('should get the first list item from the test server page', function () {
        let listItemFirst = element.all(by.css(selectorLinkCSS)).first();

        expect(listItemFirst.getText()).toBe('First');
    });

    it('should get the second list item from the test server page', function () {
        let listItemSecond = element.all(by.xpath(selectorLinkXPath)).second();

        expect(listItemSecond.getText()).toBe('Second');
    });

    it('should get the third list item from the test server page', function () {
        let listItemThird = element.all(by.css(selectorLinkCSS)).third();

        expect(listItemThird.getText()).toBe('Third');
    });

    it('should get the fourth list item from the test server page', function () {
        let listItemFourth = element.all(by.css(selectorLinkCSS)).fourth();

        expect(listItemFourth.getText()).toBe('Fourth');
    });

    it('should get the fifth list item from the test server page', function () {
        let listItemFifth = element.all(by.css(selectorLinkCSS)).fifth();

        expect(listItemFifth.getText()).toBe('Fifth');
    });

    it('should get the sixth list item from the test server page', function () {
        let listItemSixth = element.all(by.css(selectorLinkCSS)).sixth();

        expect(listItemSixth.getText()).toBe('Sixth');
    });

    it('should get the seventh list item from the test server page', function () {
        let listItemSeventh = element.all(by.css(selectorLinkCSS)).seventh();

        expect(listItemSeventh.getText()).toBe('Seventh');
    });

    it('should get the eighth list item from the test server page', function () {
        let listItemEighth = element.all(by.css(selectorLinkCSS)).eighth();

        expect(listItemEighth.getText()).toBe('Eighth');
    });

    it('should get the ninth list item from the test server page', function () {
        let listItemNinth = element.all(by.css(selectorLinkCSS)).ninth();

        expect(listItemNinth.getText()).toBe('Ninth');
    });

    it('should get the tenth list item from the test server page', function () {
        let listItemTenth = element.all(by.css(selectorLinkCSS)).tenth();

        expect(listItemTenth.getText()).toBe('Tenth');
    });

});
<commit_msg>Added e2e test for eleventh() element numeration function<commit_after>'use strict';

let nodeTestingServer = require('node-testing-server').nodeTestingServer;

// Settings for node testing server
nodeTestingServer.config = {
    hostname: 'localhost',
    port: 8001,
    logsEnabled: 0,
    pages: {
        '/test.html': `

First

Second

Third

Fourth

Fifth

Sixth

Seventh

Eighth

Ninth

Tenth

Eleventh

Twelfth

Thirteenth

Fourteenth

Fifteenth

Sixteenth

Seventeenth

Eighteenth

Nineteenth

Twentieth

`
    }
}

describe('protractor-numerator tests', function () {
    // Selectors for tests
    let selectorLinkCSS = '.items li';
    let selectorLinkXPath = '//li[ancestor::*[@class="items"]]';

    beforeAll(function () {
        // Turn off Angular synchronization
        browser.ignoreSynchronization = true;
        // Output some information about current tests process
        console.log(`==> Tests running at: ${process.cwd()}`);
        console.log(`==> With argv: ${process.argv}`);

        // Start node testing server
        nodeTestingServer.start();
    });

    beforeEach(function () {
        browser.get(`http://${nodeTestingServer.config.hostname}:${nodeTestingServer.config.port}/test.html`);
    });

    afterAll(function () {
        // Stop node testing server
        nodeTestingServer.stop();
    });

    it('should get the first list item from the test server page', function () {
        let listItemFirst = element.all(by.css(selectorLinkCSS)).first();

        expect(listItemFirst.getText()).toBe('First');
    });

    it('should get the second list item from the test server page', function () {
        let listItemSecond = element.all(by.xpath(selectorLinkXPath)).second();

        expect(listItemSecond.getText()).toBe('Second');
    });

    it('should get the third list item from the test server page', function () {
        let listItemThird = element.all(by.css(selectorLinkCSS)).third();

        expect(listItemThird.getText()).toBe('Third');
    });

    it('should get the fourth list item from the test server page', function () {
        let listItemFourth = element.all(by.css(selectorLinkCSS)).fourth();

        expect(listItemFourth.getText()).toBe('Fourth');
    });

    it('should get the fifth list item from the test server page', function () {
        let listItemFifth = element.all(by.css(selectorLinkCSS)).fifth();

        expect(listItemFifth.getText()).toBe('Fifth');
    });

    it('should get the sixth list item from the test server page', function () {
        let listItemSixth = element.all(by.css(selectorLinkCSS)).sixth();

        expect(listItemSixth.getText()).toBe('Sixth');
    });

    it('should get the seventh list item from the test server page', function () {
        let listItemSeventh = element.all(by.css(selectorLinkCSS)).seventh();

        expect(listItemSeventh.getText()).toBe('Seventh');
    });

    it('should get the eighth list item from the test server page', function () {
        let listItemEighth = element.all(by.css(selectorLinkCSS)).eighth();

        expect(listItemEighth.getText()).toBe('Eighth');
    });

    it('should get the ninth list item from the test server page', function () {
        let listItemNinth = element.all(by.css(selectorLinkCSS)).ninth();

        expect(listItemNinth.getText()).toBe('Ninth');
    });

    it('should get the tenth list item from the test server page', function () {
        let listItemTenth = element.all(by.css(selectorLinkCSS)).tenth();

        expect(listItemTenth.getText()).toBe('Tenth');
    });

    it('should get the eleventh list item from the test server page', function () {
        let listItemEleventh = element.all(by.css(selectorLinkCSS)).eleventh();

        expect(listItemEleventh.getText()).toBe('Eleventh');
    });

});
<|endoftext|>


<commit_before>const expect = require('expect');
const defaults = require('../config/defaults.js')
const CoinHive = require('../src');

describe('Coin-Hive', async () => {

  it('should mine', async () => {
    var miner = await CoinHive(defaults.SITE_KEY);
    await miner.start();
    return new Promise(resolve => {
      miner.on('update', async (data) => {
        if (data.acceptedHashes > 0) {
          await miner.kill();
          resolve();
        }
      })
    });
  });

  it('should do RPC', async () => {
    var miner = await CoinHive(defaults.SITE_KEY);
    let isRunning = await miner.rpc('isRunning');
    expect(isRunning).toBe(false);
    await miner.start();
    isRunning = await miner.rpc('isRunning');
    expect(isRunning).toBe(true);
    let threads = await miner.rpc('getNumThreads');
    expect(typeof threads).toBe('number');
    await miner.rpc('setNumThreads', [2]);
    threads = await miner.rpc('getNumThreads');
    expect(threads).toBe(2);
    await miner.kill();
  });
});
<commit_msg>skip fleaky test<commit_after>const expect = require("expect");
const defaults = require("../config/defaults.js");
const CoinHive = require("../src");

describe("Coin-Hive", async () => {
  it("should mine", async () => {
    var miner = await CoinHive(defaults.SITE_KEY);
    await miner.start();
    return new Promise(resolve => {
      miner.on("update", async data => {
        if (data.acceptedHashes > 0) {
          await miner.kill();
          resolve();
        }
      });
    });
  });

  xit("should do RPC", async () => {
    var miner = await CoinHive(defaults.SITE_KEY);
    let isRunning = await miner.rpc("isRunning");
    expect(isRunning).toBe(false);
    await miner.start();
    isRunning = await miner.rpc("isRunning");
    expect(isRunning).toBe(true);
    let threads = await miner.rpc("getNumThreads");
    expect(typeof threads).toBe("number");
    await miner.rpc("setNumThreads", [2]);
    threads = await miner.rpc("getNumThreads");
    expect(threads).toBe(2);
    await miner.kill();
  });
});
<|endoftext|>