<commit_before>/**
 * Module dependencies.
 */
var path = require('path')
    , Factory = require('./patterns/factory')
    , Singleton = require('./patterns/singleton')
    , Constructor = require('./patterns/constructor')
    , Literal = require('./patterns/literal')
    , debug = require('debug')('electrolyte');

/**
 * `Container` constructor.
 *
 * A container contains a set of named object instances, known as components.
 * These components are automatically created when needed and injected into
 * other components that require them.
 *
 * A default `Container` singleton is exported via the module.  Applications
 * should not need to construct additional instances, and are advised against
 * doing so.
 *
 * @api public
 */
function Container() {
    this._o = {};
    this._sources = {};
    this._order = [];
    this._expose = undefined;
}

/**
 * Create a component.
 *
 * When the component being created requires other components (using `@require`
 * annotations), those components will automatically be created and injected
 * into the component.  In this way, complex graphs of objects can be
 * constructed with a single line of code, eliminating extraneous boilerplate.
 *
 * A component can be annotated as being a singletion (using `@singleton`).  If
 * so, only one instance of the named component will be created.  Subsequent
 * calls to create the component will return the singleton instance.
 *
 * Examples:
 *
 *     var foo = IoC.create('foo');
 *
 *     var boop = IoC.create('beep/boop');
 *
 * @param {String} id
 * @return {mixed}
 * @api public
 */
Container.prototype.create = function (id, parent, prefixes) {
    parent = parent || {};
    prefixes = prefixes || [];
    prefixes = prefixes.map(function (pref) {
        return pref + Container.nestedResourcesSeparator + id;
    });
    prefixes.push(id);

    for (var i in prefixes) {
        var pref = prefixes[i];
        var p = this._create(pref, parent, prefixes);
        if (p.found) return p.comp;
    }

    throw new Error("Unable to create component '" + id + "'");

}

Container.nestedResourcesSeparator = ".";

Container.prototype._create = function (id, parent, prefixes) {
    if (parent && id[0] == '.') {
        // resolve relative component ID
        // TODO: Ensure that this uses '/' as a separator on Windows
        id = path.join(path.dirname(parent.id), id);
    }

    // special modules
    switch (id) {
        case '$container':
            return this;
    }

    var comp = this._o[id];
    if (!comp) {
        // No component is registered with the given ID.  Attempt to register the
        // component by loading its corresponding module.
        this._loadModule(id);
    }

    comp = this._o[id];
    if (!comp) {
        return {
            found: false
        };
    }

    return {
        found: true,
        comp: comp.create(this, prefixes)
    };
}

Container.prototype.factory = function (id, fn, dependencies, type) {
    dependencies = dependencies || fn['@require'] || [];
    type = type || fn['@type'] || 'constructorInjection';
    this._register(new Factory(id, dependencies, fn, type));
}

Container.prototype.singleton = function (id, fn, dependencies, type) {
    dependencies = dependencies || fn['@require'] || [];
    type = type || fn['@type'] || 'constructorInjection';
    this._register(new Singleton(id, dependencies, fn, type));
}

Container.prototype.constructor = function (id, ctor, dependencies, type) {
    dependencies = dependencies || ctor['@require'] || [];
    type = type || ctor['@type'] || 'constructorInjection';
    this._register(new Constructor(id, dependencies, ctor, type));
}

Container.prototype.literal = function (id, obj, dependencies, type) {
    dependencies = dependencies || (obj && obj['@require']) || [];
    type = type || (obj && obj['@type']) || 'constructorInjection';
    this._register(new Literal(id, dependencies, obj, type));
}

Container.prototype._register = function (comp) {
    // TODO: Pass sid to constructor (??)
    this._o[comp.id] = comp;
}

Container.prototype.register = function (id, module, dependencies, mode, type) {
    if (dependencies != null && (!Array.isArray(dependencies) || !dependencies instanceof Object || typeof dependencies === "string")) {
        type = mode;
        mode = dependencies;
        dependencies = null;
    }

    mode = mode || this.getModuleType(module) || "@factory";

    if (mode == "@singleton") {
        return this.singleton(id, module, dependencies, type);
    } else if (mode == "@factory") {
        return this.factory(id, module, dependencies, type);
    } else if (mode == "@constructor") {
        return this.constructor(id, module, dependencies, type);
    } else if (mode == "@literal") {
        return this.literal(id, module, dependencies, type);
    } else {
        throw new Error("Unknown mode: " + mode);
    }
};

Container.prototype.getModuleType = function (module) {
    if (module["@singleton"]) {
        return "@singleton";
    } else if (module["@factory"]) {
        return "@factory";
    } else if (module["@constructor"]) {
        return "@constructor";
    } else if (module["@literal"]) {
        return "@literal";
    } else {
        return null;
    }
};

Container.prototype.loader =
    Container.prototype.use = function (prefix, fn, options) {
        if (typeof prefix == 'function') {
            fn = prefix;
            prefix = '';
        }
        if (typeof fn != 'function') {
            // Adding a loader that isn't a function is bad mojo
            throw new Error("Loader requires a function, was passed a '" + (typeof fn) + "'");

        }
        if (prefix.length && prefix[prefix.length - 1] != '/') {
            prefix += '/';
        }
        var id = this._order.length;
        this._sources[id] = {prefix: prefix, fn: fn, options: options};
        this._order.push({id: id, prefix: prefix, fn: fn});
    }

Container.prototype.expose = function (cb) {
    this._expose = cb;
}

Container.prototype._loadModule = function (id) {
    debug('autoload %s', id);
    var sources = this._order
        , source, prefix, rid, mod;
    for (var i = 0, len = sources.length; i < len; ++i) {
        source = sources[i];
        prefix = source.prefix;
        if (id.indexOf(prefix) !== 0) {
            continue;
        }
        rid = id.slice(prefix.length);
        mod = source.fn(rid);

        if (mod) {
            this._registerModule(id, mod);
            break;
        }
    }
}

Container.prototype._registerModule = function (id, mod) {
    var dependencies = mod['@require'] || []
        , pattern = '@literal';

    if (typeof mod == 'function') {
        var name = mod.name || 'anonymous';
        if (name[0] == name[0].toUpperCase()) {
            pattern = '@constructor';
        } else {
            if (mod['@singleton']) {
                pattern = '@singleton';
            } else {
                pattern = '@factory';
            }
        }

        if (mod['@literal'] === true) {
            pattern = '@literal';
        }
    }

    pattern = this.getModuleType(mod) || pattern;

    // TODO: Clean this up.  Singleton should be eliminated and handled
    //       as an option by both factory and constructor patterns.
    switch (pattern) {
        case '@factory':
            this.factory(id, mod, dependencies);
            break;
        case '@singleton':
            this.singleton(id, mod, dependencies);
            break;
        case '@constructor':
            this.constructor(id, mod, dependencies);
            break;
        case '@literal':
            this.literal(id, mod);
            break;
    }
};

module.exports = Container;
<commit_msg>bugfix register parameters<commit_after>/**
 * Module dependencies.
 */
var path = require('path')
    , Factory = require('./patterns/factory')
    , Singleton = require('./patterns/singleton')
    , Constructor = require('./patterns/constructor')
    , Literal = require('./patterns/literal')
    , debug = require('debug')('electrolyte');

/**
 * `Container` constructor.
 *
 * A container contains a set of named object instances, known as components.
 * These components are automatically created when needed and injected into
 * other components that require them.
 *
 * A default `Container` singleton is exported via the module.  Applications
 * should not need to construct additional instances, and are advised against
 * doing so.
 *
 * @api public
 */
function Container() {
    this._o = {};
    this._sources = {};
    this._order = [];
    this._expose = undefined;
}

/**
 * Create a component.
 *
 * When the component being created requires other components (using `@require`
 * annotations), those components will automatically be created and injected
 * into the component.  In this way, complex graphs of objects can be
 * constructed with a single line of code, eliminating extraneous boilerplate.
 *
 * A component can be annotated as being a singletion (using `@singleton`).  If
 * so, only one instance of the named component will be created.  Subsequent
 * calls to create the component will return the singleton instance.
 *
 * Examples:
 *
 *     var foo = IoC.create('foo');
 *
 *     var boop = IoC.create('beep/boop');
 *
 * @param {String} id
 * @return {mixed}
 * @api public
 */
Container.prototype.create = function (id, parent, prefixes) {
    parent = parent || {};
    prefixes = prefixes || [];
    prefixes = prefixes.map(function (pref) {
        return pref + Container.nestedResourcesSeparator + id;
    });
    prefixes.push(id);

    for (var i in prefixes) {
        var pref = prefixes[i];
        var p = this._create(pref, parent, prefixes);
        if (p.found) return p.comp;
    }

    throw new Error("Unable to create component '" + id + "'");

}

Container.nestedResourcesSeparator = ".";

