<commit_before>var assert = require("assert");
var fs = require("fs");
var path = require("path");
var isBinaryFile = require("../index");

var FIXTURE_PATH = "./test/fixtures";

describe('isBinaryFile()', function() {
  it('should return true on a binary program', function(cb) {
    isBinaryFile(path.join(FIXTURE_PATH, "grep"), function (err, result) {
      assert(result);
      cb();
    });
  });

  it('should return false on an extensionless script', function(cb) {
    isBinaryFile(path.join(FIXTURE_PATH, "perl_script"), function (err, result) {
      assert(!result);
      cb();
    });
  });

  it('should return false on a russian text', function(cb) {
    isBinaryFile(path.join(FIXTURE_PATH, "russian_file.rst"), function (err, result) {
      assert(!result);
      cb();
    });
  });

  it('should return false on a zero-byte image file', function(cb) {
    isBinaryFile(path.join(FIXTURE_PATH, "null_file.gif"), function (err, result) {
      assert(!result);
      cb();
    });
  });

  it('should return true on a gif', function(cb) {
    isBinaryFile(path.join(FIXTURE_PATH, "trunks.gif"), function (err, result) {
      assert(result);
      cb();
    });
  });

  it('should return false on some UTF8 lua file', function(cb) {
    isBinaryFile(path.join(FIXTURE_PATH, "no.lua"), function (err, result) {
      assert(!result);
      cb();
    });
  });

  it('should return false on a directory', function(cb) {
    isBinaryFile(path.join(FIXTURE_PATH, "dir"), function (err, result) {
      assert(!err);
      assert(!result);
      cb();
    });
  });

  it('should return true on a PDF', function(cb) {
    isBinaryFile(path.join(FIXTURE_PATH, "pdf.pdf"), function (err, result) {
      assert(result);
      cb();
    });
  });
});

describe('isBinaryFile.sync()', function() {
  it('should return true on a binary program', function() {
    assert(isBinaryFile.sync(path.join(FIXTURE_PATH, "grep")));

    var bytes = fs.readFileSync(path.join(FIXTURE_PATH, "grep"));
    var stat = fs.lstatSync(path.join(FIXTURE_PATH, "grep"));
    assert(isBinaryFile.sync(bytes, stat.size));
  });

  it('should return false on an extensionless text script', function() {
    assert(!isBinaryFile.sync(path.join(FIXTURE_PATH, "perl_script")));

    var bytes = fs.readFileSync(path.join(FIXTURE_PATH, "perl_script"));
    var stat = fs.lstatSync(path.join(FIXTURE_PATH, "perl_script"));
    assert(!isBinaryFile.sync(bytes, stat.size));
  });

  it('should return false on a russian text', function() {
    assert(!isBinaryFile.sync(path.join(FIXTURE_PATH, "russian_file.rst")));

    var bytes = fs.readFileSync(path.join(FIXTURE_PATH, "russian_file.rst"));
    var stat = fs.lstatSync(path.join(FIXTURE_PATH, "russian_file.rst"));
    assert(!isBinaryFile.sync(bytes, stat.size));
  });

  it('should return false on a zero-byte image file', function() {
    assert(!isBinaryFile.sync(path.join(FIXTURE_PATH, "null_file.gif")));

    var bytes = fs.readFileSync(path.join(FIXTURE_PATH, "null_file.gif"));
    var stat = fs.lstatSync(path.join(FIXTURE_PATH, "null_file.gif"));
    assert(!isBinaryFile.sync(bytes, stat.size));
  });

  it('should return true on a gif', function() {
    assert(isBinaryFile.sync(path.join(FIXTURE_PATH, "trunks.gif")));

    var bytes = fs.readFileSync(path.join(FIXTURE_PATH, "trunks.gif"));
    var stat = fs.lstatSync(path.join(FIXTURE_PATH, "trunks.gif"));
    assert(isBinaryFile.sync(bytes, stat.size));
  });

  it('should return false on some UTF8 lua file', function() {
    assert(!isBinaryFile.sync(path.join(FIXTURE_PATH, "no.lua")));

    var bytes = fs.readFileSync(path.join(FIXTURE_PATH, "no.lua"));
    var stat = fs.lstatSync(path.join(FIXTURE_PATH, "no.lua"));
    assert(!isBinaryFile.sync(bytes, stat.size));
  });

  it('should return false on a directory', function() {
    assert(!isBinaryFile.sync(path.join(FIXTURE_PATH, "dir")));
  });

  it('should return true on a PDF', function() {
    assert(isBinaryFile.sync(path.join(FIXTURE_PATH, "pdf.pdf")));

    var bytes = fs.readFileSync(path.join(FIXTURE_PATH, "pdf.pdf"));
    var stat = fs.lstatSync(path.join(FIXTURE_PATH, "pdf.pdf"));
    assert(isBinaryFile.sync(bytes, stat.size));
  });

  it('should return false for non-UTF8 files', function() {
    encoding_dir = path.join(FIXTURE_PATH, "encodings")
    files = fs.readdirSync(encoding_dir);
    files.forEach(function(file) {
      if (!/big5/.test(file) && !/gb/.test(file) && !/kr/.test(file))
        assert(!isBinaryFile.sync(path.join(encoding_dir, file)));
    });
  });
});
<commit_msg>Better variable naming<commit_after>var assert = require("assert");
var fs = require("fs");
var path = require("path");
var isBinaryFile = require("../index");

var FIXTURE_PATH = "./test/fixtures";

describe('isBinaryFile()', function() {
  it('should return true on a binary program', function(cb) {
    isBinaryFile(path.join(FIXTURE_PATH, "grep"), function (err, result) {
      assert(result);
      cb();
    });
  });

  it('should return false on an extensionless script', function(cb) {
    isBinaryFile(path.join(FIXTURE_PATH, "perl_script"), function (err, result) {
      assert(!result);
      cb();
    });
  });

  it('should return false on a russian text', function(cb) {
    isBinaryFile(path.join(FIXTURE_PATH, "russian_file.rst"), function (err, result) {
      assert(!result);
      cb();
    });
  });

  it('should return false on a zero-byte image file', function(cb) {
    isBinaryFile(path.join(FIXTURE_PATH, "null_file.gif"), function (err, result) {
      assert(!result);
      cb();
    });
  });

  it('should return true on a gif', function(cb) {
    isBinaryFile(path.join(FIXTURE_PATH, "trunks.gif"), function (err, result) {
      assert(result);
      cb();
    });
  });

  it('should return false on some UTF8 lua file', function(cb) {
    isBinaryFile(path.join(FIXTURE_PATH, "no.lua"), function (err, result) {
      assert(!result);
      cb();
    });
  });

  it('should return false on a directory', function(cb) {
    isBinaryFile(path.join(FIXTURE_PATH, "dir"), function (err, result) {
      assert(!err);
      assert(!result);
      cb();
    });
  });

  it('should return true on a PDF', function(cb) {
    isBinaryFile(path.join(FIXTURE_PATH, "pdf.pdf"), function (err, result) {
      assert(result);
      cb();
    });
  });
});

describe('isBinaryFile.sync()', function() {
  it('should return true on a binary program', function() {
    assert(isBinaryFile.sync(path.join(FIXTURE_PATH, "grep")));

    var bytes = fs.readFileSync(path.join(FIXTURE_PATH, "grep"));
    var size = fs.lstatSync(path.join(FIXTURE_PATH, "grep")).size;
    assert(isBinaryFile.sync(bytes, size));
  });

  it('should return false on an extensionless text script', function() {
    assert(!isBinaryFile.sync(path.join(FIXTURE_PATH, "perl_script")));

    var bytes = fs.readFileSync(path.join(FIXTURE_PATH, "perl_script"));
    var size = fs.lstatSync(path.join(FIXTURE_PATH, "perl_script")).size;
    assert(!isBinaryFile.sync(bytes, size));
  });

  it('should return false on a russian text', function() {
    assert(!isBinaryFile.sync(path.join(FIXTURE_PATH, "russian_file.rst")));

    var bytes = fs.readFileSync(path.join(FIXTURE_PATH, "russian_file.rst"));
    var size = fs.lstatSync(path.join(FIXTURE_PATH, "russian_file.rst")).size;
    assert(!isBinaryFile.sync(bytes, size));
  });

  it('should return false on a zero-byte image file', function() {
    assert(!isBinaryFile.sync(path.join(FIXTURE_PATH, "null_file.gif")));

    var bytes = fs.readFileSync(path.join(FIXTURE_PATH, "null_file.gif"));
    var size = fs.lstatSync(path.join(FIXTURE_PATH, "null_file.gif")).size;
    assert(!isBinaryFile.sync(bytes, size));
  });

  it('should return true on a gif', function() {
    assert(isBinaryFile.sync(path.join(FIXTURE_PATH, "trunks.gif")));

    var bytes = fs.readFileSync(path.join(FIXTURE_PATH, "trunks.gif"));
    var size = fs.lstatSync(path.join(FIXTURE_PATH, "trunks.gif")).size;
    assert(isBinaryFile.sync(bytes, size));
  });

  it('should return false on some UTF8 lua file', function() {
    assert(!isBinaryFile.sync(path.join(FIXTURE_PATH, "no.lua")));

    var bytes = fs.readFileSync(path.join(FIXTURE_PATH, "no.lua"));
    var size = fs.lstatSync(path.join(FIXTURE_PATH, "no.lua")).size;
    assert(!isBinaryFile.sync(bytes, size));
  });

  it('should return false on a directory', function() {
    assert(!isBinaryFile.sync(path.join(FIXTURE_PATH, "dir")));
  });

  it('should return true on a PDF', function() {
    assert(isBinaryFile.sync(path.join(FIXTURE_PATH, "pdf.pdf")));

    var bytes = fs.readFileSync(path.join(FIXTURE_PATH, "pdf.pdf"));
    var size = fs.lstatSync(path.join(FIXTURE_PATH, "pdf.pdf")).size;
    assert(isBinaryFile.sync(bytes, size));
  });

  it('should return false for non-UTF8 files', function() {
    encoding_dir = path.join(FIXTURE_PATH, "encodings")
    files = fs.readdirSync(encoding_dir);
    files.forEach(function(file) {
      if (!/big5/.test(file) && !/gb/.test(file) && !/kr/.test(file))
        assert(!isBinaryFile.sync(path.join(encoding_dir, file)));
    });
  });
});
<|endoftext|>


<commit_before>var assert = require('assert')
var final = require('..')
var http = require('http')
var sinon = require('sinon')

var add = function (options) {
  var first = parseInt(options.first, 10)
  var second = parseInt(options.second, 10)

  return first + second
}

describe('final', () => {
  describe('Runner', () => {
    var runner

    beforeEach(() => runner = new final.Runner(add))

    describe('constructor', () => {
      it('creates a new Runner with the given core', () => {
        assert.equal(runner.core, add)
      })
    })
  })

  describe('CLI', () => {
    var cli

    beforeEach(() => cli = new final.CLI(add))

    describe('#options()', () => {
      it('returns args from argv', () => {
        process.argv = 'node cli.js --first 1 --second 2'.split(' ')
        assert.deepEqual(cli.options(), { first: '1', second: '2' })
      })
    })

    describe('#run()', () => {
      it('runs a cli for the given core', sinon.test(function () {
        this.stub(console, 'log')
        process.argv = 'node cli.js --first 1 --second 2'.split(' ')
        cli.run()

        sinon.assert.calledOnce(console.log)
        sinon.assert.calledWithExactly(console.log, 3)
      }))
    })
  })

  describe('Server', () => {
    var server

    beforeEach(() => server = new final.Server(add))

    afterEach(() => server.close())

    describe('constructor', () => {
      it('creates a new Server with a callback', () => {
        assert(server.callback instanceof Function)
        assert.equal(server.callback.length, 2)
      })

      it('creates a new Server with a server', () => {
        assert(server.server instanceof http.Server)
      })
    })

    describe('#close()', () => {
      it('closes the Server', (done) => {
        server.close()

        http.get('http://localhost:3000', res => {
          done('Error: Server should be closed')
        }).on('error', () => done())
      })
    })

    describe('#options()', () => {
      it('returns options from the given request', () => {
        var req = { url: '/?first=1&second=2' }
        assert.deepEqual(server.options(req), { first: '1', second: '2' })
      })
    })

    describe('#run()', () => {
      it('runs a Server for the given core', (done) => {
        server.run()

        http.get('http://localhost:3000?first=1&second=2', res => {
          assert.equal(res.statusCode, 200)
          assert.equal(res.headers['content-type'], 'text/plain')

          res.on('data', (chunk) => {
            assert.equal(chunk.toString('utf8'), '3\n')
            done()
          })
        }).on('error', done)
      })
    })
  })
})
<commit_msg>Refactor tests<commit_after>var assert = require('assert')
var final = require('..')
var http = require('http')
var sinon = require('sinon')

