<commit_before>/*

count = 5

items = .items.item[ .count < count ]

match / {
    id = .id

        apply items content
        apply .items.item[ .selected && .id == id ] content

}

match .item content {

{ .title }

}

*/

var P = Module.prototype;

//  ---------------------------------------------------------------------------------------------------------------  //
//  JPaths
//  ---------------------------------------------------------------------------------------------------------------  //

//  .count
P.j0 = [ 'count' ];

//  .items.item[ .count > count ]
P.j1 = [ 'items', 'item', 2, 'p0' ];

//  .title
P.j2 = [ 'title' ];

//  .id
P.j3 = [ 'id' ];

//  .selected
P.j4 = [ 'selected' ];

//  .items.item[ .selected && .id = id ]
P.j5 = [ 'items', 'item', 2, 'p1' ];

//  .item
P.j6 = [ 'item' ];

//  ---------------------------------------------------------------------------------------------------------------  //
//  Vars
//  ---------------------------------------------------------------------------------------------------------------  //

function selector(jid) {
    return function(c0) {
        return this.select(jid, c0);
    };
}

//  5
P.v0 = 5;
//  .items.item[ .count > count ]
P.v1 = selector('j1');
/*
P.v1 = function(c0) {
    return this.select('j1', c0);
};
*/
//  .id
P.v2 = selector('j3');
/*
P.v2 = function(c0) {
    return this.select('j3', c0);
};
*/

//  ---------------------------------------------------------------------------------------------------------------  //
//  Predicates
//  ---------------------------------------------------------------------------------------------------------------  //

//  .count < count
P.p0 = function(c0, i0, l0) {
    return this.selectAsScalar('j0', c0) < this.v0;
};
//  .selected && .id = id
P.p1 = function(c0, i0, l0) {
    var v2_ = this.vars('v2', c0);
    return this.selectAsBool('j4', c0) && this.selectAsScalar('j3', c0) == v2_;
};

//  ---------------------------------------------------------------------------------------------------------------  //
//  Templates
//  ---------------------------------------------------------------------------------------------------------------  //

//  match /
P.t0 = function(c0, a0, i0, l0) {
    //  items = .items.item[ .count < count ]
    var v1_ = this.gvars('v1', c0);
    //  id = .id
    var v2_ = this.vars('v2', c0);
    var r0 = '';
    r0 += '
';
    //  apply items
    r0 += this.applyValue(v1_, 'content', a0);
    //  apply .items.item[ .selected && .id == id ]
    r0 += this.applyValue(this.select('j5', c0), 'content', a0);
    r0 += '
';
    return r0;
};
P.t0.selector = null;

//  match .item content
P.t1 = function(c0, a0, i0, l0) {
    var r0 = '';
    r0 += '
';
    //  .title
    r0 += this.selectAsScalar('j2', c0);
    r0 += '
';
    return r0;
};
P.t1.selector = 'j6';

P.matcher = {
    '': {
        '': [ 't0' ]
    },
    'content': {
        'item': [ 't1' ]
    }
};

<commit_msg>Наброски<commit_after>/*

id = "foo"
count = 5

items = .items.item[ .count < count ]

match / {
    id = .id

        apply items content
        apply .items.item[ .selected && .id == id ] content

}

match .item[ .id == id ] content {

{ .title }

}

*/

var P = Module.prototype;

//  ---------------------------------------------------------------------------------------------------------------  //
//  JPaths
//  ---------------------------------------------------------------------------------------------------------------  //

//  .count
P.j0 = [ 'count' ];

//  .items.item[ .count > count ]
P.j1 = [ 'items', 'item', 2, 'p0' ];

//  .title
P.j2 = [ 'title' ];

//  .id
P.j3 = [ 'id' ];

//  .selected
P.j4 = [ 'selected' ];

//  .items.item[ .selected && .id = id ]
P.j5 = [ 'items', 'item', 2, 'p1' ];

//  .item
P.j6 = [ 'item' ];

//  .item[ .id = id ]
P.j7 = [ 'item', 2, 'p2' ];

//  ---------------------------------------------------------------------------------------------------------------  //
//  Vars
//  ---------------------------------------------------------------------------------------------------------------  //

function selector(jid) {
    return function(c0) {
        return this.select(jid, c0);
    };
}

//  5
P.v0 = 5;
//  .items.item[ .count > count ]
P.v1 = selector('j1');
/*
P.v1 = function(c0) {
    return this.select('j1', c0);
};
*/
//  .id
P.v2 = selector('j3');
/*
P.v2 = function(c0) {
    return this.select('j3', c0);
};
*/
P.v3 = "foo";

//  ---------------------------------------------------------------------------------------------------------------  //
//  Predicates
//  ---------------------------------------------------------------------------------------------------------------  //

//  .count < count
P.p0 = function(c0, i0, l0) {
    return this.selectAsScalar('j0', c0) < this.v0;
};

//  .selected && .id = id
P.p1 = function(c0, i0, l0) {
    var v2_ = this.v2(c0);
    return this.selectAsBool('j4', c0) && this.selectAsScalar('j3', c0) == v2_;
};

//  .id = id
P.p2 = function(c0, i0, l0) {
    return this.selectAsScalar('j3', c0) == this.v3;
};

//  ---------------------------------------------------------------------------------------------------------------  //
//  Templates
//  ---------------------------------------------------------------------------------------------------------------  //

//  match /
P.t0 = function(c0, a0, i0, l0) {
    //  items = .items.item[ .count < count ]
    var v1_ = this.gvars('v1', c0);
    //  id = .id
    var v2_ = this.v2(c0);
    var r0 = '';
    r0 += '
';
    //  apply items
    r0 += this.applyValue(v1_, 'content', a0);
    //  apply .items.item[ .selected && .id == id ]
    r0 += this.applyValue(this.select('j5', c0), 'content', a0);
    r0 += '
';
    return r0;
};
P.t0.selector = null;

//  match .item content
P.t1 = function(c0, a0, i0, l0) {
    var r0 = '';
    r0 += '
';
    //  .title
    r0 += this.selectAsScalar('j2', c0);
    r0 += '
';
    return r0;
};
P.t1.selector = 'j7';

P.matcher = {
    '': {
        '': [ 't0' ]
    },
    'content': {
        'item': [ 't1' ]
    }
};

<|endoftext|>


<commit_before>var mocha = require('mocha'),
  should = require('should'),
  config = require('./config.js'),
  Blogs = require('../lib/blogs.js').Blogs;

describe('Testing GET blogs:', function() {
  var blogs = new Blogs(config.secrets.consumer_key),
    user_id = config.secrets.user_id,
    user_name = config.secrets.user_name;

  // describe('#getById()', function() {
  //   it('should return a json with the blog data', function(done) {
  //     blogs.getById(1704, {}, function(err, result) {
  //       should.not.exist(err);
  //       should.exist(result);
  //       result.should.have.property('body');

  //       done();
  //     });
  //   });
  // });

  describe('#getCommentsById()', function() {
    it('should return a json with the blog comments', function(done) {
      blogs.getCommentsById(1704, {}, function(err, result) {
        should.not.exist(err);
        should.exist(result);
        result.should.have.property('comments');

        done();
      });
    });
  });

  describe('#getFresh()', function() {
    it('should return a json with the freshest blogs data', function(done) {
      blogs.getFresh({'rpp': '10'}, function(err, result) {
        should.not.exist(err);
        should.exist(result);
        result.should.have.property('blog_posts');
        result.blog_posts.should.have.lengthOf(10);

        done();
      });
    });
  });

  describe('#getByUsername()', function() {
    it('should return a json with the blog data', function(done) {
      blogs.getByUsername(user_name, {}, function(err, result) {
        should.not.exist(err);
        should.exist(result);
        result.should.have.property('blog_posts');

        done();
      });
    });
  });

  describe('#getByUserId()', function() {
    it('should return a json with the blog data', function(done) {
      blogs.getByUserId(user_id, {}, function(err, result) {
        should.not.exist(err);
        should.exist(result);
        result.should.have.property('blog_posts');

        done();
      });
    });
  });
});<commit_msg>Fix failing blog test<commit_after>var mocha = require('mocha'),
  should = require('should'),
  config = require('./config.js'),
  Blogs = require('../lib/blogs.js').Blogs;