Container.prototype._create = function (id, parent, prefixes) {
    if (parent && id[0] == '.') {
        // resolve relative component ID
        // TODO: Ensure that this uses '/' as a separator on Windows
        id = path.join(path.dirname(parent.id), id);
    }

    // special modules
    switch (id) {
        case '$container':
            return this;
    }

    var comp = this._o[id];
    if (!comp) {
        // No component is registered with the given ID.  Attempt to register the
        // component by loading its corresponding module.
        this._loadModule(id);
    }

    comp = this._o[id];
    if (!comp) {
        return {
            found: false
        };
    }

    return {
        found: true,
        comp: comp.create(this, prefixes)
    };
}

Container.prototype.factory = function (id, fn, dependencies, type) {
    dependencies = dependencies || fn['@require'] || [];
    type = type || fn['@type'] || 'constructorInjection';
    this._register(new Factory(id, dependencies, fn, type));
}

Container.prototype.singleton = function (id, fn, dependencies, type) {
    dependencies = dependencies || fn['@require'] || [];
    type = type || fn['@type'] || 'constructorInjection';
    this._register(new Singleton(id, dependencies, fn, type));
}

Container.prototype.constructor = function (id, ctor, dependencies, type) {
    dependencies = dependencies || ctor['@require'] || [];
    type = type || ctor['@type'] || 'constructorInjection';
    this._register(new Constructor(id, dependencies, ctor, type));
}

Container.prototype.literal = function (id, obj, dependencies, type) {
    dependencies = dependencies || (obj && obj['@require']) || [];
    type = type || (obj && obj['@type']) || 'constructorInjection';
    this._register(new Literal(id, dependencies, obj, type));
}

Container.prototype._register = function (comp) {
    // TODO: Pass sid to constructor (??)
    this._o[comp.id] = comp;
}

Container.prototype.register = function (id, module, dependencies, mode, type) {
    if (dependencies != null && (!dependencies instanceof Object || typeof dependencies === "string")) {
        type = mode;
        mode = dependencies;
        dependencies = null;
    }

    mode = mode || this.getModuleType(module) || "@factory";

    if (mode == "@singleton") {
        return this.singleton(id, module, dependencies, type);
    } else if (mode == "@factory") {
        return this.factory(id, module, dependencies, type);
    } else if (mode == "@constructor") {
        return this.constructor(id, module, dependencies, type);
    } else if (mode == "@literal") {
        return this.literal(id, module, dependencies, type);
    } else {
        throw new Error("Unknown mode: " + mode);
    }
};

Container.prototype.getModuleType = function (module) {
    if (module["@singleton"]) {
        return "@singleton";
    } else if (module["@factory"]) {
        return "@factory";
    } else if (module["@constructor"]) {
        return "@constructor";
    } else if (module["@literal"]) {
        return "@literal";
    } else {
        return null;
    }
};

Container.prototype.loader =
    Container.prototype.use = function (prefix, fn, options) {
        if (typeof prefix == 'function') {
            fn = prefix;
            prefix = '';
        }
        if (typeof fn != 'function') {
            // Adding a loader that isn't a function is bad mojo
            throw new Error("Loader requires a function, was passed a '" + (typeof fn) + "'");

        }
        if (prefix.length && prefix[prefix.length - 1] != '/') {
            prefix += '/';
        }
        var id = this._order.length;
        this._sources[id] = {prefix: prefix, fn: fn, options: options};
        this._order.push({id: id, prefix: prefix, fn: fn});
    }

Container.prototype.expose = function (cb) {
    this._expose = cb;
}

Container.prototype._loadModule = function (id) {
    debug('autoload %s', id);
    var sources = this._order
        , source, prefix, rid, mod;
    for (var i = 0, len = sources.length; i < len; ++i) {
        source = sources[i];
        prefix = source.prefix;
        if (id.indexOf(prefix) !== 0) {
            continue;
        }
        rid = id.slice(prefix.length);
        mod = source.fn(rid);

        if (mod) {
            this._registerModule(id, mod);
            break;
        }
    }
}

Container.prototype._registerModule = function (id, mod) {
    var dependencies = mod['@require'] || []
        , pattern = '@literal';

    if (typeof mod == 'function') {
        var name = mod.name || 'anonymous';
        if (name[0] == name[0].toUpperCase()) {
            pattern = '@constructor';
        } else {
            if (mod['@singleton']) {
                pattern = '@singleton';
            } else {
                pattern = '@factory';
            }
        }

        if (mod['@literal'] === true) {
            pattern = '@literal';
        }
    }

    pattern = this.getModuleType(mod) || pattern;

    // TODO: Clean this up.  Singleton should be eliminated and handled
    //       as an option by both factory and constructor patterns.
    switch (pattern) {
        case '@factory':
            this.factory(id, mod, dependencies);
            break;
        case '@singleton':
            this.singleton(id, mod, dependencies);
            break;
        case '@constructor':
            this.constructor(id, mod, dependencies);
            break;
        case '@literal':
            this.literal(id, mod);
            break;
    }
};

module.exports = Container;
<|endoftext|>


<commit_before>/* global describe it beforeEach */

require('./helpers/before');

var request = require('supertest');
var resetHelper = require('./helpers/reset');
var storage = require('../src/storage');
var server = require('../src/server');

describe('/search', function () {
  beforeEach(resetHelper);

  beforeEach(function (done) {
    storage.indexContent('foo/aaa', { title: 'first', body: 'all aaa', keywords: '' }, done);
  });
  beforeEach(function (done) {
    storage.indexContent('foo/bbb', { title: 'second', body: 'all bbb', keywords: '' }, done);
  });
  beforeEach(function (done) {
    storage.indexContent('foo/ccc', { title: 'third', body: 'all ccc', keywords: '' }, done);
  });

  it('returns IDs of matching documents', function (done) {
    request(server.create())
      .get('/search?q=all')
      .expect(200)
      .expect({
        total: 3,
        results: [
          {
            contentID: 'foo/aaa',
            title: 'first',
            excerpt: '...all...'
          },
          {
            contentID: 'foo/bbb',
            title: 'second',
            excerpt: '...all...'
          },
          {
            contentID: 'foo/ccc',
            title: 'third',
            excerpt: '...all...'
          }
        ]
      }, done);
  });

  it('responds with a 409 if no query is provided', function (done) {
    request(server.create())
      .get('/search')
      .expect(409, done);
  });
});
<commit_msg>Pending unit test.<commit_after>/* global describe it beforeEach */

require('./helpers/before');

var request = require('supertest');
var resetHelper = require('./helpers/reset');
var storage = require('../src/storage');
var server = require('../src/server');

describe('/search', function () {
  beforeEach(resetHelper);

  beforeEach(function (done) {
    storage.indexContent('foo/aaa', { title: 'first', body: 'all aaa', keywords: '' }, done);
  });
  beforeEach(function (done) {
    storage.indexContent('foo/bbb', { title: 'second', body: 'all bbb', keywords: '' }, done);
  });
  beforeEach(function (done) {
    storage.indexContent('foo/ccc', { title: 'third', body: 'all ccc', keywords: '' }, done);
  });

  it('returns IDs of matching documents', function (done) {
    request(server.create())
      .get('/search?q=all')
      .expect(200)
      .expect({
        total: 3,
        results: [
          {
            contentID: 'foo/aaa',
            title: 'first',
            excerpt: '...all...'
          },
          {
            contentID: 'foo/bbb',
            title: 'second',
            excerpt: '...all...'
          },
          {
            contentID: 'foo/ccc',
            title: 'third',
            excerpt: '...all...'
          }
        ]
      }, done);
  });

  it('returns an empty excerpt when a match is only in the title');

  it('responds with a 409 if no query is provided', function (done) {
    request(server.create())
      .get('/search')
      .expect(409, done);
  });
});
<|endoftext|>


<commit_before>var Compiler = require('./compiler.js');

var ContractsManager = function(options) {
  this.contractFiles = options.contractFiles;
  this.contractsConfig = options.contractsConfig;
  this.contracts = {};
  this.logger = options.logger;
};

ContractsManager.prototype.init = function() {
  this.compiledContracts = this.compileContracts();
};

ContractsManager.prototype.compileContracts = function() {
  var compiler = new Compiler();
  return compiler.compile_solidity(this.contractFiles);
};

ContractsManager.prototype.build = function() {
  for(var className in this.compiledContracts) {
    var contract = this.compiledContracts[className];
    var contractConfig = this.contractsConfig.contracts[className];

    if (this.contractsConfig.gas === 'auto') {
      var maxGas = Math.max(contract.gasEstimates.creation[0], contract.gasEstimates.creation[1], 500000);
      var adjustedGas = Math.round(maxGas * 1.01);
      contract.gas = adjustedGas;
    } else {
      contract.gas = this.contractsConfig.gas;
    }
    contract.gasPrice = this.contractsConfig.gasPrice;

    if (contractConfig === undefined) {
      contract.args = [];
    } else {
      contract.args = contractConfig.args || [];
    }

    contract.className = className;
    this.contracts[className] = contract;
  }
};