var add = function (options) {
  var first = parseInt(options.first, 10)
  var second = parseInt(options.second, 10)

  return first + second
}

describe('final', () => {
  describe('Runner', () => {
    var runner = new final.Runner(add)

    describe('constructor', () => {
      it('creates a new Runner with the given core', () => {
        assert.equal(runner.core, add)
      })
    })
  })

  describe('CLI', () => {
    var cli = new final.CLI(add)

    process.argv = 'node cli.js --first 1 --second 2'.split(' ')

    describe('#options()', () => {
      it('returns args from argv', () => {
        assert.deepEqual(cli.options(), { first: '1', second: '2' })
      })
    })

    describe('#run()', () => {
      it('runs a cli for the given core', sinon.test(function () {
        this.stub(console, 'log')
        cli.run()

        sinon.assert.calledOnce(console.log)
        sinon.assert.calledWithExactly(console.log, 3)
      }))
    })
  })

  describe('Server', () => {
    var req = { url: 'http://localhost:3000?first=1&second=2' }

    var server

    beforeEach(() => server = new final.Server(add))

    afterEach(() => server.close())

    describe('constructor', () => {
      it('creates a new Server with a callback', () => {
        assert(server.callback instanceof Function)
        assert.equal(server.callback.length, 2)
      })

      it('creates a new Server with a server', () => {
        assert(server.server instanceof http.Server)
      })
    })

    describe('#close()', () => {
      it('closes the Server', (done) => {
        server.close()

        http.get('http://localhost:3000', res =>
          done('Error: Server should be closed')
        ).on('error', () => done())
      })
    })

    describe('#options()', () => {
      it('returns options from the given request', () => {
        assert.deepEqual(server.options(req), { first: '1', second: '2' })
      })
    })

    describe('#run()', () => {
      it('runs a Server for the given core', (done) => {
        server.run()

        http.get(req.url, res => {
          assert.equal(res.statusCode, 200)
          assert.equal(res.headers['content-type'], 'text/plain')

          res.on('data', (chunk) => {
            assert.equal(chunk.toString('utf8'), '3\n')
            done()
          })
        }).on('error', done)
      })
    })
  })
})
<|endoftext|>


<commit_before>
var OAuth = require( '../' );

var example = new OAuth.Client({
  version: 1,
  consumer: {
    key: 'key',
    secret: 'secret'
  },
  options: {
    tokenUrl: 'http://term.ie/oauth/example/request_token.php',
    accessUrl: 'http://term.ie/oauth/example/access_token.php',
    // authorizeUrl: '',
    // authenticateUrl: '',
  }
});

example.getRequestToken(function( error, token, response ) {

  console.log( token );

  example.getAccessToken(function( error, token, response ) {

    console.log( token );

    example.get(
      'http://term.ie/oauth/example/echo_api.php',
      { message: 'test' },
      function() {
        console.log( arguments[1] );
      }
    );

  });

});
<commit_msg>Updated test/index.js according to the changes in commit [bb26671]<commit_after>
var OAuth = require( '../' );

var example = new OAuth.Client({
  version: 1,
  consumer: {
    key: 'key',
    secret: 'secret'
  },
  options: {
    tokenUrl: 'http://term.ie/oauth/example/request_token.php',
    accessUrl: 'http://term.ie/oauth/example/access_token.php',
    // authorizeUrl: '',
    // authenticateUrl: '',
  }
});

example.getRequestToken( null, function( error, token, response ) {

  console.log( token );

  example.getAccessToken( null, function( error, token, response ) {

    console.log( token );

    example.get(
      'http://term.ie/oauth/example/echo_api.php',
      { message: 'test' },
      function() {
        console.log( arguments[1] );
      }
    );

  });

});
<|endoftext|>


<commit_before>/**
 * Created by Ralph Varjabedian on 11/14/14.
 */

'use strict';

var should = require('chai').should();

var butt = require('butt');

function noop () {}

function escapeRegExp(str) {
  return str.replace(/[\-\[\]\/\{\}\(\)\*\+\?\.\\\^\$\|]/g, "\\$&");
}

function validateObj (target, validator) {
  Object.keys(validator).forEach(function (key) {
    if (!target.hasOwnProperty(key)) {
      throw new Error("Target object doesn't have key " + key);
    }

    if (validator[key] instanceof RegExp) {
      if (!validator[key].test(target[key])) {
        var msg = [
          "Target object's",
          key,
          "property didn't match RegExp",
          "\n",
          target[key]
        ].join(" ");
        throw new Error(msg);
      }
      return;
    }

    if (validator[key] !== target[key]) {
      var msg = [
        "Expected properties at key",
        key,
        "to be equal.",
        "\n",
        "Actual: ",
        target[key],
        "Expected: ",
        validator[key]
      ].join(" ");
      throw new Error(msg);
    }
  });
}

describe('replacing Module.prototype.require()', function() {

  it('attaches and detaches as expected', function() {
    var intercept = require("../");

    var Module = require("module");
    var oldRequire = Module.prototype.require;

    Module.prototype.require.should.equal(oldRequire);
    intercept.attach();
    Module.prototype.require.should.not.equal(oldRequire);
    intercept.detach();
    Module.prototype.require.should.equal(oldRequire);
  });

  it("doesn't fail if intercepting is active but no listener", function () {
    var intercept = require("..");
    intercept.attach();
    (function () {
      require("path").should.be(ok);
    }).should.not.throw();
    intercept.detach();
  });

});

function checkCalculator (calc) {
  return ["add", "subtract", "multiply", "divide"]
    .every(calc.hasOwnProperty.bind(calc));
}

describe('intercepting require()', function () {
  var intercept = require("..");

  beforeEach(butt(intercept.attach, 0));
  afterEach(butt(intercept.detach, 0));

  it('invokes the listener when `require()` is invoked', function () {
    var called = false;
    function listener () {
      called = true;
    }
    intercept.setListener(listener);
    var calc = require("./calculator.js");
    (checkCalculator(calc)).should.equal(true);
    called.should.equal(true);
  });

  it('passes the result and some info to the listener', function () {
    var calc, result, info;
    function listener (r, i) {
      result = r;
      info = i;
    }
    intercept.setListener(listener);
    calc = require("./calculator");
    calc.should.equal(result);
    (checkCalculator(calc)).should.equal(true);

    var callingFileRe = new RegExp(escapeRegExp("intercept-require/test/index.js") + "$");
    var absPathRe = new RegExp(escapeRegExp("intercept-require/test/calculator.js") + "$");

    validateObj(info, {
      callingFile: callingFileRe,
      moduleId: "./calculator",
      extname: ".js",
      native: false,
      thirdParty: false,
      absPath: absPathRe,
      absPathResolvedCorrectly: true,
      testOnly: false,
      local: true,
    });
  });

  it('allows the listener to pass back a value', function () {
    function listener () {
      return true;
    }
    intercept.setListener(listener);
    var calculator = require("./calculator.js");
    calculator.should.equal(true);
  });

  it('passes an error in the result spot if one occurs', function () {

    function listener1 (err, info) {
      (err instanceof Error).should.equal(true);
      should.exist(info);
      /unexpected identifier/i.test(err.message).should.equal(true);
      return true;
    }
    intercept.setListener(listener1);
    require("./malformed.js");

    intercept.resetListener();

    function listener2 (err, info) {
      (err instanceof Error).should.equal(true);
      should.exist(info);
      /cannot find module/i.test(err.message).should.equal(true);
      return true;
    }
    intercept.setListener(listener2);
    require("./no-exist.js");

  });

  it('throws the error if one is passed back from the listener', function () {
    intercept.setListener(noop);
    (function () {
      require("./no-exist.js");
    }).should.throw(/cannot find module/i);
  });

});
<commit_msg>fix failing test<commit_after>/**
 * Created by Ralph Varjabedian on 11/14/14.
 */

'use strict';

var should = require('chai').should();

var butt = require('butt');

function noop () {}

function escapeRegExp(str) {
  return str.replace(/[\-\[\]\/\{\}\(\)\*\+\?\.\\\^\$\|]/g, "\\$&");
}

function validateObj (target, validator) {
  Object.keys(validator).forEach(function (key) {
    if (!target.hasOwnProperty(key)) {
      throw new Error("Target object doesn't have key " + key);
    }

    if (validator[key] instanceof RegExp) {
      if (!validator[key].test(target[key])) {
        var msg = [
          "Target object's",
          key,
          "property didn't match RegExp",
          "\n",
          target[key]
        ].join(" ");
        throw new Error(msg);
      }
      return;
    }

    if (validator[key] !== target[key]) {
      var msg = [
        "Expected properties at key",
        key,
        "to be equal.",
        "\n",
        "Actual: ",
        target[key],
        "Expected: ",
        validator[key]
      ].join(" ");
      throw new Error(msg);
    }
  });
}

describe('replacing Module.prototype.require()', function() {

  it('attaches and detaches as expected', function() {
    var intercept = require("../");

    var Module = require("module");
    var oldRequire = Module.prototype.require;

    Module.prototype.require.should.equal(oldRequire);
    intercept.attach();
    Module.prototype.require.should.not.equal(oldRequire);
    intercept.detach();
    Module.prototype.require.should.equal(oldRequire);
  });

  it("doesn't fail if intercepting is active but no listener", function () {
    var intercept = require("..");
    intercept.attach();
    (function () {
      require("path").should.be.ok();
    }).should.not.throw();
    intercept.detach();
  });

});

function checkCalculator (calc) {
  return ["add", "subtract", "multiply", "divide"]
    .every(calc.hasOwnProperty.bind(calc));
}

describe('intercepting require()', function () {
  var intercept = require("..");

  beforeEach(butt(intercept.attach, 0));
  afterEach(butt(intercept.detach, 0));

  it('invokes the listener when `require()` is invoked', function () {
    var called = false;
    function listener () {
      called = true;
    }
    intercept.setListener(listener);
    var calc = require("./calculator.js");
    (checkCalculator(calc)).should.equal(true);
    called.should.equal(true);
  });

  it('passes the result and some info to the listener', function () {
    var calc, result, info;
    function listener (r, i) {
      result = r;
      info = i;
    }
    intercept.setListener(listener);
    calc = require("./calculator");
    calc.should.equal(result);
    (checkCalculator(calc)).should.equal(true);

    var callingFileRe = new RegExp(escapeRegExp("intercept-require/test/index.js") + "$");
    var absPathRe = new RegExp(escapeRegExp("intercept-require/test/calculator.js") + "$");

    validateObj(info, {
      callingFile: callingFileRe,
      moduleId: "./calculator",
      extname: ".js",
      native: false,
      thirdParty: false,
      absPath: absPathRe,
      absPathResolvedCorrectly: true,
      testOnly: false,
      local: true,
    });
  });

  it('allows the listener to pass back a value', function () {
    function listener () {
      return true;
    }
    intercept.setListener(listener);
    var calculator = require("./calculator.js");
    calculator.should.equal(true);
  });

  it('passes an error in the result spot if one occurs', function () {

    function listener1 (err, info) {
      (err instanceof Error).should.equal(true);
      should.exist(info);
      /unexpected identifier/i.test(err.message).should.equal(true);
      return true;
    }
    intercept.setListener(listener1);
    require("./malformed.js");

    intercept.resetListener();

    function listener2 (err, info) {
      (err instanceof Error).should.equal(true);
      should.exist(info);
      /cannot find module/i.test(err.message).should.equal(true);
      return true;
    }
    intercept.setListener(listener2);
    require("./no-exist.js");

  });

  it('throws the error if one is passed back from the listener', function () {
    intercept.setListener(noop);
    (function () {
      require("./no-exist.js");
    }).should.throw(/cannot find module/i);
  });

});
<|endoftext|>


<commit_before>'use strict'

const should = require('should')
const dao = require('../lib/dao')
<commit_msg>update test test suite<commit_after>'use strict'

const should = require('should')
const DAO = require('../lib/dao')