describe('Testing GET blogs:', function() {
  var blogs = new Blogs(config.secrets.consumer_key),
    user_id = config.secrets.user_id,
    user_name = config.secrets.user_name;

  describe('#getById()', function() {
    it('should return a json with the blog data', function(done) {
      blogs.getById(27105, {}, function(err, result) {
        should.not.exist(err);
        should.exist(result);
        result.should.have.property('body');

        done();
      });
    });
  });

  describe('#getCommentsById()', function() {
    it('should return a json with the blog comments', function(done) {
      blogs.getCommentsById(1704, {}, function(err, result) {
        should.not.exist(err);
        should.exist(result);
        result.should.have.property('comments');

        done();
      });
    });
  });

  describe('#getFresh()', function() {
    it('should return a json with the freshest blogs data', function(done) {
      blogs.getFresh({'rpp': '10'}, function(err, result) {
        should.not.exist(err);
        should.exist(result);
        result.should.have.property('blog_posts');
        result.blog_posts.should.have.lengthOf(10);

        done();
      });
    });
  });

  describe('#getByUsername()', function() {
    it('should return a json with the blog data', function(done) {
      blogs.getByUsername(user_name, {}, function(err, result) {
        should.not.exist(err);
        should.exist(result);
        result.should.have.property('blog_posts');

        done();
      });
    });
  });

  describe('#getByUserId()', function() {
    it('should return a json with the blog data', function(done) {
      blogs.getByUserId(user_id, {}, function(err, result) {
        should.not.exist(err);
        should.exist(result);
        result.should.have.property('blog_posts');

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


<commit_before>var assert = require('assert');
var cp = require('child_process')
var path = require('path');
var existsSync = require('fs').existsSync || require('path').existsSync;

var cmd_path = path.join(__dirname,'../bin/');
var sep = ':';
if (process.platform === 'win32') {
    sep = ';'
}
process.env.PATH = cmd_path + sep + process.env.PATH;
process.env.NODE_PATH = path.join(__dirname,'../lib/');

function run(command,app,opts,cb) {
    if (!opts.cwd) {
        command += ' -C ' + path.join(__dirname,app.name);
    }
    if (process.platform === 'win32') {
        command += ' --msvs_version=2013 '
    }
    command += ' ' + app.args;
    cp.exec(command,opts, cb);
}

var apps = [
    {
        'name': 'app1',
        'args': ''
    }
    ,{
        'name': 'app2',
        'args': '--custom_include_path=../include'
    }
    ,{
        'name': 'app2',
        'args': '--custom_include_path=../include --debug'
    }
    ,{
        'name': 'app2',
        'args': '--custom_include_path=../include --toolset=cpp11'
    }
    ,{
        'name': 'app3',
        'args': ''
    }
    ,{
        'name': 'app4',
        'args': ''
    }
]

describe('build', function() {
    apps.forEach(function(app) {

        it(app.name + ' builds ' + app.args, function(done) {
            run('node-pre-gyp rebuild --fallback-to-build --loglevel=silent', app, {}, function(err,stdout,stderr) {
                if (err) throw err;
                assert.ok(stdout.search(app.name+'.node') > -1);
                assert.equal(stderr,'');
                done();
            })
        });

        it(app.name + ' passes --nodedir down to node-gyp ' + app.args, function(done) {
            run('node-pre-gyp rebuild --fallback-to-build --nodedir=invalid-value', app, {}, function(err,stdout,stderr) {
                assert.ok(err);
                assert.ok(stdout.search(app.name+'.node') > -1);
                assert.ok(stderr.indexOf('common.gypi not found' > -1));
                done();
            })
        });

        it(app.name + ' builds with custom --target ' + app.args, function(done) {
            run('node-pre-gyp rebuild --fallback-to-build --target='+process.versions.node, app, {}, function(err,stdout,stderr) {
                if (err) throw err;
                assert.ok(stdout.search(app.name+'.node') > -1);
                assert.equal(stderr,'');
                done();
            })
        });

        it(app.name + ' is found ' + app.args, function(done) {
            run('node-pre-gyp reveal module_path --silent', app, {}, function(err,stdout,stderr) {
                if (err) throw err;
                assert.equal(stderr,'');
                var module_path = stdout.trim();
                assert.ok(module_path.search(app.name) > -1);
                assert.ok(existsSync(module_path));
                var module_binary = path.join(module_path,app.name+'.node');
                assert.ok(existsSync(module_binary));
                done();
            });
        });

        it(app.name + ' passes tests ' + app.args, function(done) {
            run('npm test', app, {cwd: path.join(__dirname,app.name)}, function(err,stdout,stderr) {
                if (err) throw err;
                assert.equal(stderr,'');
                assert.notEqual(stdout,'');
                done();
            });
        });

        it(app.name + ' packages ' + app.args, function(done) {
            run('node-pre-gyp package', app, {}, function(err,stdout,stderr) {
                if (err) throw err;
                assert.equal(stderr,'');
                done();
            });
        });

        it(app.name + ' package is valid ' + app.args, function(done) {
            run('node-pre-gyp testpackage', app, {}, function(err,stdout,stderr) {
                if (err) throw err;
                assert.equal(stderr,'');
                done();
            });
        });

        if (process.env.AWS_ACCESS_KEY_ID || process.env.node_pre_gyp_accessKeyId) {

            it(app.name + ' publishes ' + app.args, function(done) {
                run('node-pre-gyp unpublish publish', app, {}, function(err,stdout,stderr) {
                    if (err) throw err;
                    assert.equal(stderr,'');
                    assert.notEqual(stdout,'');
                    done();
                });
            });

            it(app.name + ' info shows it ' + app.args, function(done) {
                run('node-pre-gyp reveal package_name --silent', app, {}, function(err,stdout,stderr) {
                    if (err) throw err;
                    assert.equal(stderr,'');
                    assert.notEqual(stdout,'');
                    var package_name = stdout.trim();
                    run('node-pre-gyp info', app, {}, function(err,stdout,stderr) {
                        if (err) throw err;
                        assert.equal(stderr,'');
                        assert.ok(stdout.indexOf(package_name) > -1);
                        done();
                    });
                });
            });

            it(app.name + ' can be uninstalled ' + app.args, function(done) {
                run('node-pre-gyp clean', app, {}, function(err,stdout,stderr) {
                    if (err) throw err;
                    assert.equal(stderr,'');
                    assert.notEqual(stdout,'');
                    done();
                });
            });

            it(app.name + ' can be installed via remote ' + app.args, function(done) {
                run('npm install --fallback-to-build=false --silent', app, {cwd: path.join(__dirname,app.name)}, function(err,stdout,stderr) {
                    if (err) throw err;
                    assert.equal(stderr,'');
                    assert.notEqual(stdout,'');
                    done();
                });
            });

            it(app.name + ' can be reinstalled via remote ' + app.args, function(done) {
                run('npm install --update-binary --fallback-to-build=false --silent', app, {cwd: path.join(__dirname,app.name)}, function(err,stdout,stderr) {
                    if (err) throw err;
                    assert.equal(stderr,'');
                    assert.notEqual(stdout,'');
                    done();
                });
            });

            it(app.name + ' via remote passes tests ' + app.args, function(done) {
                run('npm test', app, {cwd: path.join(__dirname,app.name)}, function(err,stdout,stderr) {
                    if (err) throw err;
                    assert.equal(stderr,'');
                    assert.notEqual(stdout,'');
                    done();
                });
            });

        } else {
            it.skip(app.name + ' publishes ' + app.args, function() {});
        }

    });
});
<commit_msg>ignore child_process deprecations since an update node-gyp is still not tagged - closes #125 - refs #135<commit_after>var assert = require('assert');
var cp = require('child_process')
var path = require('path');
var existsSync = require('fs').existsSync || require('path').existsSync;

var cmd_path = path.join(__dirname,'../bin/');
var sep = ':';
if (process.platform === 'win32') {
    sep = ';'
}
process.env.PATH = cmd_path + sep + process.env.PATH;
process.env.NODE_PATH = path.join(__dirname,'../lib/');

function run(command,app,opts,cb) {
    if (!opts.cwd) {
        command += ' -C ' + path.join(__dirname,app.name);
    }
    if (process.platform === 'win32') {
        command += ' --msvs_version=2013 '
    }
    command += ' ' + app.args;
    cp.exec(command,opts, cb);
}

var apps = [
    {
        'name': 'app1',
        'args': ''
    }
    ,{
        'name': 'app2',
        'args': '--custom_include_path=../include'
    }
    ,{
        'name': 'app2',
        'args': '--custom_include_path=../include --debug'
    }
    ,{
        'name': 'app2',
        'args': '--custom_include_path=../include --toolset=cpp11'
    }
    ,{
        'name': 'app3',
        'args': ''
    }
    ,{
        'name': 'app4',
        'args': ''
    }
]

describe('build', function() {
    apps.forEach(function(app) {

        it(app.name + ' builds ' + app.args, function(done) {
            run('node-pre-gyp rebuild --fallback-to-build --loglevel=silent', app, {}, function(err,stdout,stderr) {
                if (err) throw err;
                assert.ok(stdout.search(app.name+'.node') > -1);
                if (stderr != "child_process: customFds option is deprecated, use stdio instead.\n") {
                    assert.equal(stderr,'');
                }
                done();
            })
        });

        it(app.name + ' passes --nodedir down to node-gyp ' + app.args, function(done) {
            run('node-pre-gyp rebuild --fallback-to-build --nodedir=invalid-value', app, {}, function(err,stdout,stderr) {
                assert.ok(err);
                assert.ok(stdout.search(app.name+'.node') > -1);
                assert.ok(stderr.indexOf('common.gypi not found' > -1));
                done();
            })
        });

        it(app.name + ' builds with custom --target ' + app.args, function(done) {
            run('node-pre-gyp rebuild --fallback-to-build --target='+process.versions.node, app, {}, function(err,stdout,stderr) {
                if (err) throw err;
                assert.ok(stdout.search(app.name+'.node') > -1);
                if (stderr != "child_process: customFds option is deprecated, use stdio instead.\n") {
                    assert.equal(stderr,'');
                }
                done();
            })
        });

        it(app.name + ' is found ' + app.args, function(done) {
            run('node-pre-gyp reveal module_path --silent', app, {}, function(err,stdout,stderr) {
                if (err) throw err;
                if (stderr != "child_process: customFds option is deprecated, use stdio instead.\n") {
                    assert.equal(stderr,'');
                }
                var module_path = stdout.trim();
                assert.ok(module_path.search(app.name) > -1);
                assert.ok(existsSync(module_path));
                var module_binary = path.join(module_path,app.name+'.node');
                assert.ok(existsSync(module_binary));
                done();
            });
        });

        it(app.name + ' passes tests ' + app.args, function(done) {
            run('npm test', app, {cwd: path.join(__dirname,app.name)}, function(err,stdout,stderr) {
                if (err) throw err;
                if (stderr != "child_process: customFds option is deprecated, use stdio instead.\n") {
                    assert.equal(stderr,'');
                }
                assert.notEqual(stdout,'');
                done();
            });
        });

        it(app.name + ' packages ' + app.args, function(done) {
            run('node-pre-gyp package', app, {}, function(err,stdout,stderr) {
                if (err) throw err;
                if (stderr != "child_process: customFds option is deprecated, use stdio instead.\n") {
                    assert.equal(stderr,'');
                }
                done();
            });
        });

        it(app.name + ' package is valid ' + app.args, function(done) {
            run('node-pre-gyp testpackage', app, {}, function(err,stdout,stderr) {
                if (err) throw err;
                if (stderr != "child_process: customFds option is deprecated, use stdio instead.\n") {
                    assert.equal(stderr,'');
                }
                done();
            });
        });

        if (process.env.AWS_ACCESS_KEY_ID || process.env.node_pre_gyp_accessKeyId) {

            it(app.name + ' publishes ' + app.args, function(done) {
                run('node-pre-gyp unpublish publish', app, {}, function(err,stdout,stderr) {
                    if (err) throw err;
                    if (stderr != "child_process: customFds option is deprecated, use stdio instead.\n") {
                        assert.equal(stderr,'');
                    }
                    assert.notEqual(stdout,'');
                    done();
                });
            });

            it(app.name + ' info shows it ' + app.args, function(done) {
                run('node-pre-gyp reveal package_name --silent', app, {}, function(err,stdout,stderr) {
                    if (err) throw err;
                    assert.equal(stderr,'');
                    assert.notEqual(stdout,'');
                    var package_name = stdout.trim();
                    run('node-pre-gyp info', app, {}, function(err,stdout,stderr) {
                        if (err) throw err;
                        if (stderr != "child_process: customFds option is deprecated, use stdio instead.\n") {
                            assert.equal(stderr,'');
                        }
                        assert.ok(stdout.indexOf(package_name) > -1);
                        done();
                    });
                });
            });

            it(app.name + ' can be uninstalled ' + app.args, function(done) {
                run('node-pre-gyp clean', app, {}, function(err,stdout,stderr) {
                    if (err) throw err;
                    if (stderr != "child_process: customFds option is deprecated, use stdio instead.\n") {
                        assert.equal(stderr,'');
                    }
                    assert.notEqual(stdout,'');
                    done();
                });
            });

            it(app.name + ' can be installed via remote ' + app.args, function(done) {
                run('npm install --fallback-to-build=false --silent', app, {cwd: path.join(__dirname,app.name)}, function(err,stdout,stderr) {
                    if (err) throw err;
                    if (stderr != "child_process: customFds option is deprecated, use stdio instead.\n") {
                        assert.equal(stderr,'');
                    }
                    assert.notEqual(stdout,'');
                    done();
                });
            });

            it(app.name + ' can be reinstalled via remote ' + app.args, function(done) {
                run('npm install --update-binary --fallback-to-build=false --silent', app, {cwd: path.join(__dirname,app.name)}, function(err,stdout,stderr) {
                    if (err) throw err;
                    if (stderr != "child_process: customFds option is deprecated, use stdio instead.\n") {
                        assert.equal(stderr,'');
                    }
                    assert.notEqual(stdout,'');
                    done();
                });
            });

            it(app.name + ' via remote passes tests ' + app.args, function(done) {
                run('npm test', app, {cwd: path.join(__dirname,app.name)}, function(err,stdout,stderr) {
                    if (err) throw err;
                    if (stderr != "child_process: customFds option is deprecated, use stdio instead.\n") {
                        assert.equal(stderr,'');
                    }
                    assert.notEqual(stdout,'');
                    done();
                });
            });

        } else {
            it.skip(app.name + ' publishes ' + app.args, function() {});
        }

    });
});
<|endoftext|>


<commit_before>// This is a manifest file that'll be compiled into including all the files listed below.
// Add new JavaScript/Coffee code in separate files in this directory and they'll automatically
// be included in the compiled file accessible from http://example.com/assets/application.js
// It's not advisable to add code directly here, but if you do, it'll appear at the bottom of the
// the compiled file.
//
//= require jquery.flot
//= require jquery.flot.selection

$(document).ready(function () {
  var red = "rgba(255, 0, 0, 1)",
      light_red = "rgba(255, 0, 0, 0.5)",
      tomatoes_by_day_chart_opts = {
        series: {
          color: red,
          lines: { show: true, fill: true, fillColor: light_red }
        },
        selection: { mode: "x" },
        xaxis: { mode: "time", ticks: 14, min: THIRTY_DAYS_AGO, max: TODAY },
        yaxis: { ticks: 14, tickFormatter: function(n) { return n.toFixed(0) } }
      };

  var tomatoes_by_day_chart = $.plot($("#tomatoes_by_day"), [tomatoes_by_day], tomatoes_by_day_chart_opts);

  var tomatoes_by_day_chart_overview = $.plot($("#tomatoes_by_day_overview"), [tomatoes_by_day], {
    series: {
      color: red,
      lines: { show: true, fill: true, lineWidth: 1, fillColor: light_red },
      shadowSize: 0
    },
    selection: { mode: "x" },
    xaxis: { mode: "time", ticks: [] },
    yaxis: { ticks: [], autoscaleMargin: 0.1, tickSize: 1 }
  });

  tomatoes_by_day_chart_overview.setSelection({xaxis: {from: THIRTY_DAYS_AGO, to: TODAY}}, true);

  // connect charts
  $("#tomatoes_by_day").bind("plotselected", function (event, ranges) {
    // do the zooming
    tomatoes_by_day_chart = $.plot($("#tomatoes_by_day"), [tomatoes_by_day], $.extend(true, {}, tomatoes_by_day_chart_opts, {
      xaxis: { min: ranges.xaxis.from, max: ranges.xaxis.to }
    }));

    // don't fire event on the overview to prevent eternal loop
    tomatoes_by_day_chart_overview.setSelection(ranges, true);
  });

  $("#tomatoes_by_day_overview").bind("plotselected", function (event, ranges) {
    tomatoes_by_day_chart.setSelection(ranges);
  });

  $.plot(
    $("#tomatoes_by_hour"), [tomatoes_by_hour],
    {
      series: {
        color: red,
        bars: { show: true, barWidth: 60*60*1000, fillColor: light_red }
      },
      xaxis: { mode: "time", tickSize: [1, "hour"] },
      yaxis: { ticks: 14, tickFormatter: function(n) { return n.toFixed(0) } }
    }
  );
});<commit_msg>Remove duplicated code<commit_after>// This is a manifest file that'll be compiled into including all the files listed below.
// Add new JavaScript/Coffee code in separate files in this directory and they'll automatically
// be included in the compiled file accessible from http://example.com/assets/application.js
// It's not advisable to add code directly here, but if you do, it'll appear at the bottom of the
// the compiled file.
//
//= require jquery.flot
//= require jquery.flot.selection<|endoftext|>


<commit_before>'use strict';

module.factory('browserService', [
	'$rootScope',
	'ArrayHelper',
	'slot',
	'typeService',
	'messageService',
	'constantService',
	'tooltipService',
	'$timeout',
	'displayService',
	function ($rootScope, ArrayHelper, slot, typeService, messages, constants, tooltips, $timeout, display) {
		var browserService = {};

		//

		var DEFAULT_OPTIONS = {
			record: {
				allow: true,
				categories: new ArrayHelper([])
			},

			session: {
				allow: true,
				active: true,
				expand: false,
			}
		};

		var DEFAULT_CATEGORY = {
			allow: true,
			active: false,
			expand: true,
		};

		//

		var volume;

		//

		browserService.options = {};

		browserService.data = {};

		browserService.groups = {};

		//

		browserService.initialize = function (newVolume) {
			browserService.query = '';

			newVolume.$promise.then(initialize);
		};

		var initialize = function (newVolume) {
                        volume = newVolume;

			angular.extend(browserService.options, DEFAULT_OPTIONS);

                        browserService.options.record.categories = new ArrayHelper(
                                volume.categories.map(function (category) {
                                        return angular.extend({
                                                id: category,
                                                name: constants.data.category[category].name,
                                        }, DEFAULT_CATEGORY);
                                }));

			rebuildData();
		};

		//

		var focus, focusInvert, focusPosition;

		var rebuildData = function (focusGroup) {
			if (focusGroup) {
				focusInvert = (focus == focusGroup && getLevelByGroup(focusGroup.id) == focusPosition) ? !focusInvert : undefined;
				focusPosition = getLevelByGroup(focusGroup.id);
			}

			focus = focusGroup;

			var groups = getActiveGroups(),
				data = {
					items: [],
					level: -1,
					group: 'browser',
					limit: 20
				};

			browserService.groups = {};

			angular.forEach(groups, function (group) {
				browserService.groups[group] = [];
			});

			if (groups[0] == 'session')
                                callbackSessions(data, volume);
                        else
                                callbackRecords(data, volume, groups);

			angular.extend(browserService.data, data);

			return data;
		};

		var updateData = function (data) {
			if (!data.object) {
				return undefined;
			}

			var groups = getActiveGroups();

			if (!groups[data.level]) {
				return undefined;
			}

			if (data.group == 'session')
                                callbackSessionChildren(data);
                        else
                                callbackRecordChildren(data, data.volume, groups);

			return data;
		};

		var isGroupAllowed = function (group) {
			return browserService.options[group] && browserService.options[group].allow;
		};

		var isGroupActive = function (group) {
			return isGroupAllowed(group) && browserService.options[group].active;
		};

		var getActiveGroups = function () {
			var groups = [];

			groups.push.apply(groups, getActiveRecordGroups());

			if (isGroupActive('session')) {
				groups.push('session');
			}

			return groups;
		};

		var getAllowedGroups = function () {
			var groups = [];

			groups.push.apply(groups, getAllowedRecordGroups());

			if (isGroupAllowed('session')) {
				groups.push('session');
			}

			return groups;
		};

		var getActiveRecordGroups = function () {
			var groups = [];

			angular.forEach(browserService.options.record.categories, function (category) {
				if (category.allow && category.active) {
					groups.push(category.id);
				}
			});

			return groups;
		};

		var getAllowedRecordGroups = function () {
			var groups = [];

			angular.forEach(browserService.options.record.categories, function (category) {
				if (category.allow) {
					groups.push(category.id);
				}
			});

			return groups;
		};

		browserService.isLastGroup = function (group) {
			var groups = getAllowedGroups();

			return groups.indexOf(group) == groups.length - 1;
		};

		browserService.showList = function (data) {
			return !!getActiveGroups()[data.level + 1];
		};

		//

		var callbackRecords = function (data, volume, groups) {
                        var category = groups[data.level+1];
			var tempData = {};
			var sessions = data.sessions || volume.sessions;

			angular.forEach(sessions, function (session, sid) {
                                var any = false;
                                angular.forEach(session.records, function (record) {
                                        if (volume.records[record.id].category == category) {
						if (!(record.id in tempData))
							tempData[record.id] = {};
						tempData[record.id][sid] = session;
                                                any = true;
                                        }
                                });

                                if (!any) {
					if (!('null' in tempData))
						tempData['null'] = {};
					tempData['null'][sid] = session;
				}
			});

			if (!$.isEmptyObject(tempData)) {
				angular.forEach(tempData, function (newSessions, recordID) {
					var newData;

					if (recordID != 'null') {
						newData = callbackItem(data, volume, newSessions, volume.records[recordID], category);
					}
					else {
						newData = callbackItem(data, volume, newSessions, {
							category: category,
							id: 0,
							measures: {}
						}, category);
					}

					callbackRecordChildren(newData, volume, groups);
				});

				data.items.reverse();
			}

			return data;
		};

		var callbackRecordChildren = function (data, volume, groups) {
			if (!browserService.getItemExpand(data)) {
				return data;
			}

			if (groups[data.level + 1] == 'session') {
				callbackSessions(data, volume);
			} else {
				callbackRecords(data, volume, groups);
			}

			return data;
		};

		var callbackSessions = function (data, volume) {
			var sessions = data.sessions || volume.sessions;

			angular.forEach(sessions, function (session) {
				var newData = callbackItem(data, volume, undefined, session, 'session');

				callbackSessionChildren(newData);
			});

			return data;
		};

		var callbackSessionChildren = function (data) {
			if (!browserService.getItemExpand(data)) {
				return data;
			}

			browserService.loading = false;
		};

		var callbackItem = function (data, volume, sessions, object, group) {
			var option = getOptionByGroup(group);

			var id = 'data-' + group + '-' + object.id ;

			var newData = {
				parent: data,
				volume: volume,
				sessions: sessions,
				level: data.level + 1,

				id: id,
				object: object,
				permission: object.permission || volume.permission,
				group: group,
				items: [],

				select: false,
				expand: (focus && focus.id == group) ? ((angular.isDefined(focusInvert)) ? focusInvert : false) : option.expand,
				limit: 10
			};

			if (group == 'session') {
				var newSegment;
				var records = volume.sessions[newData.object.id].records;
				var cur, obj;
				var union = function (seg, c) {
					if (c.id === obj.id) {
						/* if record coverage is disjoint we pretend it's continuous: */
						seg = typeService.segmentUnion(seg, c.segment);
					}
					return seg;
				};
				for (cur = newData.parent; (obj = cur.object); cur = cur.parent) {
                                        if (obj.id !== 0)
                                                newSegment = typeService.segmentIntersect(newSegment,
                                                                records.reduce(union, null));
				}
				newData.segment = newSegment;
				if (typeService.segmentEmpty(newSegment)) {
					return newData; //in order to not push empty segmented things (contradictory constraints) onto list
				}
			}

			browserService.groups[group].push(newData);

			if (group == 'session' && object.top) {
				data.items.unshift(newData);
			}
			else {
				data.items.push(newData);
			}

			return newData;
		};

		//

		var recordGroupToggle;

		browserService.setRecordGroupToggle = function (group) {
			if (group == 'add') {
				var c = 0, maybe;

				angular.forEach(browserService.options.record.categories, function (recordGroup) {
					if (!recordGroup.active) {
						maybe = recordGroup;
						c++;
					}
				});

				if (c == 1) {
					browserService.addRecordGroup(maybe);
					return true;
				}
			}

			recordGroupToggle = angular.isUndefined(recordGroupToggle) ? group : undefined;
		};

		browserService.clearRecordGroupToggle = function () {
			if (angular.isDefined(recordGroupToggle)) {
				recordGroupToggle = undefined;
			}
		};

		browserService.isRecordGroupToggle = function (group) {
			return recordGroupToggle == group;
		};

		//

		browserService.canAddRecordGroup = function () {
			var canAdd = false;

			angular.forEach(browserService.options.record.categories, function (recordGroup) {
				if (!canAdd && !recordGroup.active) {
					canAdd = true;
				}
			});

			return canAdd;
		};

		browserService.addRecordGroup = function (group) {
			browserService.setRecordGroupToggle(undefined);

			var i = browserService.options.record.categories.index(group);

			group.active = true;

			browserService.options.record.categories.push(browserService.options.record.categories.splice(i, 1)[0]);

			rebuildData(group);
		};

		browserService.canRemoveRecordGroup = function () {
			return true;
		};

		browserService.removeRecordGroup = function (group) {
			group.active = false;

			var group_i = browserService.options.record.categories.index(group);

			browserService.options.record.categories.splice(group_i, 1);
			browserService.options.record.categories.push(group);

			rebuildData();
		};

		browserService.switchRecordGroup = function (group, maybe) {
			browserService.setRecordGroupToggle(undefined);

			var group_i = browserService.options.record.categories.index(group),
				maybe_i = browserService.options.record.categories.index(maybe);

			if (group.active != maybe.active) {
				group.active = !group.active;
				maybe.active = !maybe.active;
			}

			browserService.options.record.categories[group_i] = browserService.options.record.categories.splice(maybe_i, 1, browserService.options.record.categories[group_i])[0];

			rebuildData(maybe);
		};

		//

		browserService.setItemExpand = function (data, expand) {
			if (!data.expand && expand !== false) {
				data.expand = true;

				if (!angular.isArray(data.items) || data.items.length === 0) {
					updateData(data);
				}
			} else if (data.expand && expand !== true) {
				data.expand = false;

				if (data == browserService.player) {
					browserService.setItemPlayer(undefined);
				}
			}

			return data;
		};

		browserService.getItemExpand = function (data) {
			return data.expand;
		};

		browserService.canExpand = function (data) {
			return data.level >= 0 && getActiveGroups()[data.level + 1];
		};

		//

		var getOptionByGroup = function (group) {
			if (group == 'session')
                                return browserService.options.session;
                        else
                                return browserService.options.record.categories.find({id: group});
		};

		var getLevelByGroup = function (group) {
			return getActiveGroups().indexOf(group);
		};

		//

		browserService.player = undefined;

		browserService.setItemPlayer = function (data) {
			var newPlayer, newPlayed;

			if (angular.isUndefined(data)) {
				newPlayed = undefined;
				newPlayer = undefined;
			} else {
				newPlayed = data.items[0] || undefined;
				newPlayer = data;
			}

			if (angular.isUndefined(browserService.player)) {
				browserService.player = newPlayer;

				browserService.player.player = true;

				browserService.player.played = newPlayed;
			} else if (browserService.player != newPlayer) {
				browserService.player.player = false;

				browserService.player = newPlayer;

				if (angular.isDefined(browserService.player)) {
					browserService.player.player = true;
					browserService.player.played = newPlayed;
				}
			} else if (browserService.player.played != newPlayed) {
				browserService.player.played = newPlayed;
			} else {
				browserService.player.player = false;

				browserService.player = undefined;
			}

			if (data && data.parent && data.parent.id)
				display.scrollTo($('#' + data.parent.id).find('.browser-controller'));

			return browserService.player;
		};

		//

		return browserService;
	}
]);
<commit_msg>format code<commit_after>'use strict';

module.factory('browserService', [
	'$rootScope',
	'ArrayHelper',
	'slot',
	'typeService',
	'messageService',
	'constantService',
	'tooltipService',
	'$timeout',
	'displayService',
	function ($rootScope, ArrayHelper, slot, typeService, messages, constants, tooltips, $timeout, display) {
		var browserService = {};

		//

		var DEFAULT_OPTIONS = {
			record: {
				allow: true,
				categories: new ArrayHelper([])
			},

			session: {
				allow: true,
				active: true,
				expand: false,
			}
		};

		var DEFAULT_CATEGORY = {
			allow: true,
			active: false,
			expand: true,
		};

		//

		var volume;

		//

		browserService.options = {};

		browserService.data = {};

		browserService.groups = {};

		//

		browserService.initialize = function (newVolume) {
			browserService.query = '';

			newVolume.$promise.then(initialize);
		};

		var initialize = function (newVolume) {
			volume = newVolume;

			angular.extend(browserService.options, DEFAULT_OPTIONS);

			browserService.options.record.categories = new ArrayHelper(
				volume.categories.map(function (category) {
					return angular.extend({
						id: category,
						name: constants.data.category[category].name,
					}, DEFAULT_CATEGORY);
				}));

			rebuildData();
		};

		//

		var focus, focusInvert, focusPosition;

		var rebuildData = function (focusGroup) {
			if (focusGroup) {
				focusInvert = (focus == focusGroup && getLevelByGroup(focusGroup.id) == focusPosition) ? !focusInvert : undefined;
				focusPosition = getLevelByGroup(focusGroup.id);
			}

			focus = focusGroup;

			var groups = getActiveGroups(),
				data = {
					items: [],
					level: -1,
					group: 'browser',
					limit: 20
				};

			browserService.groups = {};

			angular.forEach(groups, function (group) {
				browserService.groups[group] = [];
			});

			if (groups[0] == 'session')
				callbackSessions(data, volume);
			else
				callbackRecords(data, volume, groups);

			angular.extend(browserService.data, data);

			return data;
		};

		var updateData = function (data) {
			if (!data.object) {
				return undefined;
			}

			var groups = getActiveGroups();

			if (!groups[data.level]) {
				return undefined;
			}

			if (data.group == 'session')
				callbackSessionChildren(data);
			else
				callbackRecordChildren(data, data.volume, groups);

			return data;
		};

		var isGroupAllowed = function (group) {
			return browserService.options[group] && browserService.options[group].allow;
		};

		var isGroupActive = function (group) {
			return isGroupAllowed(group) && browserService.options[group].active;
		};

		var getActiveGroups = function () {
			var groups = [];

			groups.push.apply(groups, getActiveRecordGroups());

			if (isGroupActive('session')) {
				groups.push('session');
			}

			return groups;
		};

		var getAllowedGroups = function () {
			var groups = [];

			groups.push.apply(groups, getAllowedRecordGroups());

			if (isGroupAllowed('session')) {
				groups.push('session');
			}

			return groups;
		};

		var getActiveRecordGroups = function () {
			var groups = [];

			angular.forEach(browserService.options.record.categories, function (category) {
				if (category.allow && category.active) {
					groups.push(category.id);
				}
			});

			return groups;
		};

		var getAllowedRecordGroups = function () {
			var groups = [];

			angular.forEach(browserService.options.record.categories, function (category) {
				if (category.allow) {
					groups.push(category.id);
				}
			});

			return groups;
		};

		browserService.isLastGroup = function (group) {
			var groups = getAllowedGroups();

			return groups.indexOf(group) == groups.length - 1;
		};

		browserService.showList = function (data) {
			return !!getActiveGroups()[data.level + 1];
		};

		//

		var callbackRecords = function (data, volume, groups) {
			var category = groups[data.level + 1];
			var tempData = {};
			var sessions = data.sessions || volume.sessions;

			angular.forEach(sessions, function (session, sid) {
				var any = false;
				angular.forEach(session.records, function (record) {
					if (volume.records[record.id].category == category) {
						if (!(record.id in tempData))
							tempData[record.id] = {};
						tempData[record.id][sid] = session;
						any = true;
					}
				});

				if (!any) {
					if (!('null' in tempData))
						tempData['null'] = {};
					tempData['null'][sid] = session;
				}
			});

			if (!$.isEmptyObject(tempData)) {
				angular.forEach(tempData, function (newSessions, recordID) {
					var newData;

					if (recordID != 'null') {
						newData = callbackItem(data, volume, newSessions, volume.records[recordID], category);
					}
					else {
						newData = callbackItem(data, volume, newSessions, {
							category: category,
							id: 0,
							measures: {}
						}, category);
					}

					callbackRecordChildren(newData, volume, groups);
				});

				data.items.reverse();
			}

			return data;
		};

		var callbackRecordChildren = function (data, volume, groups) {
			if (!browserService.getItemExpand(data)) {
				return data;
			}

			if (groups[data.level + 1] == 'session') {
				callbackSessions(data, volume);
			} else {
				callbackRecords(data, volume, groups);
			}

			return data;
		};

		var callbackSessions = function (data, volume) {
			var sessions = data.sessions || volume.sessions;

			angular.forEach(sessions, function (session) {
				var newData = callbackItem(data, volume, undefined, session, 'session');

				callbackSessionChildren(newData);
			});

			return data;
		};

		var callbackSessionChildren = function (data) {
			if (!browserService.getItemExpand(data)) {
				return data;
			}

			browserService.loading = false;
		};

		var callbackItem = function (data, volume, sessions, object, group) {
			var option = getOptionByGroup(group);

			var id = 'data-' + group + '-' + object.id;

			var newData = {
				parent: data,
				volume: volume,
				sessions: sessions,
				level: data.level + 1,

				id: id,
				object: object,
				permission: object.permission || volume.permission,
				group: group,
				items: [],

				select: false,
				expand: (focus && focus.id == group) ? ((angular.isDefined(focusInvert)) ? focusInvert : false) : option.expand,
				limit: 10
			};

			if (group == 'session') {
				var newSegment;
				var records = volume.sessions[newData.object.id].records;
				var cur, obj;
				var union = function (seg, c) {
					if (c.id === obj.id) {
						/* if record coverage is disjoint we pretend it's continuous: */
						seg = typeService.segmentUnion(seg, c.segment);
					}
					return seg;
				};
				for (cur = newData.parent; (obj = cur.object); cur = cur.parent) {
					if (obj.id !== 0)
						newSegment = typeService.segmentIntersect(newSegment,
							records.reduce(union, null));
				}
				newData.segment = newSegment;
				if (typeService.segmentEmpty(newSegment)) {
					return newData; //in order to not push empty segmented things (contradictory constraints) onto list
				}
			}

			browserService.groups[group].push(newData);

			if (group == 'session' && object.top) {
				data.items.unshift(newData);
			}
			else {
				data.items.push(newData);
			}

			return newData;
		};

		//

		var recordGroupToggle;

		browserService.setRecordGroupToggle = function (group) {
			if (group == 'add') {
				var c = 0, maybe;

				angular.forEach(browserService.options.record.categories, function (recordGroup) {
					if (!recordGroup.active) {
						maybe = recordGroup;
						c++;
					}
				});

				if (c == 1) {
					browserService.addRecordGroup(maybe);
					return true;
				}
			}

			recordGroupToggle = angular.isUndefined(recordGroupToggle) ? group : undefined;
		};

		browserService.clearRecordGroupToggle = function () {
			if (angular.isDefined(recordGroupToggle)) {
				recordGroupToggle = undefined;
			}
		};

		browserService.isRecordGroupToggle = function (group) {
			return recordGroupToggle == group;
		};

		//

		browserService.canAddRecordGroup = function () {
			var canAdd = false;

			angular.forEach(browserService.options.record.categories, function (recordGroup) {
				if (!canAdd && !recordGroup.active) {
					canAdd = true;
				}
			});

			return canAdd;
		};

		browserService.addRecordGroup = function (group) {
			browserService.setRecordGroupToggle(undefined);

			var i = browserService.options.record.categories.index(group);

			group.active = true;

			browserService.options.record.categories.push(browserService.options.record.categories.splice(i, 1)[0]);

			rebuildData(group);
		};

		browserService.canRemoveRecordGroup = function () {
			return true;
		};

		browserService.removeRecordGroup = function (group) {
			group.active = false;

			var group_i = browserService.options.record.categories.index(group);

			browserService.options.record.categories.splice(group_i, 1);
			browserService.options.record.categories.push(group);

			rebuildData();
		};

		browserService.switchRecordGroup = function (group, maybe) {
			browserService.setRecordGroupToggle(undefined);

			var group_i = browserService.options.record.categories.index(group),
				maybe_i = browserService.options.record.categories.index(maybe);

			if (group.active != maybe.active) {
				group.active = !group.active;
				maybe.active = !maybe.active;
			}

			browserService.options.record.categories[group_i] = browserService.options.record.categories.splice(maybe_i, 1, browserService.options.record.categories[group_i])[0];

			rebuildData(maybe);
		};

		//

		browserService.setItemExpand = function (data, expand) {
			if (!data.expand && expand !== false) {
				data.expand = true;

				if (!angular.isArray(data.items) || data.items.length === 0) {
					updateData(data);
				}
			} else if (data.expand && expand !== true) {
				data.expand = false;

				if (data == browserService.player) {
					browserService.setItemPlayer(undefined);
				}
			}

			return data;
		};

		browserService.getItemExpand = function (data) {
			return data.expand;
		};

		browserService.canExpand = function (data) {
			return data.level >= 0 && getActiveGroups()[data.level + 1];
		};

		//

		var getOptionByGroup = function (group) {
			if (group == 'session')
				return browserService.options.session;
			else
				return browserService.options.record.categories.find({id: group});
		};

		var getLevelByGroup = function (group) {
			return getActiveGroups().indexOf(group);
		};

		//

		browserService.player = undefined;

		browserService.setItemPlayer = function (data) {
			var newPlayer, newPlayed;

			if (angular.isUndefined(data)) {
				newPlayed = undefined;
				newPlayer = undefined;
			} else {
				newPlayed = data.items[0] || undefined;
				newPlayer = data;
			}

			if (angular.isUndefined(browserService.player)) {
				browserService.player = newPlayer;

				browserService.player.player = true;

				browserService.player.played = newPlayed;
			} else if (browserService.player != newPlayer) {
				browserService.player.player = false;

				browserService.player = newPlayer;

				if (angular.isDefined(browserService.player)) {
					browserService.player.player = true;
					browserService.player.played = newPlayed;
				}
			} else if (browserService.player.played != newPlayed) {
				browserService.player.played = newPlayed;
			} else {
				browserService.player.player = false;

				browserService.player = undefined;
			}

			if (data && data.parent && data.parent.id)
				display.scrollTo($('#' + data.parent.id).find('.browser-controller'));

			return browserService.player;
		};

		//

		return browserService;
	}
]);
<|endoftext|>


<commit_before>var compressor = require('../src/compressor'),
	es = require('event-stream'),
	fs = require('fs'),
	gulp = require('gulp'),
	path = require('path');

describe( 'compressor', function() {

	it( 'should compress a file', function( done ) {

		var filename = './test/support/file.html';
		var originalSize = fs.statSync( filename ).size;

		gulp.src( filename )
			.pipe( compressor() )
			.pipe( es.map( function( file, cb ) {
				expect( file.contents.length ).to.be.lessThan(
					originalSize / 2
				);
				cb( null, file );
				done();
			} ) );

	} );

	it( 'should add GZ extension', function( done ) {

		gulp.src('./test/support/file.js')
			.pipe( compressor() )
			.pipe( es.map( function( file, cb ) {
				expect(
					path.basename( file.path )
				).to.equal('file.js.gz');
				cb( null, file );
				done();
			} ) );

	} );

	it( 'should not compress GIFs', function( done ) {

		var filename = './test/support/file.gif';
		var originalSize = fs.statSync( filename ).size;

		gulp.src( filename )
			.pipe( compressor() )
			.pipe( es.map( function( file, cb ) {
				expect(
					path.basename( file.path )
				).to.equal('file.gif');
				expect( file.contents.length ).to.equal( originalSize );
				cb( null, file );
				done();
			} ) );

	} );

	describe( 'mocked zlib', function() {

		var error = new Error('oh no');
		var zlib = require('zlib');

		beforeEach( function() {
			zlib._gzip = zlib.gzip;
			zlib.gzip = function( contents, cb ) {
				cb( error );
			};
		} );

		afterEach( function() {
			zlib.gzip = zlib._gzip;
		} );

		it( 'should pass along errors from zlib', function( done ) {
			gulp.src('./test/support/file.js')
				.pipe( compressor() )
				.on( 'error', function( err ) {
					expect( err ).to.equal( error );
					done();
				});
		} );

	} );

} );
<commit_msg>Using the on('data') event instead of event-stream's map.<commit_after>var compressor = require('../src/compressor'),
	fs = require('fs'),
	gulp = require('gulp'),
	path = require('path');

describe( 'compressor', function() {

	it( 'should compress a file', function( done ) {

		var filename = './test/support/file.html';
		var originalSize = fs.statSync( filename ).size;

		gulp.src( filename )
			.pipe( compressor() )
			.on( 'data', function( file ) {
				expect( file.contents.length ).to.be.lessThan(
					originalSize / 2
				);
				done();
			} );

	} );

	it( 'should add GZ extension', function( done ) {

		gulp.src('./test/support/file.js')
			.pipe( compressor() )
			.on( 'data', function( file ) {
				expect(
					path.basename( file.path )
				).to.equal('file.js.gz');
				done();
			} );

	} );

	it( 'should not compress GIFs', function( done ) {

		var filename = './test/support/file.gif';
		var originalSize = fs.statSync( filename ).size;

		gulp.src( filename )
			.pipe( compressor() )
			.on( 'data', function( file ) {
				expect(
					path.basename( file.path )
				).to.equal('file.gif');
				expect( file.contents.length ).to.equal( originalSize );
				done();
			} );

	} );

	describe( 'mocked zlib', function() {

		var error = new Error('oh no');
		var zlib = require('zlib');

		beforeEach( function() {
			zlib._gzip = zlib.gzip;
			zlib.gzip = function( contents, cb ) {
				cb( error );
			};
		} );

		afterEach( function() {
			zlib.gzip = zlib._gzip;
		} );

		it( 'should pass along errors from zlib', function( done ) {
			gulp.src('./test/support/file.js')
				.pipe( compressor() )
				.on( 'error', function( err ) {
					expect( err ).to.equal( error );
					done();
				});
		} );

	} );

} );
<|endoftext|>


<commit_before>/*global describe, before, after, it, beforeEach, afterEach */
'use strict';
var fs = require('fs');
var events = require('events');
var assert = require('assert');
var log = require('yeoman-environment').util.log();
var Conflicter = require('../lib/util/conflicter');
var _ = require('lodash');
var inquirer = require('inquirer');

var fileFoo = {
  file: 'foo.js',
  content: 'var foo = "foo";\n'
};
var fileBar = {
  file: 'boo.js',
  content: 'var boo = "boo";\n'
};

describe('Conflicter', function () {
  beforeEach(function () {
    var mockAdapter = {
      prompt: function () {},
      diff: function () {},
      log: log
    };
    this.conflicter = new Conflicter(mockAdapter);
  });

  it('is an event emitter', function () {
    assert.ok(this.conflicter instanceof events.EventEmitter);
  });

  it('#add()', function () {
    this.conflicter.add(__filename);
    var conflict = this.conflicter.pop();
    assert.deepEqual(conflict.file, __filename);
    assert.deepEqual(conflict.content, fs.readFileSync(__filename, 'utf8'));
  });

  it('#pop()', function () {
    this.conflicter.add(fileFoo);
    this.conflicter.add(fileBar);
    var conflict = this.conflicter.pop();
    assert.deepEqual(conflict.file, 'boo.js');
    assert.deepEqual(conflict.content, 'var boo = "boo";\n');
  });

  it('#shift()', function () {
    this.conflicter.add(fileFoo);
    this.conflicter.add(fileBar);
    var conflict = this.conflicter.shift();
    assert.deepEqual(conflict.file, 'foo.js');
    assert.deepEqual(conflict.content, 'var foo = "foo";\n');
  });

  describe('#resolve()', function () {
    it('wihout conflict', function (done) {
      this.conflicter.resolve(done);
    });

    it('with at least one, without async callback handling', function (done) {
      var conflicts = 0;
      var callbackExecuted = false;

      this.conflicter.add(__filename);
      this.conflicter.add({
        file: 'foo.js',
        content: 'var foo = "foo";\n'
      });

      // called.
      this.conflicter.once('resolved:' + __filename, function () {
        conflicts++;
      });

      // not called.
      this.conflicter.once('resolved:foo.js', function () {
        conflicts++;
      });

      this.conflicter.resolve(function () {
        callbackExecuted = true;
      });

      assert(conflicts, 1);
      assert(!callbackExecuted);
      done();
    });

    it('with at least one, with async callback handling', function (done) {
      var called = 0;

      this.conflicter.add(__filename);
      this.conflicter.add({
        file: 'foo.js',
        content: 'var foo = "foo";\n'
      });

      this.conflicter.once('resolved:' + __filename, function (config) {
        called++;
        config.callback();
      });

      this.conflicter.once('resolved:foo.js', function (config) {
        called++;
        config.callback();
      });

      this.conflicter.resolve(function () {
        assert(called, 2);
        done();
      });
    });
  });

  describe('#collision()', function () {
    var me = fs.readFileSync(__filename, 'utf8');

    beforeEach(function () {
      var prompt = inquirer.createPromptModule();
      var mockAdapter = {
        prompt: prompt,
        diff: function () {},
        log: log
      };
      var self = this;
      var Prompt = function (q, cb) {
        this.answer = _.where(q.choices, { key: self.answer })[0].value;
      };

      Prompt.prototype.run = function (cb) {
        cb(this.answer);
      };
      prompt.registerPrompt('expand', Prompt);
      this.conflicter = new Conflicter(mockAdapter);
    });

    afterEach(function () {
      delete this.conflicter.force;
    });

    it('identical status', function (done) {
      this.conflicter.collision(__filename, me, function (status) {
        assert.equal(status, 'identical');
        done();
      });
    });

    it('create status', function (done) {
      this.conflicter.collision('file-who-does-not-exist.js', '', function (status) {
        assert.equal(status, 'create');
        done();
      });
    });

    it('user choose "yes"', function (done) {
      this.answer = 'y';
      this.conflicter.collision(__filename, '', function (status) {
        assert.equal(status, 'force');
        done();
      });
    });

    it('user chosse "skip"', function (done) {
      this.answer = 'n';
      this.conflicter.collision(__filename, '', function (status) {
        assert.equal(status, 'skip');
        done();
      });
    });

    it('user choose "all"', function (done) {
      this.answer = 'a';
      this.conflicter.collision(__filename, '', function (status) {
        assert.equal(status, 'force');
        done();
      });
    });

    it('force conflict status', function (done) {
      this.conflicter.force = true;
      this.conflicter.collision(__filename, '', function (status) {
        assert.equal(status, 'force');
        done();
      });
    });
  });

  describe('#diff()', function () {

    beforeEach(function () {
      this.oldConflicter = this.conflicter;
      this.adapterMock = {
        diff: null,
        log: function () {}
      };
      this.conflicter = new Conflicter(this.adapterMock);
    });

    afterEach(function () {
      this.conflicter = this.oldConflicter;
    });

    it('Calls adapter diff function', function () {
      var callCount = 0;
      this.adapterMock.diff = function () {
        callCount++;
      };
      this.conflicter.diff('actual', 'expected');
      assert(callCount, 1);
    });

  });

  describe('#_ask()', function () {

    beforeEach(function () {
      this.oldConflicter = this.conflicter;
      this.adapterMock = {
        prompt: function (config, cb) {
          cb({
            overwrite: this.answer
          });
        },
        err: null,
        answer: null
      };
      this.conflicter = new Conflicter(this.adapterMock);
    });

    afterEach(function () {
      this.conflicter = this.oldConflicter;
    });

    it('Calls answer related function and pass a callback', function (done) {
      var callCount = 0;
      this.adapterMock.answer = function (cb) {
        callCount++;
        cb();
      };
      this.conflicter._ask('/tmp/file', 'my file contents', function () {
        assert(callCount, 1);
        done();
      });
    });

  });
});
<commit_msg>Refactor conflicter test to be simpler<commit_after>/*global describe, before, after, it, beforeEach, afterEach */
'use strict';
var fs = require('fs');
var assert = require('assert');
var Conflicter = require('../lib/util/conflicter');
var TestAdapter = require('../lib/test/adapter').TestAdapter;
var _ = require('lodash');
var inquirer = require('inquirer');
var sinon = require('sinon');

var fileFoo = {
  file: 'foo.js',
  content: 'var foo = "foo";\n'
};
var fileBar = {
  file: 'boo.js',
  content: 'var boo = "boo";\n'
};

describe('Conflicter', function () {
  beforeEach(function () {
    this.conflicter = new Conflicter(new TestAdapter());
  });

  it('is an event emitter', function () {
    assert.ok(this.conflicter instanceof require('events').EventEmitter);
  });

  it('#add()', function () {
    this.conflicter.add(__filename);
    var conflict = this.conflicter.pop();
    assert.deepEqual(conflict.file, __filename);
    assert.deepEqual(conflict.content, fs.readFileSync(__filename, 'utf8'));
  });

  it('#pop()', function () {
    this.conflicter.add(fileFoo);
    this.conflicter.add(fileBar);
    var conflict = this.conflicter.pop();
    assert.deepEqual(conflict.file, 'boo.js');
    assert.deepEqual(conflict.content, 'var boo = "boo";\n');
  });

  it('#shift()', function () {
    this.conflicter.add(fileFoo);
    this.conflicter.add(fileBar);
    var conflict = this.conflicter.shift();
    assert.deepEqual(conflict.file, 'foo.js');
    assert.deepEqual(conflict.content, 'var foo = "foo";\n');
  });

  describe('#resolve()', function () {
    it('wihout conflict', function (done) {
      this.conflicter.resolve(done);
    });

    it('with at least one, without async callback handling', function (done) {
      var conflicts = 0;
      var callbackExecuted = false;

      this.conflicter.add(__filename);
      this.conflicter.add({
        file: 'foo.js',
        content: 'var foo = "foo";\n'
      });

      // called.
      this.conflicter.once('resolved:' + __filename, function () {
        conflicts++;
      });

      // not called.
      this.conflicter.once('resolved:foo.js', function () {
        conflicts++;
      });

      this.conflicter.resolve(function () {
        callbackExecuted = true;
      });

      assert(conflicts, 1);
      assert(!callbackExecuted);
      done();
    });

    it('with at least one, with async callback handling', function (done) {
      var called = 0;

      this.conflicter.add(__filename);
      this.conflicter.add({
        file: 'foo.js',
        content: 'var foo = "foo";\n'
      });

      this.conflicter.once('resolved:' + __filename, function (config) {
        called++;
        config.callback();
      });

      this.conflicter.once('resolved:foo.js', function (config) {
        called++;
        config.callback();
      });

      this.conflicter.resolve(function () {
        assert(called, 2);
        done();
      });
    });
  });

  describe('#collision()', function () {
    beforeEach(function () {
      var self = this;
      var mockAdapter = new TestAdapter();

      // TODO: This test must be decouple from the inquirer module. This is very ugly...
      mockAdapter.prompt = inquirer.createPromptModule();
      var Prompt = function (q, cb) {
        this.answer = _.where(q.choices, { key: self.answer })[0].value;
      };
      Prompt.prototype.run = function (cb) {
        cb(this.answer);
      };
      mockAdapter.prompt.registerPrompt('expand', Prompt);

      this.conflicter = new Conflicter(mockAdapter);
    });

    afterEach(function () {
      delete this.conflicter.force;
    });

    it('identical status', function (done) {
      var me = fs.readFileSync(__filename, 'utf8');
      this.conflicter.collision(__filename, me, function (status) {
        assert.equal(status, 'identical');
        done();
      });
    });

    it('create status', function (done) {
      this.conflicter.collision('file-who-does-not-exist.js', '', function (status) {
        assert.equal(status, 'create');
        done();
      });
    });

    it('user choose "yes"', function (done) {
      this.answer = 'y';
      this.conflicter.collision(__filename, '', function (status) {
        assert.equal(status, 'force');
        done();
      });
    });

    it('user chosse "skip"', function (done) {
      this.answer = 'n';
      this.conflicter.collision(__filename, '', function (status) {
        assert.equal(status, 'skip');
        done();
      });
    });

    it('user choose "all"', function (done) {
      this.answer = 'a';
      this.conflicter.collision(__filename, '', function (status) {
        assert.equal(status, 'force');
        done();
      });
    });

    it('force conflict status', function (done) {
      this.conflicter.force = true;
      this.conflicter.collision(__filename, '', function (status) {
        assert.equal(status, 'force');
        done();
      });
    });
  });

  describe('#diff()', function () {
    beforeEach(function () {
      this.adapter = new TestAdapter();
      this.conflicter = new Conflicter(this.adapter);
    });

    it('Calls adapter diff function', function () {
      this.conflicter.diff('actual', 'expected');
      sinon.assert.calledOnce(this.adapter.diff);
    });
  });

  describe('#_ask()', function () {
    beforeEach(function () {
      this.answer = sinon.spy(function (cb) {
        cb('skip');
      });
      var adapter = new TestAdapter({ overwrite: this.answer });
      this.conflicter = new Conflicter(adapter);
    });

    it('Calls answer related function and pass a callback', function (done) {
      this.conflicter._ask('/tmp/file', 'my file contents', function () {
        sinon.assert.calledOnce(this.answer);
        done();
      }.bind(this));
    });
  });
});
<|endoftext|>


<commit_before>var expect = require('expect.js');
var io = require('../');
var hasCORS = require('has-cors');
var textBlobBuilder = require('text-blob-builder');

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

  it('should connect to localhost', function(done){
    var socket = io({ forceNew: true });
    socket.emit('hi');
    socket.on('hi', function(data){
      socket.disconnect();
      done();
    });
  });

  it('should not connect when autoConnect option set to false', function() {
    var socket = io({ forceNew: true, autoConnect: false });
    expect(socket.io.engine).to.not.be.ok();
    socket.disconnect();
  });

  it('should start two connections with same path', function(){
    var s1 = io('/');
    var s2 = io('/');

    expect(s1.io).to.not.be(s2.io);
    s1.disconnect();
    s2.disconnect();
  });

  it('should start two connections with same path and different querystrings', function(){
    var s1 = io('/?woot');
    var s2 = io('/');

    expect(s1.io).to.not.be(s2.io);
    s1.disconnect();
    s2.disconnect();
  });

  it('should work with acks', function(done){
    var socket = io({ forceNew: true });
    socket.emit('ack');
    socket.on('ack', function(fn){
      fn(5, { test: true });
    });
    socket.on('got it', function(){
      socket.disconnect();
      done();
    });
  });

  it('should receive date with ack', function(done){
    var socket = io({ forceNew: true });
    socket.emit('getAckDate', { test: true }, function(data){
       expect(data).to.be.a('string');
       socket.disconnect();
       done();
    });
  });

  it('should work with false', function(done){
    var socket = io({ forceNew: true });
    socket.emit('false');
    socket.on('false', function(f){
      expect(f).to.be(false);
      socket.disconnect();
      done();
    });
  });

  it('should receive utf8 multibyte characters', function(done) {
    var correct = [
      'てすと',
      'Я Б Г Д Ж Й',
      'Ä ä Ü ü ß',
      'utf8 — string',
      'utf8 — string'
    ];

    var socket = io({ forceNew: true });
    var i = 0;
    socket.on('takeUtf8', function(data) {
      expect(data).to.be(correct[i]);
      i++;
      if (i == correct.length) {
        socket.disconnect();
        done();
      }
    });
    socket.emit('getUtf8');
  });

  it('should connect to a namespace after connection established', function(done) {
    var manager = io.Manager();
    var socket = manager.socket('/');
    socket.on('connect', function(){
      var foo = manager.socket('/foo');
      foo.on('connect', function(){
        foo.close();
        socket.close();
        manager.close();
        done();
      });
    });
  });

  it('should open a new namespace after connection gets closed', function(done){
    var manager = io.Manager();
    var socket = manager.socket('/');
    socket.on('connect', function() {
      socket.disconnect();
    }).on('disconnect', function() {
      var foo = manager.socket('/foo');
      foo.on('connect', function() {
        foo.disconnect();
        manager.close();
        done();
      });
    });
  });

  it('should reconnect by default', function(done){
    var socket = io({ forceNew: true });
    socket.io.on('reconnect', function() {
      socket.disconnect();
      done();
    });

    setTimeout(function() {
      socket.io.engine.close();
    }, 500);
  });

  it('should reconnect manually', function(done) {
    var socket = io({ forceNew: true });
    socket.once('connect', function() {
      socket.disconnect();
    }).once('disconnect', function() {
      socket.once('connect', function() {
        socket.disconnect();
        done();
      });
      socket.connect();
    });
  });

  it('should reconnect automatically after reconnecting manually', function(done){
    var socket = io({ forceNew: true });
    socket.once('connect', function() {
      socket.disconnect();
    }).once('disconnect', function() {
      socket.on('reconnect', function() {
        socket.disconnect();
        done();
      });
      socket.connect();
      setTimeout(function() {
        socket.io.engine.close();
      }, 500);
    });
  });

  it('should attempt reconnects after a failed reconnect', function(done){
    var manager = io.Manager({ reconnection: true, timeout: 0, reconnectionAttempts: 2, reconnectionDelay: 10 });
    var socket = manager.socket('/timeout');
    socket.once('reconnect_failed', function() {
      var reconnects = 0;
      var reconnectCb = function() {
        reconnects++;
      };

      manager.on('reconnect_attempt', reconnectCb);
      manager.on('reconnect_failed', function failed() {
        expect(reconnects).to.be(2);
        socket.close();
        manager.close();
        done();
      });
      socket.connect();
    });
  });

  it('reconnect delay should increase every time', function(done){
    var manager = io.Manager({ reconnection: true, timeout: 0, reconnectionAttempts: 5, reconnectionDelay: 10, randomizationFactor: 0.2 });
    var socket = manager.socket('/timeout');
    var reconnects = 0, increasingDelay = true, startTime, prevDelay = 0;

    socket.on('connect_error', function() {
      startTime = new Date().getTime();
    });
    socket.on('reconnect_attempt', function() {
      reconnects++;
      var currentTime = new Date().getTime();
      var delay = currentTime - startTime;
      if (delay <= prevDelay) {
        increasingDelay = false;
      }
      prevDelay = delay;
    });

    socket.on('reconnect_failed', function failed() {
      expect(reconnects).to.be(5);
      expect(increasingDelay).to.be.ok();
      socket.close();
      manager.close();
      done();
    });
  });

  it('reconnect event should fire in socket', function(done){
    var socket = io({ forceNew: true });

    socket.on('reconnect', function() {
      socket.disconnect();
      done();
    });

    setTimeout(function() {
      socket.io.engine.close();
    }, 500);
  });

  it('should not reconnect when force closed', function(done){
    var socket = io('/invalid', { forceNew: true, timeout: 0, reconnectionDelay: 10 });
    socket.on('connect_error', function() {
      socket.on('reconnect_attempt', function() {
        expect().fail();
      });
      socket.disconnect();
      // set a timeout to let reconnection possibly fire
      setTimeout(function() {
        done();
      }, 500);
    });
  });

  it('should stop reconnecting when force closed', function(done){
    var socket = io('/invalid', { forceNew: true, timeout: 0, reconnectionDelay: 10 });
    socket.once('reconnect_attempt', function() {
      socket.on('reconnect_attempt', function() {
        expect().fail();
      });
      socket.disconnect();
      // set a timeout to let reconnection possibly fire
      setTimeout(function() {
        done();
      }, 500);
    });
  });

  it('should stop reconnecting on a socket and keep to reconnect on another', function(done){
    var manager = io.Manager();
    var socket1 = manager.socket('/');
    var socket2 = manager.socket('/asd');

    manager.on('reconnect_attempt', function() {
      socket1.on('connect', function() {
        expect().fail();
      });
      socket2.on('connect', function() {
        setTimeout(function() {
          socket2.disconnect();
          manager.disconnect();
          done();
        }, 500);
      });
      socket1.disconnect();
    });

    setTimeout(function() {
      manager.engine.close();
    }, 1000);
  });

  it('should try to reconnect twice and fail when requested two attempts with immediate timeout and reconnect enabled', function(done) {
    var manager = io.Manager({ reconnection: true, timeout: 0, reconnectionAttempts: 2, reconnectionDelay: 10 });
    var socket;

    var reconnects = 0;
    var reconnectCb = function() {
      reconnects++;
    };

    manager.on('reconnect_attempt', reconnectCb);
    manager.on('reconnect_failed', function failed() {
      expect(reconnects).to.be(2);
      socket.close();
      manager.close();
      done();
    });

    socket = manager.socket('/timeout');
  });

  it('should fire reconnect_* events on socket', function(done) {
    var manager = io.Manager({ reconnection: true, timeout: 0, reconnectionAttempts: 2, reconnectionDelay: 10 });
    var socket = manager.socket('/timeout_socket');

    var reconnects = 0;
    var reconnectCb = function(attempts) {
      reconnects++;
      expect(attempts).to.be(reconnects);
    };

    socket.on('reconnect_attempt', reconnectCb);
    socket.on('reconnect_failed', function failed() {
      expect(reconnects).to.be(2);
      socket.close();
      manager.close();
      done();
    });
  });

  it('should fire error on socket', function(done) {
    var manager = io.Manager({ reconnection: true });
    var socket = manager.socket('/timeout_socket');

    socket.on('error', function(data) {
      expect(data.code).to.be('test');
      socket.close();
      manager.close();
      done();
    });

    socket.on('connect', function() {
      manager.engine.onPacket({ type: 'error', data: 'test' });
    });
  });

  it('should fire reconnecting (on socket) with attempts number when reconnecting twice', function(done) {
    var manager = io.Manager({ reconnection: true, timeout: 0, reconnectionAttempts: 2, reconnectionDelay: 10 });
    var socket = manager.socket('/timeout_socket');

    var reconnects = 0;
    var reconnectCb = function(attempts) {
      reconnects++;
      expect(attempts).to.be(reconnects);
    };

    socket.on('reconnecting', reconnectCb);
    socket.on('reconnect_failed', function failed() {
      expect(reconnects).to.be(2);
      socket.close();
      manager.close();
      done();
    });
  });

  it('should not try to reconnect and should form a connection when connecting to correct port with default timeout', function(done) {
    var manager = io.Manager({ reconnection: true, reconnectionDelay: 10 });
    var cb = function() {
      socket.close();
      expect().fail();
    };
    manager.on('reconnect_attempt', cb);

    var socket = manager.socket('/valid');
    socket.on('connect', function(){
      // set a timeout to let reconnection possibly fire
      setTimeout(function() {
        socket.close();
        manager.close();
        done();
      }, 1000);
    });
  });

  // Ignore incorrect connection test for old IE due to no support for
  // `script.onerror` (see: http://requirejs.org/docs/api.html#ieloadfail)
  if (!global.document || hasCORS) {
    it('should try to reconnect twice and fail when requested two attempts with incorrect address and reconnect enabled', function(done) {
      var manager = io.Manager('http://localhost:3940', { reconnection: true, reconnectionAttempts: 2, reconnectionDelay: 10 });
      var socket = manager.socket('/asd');
      var reconnects = 0;
      var cb = function() {
        reconnects++;
      };

      manager.on('reconnect_attempt', cb);

      manager.on('reconnect_failed', function() {
        expect(reconnects).to.be(2);
        socket.disconnect();
        manager.close();
        done();
      });
    });

    it('should not try to reconnect with incorrect port when reconnection disabled', function(done) {
      var manager = io.Manager('http://localhost:9823', { reconnection: false });
      var cb = function() {
        socket.close();
        expect().fail();
      };
      manager.on('reconnect_attempt', cb);

      manager.on('connect_error', function(){
        // set a timeout to let reconnection possibly fire
        setTimeout(function() {
          socket.disconnect();
          manager.close();
          done();
        }, 1000);
      });

      var socket = manager.socket('/invalid');
    });
  }

  it('should emit date as string', function(done){
    var socket = io({ forceNew: true });
    socket.on('takeDate', function(data) {
      socket.close();
      expect(data).to.be.a('string');
      done();
    });
    socket.emit('getDate');
  });

  it('should emit date in object', function(done){
    var socket = io({ forceNew: true });
    socket.on('takeDateObj', function(data) {
      socket.close();
      expect(data).to.be.an('object');
      expect(data.date).to.be.a('string');
      done();
    });
    socket.emit('getDateObj');
  });

  if (!global.Blob && !global.ArrayBuffer) {
    it('should get base64 data as a last resort', function(done) {
      var socket = io({ forceNew: true });
      socket.on('takebin', function(a) {
        socket.disconnect();
        expect(a.base64).to.be(true);
        expect(a.data).to.eql('YXNkZmFzZGY=');
        done();
      });
      socket.emit('getbin');
    });
  }

  if (global.ArrayBuffer) {
    var base64 = require('base64-arraybuffer');

    it('should get binary data (as an ArrayBuffer)', function(done){
      var socket = io({ forceNew: true });
      socket.emit('doge');
      socket.on('doge', function(buffer){
        expect(buffer instanceof ArrayBuffer).to.be(true);
        socket.disconnect();
        done();
      });
    });

    it('should send binary data (as an ArrayBuffer)', function(done){
      var socket = io({ forceNew: true });
      socket.on('buffack', function(){
        socket.disconnect();
        done();
      });
      var buf = base64.decode('asdfasdf');
      socket.emit('buffa', buf);
    });

    it('should send binary data (as an ArrayBuffer) mixed with json', function(done) {
      var socket = io({ forceNew: true });
      socket.on('jsonbuff-ack', function() {
        socket.disconnect();
        done();
      });
      var buf = base64.decode('howdy');
      socket.emit('jsonbuff', {hello: 'lol', message: buf, goodbye: 'gotcha'});
    });

    it('should send events with ArrayBuffers in the correct order', function(done) {
      var socket = io({ forceNew: true });
      socket.on('abuff2-ack', function() {
        socket.disconnect();
        done();
      });
      var buf = base64.decode('abuff1');
      socket.emit('abuff1', buf);
      socket.emit('abuff2', 'please arrive second');
    });
  }

  if (global.Blob && null != textBlobBuilder('xxx')) {
    it('should send binary data (as a Blob)', function(done){
      var socket = io({ forceNew: true });
      socket.on('back', function(){
        socket.disconnect();
        done();
      });
      var blob = textBlobBuilder('hello world');
      socket.emit('blob', blob);
    });

    it('should send binary data (as a Blob) mixed with json', function(done) {
      var socket = io({ forceNew: true });
      socket.on('jsonblob-ack', function() {
        socket.disconnect();
        done();
      });
      var blob = textBlobBuilder('EEEEEEEEE');
      socket.emit('jsonblob', {hello: 'lol', message: blob, goodbye: 'gotcha'});
    });

    it('should send events with Blobs in the correct order', function(done) {
      var socket = io({ forceNew: true });
      socket.on('blob3-ack', function() {
        socket.disconnect();
        done();
      });
      var blob = textBlobBuilder('BLOBBLOB');
      socket.emit('blob1', blob);
      socket.emit('blob2', 'second');
      socket.emit('blob3', blob);
    });
  }
});
<commit_msg>add a test for the case reconnection doesn't work<commit_after>var expect = require('expect.js');
var io = require('../');
var hasCORS = require('has-cors');
var textBlobBuilder = require('text-blob-builder');

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

  it('should connect to localhost', function(done){
    var socket = io({ forceNew: true });
    socket.emit('hi');
    socket.on('hi', function(data){
      socket.disconnect();
      done();
    });
  });

  it('should not connect when autoConnect option set to false', function() {
    var socket = io({ forceNew: true, autoConnect: false });
    expect(socket.io.engine).to.not.be.ok();
    socket.disconnect();
  });

  it('should start two connections with same path', function(){
    var s1 = io('/');
    var s2 = io('/');

    expect(s1.io).to.not.be(s2.io);
    s1.disconnect();
    s2.disconnect();
  });

  it('should start two connections with same path and different querystrings', function(){
    var s1 = io('/?woot');
    var s2 = io('/');

    expect(s1.io).to.not.be(s2.io);
    s1.disconnect();
    s2.disconnect();
  });

  it('should work with acks', function(done){
    var socket = io({ forceNew: true });
    socket.emit('ack');
    socket.on('ack', function(fn){
      fn(5, { test: true });
    });
    socket.on('got it', function(){
      socket.disconnect();
      done();
    });
  });

  it('should receive date with ack', function(done){
    var socket = io({ forceNew: true });
    socket.emit('getAckDate', { test: true }, function(data){
       expect(data).to.be.a('string');
       socket.disconnect();
       done();
    });
  });

  it('should work with false', function(done){
    var socket = io({ forceNew: true });
    socket.emit('false');
    socket.on('false', function(f){
      expect(f).to.be(false);
      socket.disconnect();
      done();
    });
  });

  it('should receive utf8 multibyte characters', function(done) {
    var correct = [
      'てすと',
      'Я Б Г Д Ж Й',
      'Ä ä Ü ü ß',
      'utf8 — string',
      'utf8 — string'
    ];

    var socket = io({ forceNew: true });
    var i = 0;
    socket.on('takeUtf8', function(data) {
      expect(data).to.be(correct[i]);
      i++;
      if (i == correct.length) {
        socket.disconnect();
        done();
      }
    });
    socket.emit('getUtf8');
  });

  it('should connect to a namespace after connection established', function(done) {
    var manager = io.Manager();
    var socket = manager.socket('/');
    socket.on('connect', function(){
      var foo = manager.socket('/foo');
      foo.on('connect', function(){
        foo.close();
        socket.close();
        manager.close();
        done();
      });
    });
  });

  it('should open a new namespace after connection gets closed', function(done){
    var manager = io.Manager();
    var socket = manager.socket('/');
    socket.on('connect', function() {
      socket.disconnect();
    }).on('disconnect', function() {
      var foo = manager.socket('/foo');
      foo.on('connect', function() {
        foo.disconnect();
        manager.close();
        done();
      });
    });
  });

  it('should reconnect by default', function(done){
    var socket = io({ forceNew: true });
    socket.io.on('reconnect', function() {
      socket.disconnect();
      done();
    });

    setTimeout(function() {
      socket.io.engine.close();
    }, 500);
  });

  it('should reconnect manually', function(done) {
    var socket = io({ forceNew: true });
    socket.once('connect', function() {
      socket.disconnect();
    }).once('disconnect', function() {
      socket.once('connect', function() {
        socket.disconnect();
        done();
      });
      socket.connect();
    });
  });

  it('should reconnect automatically after reconnecting manually', function(done){
    var socket = io({ forceNew: true });
    socket.once('connect', function() {
      socket.disconnect();
    }).once('disconnect', function() {
      socket.on('reconnect', function() {
        socket.disconnect();
        done();
      });
      socket.connect();
      setTimeout(function() {
        socket.io.engine.close();
      }, 500);
    });
  });

  it('should attempt reconnects after a failed reconnect', function(done){
    var manager = io.Manager({ reconnection: true, timeout: 0, reconnectionAttempts: 2, reconnectionDelay: 10 });
    var socket = manager.socket('/timeout');
    socket.once('reconnect_failed', function() {
      var reconnects = 0;
      var reconnectCb = function() {
        reconnects++;
      };

      manager.on('reconnect_attempt', reconnectCb);
      manager.on('reconnect_failed', function failed() {
        expect(reconnects).to.be(2);
        socket.close();
        manager.close();
        done();
      });
      socket.connect();
    });
  });

  it('reconnect delay should increase every time', function(done){
    var manager = io.Manager({ reconnection: true, timeout: 0, reconnectionAttempts: 5, reconnectionDelay: 10, randomizationFactor: 0.2 });
    var socket = manager.socket('/timeout');
    var reconnects = 0, increasingDelay = true, startTime, prevDelay = 0;

    socket.on('connect_error', function() {
      startTime = new Date().getTime();
    });
    socket.on('reconnect_attempt', function() {
      reconnects++;
      var currentTime = new Date().getTime();
      var delay = currentTime - startTime;
      if (delay <= prevDelay) {
        increasingDelay = false;
      }
      prevDelay = delay;
    });

    socket.on('reconnect_failed', function failed() {
      expect(reconnects).to.be(5);
      expect(increasingDelay).to.be.ok();
      socket.close();
      manager.close();
      done();
    });
  });

  it('reconnect event should fire in socket', function(done){
    var socket = io({ forceNew: true });

    socket.on('reconnect', function() {
      socket.disconnect();
      done();
    });

    setTimeout(function() {
      socket.io.engine.close();
    }, 500);
  });

  it('should not reconnect when force closed', function(done){
    var socket = io('/invalid', { forceNew: true, timeout: 0, reconnectionDelay: 10 });
    socket.on('connect_error', function() {
      socket.on('reconnect_attempt', function() {
        expect().fail();
      });
      socket.disconnect();
      // set a timeout to let reconnection possibly fire
      setTimeout(function() {
        done();
      }, 500);
    });
  });

  it('should stop reconnecting when force closed', function(done){
    var socket = io('/invalid', { forceNew: true, timeout: 0, reconnectionDelay: 10 });
    socket.once('reconnect_attempt', function() {
      socket.on('reconnect_attempt', function() {
        expect().fail();
      });
      socket.disconnect();
      // set a timeout to let reconnection possibly fire
      setTimeout(function() {
        done();
      }, 500);
    });
  });

  it('should reconnect after stopping reconnection', function(done){
    var socket = io('/invalid', { forceNew: true, timeout: 0, reconnectionDelay: 10 });
    socket.once('reconnect_attempt', function() {
      socket.on('reconnect_attempt', function() {
        socket.disconnect();
        done();
      });
      socket.disconnect();
      socket.connect();
    });
  });

  it('should stop reconnecting on a socket and keep to reconnect on another', function(done){
    var manager = io.Manager();
    var socket1 = manager.socket('/');
    var socket2 = manager.socket('/asd');

    manager.on('reconnect_attempt', function() {
      socket1.on('connect', function() {
        expect().fail();
      });
      socket2.on('connect', function() {
        setTimeout(function() {
          socket2.disconnect();
          manager.disconnect();
          done();
        }, 500);
      });
      socket1.disconnect();
    });

    setTimeout(function() {
      manager.engine.close();
    }, 1000);
  });

  it('should try to reconnect twice and fail when requested two attempts with immediate timeout and reconnect enabled', function(done) {
    var manager = io.Manager({ reconnection: true, timeout: 0, reconnectionAttempts: 2, reconnectionDelay: 10 });
    var socket;

    var reconnects = 0;
    var reconnectCb = function() {
      reconnects++;
    };

    manager.on('reconnect_attempt', reconnectCb);
    manager.on('reconnect_failed', function failed() {
      expect(reconnects).to.be(2);
      socket.close();
      manager.close();
      done();
    });

    socket = manager.socket('/timeout');
  });

  it('should fire reconnect_* events on socket', function(done) {
    var manager = io.Manager({ reconnection: true, timeout: 0, reconnectionAttempts: 2, reconnectionDelay: 10 });
    var socket = manager.socket('/timeout_socket');

    var reconnects = 0;
    var reconnectCb = function(attempts) {
      reconnects++;
      expect(attempts).to.be(reconnects);
    };

    socket.on('reconnect_attempt', reconnectCb);
    socket.on('reconnect_failed', function failed() {
      expect(reconnects).to.be(2);
      socket.close();
      manager.close();
      done();
    });
  });

  it('should fire error on socket', function(done) {
    var manager = io.Manager({ reconnection: true });
    var socket = manager.socket('/timeout_socket');

    socket.on('error', function(data) {
      expect(data.code).to.be('test');
      socket.close();
      manager.close();
      done();
    });

    socket.on('connect', function() {
      manager.engine.onPacket({ type: 'error', data: 'test' });
    });
  });

  it('should fire reconnecting (on socket) with attempts number when reconnecting twice', function(done) {
    var manager = io.Manager({ reconnection: true, timeout: 0, reconnectionAttempts: 2, reconnectionDelay: 10 });
    var socket = manager.socket('/timeout_socket');

    var reconnects = 0;
    var reconnectCb = function(attempts) {
      reconnects++;
      expect(attempts).to.be(reconnects);
    };

    socket.on('reconnecting', reconnectCb);
    socket.on('reconnect_failed', function failed() {
      expect(reconnects).to.be(2);
      socket.close();
      manager.close();
      done();
    });
  });

  it('should not try to reconnect and should form a connection when connecting to correct port with default timeout', function(done) {
    var manager = io.Manager({ reconnection: true, reconnectionDelay: 10 });
    var cb = function() {
      socket.close();
      expect().fail();
    };
    manager.on('reconnect_attempt', cb);

    var socket = manager.socket('/valid');
    socket.on('connect', function(){
      // set a timeout to let reconnection possibly fire
      setTimeout(function() {
        socket.close();
        manager.close();
        done();
      }, 1000);
    });
  });

  // Ignore incorrect connection test for old IE due to no support for
  // `script.onerror` (see: http://requirejs.org/docs/api.html#ieloadfail)
  if (!global.document || hasCORS) {
    it('should try to reconnect twice and fail when requested two attempts with incorrect address and reconnect enabled', function(done) {
      var manager = io.Manager('http://localhost:3940', { reconnection: true, reconnectionAttempts: 2, reconnectionDelay: 10 });
      var socket = manager.socket('/asd');
      var reconnects = 0;
      var cb = function() {
        reconnects++;
      };

      manager.on('reconnect_attempt', cb);

      manager.on('reconnect_failed', function() {
        expect(reconnects).to.be(2);
        socket.disconnect();
        manager.close();
        done();
      });
    });

    it('should not try to reconnect with incorrect port when reconnection disabled', function(done) {
      var manager = io.Manager('http://localhost:9823', { reconnection: false });
      var cb = function() {
        socket.close();
        expect().fail();
      };
      manager.on('reconnect_attempt', cb);

      manager.on('connect_error', function(){
        // set a timeout to let reconnection possibly fire
        setTimeout(function() {
          socket.disconnect();
          manager.close();
          done();
        }, 1000);
      });

      var socket = manager.socket('/invalid');
    });
  }

  it('should emit date as string', function(done){
    var socket = io({ forceNew: true });
    socket.on('takeDate', function(data) {
      socket.close();
      expect(data).to.be.a('string');
      done();
    });
    socket.emit('getDate');
  });

  it('should emit date in object', function(done){
    var socket = io({ forceNew: true });
    socket.on('takeDateObj', function(data) {
      socket.close();
      expect(data).to.be.an('object');
      expect(data.date).to.be.a('string');
      done();
    });
    socket.emit('getDateObj');
  });

  if (!global.Blob && !global.ArrayBuffer) {
    it('should get base64 data as a last resort', function(done) {
      var socket = io({ forceNew: true });
      socket.on('takebin', function(a) {
        socket.disconnect();
        expect(a.base64).to.be(true);
        expect(a.data).to.eql('YXNkZmFzZGY=');
        done();
      });
      socket.emit('getbin');
    });
  }

  if (global.ArrayBuffer) {
    var base64 = require('base64-arraybuffer');

    it('should get binary data (as an ArrayBuffer)', function(done){
      var socket = io({ forceNew: true });
      socket.emit('doge');
      socket.on('doge', function(buffer){
        expect(buffer instanceof ArrayBuffer).to.be(true);
        socket.disconnect();
        done();
      });
    });

    it('should send binary data (as an ArrayBuffer)', function(done){
      var socket = io({ forceNew: true });
      socket.on('buffack', function(){
        socket.disconnect();
        done();
      });
      var buf = base64.decode('asdfasdf');
      socket.emit('buffa', buf);
    });

    it('should send binary data (as an ArrayBuffer) mixed with json', function(done) {
      var socket = io({ forceNew: true });
      socket.on('jsonbuff-ack', function() {
        socket.disconnect();
        done();
      });
      var buf = base64.decode('howdy');
      socket.emit('jsonbuff', {hello: 'lol', message: buf, goodbye: 'gotcha'});
    });

    it('should send events with ArrayBuffers in the correct order', function(done) {
      var socket = io({ forceNew: true });
      socket.on('abuff2-ack', function() {
        socket.disconnect();
        done();
      });
      var buf = base64.decode('abuff1');
      socket.emit('abuff1', buf);
      socket.emit('abuff2', 'please arrive second');
    });
  }

  if (global.Blob && null != textBlobBuilder('xxx')) {
    it('should send binary data (as a Blob)', function(done){
      var socket = io({ forceNew: true });
      socket.on('back', function(){
        socket.disconnect();
        done();
      });
      var blob = textBlobBuilder('hello world');
      socket.emit('blob', blob);
    });

    it('should send binary data (as a Blob) mixed with json', function(done) {
      var socket = io({ forceNew: true });
      socket.on('jsonblob-ack', function() {
        socket.disconnect();
        done();
      });
      var blob = textBlobBuilder('EEEEEEEEE');
      socket.emit('jsonblob', {hello: 'lol', message: blob, goodbye: 'gotcha'});
    });

    it('should send events with Blobs in the correct order', function(done) {
      var socket = io({ forceNew: true });
      socket.on('blob3-ack', function() {
        socket.disconnect();
        done();
      });
      var blob = textBlobBuilder('BLOBBLOB');
      socket.emit('blob1', blob);
      socket.emit('blob2', 'second');
      socket.emit('blob3', blob);
    });
  }
});
<|endoftext|>