// TODO: should be built contracts
ContractsManager.prototype.listContracts = function() {
  var contracts = [];
  for(var className in this.compiledContracts) {
    var contract = this.compiledContracts[className];
    contracts.push(contract);
  }
  return contracts;
};

ContractsManager.prototype.contractsState = function() {
  var data = [];

  for(var className in this.contracts) {
    var contract = this.contracts[className];

    data.push([
      className.green,
      (contract.deployedAddress || '...'.green),
      ((contract.deployedAddress !== undefined) ? "\t\tDeployed".green : "\t\tPending".magenta)
    ]);
  }

  return data;
};

module.exports = ContractsManager;

<commit_msg>make address green in dashboard<commit_after>var Compiler = require('./compiler.js');

var ContractsManager = function(options) {
  this.contractFiles = options.contractFiles;
  this.contractsConfig = options.contractsConfig;
  this.contracts = {};
  this.logger = options.logger;
};

ContractsManager.prototype.init = function() {
  this.compiledContracts = this.compileContracts();
};

ContractsManager.prototype.compileContracts = function() {
  var compiler = new Compiler();
  return compiler.compile_solidity(this.contractFiles);
};

ContractsManager.prototype.build = function() {
  for(var className in this.compiledContracts) {
    var contract = this.compiledContracts[className];
    var contractConfig = this.contractsConfig.contracts[className];

    if (this.contractsConfig.gas === 'auto') {
      var maxGas = Math.max(contract.gasEstimates.creation[0], contract.gasEstimates.creation[1], 500000);
      var adjustedGas = Math.round(maxGas * 1.01);
      contract.gas = adjustedGas;
    } else {
      contract.gas = this.contractsConfig.gas;
    }
    contract.gasPrice = this.contractsConfig.gasPrice;

    if (contractConfig === undefined) {
      contract.args = [];
    } else {
      contract.args = contractConfig.args || [];
    }

    contract.className = className;
    this.contracts[className] = contract;
  }
};

// TODO: should be built contracts
ContractsManager.prototype.listContracts = function() {
  var contracts = [];
  for(var className in this.compiledContracts) {
    var contract = this.compiledContracts[className];
    contracts.push(contract);
  }
  return contracts;
};

ContractsManager.prototype.contractsState = function() {
  var data = [];

  for(var className in this.contracts) {
    var contract = this.contracts[className];

    data.push([
      className.green,
      (contract.deployedAddress || '...').green,
      ((contract.deployedAddress !== undefined) ? "\t\tDeployed".green : "\t\tPending".magenta)
    ]);
  }

  return data;
};

module.exports = ContractsManager;

<|endoftext|>


<commit_before>import chai from 'chai';

import server from '../lib/server';

const expect = chai.expect;

describe('POST :: /', () => {
  describe('action :: new', () => {
    it('should return a creation phrase for successfully creating a Emojinary', (done) => {
      server.inject({
        method: 'POST',
        url: '/',
        payload: {
          token: 'test',
          team_id: 'T001',
          team_domain: 'test',
          channel_id: 'C2147483705',
          channel_name: 'test',
          user_id: 'U2147483697',
          user_name: 'kurt',
          command: '/emojinary',
          text: ''
        }
      }, (res) => {
        expect(res.result).to.equal('Emojinary set! :smile:');
        done();
      });
    });
  });
});
<commit_msg>fixed test issue<commit_after>import chai from 'chai';

import server from '../lib/server';

const expect = chai.expect;

describe('POST :: /', () => {
  describe('action :: new', () => {
    it('should return a creation phrase for successfully creating a Emojinary', (done) => {
      server.inject({
        method: 'POST',
        url: '/',
        payload: {
          token: 'test',
          team_id: 'T001',
          team_domain: 'test',
          channel_id: 'C2147483705',
          channel_name: 'test',
          user_id: 'U2147483697',
          user_name: 'kurt',
          command: '/emojinary',
          text: 'new emojinary=[:smile: :camera:] hint=[smile for the camera!] answer=[selfie]'
        }
      }, (res) => {
        expect(res.result).to.equal('Emojinary set! :smile:');
        done();
      });
    });
  });
});
<|endoftext|>


<commit_before>var expect = require('expect.js');
var io = require('../');

describe('socket', function(){
  this.timeout(70000);

  it('should have an accessible socket id equal to the engine.io socket id', function(done) {
    var socket = io({ forceNew: true });
    socket.on('connect', function(){
      expect(socket.id).to.be.ok();
      expect(socket.id).to.eql(socket.io.engine.id);
      socket.disconnect();
      done();
    });
  });

  it('clears socket.id upon disconnection', function(done){
    var socket = io({ forceNew: true });
    socket.on('connect', function(){
      socket.on('disconnect', function(){
        expect(socket.id).to.not.be.ok();
        done();
      });

      socket.disconnect();
    });
  });

  it('doesn\'t fire a connect_error if we force disconnect in opening state', function(done){
    var socket = io({ forceNew: true, timeout: 100 });
    socket.disconnect();
    socket.on('connect_error', function(){
      throw new Error('Unexpected');
    });
    setTimeout(function(){
      done();
    }, 300);
  });

  it('should ping and pong with latency', function(done){
    var socket = io({ forceNew: true });
    socket.on('connect', function(){
      var pinged;
      socket.once('ping', function(){
        pinged = true;
      });
      socket.once('pong', function(ms){
        expect(pinged).to.be(true);
        expect(ms).to.be.a('number');
        expect(ms).to.be.greaterThan(0);
        socket.disconnect();
        done();
      });
    });
  });

  it('should change socket.id upon reconnection', function(done){
    var socket = io({ forceNew: true });
    socket.on('connect', function(){
      var id = socket.id;

      socket.on('reconnect_attempt', function(){
        expect(socket.id).to.not.be.ok();
      });

      socket.on('reconnect', function() {
        expect(socket.id).to.not.eql(id);
        socket.disconnect();
        done();
      });

      socket.io.engine.close();
    });
  });

  it('should enable compression by default', function(done){
    var socket = io({ forceNew: true });
    socket.on('connect', function(){
      socket.io.engine.once('packetCreate', function(packet){
        expect(packet.options.compress).to.be(true);
        socket.disconnect();
        done();
      });
      socket.emit('hi');
    });
  });

  it('should disable compression', function(done){
    var socket = io({ forceNew: true });
    socket.on('connect', function(){
      socket.io.engine.once('packetCreate', function(packet){
        expect(packet.options.compress).to.be(false);
        socket.disconnect();
        done();
      });
      socket.compress(false).emit('hi');
    });
  });

  it.only('should store query string as a property', function(done){
    var socket = io('/abc', {query: {a:'b'}}); //passes in as a query obj
    var socket2 = io('/abcd?b=c&d=e'); //passes in as a query string
    console.log(socket);
    expect(socket.query).to.be('a=b');
    expect(socket2.query).to.be('b=c&d=e');
    socket.disconnect();
    socket2.disconnect();
    done();
  });
});
<commit_msg>update tests<commit_after>var expect = require('expect.js');
var io = require('../');

describe('socket', function(){
  this.timeout(70000);

  it('should have an accessible socket id equal to the engine.io socket id', function(done) {
    var socket = io({ forceNew: true });
    socket.on('connect', function(){
      expect(socket.id).to.be.ok();
      expect(socket.id).to.eql(socket.io.engine.id);
      socket.disconnect();
      done();
    });
  });

  it('clears socket.id upon disconnection', function(done){
    var socket = io({ forceNew: true });
    socket.on('connect', function(){
      socket.on('disconnect', function(){
        expect(socket.id).to.not.be.ok();
        done();
      });

      socket.disconnect();
    });
  });

  it('doesn\'t fire a connect_error if we force disconnect in opening state', function(done){
    var socket = io({ forceNew: true, timeout: 100 });
    socket.disconnect();
    socket.on('connect_error', function(){
      throw new Error('Unexpected');
    });
    setTimeout(function(){
      done();
    }, 300);
  });

  it('should ping and pong with latency', function(done){
    var socket = io({ forceNew: true });
    socket.on('connect', function(){
      var pinged;
      socket.once('ping', function(){
        pinged = true;
      });
      socket.once('pong', function(ms){
        expect(pinged).to.be(true);
        expect(ms).to.be.a('number');
        expect(ms).to.be.greaterThan(0);
        socket.disconnect();
        done();
      });
    });
  });

  it('should change socket.id upon reconnection', function(done){
    var socket = io({ forceNew: true });
    socket.on('connect', function(){
      var id = socket.id;

      socket.on('reconnect_attempt', function(){
        expect(socket.id).to.not.be.ok();
      });

      socket.on('reconnect', function() {
        expect(socket.id).to.not.eql(id);
        socket.disconnect();
        done();
      });

      socket.io.engine.close();
    });
  });

  it('should enable compression by default', function(done){
    var socket = io({ forceNew: true });
    socket.on('connect', function(){
      socket.io.engine.once('packetCreate', function(packet){
        expect(packet.options.compress).to.be(true);
        socket.disconnect();
        done();
      });
      socket.emit('hi');
    });
  });

  it('should disable compression', function(done){
    var socket = io({ forceNew: true });
    socket.on('connect', function(){
      socket.io.engine.once('packetCreate', function(packet){
        expect(packet.options.compress).to.be(false);
        socket.disconnect();
        done();
      });
      socket.compress(false).emit('hi');
    });
  });

  it('should store query string as a property', function(done){
    var socket = io('/abc', {query: {a:'b'}}); //passes in as a query obj
    var socket2 = io('/abcd?b=c&d=e'); //passes in as a query string
    console.log(socket);
    expect(socket.query).to.be('a=b');
    expect(socket2.query).to.be('b=c&d=e');
    socket.disconnect();
    socket2.disconnect();
    done();
  });
});
<|endoftext|>