describe('General test cases for DAO', function () {

	describe('creates an instance correctly', function () {
		let dao = DAO()

		it('should be an Object', function () {
			dao.should.be.Object()
		})

		it('should be instance of DAO', function () {
			dao.should.be.instanceof(DAO)
		})
	})
})<|endoftext|>


<commit_before>var assert = require('assert'),
    RadioParser = require('./../lib/index');

describe('RadioParser', function () {
    it('Should create new instance', function () {
        var radio = new RadioParser('http://streaming.radionomy.com/HammerHeadRadio');
        assert(radio instanceof RadioParser, 'Should be instance of RadioParser');
    });

    it('Should properly get/set config', function () {
        var radio = new RadioParser('http://streaming.radionomy.com/HammerHeadRadio');

        assert.deepEqual(radio.getConfig(), {
            url: 'http://streaming.radionomy.com/HammerHeadRadio',
            keepListen: false,
            autoUpdate: true,
            errorInterval: 10 * 60,
            emptyInterval: 5 * 60,
            metadataInterval: 5
        }, 'Should properly set default config');

        radio.setConfig({
            url: 'http://another-link.com',
            keepListen: true,
            autoUpdate: false,
            errorInterval: 1000,
            emptyInterval: 900,
            metadataInterval: 800
        });

        assert.deepEqual(radio.getConfig(), {
            url: 'http://another-link.com',
            keepListen: true,
            autoUpdate: false,
            errorInterval: 1000,
            emptyInterval: 900,
            metadataInterval: 800
        }, 'Should properly update config');

        radio.setConfig({
            url: 'http://streaming.radionomy.com/HammerHeadRadio'
        });

        assert.deepEqual(radio.getConfig(), {
            url: 'http://streaming.radionomy.com/HammerHeadRadio',
            keepListen: true,
            autoUpdate: false,
            errorInterval: 1000,
            emptyInterval: 900,
            metadataInterval: 800
        }, 'Should properly make particular update');

        assert.equal(radio.getConfig('keepListen'), true, 'Should properly get value from config by key');
    });

    it('Should properly emit metadata', function (done) {
        var radio = new RadioParser('http://streaming.radionomy.com/HammerHeadRadio');
        radio.on('metadata', function (metadata) {
            assert.equal(typeof metadata, 'object', 'Metadata should be object');
            assert.equal(typeof metadata.StreamTitle, 'string', 'StreamTitle should be string');
            done();
        });
    });
});
<commit_msg>Add test case for ShoutCAST<commit_after>var assert = require('assert'),
    RadioParser = require('./../lib/index');

describe('RadioParser', function () {
    it('Should create new instance', function () {
        var radio = new RadioParser('http://streaming.radionomy.com/HammerHeadRadio');
        assert(radio instanceof RadioParser, 'Should be instance of RadioParser');
    });

    it('Should properly get/set config', function () {
        var radio = new RadioParser('http://streaming.radionomy.com/HammerHeadRadio');

        assert.deepEqual(radio.getConfig(), {
            url: 'http://streaming.radionomy.com/HammerHeadRadio',
            keepListen: false,
            autoUpdate: true,
            errorInterval: 10 * 60,
            emptyInterval: 5 * 60,
            metadataInterval: 5
        }, 'Should properly set default config');

        radio.setConfig({
            url: 'http://another-link.com',
            keepListen: true,
            autoUpdate: false,
            errorInterval: 1000,
            emptyInterval: 900,
            metadataInterval: 800
        });

        assert.deepEqual(radio.getConfig(), {
            url: 'http://another-link.com',
            keepListen: true,
            autoUpdate: false,
            errorInterval: 1000,
            emptyInterval: 900,
            metadataInterval: 800
        }, 'Should properly update config');

        radio.setConfig({
            url: 'http://streaming.radionomy.com/HammerHeadRadio'
        });

        assert.deepEqual(radio.getConfig(), {
            url: 'http://streaming.radionomy.com/HammerHeadRadio',
            keepListen: true,
            autoUpdate: false,
            errorInterval: 1000,
            emptyInterval: 900,
            metadataInterval: 800
        }, 'Should properly make particular update');

        assert.equal(radio.getConfig('keepListen'), true, 'Should properly get value from config by key');
    });

    it('Should properly emit metadata from Icecast', function (done) {
        this.timeout(5000);

        var radio = new RadioParser('http://streaming.radionomy.com/HammerHeadRadio');
        radio.on('metadata', function (metadata) {
            assert.equal(typeof metadata, 'object', 'Metadata should be object');
            assert.equal(typeof metadata.StreamTitle, 'string', 'StreamTitle should be string');
            console.log('Icecast -> ' + metadata.StreamTitle);
            done();
        });
    });

    it('Should properly emit metadata from ShoutCAST', function (done) {
        this.timeout(5000);

        var radio = new RadioParser('http://173.245.94.221/;?icy=http');
        radio.on('metadata', function (metadata) {
            assert.equal(typeof metadata, 'object', 'Metadata should be object');
            assert.equal(typeof metadata.StreamTitle, 'string', 'StreamTitle should be string');
            console.log('ShoutCAST -> ' + metadata.StreamTitle);
            done();
        });
    });
});
<|endoftext|>


<commit_before>var React = require('react')
var ReactMap = require('../')
var Marker = ReactMap.Marker

var App = React.createClass({
  getInitialState: function () {
    return {}
  },

  handleWindowResize: function () {
    this.setState({
        windowHeight: window.innerHeight,
        windowWidth: window.innerWidth
    })
  },

  componentDidMount: function () {
    this.handleWindowResize()
    window.addEventListener('resize', this.handleWindowResize)
  },

  componentWillUnmount: function () {
    window.removeEventListener('resize', this.handleWindowResize)
  },

  render: function () {
    var center = {
      lat: -37.8602828,
      lng: 145.079616
    }

    return (

      <ReactMap
        center={center}
        zoom={8}
        height={this.state.windowHeight}
        width={this.state.windowWidth}
      >
        <Marker position={center} label="A pleasant place to live"/>
      </ReactMap>

)
  }
})

React.render(<App/>, document.getElementById('app'))
<commit_msg>use GoogleMap over ReactMap<commit_after>var React = require('react')
var GoogleMap = require('../')
var Marker = GoogleMap.Marker

var App = React.createClass({
  getInitialState: function () {
    return {}
  },

  handleWindowResize: function () {
    this.setState({
        windowHeight: window.innerHeight,
        windowWidth: window.innerWidth
    })
  },

  componentDidMount: function () {
    this.handleWindowResize()
    window.addEventListener('resize', this.handleWindowResize)
  },

  componentWillUnmount: function () {
    window.removeEventListener('resize', this.handleWindowResize)
  },

  render: function () {
    var center = {
      lat: -37.8602828,
      lng: 145.079616
    }

    return (

      <GoogleMap
        center={center}
        zoom={8}
        height={this.state.windowHeight}
        width={this.state.windowWidth}
      >
        <Marker position={center} label="A pleasant place to live"/>
      </GoogleMap>

)
  }
})

React.render(<App/>, document.getElementById('app'))
<|endoftext|>


<commit_before>/**
 * Test Asset Hash
 */

var _			= require('lodash');
var	crypto		= require('crypto');
var	expect		= require('chai').expect;
var fs			= require('fs');
var glob		= require('glob');
var	hasher		= require('../');
var path		= require('path');

// Test variables

var tmpDir		= './tmp/';
var testFiles	= [
	path.join(tmpDir, 'img/bg.jpg'),
	path.join(tmpDir, 'img/favicon.png'),
	path.join(tmpDir, 'img/logo.png'),
	path.join(tmpDir, 'css/landing.css'),
	path.join(tmpDir, 'css/promos.css'),
	path.join(tmpDir, 'css/styles.css'),
	path.join(tmpDir, 'js/main.js'),
	path.join(tmpDir, 'js/shoestring.min.js')
];

// Utility Functions

/**
 * Clean up  test environment
 *
 * @param {string} path The path to directory to remove
 */
function removeTestDir(dirPath) {
	var files = [];

	if(fs.lstatSync(dirPath).isDirectory()) {
		files = fs.readdirSync(dirPath);

		files.forEach(function(file, index) {
			var curPath = path.join(dirPath, file);

			if(fs.lstatSync(curPath).isDirectory()) {
				removeTestDir(curPath);
			} else {
				fs.unlinkSync(curPath);
			}
		});

		fs.rmdirSync(dirPath);
    }
}

/**
 * Add test files
 *
 * @param {array} files Test files to create
 */
function addTestFiles(files) {
	if (!_.isArray(files)) {
		files = [files];
	}

	// Loop and add files
	files.forEach(function(file, index) {
		var filePath 	= path.dirname(file).split('/');
		var curDir 		= '';

		// Create parent directories for file if necessary
		while (filePath.length > 0) {
			curDir = path.join(curDir, filePath.shift());

			try {
				fs.lstatSync(curDir);
			}
			catch(e) {
				fs.mkdirSync(curDir);
			}
		}

		fs.writeFileSync(file, 'test file '+index);
	});
}

/**
 * Remove test files
 *
 * @param  {array} files The files to remove
 */
function removeTestFiles(files) {
	if (!_.isArray(files)) {
		files = [files];
	}

	files.forEach(function(file, index) {
		fs.unlinkSync(file);
	});
}

describe('Test if Asset Hasher is defined', function() {

	it('Should be an object', function() {
		expect(hasher).to.exist.and.to.be.an('object');
	})

});

describe('Test utility functions', function() {

	it('Should add a test file', function() {
		addTestFiles(testFiles[0]);

		expect(fs.lstatSync(testFiles[0]).isFile()).to.be.ok;
	})

	it('Should remove test file', function() {
		removeTestFiles(testFiles[0]);

		expect(fs.lstatSync.bind(fs.lstatSync, testFiles[0])).to.throw(Error, 'ENOENT, no such file or directory');
	})

	it('Should add test files', function() {
		addTestFiles(testFiles);

		testFiles.forEach(function(file) {
			expect(fs.lstatSync(file).isFile()).to.be.ok;
		});
	})

	it('Should remove test files', function() {
		removeTestFiles(testFiles);

		testFiles.forEach(function(file) {
			expect(fs.lstatSync.bind(fs.lstatSync, file)).to.throw(Error, 'ENOENT, no such file or directory');
		})
	})

	it('Should remove "' + tmpDir + '" directory', function() {
		try {
			removeTestDir(tmpDir);
		}
		catch(e) {
			expect(removeTestDir.bind(removeTestDir, tmpDir)).to.throw(Error, "ENOENT, no such file or directory");
		}
	})

});

describe('Test methods exist', function() {

	var methods = ['get', 'set', 'hashFiles', 'getAsset', 'getAssets', 'resetAssets', 'saveManifest', 'updateAsset'];

	methods.forEach(function(method) {
		it('Should have a ' + method + ' method', function() {
			expect(hasher[method]).to.be.a('function');
		})
	});

});

describe('Test config functionality', function() {

	it('Should get all config', function() {
		var config = hasher.get();

		expect(config).to.be.a('object');
	})

	it('Should have default config values', function() {
		var defaults = ['base', 'hasher', 'length', 'manifest', 'path', 'replace', 'save', 'template'];
		var	config = hasher.get();

		expect(config).to.have.all.keys(defaults);
	})

	it('Should get config value', function() {
		var length = hasher.get('length');

		expect(length).to.not.be.empty;
	})

	it('Should return empty string for config keys that are not present', function() {
		var bogusValue = hasher.get('bogus_key_name');

		expect(bogusValue).to.be.a('string').and.be.empty;
	})

	it('Should set config value and also not delete previous entries', function() {
		hasher.set({'key1abc': 'val1abc'});
		hasher.set({'key2abc': 'val2abc'});

		expect(hasher.get('key1abc')).to.be.equal('val1abc');
		expect(hasher.get('key2abc')).to.be.equal('val2abc');
	})

});