<commit_before>/*
Copyright (c) 2014, Groupon, Inc.
All rights reserved.

Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions
are met:

Redistributions of source code must retain the above copyright notice,
this list of conditions and the following disclaimer.

Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.

Neither the name of GROUPON nor the names of its contributors may be
used to endorse or promote products derived from this software without
specific prior written permission.

THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A
PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED
TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/

// Generated by CoffeeScript 2.0.0-beta8
void function () {
  var CS, CSON, csr, find, isLiteral, LiteralTypes, nodeTransforms, nodeTypeString, parse, stringify, syntaxErrorMessage, transformKey, transformNode;
  csr = require('coffee-script-redux');
  CS = csr.Nodes;
  find = function (arr, testFn) {
    var element;
    for (var i$ = 0, length$ = arr.length; i$ < length$; ++i$) {
      element = arr[i$];
      if (testFn(element))
        return element;
    }
    return null;
  };
  nodeTypeString = function (csNode) {
    return csNode.toBasicObject().type;
  };
  syntaxErrorMessage = function (csNode, msg) {
    return 'Syntax error on line ' + csNode.line + ', column ' + csNode.column + ': ' + msg;
  };
  nodeTransforms = [
    [
      CS.Program,
      function (node) {
        var body;
        body = node.body;
        if (!body || !body.statements || body.statements.length !== 1)
          throw new SyntaxError(syntaxErrorMessage(node, 'One top level value expected'));
        return transformNode(body.statements[0]);
      }
    ],
    [
      CS.ObjectInitialiser,
      function (node) {
        return node.members.reduce(function (outObject, param$) {
          var cache$, expression, key, keyName, value;
          {
            cache$ = param$;
            key = cache$.key;
            expression = cache$.expression;
          }
          keyName = transformKey(key);
          value = transformNode(expression);
          outObject[keyName] = value;
          return outObject;
        }, {});
      }
    ],
    [
      CS.Null,
      function () {
        return null;
      }
    ],
    [
      CS.ArrayInitialiser,
      function (node) {
        return node.members.map(transformNode);
      }
    ],
    [
      CS.UnaryNegateOp,
      function (node) {
        return -transformNode(node.expression);
      }
    ],
    [
      CS.MultiplyOp,
      function (node) {
        return transformNode(node.left) * transformNode(node.right);
      }
    ],
    [
      CS.PlusOp,
      function (node) {
        return transformNode(node.left) + transformNode(node.right);
      }
    ],
    [
      CS.DivideOp,
      function (node) {
        return transformNode(node.left) / transformNode(node.right);
      }
    ],
    [
      CS.SubtractOp,
      function (node) {
        return transformNode(node.left) - transformNode(node.right);
      }
    ],
    [
      CS.RemOp,
      function (node) {
        return transformNode(node.left) % transformNode(node.right);
      }
    ],
    [
      CS.BitAndOp,
      function (node) {
        return transformNode(node.left) & transformNode(node.right);
      }
    ],
    [
      CS.BitOrOp,
      function (node) {
        return transformNode(node.left) | transformNode(node.right);
      }
    ],
    [
      CS.BitXorOp,
      function (node) {
        return transformNode(node.left) ^ transformNode(node.right);
      }
    ],
    [
      CS.BitNotOp,
      function (node) {
        return ~transformNode(node.expression);
      }
    ],
    [
      CS.LeftShiftOp,
      function (node) {
        return transformNode(node.left) << transformNode(node.right);
      }
    ],
    [
      CS.SignedRightShiftOp,
      function (node) {
        return transformNode(node.left) >> transformNode(node.right);
      }
    ],
    [
      CS.UnsignedRightShiftOp,
      function (node) {
        return transformNode(node.left) >>> transformNode(node.right);
      }
    ]
  ];
  LiteralTypes = [
    CS.Bool,
    CS.Float,
    CS.Int,
    CS.String
  ];
  LiteralTypes.forEach(function (LiteralType) {
    return nodeTransforms.unshift([
      LiteralType,
      function (param$) {
        var data;
        data = param$.data;
        return data;
      }
    ]);
  });
  isLiteral = function (csNode) {
    return LiteralTypes.some(function (LiteralType) {
      return csNode instanceof LiteralType;
    });
  };
  transformKey = function (csNode) {
    if (!(csNode instanceof CS.Identifier || isLiteral(csNode)))
      throw new SyntaxError(syntaxErrorMessage(csNode, '' + nodeTypeString(csNode) + ' used as key'));
    return csNode.data;
  };
  transformNode = function (csNode) {
    var transform;
    transform = find(nodeTransforms, function (param$) {
      var NodeType;
      NodeType = param$[0];
      return csNode instanceof NodeType;
    });
    if (!transform)
      throw new SyntaxError(syntaxErrorMessage(csNode, 'Unexpected ' + nodeTypeString(csNode)));
    return transform[1](csNode);
  };
  stringify = function (obj, visitor, indent) {
    return JSON.stringify(obj, visitor, indent);
  };
  parse = function (source, reviver) {
    var coffeeAst;
    if (reviver)
      throw new Error('The reviver parameter is not implemented yet');
    coffeeAst = csr.parse(source.toString(), {
      bare: true,
      raw: true
    });
    return transformNode(coffeeAst);
  };
  module.exports = CSON = {
    stringify: stringify,
    parse: parse
  };
}.call(this);
<commit_msg>Rebuild source code, fixes outdated js file<commit_after>/*
Copyright (c) 2014, Groupon, Inc.
All rights reserved.

Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions
are met:

Redistributions of source code must retain the above copyright notice,
this list of conditions and the following disclaimer.

Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.

Neither the name of GROUPON nor the names of its contributors may be
used to endorse or promote products derived from this software without
specific prior written permission.

THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A
PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED
TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/

// Generated by CoffeeScript 2.0.0-beta8
void function () {
  var CS, CSON, csr, find, isLiteral, LiteralTypes, nodeTransforms, nodeTypeString, parse, stringify, syntaxErrorMessage, transformKey, transformNode;
  csr = require('coffee-script-redux');
  CS = csr.Nodes;
  find = function (arr, testFn) {
    var element;
    for (var i$ = 0, length$ = arr.length; i$ < length$; ++i$) {
      element = arr[i$];
      if (testFn(element))
        return element;
    }
    return null;
  };
  nodeTypeString = function (csNode) {
    return csNode.toBasicObject().type;
  };
  syntaxErrorMessage = function (csNode, msg) {
    return 'Syntax error on line ' + csNode.line + ', column ' + csNode.column + ': ' + msg;
  };
  nodeTransforms = [
    [
      CS.Program,
      function (node) {
        var body;
        body = node.body;
        if (!body || !body.statements || body.statements.length !== 1)
          throw new SyntaxError(syntaxErrorMessage(node, 'One top level value expected'));
        return transformNode(body.statements[0]);
      }
    ],
    [
      CS.ObjectInitialiser,
      function (node) {
        return node.members.reduce(function (outObject, param$) {
          var cache$, expression, key, keyName, value;
          {
            cache$ = param$;
            key = cache$.key;
            expression = cache$.expression;
          }
          keyName = transformKey(key);
          value = transformNode(expression);
          outObject[keyName] = value;
          return outObject;
        }, {});
      }
    ],
    [
      CS.ArrayInitialiser,
      function (node) {
        return node.members.map(transformNode);
      }
    ],
    [
      CS.Null,
      function () {
        return null;
      }
    ],
    [
      CS.UnaryNegateOp,
      function (node) {
        return -transformNode(node.expression);
      }
    ],
    [
      CS.MultiplyOp,
      function (node) {
        return transformNode(node.left) * transformNode(node.right);
      }
    ],
    [
      CS.PlusOp,
      function (node) {
        return transformNode(node.left) + transformNode(node.right);
      }
    ],
    [
      CS.DivideOp,
      function (node) {
        return transformNode(node.left) / transformNode(node.right);
      }
    ],
    [
      CS.SubtractOp,
      function (node) {
        return transformNode(node.left) - transformNode(node.right);
      }
    ],
    [
      CS.RemOp,
      function (node) {
        return transformNode(node.left) % transformNode(node.right);
      }
    ],
    [
      CS.BitAndOp,
      function (node) {
        return transformNode(node.left) & transformNode(node.right);
      }
    ],
    [
      CS.BitOrOp,
      function (node) {
        return transformNode(node.left) | transformNode(node.right);
      }
    ],
    [
      CS.BitXorOp,
      function (node) {
        return transformNode(node.left) ^ transformNode(node.right);
      }
    ],
    [
      CS.BitNotOp,
      function (node) {
        return ~transformNode(node.expression);
      }
    ],
    [
      CS.LeftShiftOp,
      function (node) {
        return transformNode(node.left) << transformNode(node.right);
      }
    ],
    [
      CS.SignedRightShiftOp,
      function (node) {
        return transformNode(node.left) >> transformNode(node.right);
      }
    ],
    [
      CS.UnsignedRightShiftOp,
      function (node) {
        return transformNode(node.left) >>> transformNode(node.right);
      }
    ]
  ];
  LiteralTypes = [
    CS.Bool,
    CS.Float,
    CS.Int,
    CS.String
  ];
  LiteralTypes.forEach(function (LiteralType) {
    return nodeTransforms.unshift([
      LiteralType,
      function (param$) {
        var data;
        data = param$.data;
        return data;
      }
    ]);
  });
  isLiteral = function (csNode) {
    return LiteralTypes.some(function (LiteralType) {
      return csNode instanceof LiteralType;
    });
  };
  transformKey = function (csNode) {
    if (!(csNode instanceof CS.Identifier || isLiteral(csNode)))
      throw new SyntaxError(syntaxErrorMessage(csNode, '' + nodeTypeString(csNode) + ' used as key'));
    return csNode.data;
  };
  transformNode = function (csNode) {
    var transform;
    transform = find(nodeTransforms, function (param$) {
      var NodeType;
      NodeType = param$[0];
      return csNode instanceof NodeType;
    });
    if (!transform)
      throw new SyntaxError(syntaxErrorMessage(csNode, 'Unexpected ' + nodeTypeString(csNode)));
    return transform[1](csNode);
  };
  stringify = function (obj, visitor, indent) {
    return JSON.stringify(obj, visitor, indent);
  };
  parse = function (source, reviver) {
    var coffeeAst;
    if (reviver)
      throw new Error('The reviver parameter is not implemented yet');
    coffeeAst = csr.parse(source.toString(), {
      bare: true,
      raw: true
    });
    return transformNode(coffeeAst);
  };
  module.exports = CSON = {
    stringify: stringify,
    parse: parse
  };
}.call(this);
<|endoftext|>


<commit_before>const tap = require('tap');
const fastly = require('../lib/fastly.js');

const fastly_api_key =  process.env.FASTLY_API_KEY || '';
const content_url =  process.env.CONTENT_URL || '';

var flib = new fastly(fastly_api_key);

tap.test('fastly constructor', function(t){
	t.type(flib.request, 'object', 'request => object');
	t.type(flib.request.options, 'object', '.options => object');
	t.match(flib.request.options, {
		method: 'GET',
		hostname: 'api.fastly.com',
		path: '/',
		headers: {
			'Fastly-Key': fastly_api_key,
			'Accept': 'application/json'
		}
	}, 'options => match the initial pattern');
	t.type(flib.request.send, 'function', '..send => is function');
	t.type(flib.request.get, 'function', '..get => is function');
	t.type(flib.request.post, 'function', '..post => is function');
	t.type(flib.request.purge, 'function', '..purge => is function');
	t.end();
})

tap.test('fastly.content', function(t) {
	var flib = new fastly(fastly_api_key);
	t.type(flib.content, 'function', '.content() => is function')
	//
	flib.content(content_url)
		.then((res)=>{
			t.comment(res)
			t.type(res, 'function', '.content().then => return function done.');
			t.end();
		})
		.catch((err)=>{
			t.comment(err);
			t.end();
		})

});

tap.test('purge', function(t) {

	var flib = new fastly(fastly_api_key);

	t.type(flib, 'object', 'constructor');
	t.type(flib.purge, 'function', 'purge method');
	t.type(flib.purge_all, 'function', 'purge all method');
	t.type(flib.purge_by_key, 'function', 'purge by key method');
	t.type(flib.purge_multiple, 'function', 'purge multiple method');
	t.end();
});
<commit_msg>more tests<commit_after>const tap = require('tap');
const fastly = require('../lib/fastly.js');

const fastly_api_key =  process.env.FASTLY_API_KEY || '';
const content_url =  process.env.CONTENT_URL || '';

var flib = new fastly(fastly_api_key);

tap.test('fastly constructor', function(t){
	t.type(flib.request, 'object', 'request => object');
	t.type(flib.request.options, 'object', '.options => object');
	t.match(flib.request.options, {
		method: 'GET',
		hostname: 'api.fastly.com',
		path: '/',
		headers: {
			'Fastly-Key': fastly_api_key,
			'Accept': 'application/json'
		}
	}, 'options => match the initial pattern');
	t.type(flib.request.send, 'function', '..send => is function');
	t.type(flib.request.get, 'function', '..get => is function');
	t.type(flib.request.post, 'function', '..post => is function');
	t.type(flib.request.purge, 'function', '..purge => is function');
	t.end();
})

tap.test('function content', function(t) {
	var flib = new fastly(fastly_api_key);
	t.type(flib.content, 'function', '.content() => is function')
	t.end();
});

tap.test('...content.then()', function(t) {
	var flib = new fastly(fastly_api_key);
	//
	t.comment('Executing function: content')
	t.comment('Waiting a response through .then()...')
	flib.content(content_url)
		.then((res)=>{
			t.type(res, 'object', '..then() => is object');
			t.end();
		}).
		.catch((err)=>{
			t.fail(err);
			t.end();
		})
});

tap.test('...content.catch()', function(t) {
	var flib = new fastly(fastly_api_key);
	//
	t.comment('Executing function: content')
	t.comment('Waiting an error through .catch()')
	flib.content('sorry for the inconveniences, im testing a new library :(')
		.then((res)=> {
			t.fail(res);
			t.end();
		})
		.catch((err)=> {
			t.type(res, 'object', '..catch() => is object');
			t.end();
		})
});

tap.test('purge', function(t) {

	var flib = new fastly(fastly_api_key);

	t.type(flib, 'object', 'constructor');
	t.type(flib.purge, 'function', 'purge method');
	t.type(flib.purge_all, 'function', 'purge all method');
	t.type(flib.purge_by_key, 'function', 'purge by key method');
	t.type(flib.purge_multiple, 'function', 'purge multiple method');
	t.end();
});
<|endoftext|>


<commit_before>
QUnit.test("Check environmental variables", function(assert) {

  // Given
  var itb = imageTagBuilder({});

  // Then
  assert.equal(itb.innerWidth, window.innerWidth, "Load innerWidth");
  assert.equal(itb.innerHeight, window.innerHeight, "Load innerHeight");
  assert.equal(itb.dpr, window.devicePixelRatio, "Load innerHeight");

});

QUnit.test("Verify variable override", function(assert) {

  // Given
  var itb = imageTagBuilder({});
  itb.innerWidth = 4000;
  itb.innerHeight = 5000;
  itb.dpr = 9;

  // Then
  assert.equal(itb.innerWidth, 4000, "Override innerWidth");
  assert.equal(itb.innerHeight, 5000, "Override innerHeight");
  assert.equal(itb.dpr, 9, "Override device pixel ratio");

});

QUnit.test("Target test", function(assert) {

  // Given
  var itb = imageTagBuilder({});

  // When
  itb.prep({ image: "horses.jpg", style: "basic", alt: "some horses", maxSize: "1600x1000"});

  // Then
  assert.equal(itb.imageTag(),'', "Target `img` tag.");

});

QUnit.test("Set attribute width via `requestWidth`", function(assert) {

  // Given
  var itb = imageTagBuilder({});

  // When
  itb.requestWidth(800);

  // Then
  assert.equal(itb.attributeWidth(), 800);

});

QUnit.test("Set source dimensions", function(assert) {

  // Given
  var itb = imageTagBuilder({});

  // When
  itb.setSourceWidth(1600);
  itb.setSourceHeight(1000);

  // Then
  assert.equal(itb.sourceWidth(), 1600, "Source width");
  assert.equal(itb.sourceHeight(), 1000, "Source height");

});

QUnit.test("Verify attribute height", function(assert) {

  // Given
  var itb = imageTagBuilder({});

  // When
  itb.setSourceWidth(1600);
  itb.setSourceHeight(1000);
  itb.requestWidth(800);

  // Then
  assert.equal(itb.attributeHeight(), 500, "attributeHeight()");

});
<commit_msg>Cleaned up white space.<commit_after>
QUnit.test("Check environmental variables", function(assert) {

  // Given
  var itb = imageTagBuilder({});

  // Then
  assert.equal(itb.innerWidth, window.innerWidth, "Load innerWidth");
  assert.equal(itb.innerHeight, window.innerHeight, "Load innerHeight");
  assert.equal(itb.dpr, window.devicePixelRatio, "Load innerHeight");

});

QUnit.test("Verify variable override", function(assert) {

  // Given
  var itb = imageTagBuilder({});
  itb.innerWidth = 4000;
  itb.innerHeight = 5000;
  itb.dpr = 9;

  // Then
  assert.equal(itb.innerWidth, 4000, "Override innerWidth");
  assert.equal(itb.innerHeight, 5000, "Override innerHeight");
  assert.equal(itb.dpr, 9, "Override device pixel ratio");

});

QUnit.test("Target test", function(assert) {

  // Given
  var itb = imageTagBuilder({});

  // When
  itb.prep({ image: "horses.jpg", style: "basic", alt: "some horses", maxSize: "1600x1000"});

  // Then
  assert.equal(itb.imageTag(),'', "Target `img` tag.");

});

QUnit.test("Set attribute width via `requestWidth`", function(assert) {

  // Given
  var itb = imageTagBuilder({});

  // When
  itb.requestWidth(800);

  // Then
  assert.equal(itb.attributeWidth(), 800);

});

QUnit.test("Set source dimensions", function(assert) {

  // Given
  var itb = imageTagBuilder({});

  // When
  itb.setSourceWidth(1600);
  itb.setSourceHeight(1000);

  // Then
  assert.equal(itb.sourceWidth(), 1600, "Source width");
  assert.equal(itb.sourceHeight(), 1000, "Source height");

});

QUnit.test("Verify attribute height", function(assert) {

  // Given
  var itb = imageTagBuilder({});

  // When
  itb.setSourceWidth(1600);
  itb.setSourceHeight(1000);
  itb.requestWidth(800);

  // Then
  assert.equal(itb.attributeHeight(), 500, "attributeHeight()");

});
<|endoftext|>


<commit_before>/*!
 * qwebs
 * Copyright(c) 2015 Benoît Claveau <benoit.claveau@gmail.com>
 * MIT Licensed
 */
 "use strict";