describe('Test default config is valid', function() {

	it('Should have a valid hasher', function() {
		var hashers = crypto.getHashes();
		var	myHasher = hasher.get('hasher');

		expect(myHasher).to.be.a('string');
		expect(hashers).to.be.an('array').and.contains(myHasher);
	})

	it('Should have a base', function() {
		expect(hasher.get('base')).to.be.a('string').and.not.be.empty;
	})

	it('Should have a valid length', function() {
		expect(hasher.get('length')).to.be.a('number').and.be.at.least(10);
	})

	it('Should have a manifest file', function() {
		expect(hasher.get('manifest')).to.match(/[a-zA-Z0-9_/\-]+\.json/)
	})

	it('Should have a path', function() {
		expect(hasher.get('path')).to.be.a('string').and.not.be.empty;
	})

	it('Should have a boolean save value', function() {
		expect(hasher.get('save')).to.be.a('boolean');
	})

	it('Should have a hashed filename template', function() {
		expect(hasher.get('template')).to.not.be.empty;
	})

	it('Should have a replace option', function() {
		expect(hasher.get('replace')).to.be.a('boolean');
	})

	it('Should have a valid template format', function() {
		hasher.set({template: '<%= name %>_<%= hash %>.<%= ext %>'});

		addTestFiles(testFiles[0]);

		var hashInfo = hasher.hashFiles(testFiles[0]);

		expect(hashInfo.original).to.equal(hashInfo.path.replace('_' + hashInfo.hash, ''));

		removeTestDir(tmpDir);
	})
});

describe('Test hashing functionality', function() {

	beforeEach(function() {
		addTestFiles(testFiles);
	})

	afterEach(function() {
		removeTestDir(tmpDir);
	})

	it('Should get a list of hashers', function() {
		expect(hasher.getHashers()).to.be.a('array').and.have.length.greaterThan(0);
	})

	it('Should return an object if only one file is hashed', function() {
		expect(hasher.hashFiles(testFiles[0])).to.be.an('object');
	})

	it('Should return object with default fields', function() {
		var hashInfo = hasher.hashFiles(testFiles[0]);

		expect(hashInfo.hashed).to.exist;
		expect(hashInfo.path).to.be.a('string');
		expect(hashInfo.original).to.be.a('string');
		expect(hashInfo.hash).to.be.a('string');
		expect(hashInfo.type).to.be.a('string');
	})

	it('Should hash single file', function() {
		var	hashInfo = hasher.hashFiles(testFiles[0]);

		expect(hashInfo.hashed).to.be.true;
		expect(hashInfo.original).to.equal(testFiles[0]);
		expect(hashInfo.path).to.have.length.greaterThan(hashInfo.original.length);
		expect(fs.lstatSync(hashInfo.path).isFile()).to.be.ok;
	})

	it('Should hash single file and keep original file', function() {
		var hashInfo = hasher.hashFiles(testFiles[0], {replace: false});

		expect(fs.lstatSync(hashInfo.path).isFile()).to.be.ok;
		expect(fs.lstatSync(hashInfo.original).isFile()).to.be.ok;
	})

	it('Should hash single file and replace original file', function() {
		var hashInfo = hasher.hashFiles(testFiles[0], {replace: true});

		expect(fs.lstatSync(hashInfo.path).isFile()).to.be.ok;
		expect(fs.lstatSync.bind(fs.lstatSync, hashInfo.original)).to.throw(Error, "ENOENT, no such file or directory");
	})

	it('Should hash single file twice, keep the original and remove the first hashed file', function() {
		var hash1Info = hasher.hashFiles(testFiles[0], {replace: false});

		expect(fs.lstatSync(hash1Info.path).isFile()).to.be.ok;

		// Update original file contents to second hash will be different
		fs.appendFileSync(testFiles[0], 'appending more test content');

		var hash2Info = hasher.hashFiles(testFiles[0], {replace: false});

		expect(hash1Info.original).to.equal(hash2Info.original);
		expect(fs.lstatSync(hash1Info.original).isFile()).to.be.ok;
		expect(fs.lstatSync(hash2Info.path).isFile()).to.be.ok;
		expect(fs.lstatSync.bind(fs.lstatSync, hash1Info.path)).to.throw(Error, "ENOENT, no such file or directory");
	})

	it('Should have same hash for single unchanged file which is hashed multiple times', function() {
		var hash1Info = hasher.hashFiles(testFiles[0], {replace: false});
		var hash2Info = hasher.hashFiles(testFiles[0], {replace: false});

		expect(hash1Info.path).to.equal(hash2Info.path);
	})

	it('Should return an array if multiple files are hashed', function() {
		expect(hasher.hashFiles(testFiles)).to.be.a('array');
	})

	it('Should hash multiple individual files', function() {
		var hashInfo = hasher.hashFiles(testFiles);

		testFiles.forEach(function(file, index) {
			expect(hashInfo[index].original).to.equal(file);
			expect(fs.lstatSync(hashInfo[index].path).isFile()).to.be.ok;
		});
	})

	it('Should hash files specified by single glob entry', function() {
		var testGlob = path.join(tmpDir, 'css/*');
		var files = glob.sync(testGlob);
		var hashInfo = hasher.hashFiles(testGlob);

		expect(files.length).to.equal(hashInfo.length);

		hashInfo.forEach(function(fileInfo) {
			expect(fileInfo.hashed).to.be.true;
			expect(fs.lstatSync(fileInfo.path).isFile()).to.be.ok;
		});
	})

	it('Should hash files specified by multiple glob entries', function() {
		var test1Glob = path.join(tmpDir, 'css/*');
		var test2Glob = path.join(tmpDir, 'js/*');
		var files1 = glob.sync(test1Glob);
		var files2 = glob.sync(test2Glob);
		var hashInfo = hasher.hashFiles([test1Glob, test2Glob]);

		expect(files1.concat(files2).length).to.equal(hashInfo.length);

		hashInfo.forEach(function(fileInfo) {
			expect(fileInfo.hashed).to.be.true;
			expect(fs.lstatSync(fileInfo.path).isFile()).to.be.ok;
		});
	})

});

describe('Test asset library and manifest', function() {

	beforeEach(function() {
		addTestFiles(testFiles);
	})

	afterEach(function() {
		removeTestDir(tmpDir);
	})

	it('Should return an empty object when asset library is reset', function() {
		var assets = hasher.resetAssets();

		expect(assets).to.be.an('object');
		expect(_.size(assets)).to.equal(0);
	})

	it('Should return an object for asset library', function() {
		hasher.hashFiles(testFiles);

		var info = hasher.getAsset(testFiles[0]);

		expect(info).to.be.an('object');
		expect(info.original).to.equal(testFiles[0]);
	})

	it('Should return null if asset library entery does not exist', function() {
		hasher.hashFiles(testFiles);

		expect(hasher.getAsset('this-is-a-bogus-entry-asdgir82')).to.be.null;
	})

	it('Should update asset library entry', function() {
		hasher.hashFiles(testFiles);

		var data = hasher.getAsset(testFiles[0]);
		var prefixed = 'testupdate_' + data.path;

		hasher.updateAsset(testFiles[0], {path: prefixed});

		var updatedData = hasher.getAsset(testFiles[0]);

		expect(updatedData.path).to.equal(prefixed);
	})

	it('Should return object for assets library', function() {
		expect(hasher.getAssets()).to.be.a('object');
	})

	it('Should have same number of entries as total number of files hashed', function() {
		expect(_.keys(hasher.getAssets()).length).to.equal(testFiles.length);
	})

	it('Should save asset manifest file', function() {
		var manifestFile = hasher.get('manifest');

		hasher.saveManifest();

		expect(fs.lstatSync(manifestFile).isFile()).to.be.ok;

		removeTestFiles(manifestFile);
	})

	it('Should save asset manifest file with custom name provided in saveManifest options', function() {
		var oldManifestFile = hasher.get('manifest');
		var manifestFile = 'test_manifest.json';

		hasher.saveManifest({manifest: manifestFile});

		expect(manifestFile).to.not.equal(oldManifestFile);
		expect(fs.lstatSync(manifestFile).isFile()).to.be.ok;

		removeTestFiles(manifestFile);
	})

});<commit_msg>Updated file<commit_after>/**
 * Test Asset Hash
 */

var _			= require('lodash');
var	crypto		= require('crypto');
var	expect		= require('chai').expect;
var fs			= require('fs');
var glob		= require('glob');
var	hasher		= require('../');
var path		= require('path');
var vinylFile	= require('vinyl-file');

// Test variables

var tmpDir		= './tmp/';
var testFiles	= [
	path.join(tmpDir, 'img/bg.jpg'),
	path.join(tmpDir, 'img/favicon.png'),
	path.join(tmpDir, 'img/logo.png'),
	path.join(tmpDir, 'css/landing.css'),
	path.join(tmpDir, 'css/promos.css'),
	path.join(tmpDir, 'css/styles.css'),
	path.join(tmpDir, 'js/main.js'),
	path.join(tmpDir, 'js/shoestring.min.js')
];

// Utility Functions

/**
 * Clean up  test environment
 *
 * @param {string} path The path to directory to remove
 */
function removeTestDir(dirPath) {
	var files = [];

	if(fs.lstatSync(dirPath).isDirectory()) {
		files = fs.readdirSync(dirPath);

		files.forEach(function(file, index) {
			var curPath = path.join(dirPath, file);

			if(fs.lstatSync(curPath).isDirectory()) {
				removeTestDir(curPath);
			} else {
				fs.unlinkSync(curPath);
			}
		});

		fs.rmdirSync(dirPath);
    }
}

/**
 * Add test files
 *
 * @param {array} files Test files to create
 */
function addTestFiles(files) {
	if (!_.isArray(files)) {
		files = [files];
	}

	// Loop and add files
	files.forEach(function(file, index) {
		var filePath 	= path.dirname(file).split('/');
		var curDir 		= '';

		// Create parent directories for file if necessary
		while (filePath.length > 0) {
			curDir = path.join(curDir, filePath.shift());

			try {
				fs.lstatSync(curDir);
			}
			catch(e) {
				fs.mkdirSync(curDir);
			}
		}

		fs.writeFileSync(file, 'test file '+index);
	});
}

/**
 * Remove test files
 *
 * @param  {array} files The files to remove
 */
function removeTestFiles(files) {
	if (!_.isArray(files)) {
		files = [files];
	}

	files.forEach(function(file, index) {
		fs.unlinkSync(file);
	});
}

describe('Test if Asset Hasher is defined', function() {

	it('Should be an object', function() {
		expect(hasher).to.exist.and.to.be.an('object');
	})

});

describe('Test utility functions', function() {

	it('Should add a test file', function() {
		addTestFiles(testFiles[0]);

		expect(fs.lstatSync(testFiles[0]).isFile()).to.be.ok;
	})

	it('Should remove test file', function() {
		removeTestFiles(testFiles[0]);

		expect(fs.lstatSync.bind(fs.lstatSync, testFiles[0])).to.throw(Error, 'ENOENT, no such file or directory');
	})

	it('Should add test files', function() {
		addTestFiles(testFiles);

		testFiles.forEach(function(file) {
			expect(fs.lstatSync(file).isFile()).to.be.ok;
		});
	})

	it('Should remove test files', function() {
		removeTestFiles(testFiles);

		testFiles.forEach(function(file) {
			expect(fs.lstatSync.bind(fs.lstatSync, file)).to.throw(Error, 'ENOENT, no such file or directory');
		})
	})

	it('Should remove "' + tmpDir + '" directory', function() {
		try {
			removeTestDir(tmpDir);
		}
		catch(e) {
			expect(removeTestDir.bind(removeTestDir, tmpDir)).to.throw(Error, "ENOENT, no such file or directory");
		}
	})

});

describe('Test methods exist', function() {

	var methods = ['get', 'set', 'hashFiles', 'getAsset', 'getAssets', 'resetAssets', 'saveManifest', 'updateAsset'];

	methods.forEach(function(method) {
		it('Should have a ' + method + ' method', function() {
			expect(hasher[method]).to.be.a('function');
		})
	});

});

describe('Test config functionality', function() {

	it('Should get all config', function() {
		var config = hasher.get();

		expect(config).to.be.a('object');
	})

	it('Should have default config values', function() {
		var defaults = ['base', 'hasher', 'length', 'manifest', 'path', 'replace', 'save', 'template'];
		var	config = hasher.get();

		expect(config).to.have.all.keys(defaults);
	})

	it('Should get config value', function() {
		var length = hasher.get('length');

		expect(length).to.not.be.empty;
	})

	it('Should return empty string for config keys that are not present', function() {
		var bogusValue = hasher.get('bogus_key_name');

		expect(bogusValue).to.be.a('string').and.be.empty;
	})

	it('Should set config value and also not delete previous entries', function() {
		hasher.set({'key1abc': 'val1abc'});
		hasher.set({'key2abc': 'val2abc'});

		expect(hasher.get('key1abc')).to.be.equal('val1abc');
		expect(hasher.get('key2abc')).to.be.equal('val2abc');
	})

});

describe('Test default config is valid', function() {

	it('Should have a valid hasher', function() {
		var hashers = crypto.getHashes();
		var	myHasher = hasher.get('hasher');

		expect(myHasher).to.be.a('string');
		expect(hashers).to.be.an('array').and.contains(myHasher);
	})

	it('Should have a base', function() {
		expect(hasher.get('base')).to.be.a('string').and.not.be.empty;
	})

	it('Should have a valid length', function() {
		expect(hasher.get('length')).to.be.a('number').and.be.at.least(10);
	})

	it('Should have a manifest file', function() {
		expect(hasher.get('manifest')).to.match(/[a-zA-Z0-9_/\-]+\.json/)
	})

	it('Should have a path', function() {
		expect(hasher.get('path')).to.be.a('string').and.not.be.empty;
	})

	it('Should have a boolean save value', function() {
		expect(hasher.get('save')).to.be.a('boolean');
	})

	it('Should have a hashed filename template', function() {
		expect(hasher.get('template')).to.not.be.empty;
	})

	it('Should have a replace option', function() {
		expect(hasher.get('replace')).to.be.a('boolean');
	})

	it('Should have a valid template format', function() {
		hasher.set({template: '<%= name %>_<%= hash %>.<%= ext %>'});

		addTestFiles(testFiles[0]);

		var hashInfo = hasher.hashFiles(testFiles[0]);

		expect(hashInfo.original).to.equal(hashInfo.path.replace('_' + hashInfo.hash, ''));

		removeTestDir(tmpDir);
	})
});

describe('Test hashing functionality', function() {

	beforeEach(function() {
		addTestFiles(testFiles);
	})

	afterEach(function() {
		removeTestDir(tmpDir);
	})

	it('Should get a list of hashers', function() {
		expect(hasher.getHashers()).to.be.a('array').and.have.length.greaterThan(0);
	})

	it('Should return an object if only one file is hashed', function() {
		expect(hasher.hashFiles(testFiles[0])).to.be.an('object');
	})

	it('Should return object with default fields', function() {
		var hashInfo = hasher.hashFiles(testFiles[0]);

		expect(hashInfo.hashed).to.exist;
		expect(hashInfo.path).to.be.a('string');
		expect(hashInfo.original).to.be.a('string');
		expect(hashInfo.hash).to.be.a('string');
		expect(hashInfo.type).to.be.a('string');
	})

	it('Should hash single file', function() {
		var	hashInfo = hasher.hashFiles(testFiles[0]);

		expect(hashInfo.hashed).to.be.true;
		expect(hashInfo.original).to.equal(testFiles[0]);
		expect(hashInfo.path).to.have.length.greaterThan(hashInfo.original.length);
		expect(fs.lstatSync(hashInfo.path).isFile()).to.be.ok;
	})

	it('Should hash single file and keep original file', function() {
		var hashInfo = hasher.hashFiles(testFiles[0], {replace: false});

		expect(fs.lstatSync(hashInfo.path).isFile()).to.be.ok;
		expect(fs.lstatSync(hashInfo.original).isFile()).to.be.ok;
	})

	it('Should hash single file and replace original file', function() {
		var hashInfo = hasher.hashFiles(testFiles[0], {replace: true});

		expect(fs.lstatSync(hashInfo.path).isFile()).to.be.ok;
		expect(fs.lstatSync.bind(fs.lstatSync, hashInfo.original)).to.throw(Error, "ENOENT, no such file or directory");
	})

	it('Should hash single file twice, keep the original and remove the first hashed file', function() {
		var hash1Info = hasher.hashFiles(testFiles[0], {replace: false});

		expect(fs.lstatSync(hash1Info.path).isFile()).to.be.ok;

		// Update original file contents to second hash will be different
		fs.appendFileSync(testFiles[0], 'appending more test content');

		var hash2Info = hasher.hashFiles(testFiles[0], {replace: false});

		expect(hash1Info.original).to.equal(hash2Info.original);
		expect(fs.lstatSync(hash1Info.original).isFile()).to.be.ok;
		expect(fs.lstatSync(hash2Info.path).isFile()).to.be.ok;
		expect(fs.lstatSync.bind(fs.lstatSync, hash1Info.path)).to.throw(Error, "ENOENT, no such file or directory");
	})

	it('Should have same hash for single unchanged file which is hashed multiple times', function() {
		var hash1Info = hasher.hashFiles(testFiles[0], {replace: false});
		var hash2Info = hasher.hashFiles(testFiles[0], {replace: false});

		expect(hash1Info.path).to.equal(hash2Info.path);
	})

	it('Should return an array if multiple files are hashed', function() {
		expect(hasher.hashFiles(testFiles)).to.be.a('array');
	})

	it('Should hash multiple individual files', function() {
		var hashInfo = hasher.hashFiles(testFiles);

		testFiles.forEach(function(file, index) {
			expect(hashInfo[index].original).to.equal(file);
			expect(fs.lstatSync(hashInfo[index].path).isFile()).to.be.ok;
		});
	})

	it('Should hash files specified by single glob entry', function() {
		var testGlob = path.join(tmpDir, 'css/*');
		var files = glob.sync(testGlob);
		var hashInfo = hasher.hashFiles(testGlob);

		expect(files.length).to.equal(hashInfo.length);

		hashInfo.forEach(function(fileInfo) {
			expect(fileInfo.hashed).to.be.true;
			expect(fs.lstatSync(fileInfo.path).isFile()).to.be.ok;
		});
	})

	it('Should hash files specified by multiple glob entries', function() {
		var test1Glob = path.join(tmpDir, 'css/*');
		var test2Glob = path.join(tmpDir, 'js/*');
		var files1 = glob.sync(test1Glob);
		var files2 = glob.sync(test2Glob);
		var hashInfo = hasher.hashFiles([test1Glob, test2Glob]);

		expect(files1.concat(files2).length).to.equal(hashInfo.length);

		hashInfo.forEach(function(fileInfo) {
			expect(fileInfo.hashed).to.be.true;
			expect(fs.lstatSync(fileInfo.path).isFile()).to.be.ok;
		});
	})

});

describe('Test asset library and manifest', function() {

	beforeEach(function() {
		addTestFiles(testFiles);
	})

	afterEach(function() {
		removeTestDir(tmpDir);
	})

	it('Should return an empty object when asset library is reset', function() {
		var assets = hasher.resetAssets();

		expect(assets).to.be.an('object');
		expect(_.size(assets)).to.equal(0);
	})

	it('Should return an object for asset library', function() {
		hasher.hashFiles(testFiles);

		var info = hasher.getAsset(testFiles[0]);

		expect(info).to.be.an('object');
		expect(info.original).to.equal(testFiles[0]);
	})

	it('Should return null if asset library entery does not exist', function() {
		hasher.hashFiles(testFiles);

		expect(hasher.getAsset('this-is-a-bogus-entry-asdgir82')).to.be.null;
	})

	it('Should update asset library entry', function() {
		hasher.hashFiles(testFiles);

		var data = hasher.getAsset(testFiles[0]);
		var prefixed = 'testupdate_' + data.path;

		hasher.updateAsset(testFiles[0], {path: prefixed});

		var updatedData = hasher.getAsset(testFiles[0]);

		expect(updatedData.path).to.equal(prefixed);
	})

	it('Should return object for assets library', function() {
		expect(hasher.getAssets()).to.be.a('object');
	})

	it('Should have same number of entries as total number of files hashed', function() {
		expect(_.keys(hasher.getAssets()).length).to.equal(testFiles.length);
	})

	it('Should save asset manifest file', function() {
		var manifestFile = hasher.get('manifest');

		hasher.saveManifest();

		expect(fs.lstatSync(manifestFile).isFile()).to.be.ok;

		removeTestFiles(manifestFile);
	})

	it('Should save asset manifest file with custom name provided in saveManifest options', function() {
		var oldManifestFile = hasher.get('manifest');
		var manifestFile = 'test_manifest.json';

		hasher.saveManifest({manifest: manifestFile});

		expect(manifestFile).to.not.equal(oldManifestFile);
		expect(fs.lstatSync(manifestFile).isFile()).to.be.ok;

		removeTestFiles(manifestFile);
	})

});<|endoftext|>


<commit_before>
var tape = require('tape')
var pull = require('pull-stream')
var split = require('pull-randomly-split')

var psc = require('../')

function flat (err) {
  return {
    message: err.message,
    name: err.name,
    stack: err.stack
  }
}

var examples = [
  {req: 0, stream: false, end: false, value: ['event', {okay: true}]}, //an event

  {req: 1, stream: false, end: false, value: 'whatever'}, //a request
  {req:  2, stream: true, end: false, value: new Buffer('hello')}, //a stream packet
  {req: -2, stream: true, end: false, value: new Buffer('goodbye')}, //a stream response
  {req: -3, stream: false, end: true, value: flat(new Error('intentional'))},
  {req:  2, stream: true, end: true, value: true}, //a stream packet
  {req: -2, stream: true, end: true, value: true}, //a stream response
  "GOODBYE"
]

tape('simple', function (t) {
  examples.forEach(function (e) {
    var c = psc.encodePair(e)

    var msg = psc.decodeHead(c[0])

    if(c[1]) {
      t.equal(msg.length, c[1].length)
      msg = psc.decodeBody(c[1], msg)
      delete msg.length
      delete msg.type
      t.deepEqual(e, msg)
    }
  })
  t.end()
})

tape('streaming', function (t) {

  pull(
    pull.values(examples),
    psc.encode(),
    split(),
    psc.decode(),
    pull.collect(function (err, actual) {

      examples.forEach(function (expected, i) {
        delete actual[i].length
        delete actual[i].type

        t.deepEqual(actual[i], expected)
      })
      t.end()
    })
  )

})

tape('streaming', function (t) {

  var duplex = {
    source: pull.values(examples),
    sink: pull.collect(function (err, actual) {

      examples.forEach(function (expected, i) {
        delete actual[i].length
        delete actual[i].type

        t.deepEqual(actual[i], expected)
      })
      t.end()
    })

  }

  var s = psc(duplex)

  pull(s, s)

})

<commit_msg>also test a large buffer<commit_after>
var tape = require('tape')
var pull = require('pull-stream')
var split = require('pull-randomly-split')

var psc = require('../')

function flat (err) {
  return {
    message: err.message,
    name: err.name,
    stack: err.stack
  }
}

var examples = [
  {req: 0, stream: false, end: false, value: ['event', {okay: true}]}, //an event

  {req: 1, stream: false, end: false, value: 'whatever'}, //a request
  {req:  2, stream: true, end: false, value: new Buffer('hello')}, //a stream packet
  {req: -2, stream: true, end: false, value: new Buffer('goodbye')}, //a stream response
  {req: -3, stream: false, end: true, value: flat(new Error('intentional'))},
  {req:  2, stream: true, end: true, value: true}, //a stream packet
  {req: -2, stream: true, end: true, value: true}, //a stream response
  {req: 1, stream: false, end: false, value: new Buffer(1024*1024)}, //a large buffer
  "GOODBYE"
]

tape('simple', function (t) {
  examples.forEach(function (e) {
    var c = psc.encodePair(e)

    var msg = psc.decodeHead(c[0])

    if(c[1]) {
      t.equal(msg.length, c[1].length)
      msg = psc.decodeBody(c[1], msg)
      delete msg.length
      delete msg.type
      t.deepEqual(e, msg)
    }
  })
  t.end()
})

tape('streaming', function (t) {

  pull(
    pull.values(examples),
    psc.encode(),
    split(),
    psc.decode(),
    pull.collect(function (err, actual) {

      examples.forEach(function (expected, i) {
        delete actual[i].length
        delete actual[i].type

        t.deepEqual(actual[i], expected)
      })
      t.end()
    })
  )

})

tape('streaming', function (t) {

  var duplex = {
    source: pull.values(examples),
    sink: pull.collect(function (err, actual) {

      examples.forEach(function (expected, i) {
        delete actual[i].length
        delete actual[i].type

        t.deepEqual(actual[i], expected)
      })
      t.end()
    })

  }

  var s = psc(duplex)

  pull(s, s)

})

<|endoftext|>


<commit_before>const path = require('path')
const chai = require('chai')
const should = chai.should()
const prefixnote = require('../index.js')
const toArray = require('stream-to-array')
const Promise = require('bluebird')