var http = require("http");

class DataError extends Error {
    constructor(options) {
        super(options.message || "Qwebs error");
        if (Error.captureStackTrace) Error.captureStackTrace(this, this.constructor);
        if (this.message[this.message.length - 1] !== ".") this.message += ".";

        this.name = this.constructor.name;

        if (options.stack) this.stack = options.stack;
        if (options.fileName) this.fileName = options.fileName;
        if (options.lineNumber) this.lineNumber = options.lineNumber;
        if (options.columnNumber) this.columnNumber = options.columnNumber;
        if (options.request) this.request = options.request;

        if (!options.data) this.data = {};
        else if (options.data instanceof Array) this.data = { array: options.data };
        else this.data = options.data;

        this.headers = options.headers || {};
        this.headers["Content-Type"] = this.headers["Content-Type"] || "application/json";

        this.statusCode = options.statusCode || 500;
    };

    //use by request.send
    get content() {
        if (this.request.headers.accept.match(/application\/json/)) return { statusCode: this.statusCode, message: this.message };
        if (this.request.headers.accept.match(/text\/html/)) return `${this.message}
${JSON.stringify(this.data)}
${this.stack}
`;
        return this.message;
    }

    toString() {
        let data = [];
        data.push({key: "statusCode", value: this.statusCode });
        data.push({key: "data", value: JSON.stringify(this.data) });
        data.push({key: "headers", value: JSON.stringify(this.headers) });
        if (this.fileName) data.push({key: "fileName", value: this.fileName });
        if (this.lineNumber) data.push({key: "lineNumber", value: this.lineNumber });
        if (this.columnNumber) data.push({key: "columnNumber", value: this.columnNumber });
        data.push({key: "stack", value: this.stack });

        return `${this.name}: ${this.message} ${data.map(e => `
    - ${e.key}: ${e.value}`)}`
        };
}