chai.use(require('chai-things'))
chai.use(require('chai-as-promised'))

describe('prefixnote', function() {

  describe('parse', function() {

    it('should parse a string without an expression', function() {
      prefixnote.parse('test').should.eql({
        original: 'test',
        value: 'test',
        expressions: []
      })
    })

    it('should parse basic expressions', function() {

      prefixnote.parse('{a}test').should.eql({
        original: '{a}test',
        value: 'test',
        expressions: [{
          expression: 'a',
          args: [],
          options: {}
        }]
      })

      prefixnote.parse('{a}').should.eql({
        original: '{a}',
        value: '',
        expressions: [{
          expression: 'a',
          args: [],
          options: {}
        }]
      })

      prefixnote.parse('{a && b}').should.eql({
        original: '{a && b}',
        value: '',
        expressions: [{
          expression: 'a && b',
          args: [],
          options: {}
        }]
      })

    })

    it('should parse multiple expressions', function() {
      prefixnote.parse('{a}{b}test').should.eql({
        original: '{a}{b}test',
        value: 'test',
        expressions: [
          {
            expression: 'a',
            args: [],
            options: {}
          },
          {
            expression: 'b',
            args: [],
            options: {}
          }
        ]
      })
    })

    it('should parse arguments', function() {

      prefixnote.parse('{: a, b, c}test').should.eql({
        original: '{: a, b, c}test',
        value: 'test',
        expressions: [{
          expression: null,
          args: ['a', 'b', 'c'],
          options: {}
        }]
      })

    })

    it('should parse options', function() {

      prefixnote.parse('{: a=1, b=2, c=3}test').should.eql({
        original: '{: a=1, b=2, c=3}test',
        value: 'test',
        expressions: [{
          expression: null,
          args: [],
          options: {
            a: '1',
            b: '2',
            c: '3'
          }
        }]
      })

    })

    it('should parse arguments and options', function() {

      prefixnote.parse('{: a=1, b, c=3}test').should.eql({
        original: '{: a=1, b, c=3}test',
        value: 'test',
        expressions: [{
          expression: null,
          args: ['b'],
          options: {
            a: '1',
            c: '3'
          }
        }]
      })

    })

  })

  describe('test', function() {

    it('should pass for plain strings', function() {
      prefixnote.test('test', { a: true }).should.eql({
        expression: null,
        args: [],
        options: {}
      })
    })

    it('should pass for empty expressions', function() {
      prefixnote.test('{}test', { a: true }).should.eql({
        expression: null,
        args: [],
        options: {}
      })
    })

    it('should evaluate a simple expression with the given data', function() {
      prefixnote.test('{a}', { a: true }).should.eql({
        expression: 'a',
        args: [],
        options: {}
      })
      should.equal(prefixnote.test('{a}', { a: false }), null)
      should.equal(prefixnote.test('{a}', {}), null)
    })

    it('should accept already parsed strings', function() {
      const parsed = prefixnote.parse('{a}')
      prefixnote.test(parsed, { a: true }).should.eql({
        expression: 'a',
        args: [],
        options: {}
      })
    })

    it('should evaluate a boolean expression', function() {
      prefixnote.test('{a && b}', {
        a: true,
        b: true
      }).should.eql({
        expression: 'a && b',
        args: [],
        options: {}
      })

      should.equal(prefixnote.test('{a && b}', {
        a: true,
        b: false
      }), null)

      should.equal(prefixnote.test('{a && b}', {
        a: false,
        b: true
      }), null)

    })

    it('if there are multiple expressions, should return the first one that is true', function() {

      prefixnote.test('{a}{b}', { a: true }).should.eql({
        expression: 'a',
        args: [],
        options: {}
      })

      prefixnote.test('{a}{b}', { b: true }).should.eql({
        expression: 'b',
        args: [],
        options: {}
      })

      should.equal(prefixnote.test('{a}{b}', {}), null)

    })

  })

  describe('parseFiles', function() {

    it('should only parse files whose prefix evaluates to true', function() {
      const parsedArray = toArray(prefixnote.parseFiles(path.join('test/sample'), {
        a: false,
        b: false
      }))
      return Promise.join(
        parsedArray.should.eventually.deep.include({
          original: path.join('test/sample/{}package.json'),
          parsed: path.join('test/sample/package.json'),
          parsedObject: { expression: null, args: [], options: {} }
        }),
        parsedArray.should.eventually.deep.include({
          original: path.join('test/sample/README.md'),
          parsed: path.join('test/sample/README.md'),
          parsedObject: { expression: null, args: [], options: {} }
        }),
        parsedArray.should.eventually.deep.include({
          original: path.join('test/sample/LICENSE'),
          parsed: path.join('test/sample/LICENSE'),
          parsedObject: { expression: null, args: [], options: {} }
        })
      )
    })

    it('should parse nested folders', function() {
      const parsedArray = toArray(prefixnote.parseFiles(path.join('test/sample'), {
        a: true,
        a1: true,
        a2: false,
        b: false
      }))// .tap(console.log)
      return Promise.join(
        parsedArray.should.eventually.deep.include({
          original: path.join('test/sample/{}package.json'),
          parsed: path.join('test/sample/package.json'),
          parsedObject: { expression: null, args: [], options: {} }
        }),
        parsedArray.should.eventually.deep.include({
          original: path.join('test/sample/LICENSE'),
          parsed: path.join('test/sample/LICENSE'),
          parsedObject: { expression: null, args: [], options: {} }
        }),
        parsedArray.should.eventually.deep.include({
          original: path.join('test/sample/README.md'),
          parsed: path.join('test/sample/README.md'),
          parsedObject: { expression: null, args: [], options: {} }
        }),
        parsedArray.should.eventually.deep.include({
          original: path.join('test/sample/{a}a/{a1}1'),
          parsed: path.join('test/sample/a/1'),
          parsedObject: { expression: 'a1', args: [], options: {} }
        }),
        parsedArray.should.eventually.deep.include({
          original: path.join('test/sample/{a}a/3'),
          parsed: path.join('test/sample/a/3'),
          parsedObject: { expression: null, args: [], options: {} }
        }),
        parsedArray.should.eventually.deep.include({
          original: path.join('test/sample/{a}a/4'),
          parsed: path.join('test/sample/a/4'),
          parsedObject: { expression: null, args: [], options: {} }
        })
      )
    })

    it('should parse files in null folders as children of the parent', function() {
      const parsedArray = toArray(prefixnote.parseFiles(path.join('test/sample'), {
        a: false,
        b: true
      }))
      return Promise.join(
        parsedArray.should.eventually.deep.include({
          original: path.join('test/sample/{}package.json'),
          parsed: path.join('test/sample/package.json'),
          parsedObject: { expression: null, args: [], options: {} }
        }),
        parsedArray.should.eventually.deep.include({
          original: path.join('test/sample/LICENSE'),
          parsed: path.join('test/sample/LICENSE'),
          parsedObject: { expression: null, args: [], options: {} }
        }),
        parsedArray.should.eventually.deep.include({
          original: path.join('test/sample/README.md'),
          parsed: path.join('test/sample/README.md'),
          parsedObject: { expression: null, args: [], options: {} }
        }),
        parsedArray.should.eventually.deep.include({
          original: path.join('test/sample/{b}/1'),
          parsed: path.join('test/sample/1'),
          parsedObject: { expression: null, args: [], options: {} }
        }),
        parsedArray.should.eventually.deep.include({
          original: path.join('test/sample/{b}/2'),
          parsed: path.join('test/sample/2'),
          parsedObject: { expression: null, args: [], options: {} }
        })
      )
    })

  })

})
<commit_msg>Use async/await in tests.<commit_after>const path = require('path')
const chai = require('chai')
const should = chai.should()
const prefixnote = require('../index.js')
const toArray = require('stream-to-array')

chai.use(require('chai-things'))
chai.use(require('chai-as-promised'))

describe('parse', function() {

  it('should parse a string without an expression', function() {
    prefixnote.parse('test').should.eql({
      original: 'test',
      value: 'test',
      expressions: []
    })
  })

  it('should parse basic expressions', function() {

    prefixnote.parse('{a}test').should.eql({
      original: '{a}test',
      value: 'test',
      expressions: [{
        expression: 'a',
        args: [],
        options: {}
      }]
    })

    prefixnote.parse('{a}').should.eql({
      original: '{a}',
      value: '',
      expressions: [{
        expression: 'a',
        args: [],
        options: {}
      }]
    })

    prefixnote.parse('{a && b}').should.eql({
      original: '{a && b}',
      value: '',
      expressions: [{
        expression: 'a && b',
        args: [],
        options: {}
      }]
    })

  })

  it('should parse multiple expressions', function() {
    prefixnote.parse('{a}{b}test').should.eql({
      original: '{a}{b}test',
      value: 'test',
      expressions: [
        {
          expression: 'a',
          args: [],
          options: {}
        },
        {
          expression: 'b',
          args: [],
          options: {}
        }
      ]
    })
  })

  it('should parse arguments', function() {

    prefixnote.parse('{: a, b, c}test').should.eql({
      original: '{: a, b, c}test',
      value: 'test',
      expressions: [{
        expression: null,
        args: ['a', 'b', 'c'],
        options: {}
      }]
    })

  })

  it('should parse options', function() {

    prefixnote.parse('{: a=1, b=2, c=3}test').should.eql({
      original: '{: a=1, b=2, c=3}test',
      value: 'test',
      expressions: [{
        expression: null,
        args: [],
        options: {
          a: '1',
          b: '2',
          c: '3'
        }
      }]
    })

  })

  it('should parse arguments and options', function() {

    prefixnote.parse('{: a=1, b, c=3}test').should.eql({
      original: '{: a=1, b, c=3}test',
      value: 'test',
      expressions: [{
        expression: null,
        args: ['b'],
        options: {
          a: '1',
          c: '3'
        }
      }]
    })

  })

})

describe('test', function() {

  it('should pass for plain strings', function() {
    prefixnote.test('test', { a: true }).should.eql({
      expression: null,
      args: [],
      options: {}
    })
  })

  it('should pass for empty expressions', function() {
    prefixnote.test('{}test', { a: true }).should.eql({
      expression: null,
      args: [],
      options: {}
    })
  })

  it('should evaluate a simple expression with the given data', function() {
    prefixnote.test('{a}', { a: true }).should.eql({
      expression: 'a',
      args: [],
      options: {}
    })
    should.equal(prefixnote.test('{a}', { a: false }), null)
    should.equal(prefixnote.test('{a}', {}), null)
  })

  it('should accept already parsed strings', function() {
    const parsed = prefixnote.parse('{a}')
    prefixnote.test(parsed, { a: true }).should.eql({
      expression: 'a',
      args: [],
      options: {}
    })
  })

  it('should evaluate a boolean expression', function() {
    prefixnote.test('{a && b}', {
      a: true,
      b: true
    }).should.eql({
      expression: 'a && b',
      args: [],
      options: {}
    })

    should.equal(prefixnote.test('{a && b}', {
      a: true,
      b: false
    }), null)

    should.equal(prefixnote.test('{a && b}', {
      a: false,
      b: true
    }), null)

  })

  it('if there are multiple expressions, should return the first one that is true', function() {

    prefixnote.test('{a}{b}', { a: true }).should.eql({
      expression: 'a',
      args: [],
      options: {}
    })

    prefixnote.test('{a}{b}', { b: true }).should.eql({
      expression: 'b',
      args: [],
      options: {}
    })

    should.equal(prefixnote.test('{a}{b}', {}), null)

  })

})

describe('parseFiles', function() {

  it('should only parse files whose prefix evaluates to true', async () => {
    const parsedArray = await toArray(prefixnote.parseFiles(path.join('test/sample'), {
      a: false,
      b: false
    }))
    parsedArray.should.deep.include({
      original: path.join('test/sample/{}package.json'),
      parsed: path.join('test/sample/package.json'),
      parsedObject: { expression: null, args: [], options: {} }
    }),
    parsedArray.should.deep.include({
      original: path.join('test/sample/README.md'),
      parsed: path.join('test/sample/README.md'),
      parsedObject: { expression: null, args: [], options: {} }
    }),
    parsedArray.should.deep.include({
      original: path.join('test/sample/LICENSE'),
      parsed: path.join('test/sample/LICENSE'),
      parsedObject: { expression: null, args: [], options: {} }
    })
  })

  it('should parse nested folders', async () => {
    const parsedArray = await toArray(prefixnote.parseFiles(path.join('test/sample'), {
      a: true,
      a1: true,
      a2: false,
      b: false
    }))// .tap(console.log)

    parsedArray.should.deep.include({
      original: path.join('test/sample/{}package.json'),
      parsed: path.join('test/sample/package.json'),
      parsedObject: { expression: null, args: [], options: {} }
    }),
    parsedArray.should.deep.include({
      original: path.join('test/sample/LICENSE'),
      parsed: path.join('test/sample/LICENSE'),
      parsedObject: { expression: null, args: [], options: {} }
    }),
    parsedArray.should.deep.include({
      original: path.join('test/sample/README.md'),
      parsed: path.join('test/sample/README.md'),
      parsedObject: { expression: null, args: [], options: {} }
    }),
    parsedArray.should.deep.include({
      original: path.join('test/sample/{a}a/{a1}1'),
      parsed: path.join('test/sample/a/1'),
      parsedObject: { expression: 'a1', args: [], options: {} }
    }),
    parsedArray.should.deep.include({
      original: path.join('test/sample/{a}a/3'),
      parsed: path.join('test/sample/a/3'),
      parsedObject: { expression: null, args: [], options: {} }
    }),
    parsedArray.should.deep.include({
      original: path.join('test/sample/{a}a/4'),
      parsed: path.join('test/sample/a/4'),
      parsedObject: { expression: null, args: [], options: {} }
    })
  })

  it('should parse files in null folders as children of the parent', async () => {
    const parsedArray = await toArray(prefixnote.parseFiles(path.join('test/sample'), {
      a: false,
      b: true
    }))
    parsedArray.should.deep.include({
      original: path.join('test/sample/{}package.json'),
      parsed: path.join('test/sample/package.json'),
      parsedObject: { expression: null, args: [], options: {} }
    }),
    parsedArray.should.deep.include({
      original: path.join('test/sample/LICENSE'),
      parsed: path.join('test/sample/LICENSE'),
      parsedObject: { expression: null, args: [], options: {} }
    }),
    parsedArray.should.deep.include({
      original: path.join('test/sample/README.md'),
      parsed: path.join('test/sample/README.md'),
      parsedObject: { expression: null, args: [], options: {} }
    }),
    parsedArray.should.deep.include({
      original: path.join('test/sample/{b}/1'),
      parsed: path.join('test/sample/1'),
      parsedObject: { expression: null, args: [], options: {} }
    }),
    parsedArray.should.deep.include({
      original: path.join('test/sample/{b}/2'),
      parsed: path.join('test/sample/2'),
      parsedObject: { expression: null, args: [], options: {} }
    })
  })

})
<|endoftext|>


<commit_before>var ruleTester = require('stylelint-rule-tester');
var statementMaxNestingDepth = require('..');

var messages = statementMaxNestingDepth.messages;
var testRule = ruleTester(statementMaxNestingDepth.rule, statementMaxNestingDepth.ruleName);

testRule({ noElementWithAttribute: true }, function(tr) {
  basics(tr);

  tr.ok('input { top: 0; }');
  tr.notOk('input[type=\'button\'] { top: 0; }', 'Avoid qualifying attribute selectors with an element.');
});

testRule({ noElementWithClass: true }, function(tr) {
  basics(tr);

  tr.ok('.class { top: 0; }');
  tr.ok('div>.class { top: 0; }');
  tr.ok('div+.class { top: 0; }');
  tr.ok('div~.class { top: 0; }');
  tr.notOk('div.class { top: 0; }','Avoid qualifying class selectors with an element.');
});

testRule({ noElementWithId: true }, function(tr) {
  basics(tr);

  tr.ok('#id { top: 0; }');
  tr.ok('div>#id { top: 0; }');
  tr.ok('div+#id { top: 0; }');
  tr.ok('div~#id { top: 0; }');
  tr.notOk('div#id { top: 0; }', 'Avoid qualifying id selectors with an element.');
});

function basics(tr) {
  tr.ok('');
  tr.ok('a {}');
  tr.ok('@import "foo.css";');
  tr.ok('a { top: 0; }');
}
<commit_msg>Update index.js<commit_after>var ruleTester = require('stylelint-rule-tester');
var statementMaxNestingDepth = require('..');

var messages = statementMaxNestingDepth.messages;
var testRule = ruleTester(statementMaxNestingDepth.rule, statementMaxNestingDepth.ruleName);

testRule({ noElementWithAttribute: true }, function(tr) {
  basics(tr);

  tr.ok('input { top: 0; }');
  tr.notOk('input[type=\'button\'] { top: 0; }', 'Avoid qualifying attribute selectors with an element');
});

testRule({ noElementWithClass: true }, function(tr) {
  basics(tr);

  tr.ok('.class { top: 0; }');
  tr.ok('div>.class { top: 0; }');
  tr.ok('div+.class { top: 0; }');
  tr.ok('div~.class { top: 0; }');
  tr.notOk('div.class { top: 0; }','Avoid qualifying class selectors with an element');
});

testRule({ noElementWithId: true }, function(tr) {
  basics(tr);

  tr.ok('#id { top: 0; }');
  tr.ok('div>#id { top: 0; }');
  tr.ok('div+#id { top: 0; }');
  tr.ok('div~#id { top: 0; }');
  tr.notOk('div#id { top: 0; }', 'Avoid qualifying id selectors with an element');
});

function basics(tr) {
  tr.ok('');
  tr.ok('a {}');
  tr.ok('@import "foo.css";');
  tr.ok('a { top: 0; }');
}
<|endoftext|>


<commit_before>var CircusRouter = require('circus-router'),
    expect = require('chai').expect;

describe('circus-router', function() {
  describe('config', function() {
    it('should apply additions', function() {
      var config = {
        circusNamespace: 'foo',
        plugins: [1]
      };
      config = CircusRouter.config(config);
      expect(config.circusNamespace).to.equal('foo');
      expect(config.plugins[1]).to.equal(1);
    });
  });
});
<commit_msg>Fix project reference in test<commit_after>var CircusRouter = require('../'),
    expect = require('chai').expect;

describe('circus-router', function() {
  describe('config', function() {
    it('should apply additions', function() {
      var config = {
        circusNamespace: 'foo',
        plugins: [1]
      };
      config = CircusRouter.config(config);
      expect(config.circusNamespace).to.equal('foo');
      expect(config.plugins[1]).to.equal(1);
    });
  });
});
<|endoftext|>


<commit_before>var Blockchain = require('../src/index')
var url = 'https://common-blockchain-test.herokuapp.com'

describe('cb-tests', function () {
  var options = {}

  beforeEach(function () {
    options.blockchain = new Blockchain(url)
  })

  require('cb-tester')(options)
})
<commit_msg>tests: add higher default timeout<commit_after>var Blockchain = require('../src/index')
var url = 'https://common-blockchain-test.herokuapp.com'

describe('cb-tests', function () {
  var options = {}

  beforeEach(function () {
    options.blockchain = new Blockchain(url)
    options.blockchain.timeout = 1000000
  })

  require('cb-tester')(options)
})
<|endoftext|>


<commit_before>'use strict';

var expect = require('chai').expect;
var Shimo = require('..');
var Promise = require('bluebird');

describe('shimo', function () {
  it('has default options', function () {
    var shimo = new Shimo();
    expect(shimo.options.protocol).to.eql('https');
    expect(shimo.options.host).to.eql('api.shimo.im');
    expect(shimo.options.base).to.eql('https://api.shimo.im');
  });

  describe('#:method', function () {
    it('should send correct options', function (done) {
      var shimo = new Shimo();
      shimo._request = function (options) {
        expect(options.json).to.eql(true);
        expect(options.method).to.eql('post');
        expect(options.path).to.eql('foo');
        expect(options.qs).to.eql({ q: 1 });
        expect(options.body).to.eql({ b: 1 });
        setTimeout(done, 0);
        return Promise.resolve(1);
      };
      shimo.post('foo', { qs: { q: 1 }, body: { b: 1 } });
    });

    it('should return results', function (done) {
      var shimo = new Shimo();
      shimo.get('', function (err, res) {
        expect(err).to.eql(null);
        expect(res).to.match(/shimo-api/);
        done();
      });
    });
  });

  describe('#token', function () {
    it('should send correct options', function (done) {
      var shimo = new Shimo();
      shimo._request = function (options) {
        expect(options.json).to.eql(false);
        expect(options.method).to.eql('post');
        expect(options.path).to.eql('oauth/token');
        expect(options.body).to.eql({ grant_type: 'refresh_token', refresh_token: 'token' });
        setTimeout(done, 0);
        return Promise.resolve(1);
      };
      shimo.token('refresh_token', { refresh_token: 'token' });
    });
  });

  describe('#authorization', function () {
    it('should return correct url', function () {
      var shimo = new Shimo({ clientId: '123' });
      var url = shimo.authorization({ redirect_uri: 'http://my.tld/path?q=6' });
      var parsedUrl = require('url').parse(url, true);
      expect(parsedUrl.protocol).to.eql('https:');
      expect(parsedUrl.host).to.eql('api.shimo.im');
      expect(parsedUrl.pathname).to.eql('/oauth/authorization');
      expect(parsedUrl.query.redirect_uri).to.eql('http://my.tld/path?q=6');
      expect(parsedUrl.query.client_id).to.eql('123');
      expect(parsedUrl.query.response_type).to.eql('code');
    });
  });
});
<commit_msg>Fix test<commit_after>'use strict';

var expect = require('chai').expect;
var Shimo = require('..');
var Promise = require('bluebird');

describe('shimo', function () {
  it('has default options', function () {
    var shimo = new Shimo();
    expect(shimo.options.protocol).to.eql('https');
    expect(shimo.options.host).to.eql('api.shimo.im');
    expect(shimo.options.base).to.eql('https://api.shimo.im');
  });

  describe('#:method', function () {
    it('should send correct options', function (done) {
      var shimo = new Shimo();
      shimo._request = function (options) {
        expect(options.json).to.eql(true);
        expect(options.method).to.eql('post');
        expect(options.path).to.eql('foo');
        expect(options.qs).to.eql({ q: 1 });
        expect(options.body).to.eql({ b: 1 });
        setTimeout(done, 0);
        return Promise.resolve(1);
      };
      shimo.post('foo', { qs: { q: 1 }, body: { b: 1 } });
    });

    it('should return results', function (done) {
      var server = require('http').createServer(function (req, res) {
        expect(req.url).to.eql('/api?q=1');
        res.end('shimo-api');
      }).listen(0);
      var shimo = new Shimo({ protocol: 'http', host: '127.0.0.1:' + server.address().port });
      shimo.get('/api', { qs: { q: 1 } }, function (err, res) {
        expect(err).to.eql(null);
        expect(res).to.match(/shimo-api/);
        server.close();
        done();
      });
    });
  });

  describe('#token', function () {
    it('should send correct options', function (done) {
      var shimo = new Shimo();
      shimo._request = function (options) {
        expect(options.json).to.eql(false);
        expect(options.method).to.eql('post');
        expect(options.path).to.eql('oauth/token');
        expect(options.body).to.eql({ grant_type: 'refresh_token', refresh_token: 'token' });
        setTimeout(done, 0);
        return Promise.resolve(1);
      };
      shimo.token('refresh_token', { refresh_token: 'token' });
    });
  });

  describe('#authorization', function () {
    it('should return correct url', function () {
      var shimo = new Shimo({ clientId: '123' });
      var url = shimo.authorization({ redirect_uri: 'http://my.tld/path?q=6' });
      var parsedUrl = require('url').parse(url, true);
      expect(parsedUrl.protocol).to.eql('https:');
      expect(parsedUrl.host).to.eql('api.shimo.im');
      expect(parsedUrl.pathname).to.eql('/oauth/authorization');
      expect(parsedUrl.query.redirect_uri).to.eql('http://my.tld/path?q=6');
      expect(parsedUrl.query.client_id).to.eql('123');
      expect(parsedUrl.query.response_type).to.eql('code');
    });
  });
});
<|endoftext|>


<commit_before>const fs = require('fs')
const bulbo = require('../src/')

const {expect} = require('chai')
const rimraf = require('rimraf')
const request = require('superagent')
const vinylServe = require('vinyl-serve')
const through2 = require('through2')
const browserify = require('browserify')

const SERVER_LAUNCH_WAIT = 800
const BUILD_WAIT = 400