exports = module.exports = DataError;<commit_msg>Remove content property<commit_after>/*!
 * qwebs
 * Copyright(c) 2015 Benoît Claveau <benoit.claveau@gmail.com>
 * MIT Licensed
 */
 "use strict";
var http = require("http");

class DataError extends Error {
    constructor(options) {
        super(options.message || "Qwebs error");
        if (Error.captureStackTrace) Error.captureStackTrace(this, this.constructor);
        if (this.message[this.message.length - 1] !== ".") this.message += ".";

        this.name = this.constructor.name;

        if (options.stack) this.stack = options.stack;
        if (options.fileName) this.fileName = options.fileName;
        if (options.lineNumber) this.lineNumber = options.lineNumber;
        if (options.columnNumber) this.columnNumber = options.columnNumber;
        if (options.request) this.request = options.request;

        if (!options.data) this.data = {};
        else if (options.data instanceof Array) this.data = { array: options.data };
        else this.data = options.data;

        this.headers = options.headers || {};
        this.headers["Content-Type"] = this.headers["Content-Type"] || "application/json";

        this.statusCode = options.statusCode || 500;

        //use by request.send
        this.content = this.makeContent();
    };

    makeContent() {
        if (this.request.headers.accept.match(/application\/json/)) return { statusCode: this.statusCode, message: this.message };
        if (this.request.headers.accept.match(/text\/html/)) return `${this.message}
${JSON.stringify(this.data)}
${this.stack}
`;
        return this.message;
    }

    toString() {
        let data = [];
        data.push({key: "statusCode", value: this.statusCode });
        data.push({key: "data", value: JSON.stringify(this.data) });
        data.push({key: "headers", value: JSON.stringify(this.headers) });
        if (this.fileName) data.push({key: "fileName", value: this.fileName });
        if (this.lineNumber) data.push({key: "lineNumber", value: this.lineNumber });
        if (this.columnNumber) data.push({key: "columnNumber", value: this.columnNumber });
        data.push({key: "stack", value: this.stack });

        return `${this.name}: ${this.message} ${data.map(e => `
    - ${e.key}: ${e.value}`)}`
        };
}

exports = module.exports = DataError;<|endoftext|>


<commit_before>
var should = require('should');
var Slices = require('../lib/index');
var utils = require('../lib/utils');

var width = 500;
var height = 500;
var lineXArray = [100, 300];
var lineYArray = [100, 300];

describe('entrance method Slices()', function() {
  it('Slices(width, height, lineXArray, lineYArray) works', function() {
    var blocks = Slices(width, height, lineXArray, lineYArray);
    var result = [{ width: 100, height: 100, x: 0, y: 0 },
      { width: 200, height: 100, x: 100, y: 0 },
      { width: 200, height: 100, x: 300, y: 0 },
      { width: 100, height: 200, x: 0, y: 100 },
      { width: 200, height: 200, x: 100, y: 100 },
      { width: 200, height: 200, x: 300, y: 100 },
      { width: 100, height: 200, x: 0, y: 300 },
      { width: 200, height: 200, x: 100, y: 300 },
      { width: 200, height: 200, x: 300, y: 300 }];
    should(blocks).eql(result);
    //console.log(Slices(width, height, lineXArray, lineYArray, {middleBoundaryMode: true}));

    var blocks2 = Slices(width, height, [100], [100]);
    var result2 = [{ width: 100, height: 100, x: 0, y: 0 },
      { width: 400, height: 100, x: 100, y: 0 },
      { width: 100, height: 400, x: 0, y: 100 },
      { width: 400, height: 400, x: 100, y: 100 }];
    should(blocks2).eql(result2);
  });
});
<commit_msg>add test case<commit_after>
var should = require('should');
var Slices = require('../lib/index');
var utils = require('../lib/utils');

var width = 500;
var height = 500;
var lineXArray = [100, 300];
var lineYArray = [100, 300];

describe('entrance method Slices()', function() {
  it('Slices(width, height, lineXArray, lineYArray) works', function() {
    var blocks = Slices(width, height, lineXArray, lineYArray);
    var result = [{ width: 100, height: 100, x: 0, y: 0 },
      { width: 200, height: 100, x: 100, y: 0 },
      { width: 200, height: 100, x: 300, y: 0 },
      { width: 100, height: 200, x: 0, y: 100 },
      { width: 200, height: 200, x: 100, y: 100 },
      { width: 200, height: 200, x: 300, y: 100 },
      { width: 100, height: 200, x: 0, y: 300 },
      { width: 200, height: 200, x: 100, y: 300 },
      { width: 200, height: 200, x: 300, y: 300 }];
    should(blocks).eql(result);
    //console.log(Slices(width, height, lineXArray, lineYArray, {middleBoundaryMode: true}));

    var blocks2 = Slices(width, height, [100], [100]);
    var result2 = [{ width: 100, height: 100, x: 0, y: 0 },
      { width: 400, height: 100, x: 100, y: 0 },
      { width: 100, height: 400, x: 0, y: 100 },
      { width: 400, height: 400, x: 100, y: 100 }];
    should(blocks2).eql(result2);

    var result3 = Slices(width, height, [100, 300], [100, 200, 300], {middleBoundaryMode: true});
    console.log(JSON.stringify(result3));
  });
});
<|endoftext|>