describe('bulbo', () => {
  beforeEach(() => {
    bulbo.clear()
    bulbo.setLogger(require('../src/util/logger')('bulbo'))
  })

  describe('asset', () => {
    it('registers the asset', () => {
      bulbo.asset('test/fixture/**/*.js')
      expect(bulbo.isEmpty()).to.be.false
    })

    it('returns the asset\'s modifier', () => {
      expect(bulbo.asset('test/fixture/**/*.js')).to.be.an('object')
      expect(bulbo.asset('test/fixture/**/*.js').watch).to.be.a('function')
      expect(bulbo.asset('test/fixture/**/*.js').watchOptions).to.be.a('function')
      expect(bulbo.asset('test/fixture/**/*.js').base).to.be.a('function')
    })

    describe('.pipe', () => {
      it('sets the transform to the asset', done => {
        bulbo
        .asset('test/fixture/js/{foo,bar}.js')
        .base('test/fixture')
        .pipe(through2.obj(function (file, enc, cb) {
          file.contents = browserify(file.path).bundle()

          cb(null, file)
        }))

        bulbo.build().then(() => {
          const contents = fs.readFileSync('build/js/foo.js').toString()

          expect(contents).to.contain('This is foo.js')
          expect(contents).to.contain('This is bar.js')

          rimraf('build', done)
        }).catch(done)
      })
    })
  })

  describe('build', () => {
    it('builds the assets and put them in build/ dir', done => {
      bulbo.asset('test/fixture/**/*.js')

      bulbo.build().then(() => {
        expect(fs.readFileSync('build/js/foo.js').toString()).to.have.length.above(1)

        rimraf('build', done)
      })
    })

    it('does not stop at highWaterMark(=16) files', done => {
      bulbo.asset('test/fixture/**/*.js')

      bulbo.build().then(() => {
        expect(fs.readFileSync('build/js/0.js').toString()).to.have.length.above(1)
        expect(fs.readFileSync('build/js/1.js').toString()).to.have.length.above(1)
        expect(fs.readFileSync('build/js/2.js').toString()).to.have.length.above(1)
        expect(fs.readFileSync('build/js/3.js').toString()).to.have.length.above(1)
        expect(fs.readFileSync('build/js/4.js').toString()).to.have.length.above(1)
        expect(fs.readFileSync('build/js/5.js').toString()).to.have.length.above(1)
        expect(fs.readFileSync('build/js/6.js').toString()).to.have.length.above(1)
        expect(fs.readFileSync('build/js/7.js').toString()).to.have.length.above(1)
        expect(fs.readFileSync('build/js/8.js').toString()).to.have.length.above(1)
        expect(fs.readFileSync('build/js/9.js').toString()).to.have.length.above(1)
        expect(fs.readFileSync('build/js/10.js').toString()).to.have.length.above(1)
        expect(fs.readFileSync('build/js/11.js').toString()).to.have.length.above(1)
        expect(fs.readFileSync('build/js/12.js').toString()).to.have.length.above(1)
        expect(fs.readFileSync('build/js/13.js').toString()).to.have.length.above(1)
        expect(fs.readFileSync('build/js/14.js').toString()).to.have.length.above(1)
        expect(fs.readFileSync('build/js/15.js').toString()).to.have.length.above(1)
        expect(fs.readFileSync('build/js/16.js').toString()).to.have.length.above(1)

        rimraf('build', done)
      })
    })

    it('does not throw when assets are empty', done => {
      bulbo.build()

      setTimeout(done, BUILD_WAIT)
    })
  })

  describe('serve', () => {
    it('serves the assets at port 7100', done => {
      bulbo.asset('test/fixture/**/*.js')

      bulbo.serve().then(() => {
        setTimeout(() => {
          request.get('0.0.0.0:7100/js/foo.js').buffer().end((err, res) => {
            if (err) { done(err) }

            expect(res.text).to.contain('This is foo.js')

            vinylServe.stop(7100)

            done()
          })
        }, SERVER_LAUNCH_WAIT)
      })
    })

    it('does not throw when the assets are empty', done => {
      bulbo.serve()

      setTimeout(() => {
        vinylServe.stop(7100)

        done()
      }, SERVER_LAUNCH_WAIT)
    })
  })

  describe('port', () => {
    it('sets the port number', done => {
      bulbo.port(8500)

      bulbo.serve().then(() => {
        request.get('0.0.0.0:8500/__bulbo__').end((err, res) => {
          vinylServe.stop(8500)

          done(err)
        })
      })
    })
  })

  describe('dest', () => {
    it('sets the build destination', done => {
      bulbo.dest('build/dist')

      bulbo.asset('test/fixture/**/*.js')

      bulbo.build().then(() => {
        expect(fs.readFileSync('build/dist/js/foo.js').toString()).to.have.length.above(1)

        rimraf('build', done)
      })
    })
  })

  describe('debugPageTitle', () => {
    it('sets the debug page\'s title', done => {
      bulbo.asset('test/fixture/**/*.js')
      bulbo.debugPageTitle('FooBarBaz')
      bulbo.port(7111)

      bulbo.serve().then(() => {
        request.get('0.0.0.0:7111/__bulbo__').buffer().end((err, res) => {
          if (err) { done(err) }

          expect(res.text).to.contain('<title>FooBarBaz</title>')

          vinylServe.stop(7111)

          done()
        })
      })
    })
  })

  describe('debugPagePath', () => {
    it('sets the debug page path', done => {
      bulbo.asset('test/fixture/**/*.js')
      bulbo.debugPagePath('__foobarbaz__')
      bulbo.port(8113)

      bulbo.serve().then(() => {
        request.get('0.0.0.0:8113/__foobarbaz__').buffer().end((err, res) => {
          if (err) { done(err) }

          expect(res.text).to.contain('<html>')

          vinylServe.stop(8113)

          done()
        })
      })
    })
  })
})
<commit_msg>test(watchAndBuild): add test of watch and build<commit_after>const fs = require('fs')
const bulbo = require('../src/')

const {expect} = require('chai')
const rimraf = require('rimraf')
const request = require('superagent')
const vinylServe = require('vinyl-serve')
const through2 = require('through2')
const browserify = require('browserify')

const SERVER_LAUNCH_WAIT = 800
const BUILD_WAIT = 400
const WATCH_BUILD_WAIT = 1000

describe('bulbo', () => {
  beforeEach(() => {
    bulbo.clear()
    bulbo.setLogger(require('../src/util/logger')('bulbo'))
  })

  describe('asset', () => {
    it('registers the asset', () => {
      bulbo.asset('test/fixture/**/*.js')
      expect(bulbo.isEmpty()).to.be.false
    })

    it('returns the asset\'s modifier', () => {
      expect(bulbo.asset('test/fixture/**/*.js')).to.be.an('object')
      expect(bulbo.asset('test/fixture/**/*.js').watch).to.be.a('function')
      expect(bulbo.asset('test/fixture/**/*.js').watchOptions).to.be.a('function')
      expect(bulbo.asset('test/fixture/**/*.js').base).to.be.a('function')
    })

    describe('.pipe', () => {
      it('sets the transform to the asset', done => {
        bulbo
        .asset('test/fixture/js/{foo,bar}.js')
        .base('test/fixture')
        .pipe(through2.obj(function (file, enc, cb) {
          file.contents = browserify(file.path).bundle()

          cb(null, file)
        }))

        bulbo.build().then(() => {
          const contents = fs.readFileSync('build/js/foo.js').toString()

          expect(contents).to.contain('This is foo.js')
          expect(contents).to.contain('This is bar.js')

          rimraf('build', done)
        }).catch(done)
      })
    })
  })

  describe('build', () => {
    it('builds the assets and put them in build/ dir', done => {
      bulbo.asset('test/fixture/**/*.js')

      bulbo.build().then(() => {
        expect(fs.readFileSync('build/js/foo.js').toString()).to.have.length.above(1)

        rimraf('build', done)
      })
    })

    it('does not stop at highWaterMark(=16) files', done => {
      bulbo.asset('test/fixture/**/*.js')

      bulbo.build().then(() => {
        expect(fs.readFileSync('build/js/0.js').toString()).to.have.length.above(1)
        expect(fs.readFileSync('build/js/1.js').toString()).to.have.length.above(1)
        expect(fs.readFileSync('build/js/2.js').toString()).to.have.length.above(1)
        expect(fs.readFileSync('build/js/3.js').toString()).to.have.length.above(1)
        expect(fs.readFileSync('build/js/4.js').toString()).to.have.length.above(1)
        expect(fs.readFileSync('build/js/5.js').toString()).to.have.length.above(1)
        expect(fs.readFileSync('build/js/6.js').toString()).to.have.length.above(1)
        expect(fs.readFileSync('build/js/7.js').toString()).to.have.length.above(1)
        expect(fs.readFileSync('build/js/8.js').toString()).to.have.length.above(1)
        expect(fs.readFileSync('build/js/9.js').toString()).to.have.length.above(1)
        expect(fs.readFileSync('build/js/10.js').toString()).to.have.length.above(1)
        expect(fs.readFileSync('build/js/11.js').toString()).to.have.length.above(1)
        expect(fs.readFileSync('build/js/12.js').toString()).to.have.length.above(1)
        expect(fs.readFileSync('build/js/13.js').toString()).to.have.length.above(1)
        expect(fs.readFileSync('build/js/14.js').toString()).to.have.length.above(1)
        expect(fs.readFileSync('build/js/15.js').toString()).to.have.length.above(1)
        expect(fs.readFileSync('build/js/16.js').toString()).to.have.length.above(1)

        rimraf('build', done)
      })
    })

    it('does not throw when assets are empty', done => {
      bulbo.build()

      setTimeout(done, BUILD_WAIT)
    })
  })

  describe('watchAndBuild', () => {
    it('builds the assets', done => {
      bulbo.asset('test/fixture/**/*.js')

      bulbo.watchAndBuild()

      setTimeout(() => {
        expect(fs.readFileSync('build/js/0.js').toString()).to.have.length.above(1)

        rimraf('build', done)
      }, WATCH_BUILD_WAIT)
    })
  })

  describe('serve', () => {
    it('serves the assets at port 7100', done => {
      bulbo.asset('test/fixture/**/*.js')

      bulbo.serve().then(() => {
        setTimeout(() => {
          request.get('0.0.0.0:7100/js/foo.js').buffer().end((err, res) => {
            if (err) { done(err) }

            expect(res.text).to.contain('This is foo.js')

            vinylServe.stop(7100)

            done()
          })
        }, SERVER_LAUNCH_WAIT)
      })
    })

    it('does not throw when the assets are empty', done => {
      bulbo.serve()

      setTimeout(() => {
        vinylServe.stop(7100)

        done()
      }, SERVER_LAUNCH_WAIT)
    })
  })

  describe('port', () => {
    it('sets the port number', done => {
      bulbo.port(8500)

      bulbo.serve().then(() => {
        request.get('0.0.0.0:8500/__bulbo__').end((err, res) => {
          vinylServe.stop(8500)

          done(err)
        })
      })
    })
  })

  describe('dest', () => {
    it('sets the build destination', done => {
      bulbo.dest('build/dist')

      bulbo.asset('test/fixture/**/*.js')

      bulbo.build().then(() => {
        expect(fs.readFileSync('build/dist/js/foo.js').toString()).to.have.length.above(1)

        rimraf('build', done)
      })
    })
  })

  describe('debugPageTitle', () => {
    it('sets the debug page\'s title', done => {
      bulbo.asset('test/fixture/**/*.js')
      bulbo.debugPageTitle('FooBarBaz')
      bulbo.port(7111)

      bulbo.serve().then(() => {
        request.get('0.0.0.0:7111/__bulbo__').buffer().end((err, res) => {
          if (err) { done(err) }

          expect(res.text).to.contain('<title>FooBarBaz</title>')

          vinylServe.stop(7111)

          done()
        })
      })
    })
  })

  describe('debugPagePath', () => {
    it('sets the debug page path', done => {
      bulbo.asset('test/fixture/**/*.js')
      bulbo.debugPagePath('__foobarbaz__')
      bulbo.port(8113)

      bulbo.serve().then(() => {
        request.get('0.0.0.0:8113/__foobarbaz__').buffer().end((err, res) => {
          if (err) { done(err) }

          expect(res.text).to.contain('<html>')

          vinylServe.stop(8113)

          done()
        })
      })
    })
  })
})
<|endoftext|>