<commit_before>// documentation on writing tests here: http://docs.jquery.com/QUnit
// example tests: https://github.com/jquery/qunit/blob/master/test/same.js

// below are some general tests but feel free to delete them.

module("example tests");
test('HTML5 Boilerplate is sweet',function(){
  expect(1);
  equal('boilerplate'.replace('boilerplate','sweet'),'sweet','Yes. HTML5 Boilerplate is, in fact, sweet');

})

// these test things from plugins.js
test('Environment is good',function(){
  expect(2);
  ok( !!window.console.log, 'log function present');

  // var history = log.history && log.history.length || 0;
  // log('logging from the test suite.')
  // equals( log.history.length - history, 1, 'log history keeps track' )

  ok( !!window.Modernizr, 'Modernizr global is present')
})

<commit_msg>tests without console.log<commit_after>// documentation on writing tests here: http://docs.jquery.com/QUnit
// example tests: https://github.com/jquery/qunit/blob/master/test/same.js

// below are some general tests but feel free to delete them.

module("example tests");
test('HTML5 Boilerplate is sweet',function(){
  expect(1);
  equal('boilerplate'.replace('boilerplate','sweet'),'sweet','Yes. HTML5 Boilerplate is, in fact, sweet');

})

// these test things from plugins.js
test('Environment is good',function(){
  expect(1);
  // ok( !!window.console && !!window.console.log, 'log function present');

  // var history = log.history && log.history.length || 0;
  // log('logging from the test suite.')
  // equals( log.history.length - history, 1, 'log history keeps track' )

  ok( !!window.Modernizr, 'Modernizr global is present')
})

<|endoftext|>


<commit_before>process.env.NODE_ENV = 'test';

require('source-map-support').install();
require('../packages/graphql-server-core/dist/runQuery.test.js');
require('../packages/graphql-server-module-operation-store/dist/operationStore.test');
require('../packages/graphql-server-express/dist/expressApollo.test');
require('../packages/graphql-server-express/dist/connectApollo.test');
require('../packages/graphql-server-hapi/dist/hapiApollo.test');
require('../packages/graphql-server-koa/dist/koaApollo.test');
require('../packages/graphql-server-restify/dist/restifyApollo.test');
require('../packages/graphql-server-express/dist/apolloServerHttp.test');
<commit_msg>test(pacakge): remove source-map-support require which looks redundant<commit_after>process.env.NODE_ENV = 'test';

require('../packages/graphql-server-core/dist/runQuery.test.js');
require('../packages/graphql-server-module-operation-store/dist/operationStore.test');
require('../packages/graphql-server-express/dist/expressApollo.test');
require('../packages/graphql-server-express/dist/connectApollo.test');
require('../packages/graphql-server-hapi/dist/hapiApollo.test');
require('../packages/graphql-server-koa/dist/koaApollo.test');
require('../packages/graphql-server-restify/dist/restifyApollo.test');
require('../packages/graphql-server-express/dist/apolloServerHttp.test');
<|endoftext|>


<commit_before>var assert = require("assert");

var Overlay = require("../src/Overlay/");
var LoadingBar = require("../src/Overlay/LoadingBar.js");
var Percentage = require("../src/Overlay/Percentage.js");
var Image = require("../src/ImagePreloader/Image.js");
var ImagePreloader = require("../src/ImagePreloader/");
var QueryLoader = require("../src/QueryLoader.js");

describe('LoadingBar', function() {
    describe('#create()', function () {
        var lb = new LoadingBar();
        lb.create();

        it('should create an element for itself', function () {
            assert.notEqual(null, lb.element);
            assert.notEqual("undefined", typeof lb.element);
            assert.notEqual("undefined", typeof lb.element.tagName);
            assert.equal("div", lb.element.tagName.toLowerCase());
            assert.equal(lb.className, lb.element.getAttribute("class"));
        });

        it('should apply default styling', function () {
            assert.equal("absolute", lb.element.style.position);
            assert.equal(lb.barHeight + "px", lb.element.style.height);
        });
    });

    describe('#updateProgress()', function () {
        it('should update the progress and adjust the loading bar', function () {
            var lb = new LoadingBar();
            lb.create();

            assert.equal("0%", lb.element.style.width);

            lb.updateProgress(10, 0);

            assert.equal("10%", lb.element.style.width);

            lb.updateProgress(50, 0);

            assert.equal("50%", lb.element.style.width);

            lb.updateProgress(100, 0);

            assert.equal("100%", lb.element.style.width);

            lb.updateProgress(-20, 0);

            assert.equal("0%", lb.element.style.width);

            lb.updateProgress(420, 0);

            assert.equal("100%", lb.element.style.width);
        });

        it('should not break on floats', function () {
            var lb = new LoadingBar();
            lb.create();

            lb.updateProgress(10.6, 0);

            assert.equal("10%", lb.element.style.width);

            lb.updateProgress(50.456, 0);

            assert.equal("50%", lb.element.style.width);
        });
    });
});

describe('Percentage', function() {
    describe('#create()', function () {
        var p = new Percentage();
        p.create();

        it('should create an element for itself', function () {
            assert.notEqual(null, p.element);
            assert.notEqual("undefined", typeof p.element);
            assert.notEqual("undefined", typeof p.element.tagName);
            assert.equal("div", p.element.tagName.toLowerCase());
            assert.equal(p.className, p.element.getAttribute("class"));
        });

        it('should apply default styling', function () {
            assert.equal("absolute", p.element.style.position);
        });
    });

    describe('#updateProgress()', function () {
        var p = new Percentage();
        p.create();

        it('should update the progress and adjust the loading bar', function () {
            assert.equal("0%", p.element.innerHTML);

            p.updateProgress(10, 0);

            assert.equal("10%", p.element.innerHTML);

            p.updateProgress(50, 0);

            assert.equal("50%", p.element.innerHTML);

            p.updateProgress(100, 0);

            assert.equal("100%", p.element.innerHTML);

            p.updateProgress(-20, 0);

            assert.equal("0%", p.element.innerHTML);

            p.updateProgress(420, 0);

            assert.equal("100%", p.element.innerHTML);
        });

        it('should not break on floats', function () {
            p.updateProgress(10.6, 0);

            assert.equal("10%", p.element.innerHTML);

            p.updateProgress(50.456, 0);

            assert.equal("50%", p.element.innerHTML);
        });
    });
});

describe('Overlay', function() {
    var fakeBody = document.createElement("body");

    describe('#create()', function () {
        var o = new Overlay(fakeBody);
        o.create();

        it('should create an element for itself', function () {
            assert.notEqual(null, o.element);
            assert.notEqual("undefined", typeof o.element);
            assert.notEqual("undefined", typeof o.element.tagName);
            assert.equal("div", o.element.tagName.toLowerCase());
            assert.equal(o.className, o.element.getAttribute("class"));
        });
    });

    describe('#calculatePosition()', function () {
        var o = new Overlay();

        it('should give the correct needed position of the overlay', function () {
            o.parentElement = fakeBody;

            assert.equal("fixed", o.calculatePosition());

            var fakeContainer = document.createElement("div");
            fakeContainer.style.position = "static";

            o.parentElement = fakeContainer;

            assert.equal("absolute", o.calculatePosition());
            assert.equal("relative", o.parentElement.style.position);

            o.parentElement.style.position = "absolute";

            assert.equal("absolute", o.calculatePosition());
        });
    });

    describe('#updateProgess()', function () {
        var o = new Overlay();
        o.parentElement = fakeBody;
        o.create();

        o.percentage = new Percentage();
        o.percentage.create();

        o.loadingBar = new LoadingBar();
        o.loadingBar.create();

        it('should update the loading progress of both percentage and loadingbar', function () {
            assert.equal("0%", o.percentage.element.innerHTML);
            assert.equal("0%", o.loadingBar.element.style.width);

            o.updateProgress(10, 0);

            assert.equal("10%", o.percentage.element.innerHTML);
            assert.equal("10%", o.loadingBar.element.style.width);
        });
    });
});

describe('Image', function() {
    describe('#constructor()', function () {
        it('should create an image object with given src', function () {
            var exampleImage = new Image("some/src");

            assert.equal("some/src", exampleImage.src);
        });

        it('should create a dom object with given src', function () {
            var exampleImage = new Image("some/src");

            assert.notEqual(-1, exampleImage.element.src.indexOf("some/src"));
        });
    });

    describe('#preload()', function () {
        it('should callback when an image is loaded', function (done) {
            var exampleImage = new Image("images/1.jpg");

            exampleImage.preload(done);
        });
    });
});

describe('QueryLoader', function() {
    describe('#createOverlay()', function () {
        var ql = new QueryLoader();

        it('should create an overlay when called', function () {
            ql.createOverlay();

            assert.equal(ql.overlay instanceof Overlay, true);
        });
    });

    describe('#createPreloader()', function () {
        var ql = new QueryLoader();

        it('should create the preloader', function () {
            ql.createPreloader();

            assert.equal(ql.preloader instanceof ImagePreloader, true);
        });
    });

    describe('#extend()', function () {
        it('should merge two objects', function () {
            var ql = new QueryLoader();

            var destination = {
                some: "thing",
                is: "not",
                right: "man"
            };

            var source = {
                some: "one",
                right: "dude"
            };

            assert.deepEqual({
                "some": "one",
                "is": "not",
                "right": "dude"
            }, ql.extend(destination, source));
        });
    });
});

describe('ImagePreloader', function() {
    "use strict";
    describe('#getImages()', function () {
        var ip = new ImagePreloader();

        it('should get all images within the given element', function () {
            assert.equal(false, true);
        });
    });

    describe('#findAndPreload()', function () {
        var ip = new ImagePreloader();

        it('should find all images and start preloading', function () {
            assert.equal(false, true);
        });
    });

    describe('#updateProgess()', function () {
        var ip = new ImagePreloader();

        it('should update the loading progress', function () {
            assert.equal(false, true);
        });
    });
});<commit_msg>Wrote get images test<commit_after>var assert = require("assert");

var Overlay = require("../src/Overlay/");
var LoadingBar = require("../src/Overlay/LoadingBar.js");
var Percentage = require("../src/Overlay/Percentage.js");
var Image = require("../src/ImagePreloader/Image.js");
var ImagePreloader = require("../src/ImagePreloader/");
var QueryLoader = require("../src/QueryLoader.js");

describe('LoadingBar', function() {
    describe('#create()', function () {
        var lb = new LoadingBar();
        lb.create();

        it('should create an element for itself', function () {
            assert.notEqual(null, lb.element);
            assert.notEqual("undefined", typeof lb.element);
            assert.notEqual("undefined", typeof lb.element.tagName);
            assert.equal("div", lb.element.tagName.toLowerCase());
            assert.equal(lb.className, lb.element.getAttribute("class"));
        });

        it('should apply default styling', function () {
            assert.equal("absolute", lb.element.style.position);
            assert.equal(lb.barHeight + "px", lb.element.style.height);
        });
    });

    describe('#updateProgress()', function () {
        it('should update the progress and adjust the loading bar', function () {
            var lb = new LoadingBar();
            lb.create();

            assert.equal("0%", lb.element.style.width);

            lb.updateProgress(10, 0);

            assert.equal("10%", lb.element.style.width);

            lb.updateProgress(50, 0);

            assert.equal("50%", lb.element.style.width);

            lb.updateProgress(100, 0);

            assert.equal("100%", lb.element.style.width);

            lb.updateProgress(-20, 0);

            assert.equal("0%", lb.element.style.width);

            lb.updateProgress(420, 0);

            assert.equal("100%", lb.element.style.width);
        });

        it('should not break on floats', function () {
            var lb = new LoadingBar();
            lb.create();

            lb.updateProgress(10.6, 0);

            assert.equal("10%", lb.element.style.width);

            lb.updateProgress(50.456, 0);

            assert.equal("50%", lb.element.style.width);
        });
    });
});

describe('Percentage', function() {
    describe('#create()', function () {
        var p = new Percentage();
        p.create();

        it('should create an element for itself', function () {
            assert.notEqual(null, p.element);
            assert.notEqual("undefined", typeof p.element);
            assert.notEqual("undefined", typeof p.element.tagName);
            assert.equal("div", p.element.tagName.toLowerCase());
            assert.equal(p.className, p.element.getAttribute("class"));
        });

        it('should apply default styling', function () {
            assert.equal("absolute", p.element.style.position);
        });
    });

    describe('#updateProgress()', function () {
        var p = new Percentage();
        p.create();

        it('should update the progress and adjust the loading bar', function () {
            assert.equal("0%", p.element.innerHTML);

            p.updateProgress(10, 0);

            assert.equal("10%", p.element.innerHTML);

            p.updateProgress(50, 0);

            assert.equal("50%", p.element.innerHTML);

            p.updateProgress(100, 0);

            assert.equal("100%", p.element.innerHTML);

            p.updateProgress(-20, 0);

            assert.equal("0%", p.element.innerHTML);

            p.updateProgress(420, 0);

            assert.equal("100%", p.element.innerHTML);
        });

        it('should not break on floats', function () {
            p.updateProgress(10.6, 0);

            assert.equal("10%", p.element.innerHTML);

            p.updateProgress(50.456, 0);

            assert.equal("50%", p.element.innerHTML);
        });
    });
});

describe('Overlay', function() {
    var fakeBody = document.createElement("body");

    describe('#create()', function () {
        var o = new Overlay(fakeBody);
        o.create();

        it('should create an element for itself', function () {
            assert.notEqual(null, o.element);
            assert.notEqual("undefined", typeof o.element);
            assert.notEqual("undefined", typeof o.element.tagName);
            assert.equal("div", o.element.tagName.toLowerCase());
            assert.equal(o.className, o.element.getAttribute("class"));
        });
    });

    describe('#calculatePosition()', function () {
        var o = new Overlay();

        it('should give the correct needed position of the overlay', function () {
            o.parentElement = fakeBody;

            assert.equal("fixed", o.calculatePosition());

            var fakeContainer = document.createElement("div");
            fakeContainer.style.position = "static";

            o.parentElement = fakeContainer;

            assert.equal("absolute", o.calculatePosition());
            assert.equal("relative", o.parentElement.style.position);

            o.parentElement.style.position = "absolute";

            assert.equal("absolute", o.calculatePosition());
        });
    });

    describe('#updateProgess()', function () {
        var o = new Overlay();
        o.parentElement = fakeBody;
        o.create();

        o.percentage = new Percentage();
        o.percentage.create();

        o.loadingBar = new LoadingBar();
        o.loadingBar.create();

        it('should update the loading progress of both percentage and loadingbar', function () {
            assert.equal("0%", o.percentage.element.innerHTML);
            assert.equal("0%", o.loadingBar.element.style.width);

            o.updateProgress(10, 0);

            assert.equal("10%", o.percentage.element.innerHTML);
            assert.equal("10%", o.loadingBar.element.style.width);
        });
    });
});

describe('Image', function() {
    describe('#constructor()', function () {
        it('should create an image object with given src', function () {
            var exampleImage = new Image("some/src");

            assert.equal("some/src", exampleImage.src);
        });

        it('should create a dom object with given src', function () {
            var exampleImage = new Image("some/src");

            assert.notEqual(-1, exampleImage.element.src.indexOf("some/src"));
        });
    });

    describe('#preload()', function () {
        it('should callback when an image is loaded', function (done) {
            var exampleImage = new Image("images/1.jpg");

            exampleImage.preload(done);
        });
    });
});

describe('QueryLoader', function() {
    describe('#createOverlay()', function () {
        var ql = new QueryLoader();

        it('should create an overlay when called', function () {
            ql.createOverlay();

            assert.equal(ql.overlay instanceof Overlay, true);
        });
    });

    describe('#createPreloader()', function () {
        var ql = new QueryLoader();

        it('should create the preloader', function () {
            ql.createPreloader();

            assert.equal(ql.preloader instanceof ImagePreloader, true);
        });
    });

    describe('#extend()', function () {
        it('should merge two objects', function () {
            var ql = new QueryLoader();

            var destination = {
                some: "thing",
                is: "not",
                right: "man"
            };

            var source = {
                some: "one",
                right: "dude"
            };

            assert.deepEqual({
                "some": "one",
                "is": "not",
                "right": "dude"
            }, ql.extend(destination, source));
        });
    });
});

describe('ImagePreloader', function() {
    "use strict";
    describe('#getImages()', function () {
        var ip = new ImagePreloader();

        var fakeImagesContainer = document.createElement("div");

        var img1 = document.createElement("img");
        img1.setAttribute("src", "fakeimg1.png");
        fakeImagesContainer.appendChild(img1);

        var img2 = document.createElement("img");
        img2.setAttribute("src", "fakeimg2.png");
        fakeImagesContainer.appendChild(img2);

        var img3 = document.createElement("section");
        img3.style.backgroundImage = "url(fakeimg3.png)";
        fakeImagesContainer.appendChild(img3);

        it('should get all images within the given element', function () {
            var images = ip.getImages(fakeImagesContainer);

            assert.equal(3, images.length);
            assert.notEqual(-1, images[0].indexOf("fakeimg1.png"));
            assert.notEqual(-1, images[1].indexOf("fakeimg2.png"));
            assert.notEqual(-1, images[3].indexOf("fakeimg3.png"));
        });
    });

    describe('#findAndPreload()', function () {
        var ip = new ImagePreloader();

        it('should find all images and start preloading', function () {
            assert.equal(false, true);
        });
    });

    describe('#updateProgess()', function () {
        var ip = new ImagePreloader();

        it('should update the loading progress', function () {
            assert.equal(false, true);
        });
    });
});<|endoftext|>