<commit_before>describe('Pagelet', function () {
  'use strict';

  var Pagelet = require('../').extend({ name: 'test' })
    , custom = '/unexisting/absolute/path/to/prepend'
    , assume = require('assume')
    , pagelet
    , P;

  //
  // A lazy mans temper, we just want ignore all temper actions sometimes
  // because our pagelet is not exported using `.on(module)`
  //
  var temper = { prefetch: function () {} };

  beforeEach(function () {
    P = Pagelet.extend({
      directory: __dirname,
      view: 'fixtures/view.html',
      css: 'fixtures/style.css',
      js: '//cdnjs.cloudflare.com/ajax/libs/d3/3.4.8/d3.min.js',
      dependencies: [
        'http://code.jquery.com/jquery-2.0.0.js',
        'fixtures/custom.js'
      ]
    });

    pagelet = new P();
  });

  afterEach(function each() {
    pagelet = null;
  });

  it('rendering is asynchronously', function (done) {
    pagelet.get(pagelet.emits('called'));

    // Listening only till after the event is potentially emitted, will ensure
    // callbacks are called asynchronously by pagelet#render.
    pagelet.on('called', done);
  });

  describe('.on', function () {
    it('sets the pathname', function () {
      var pagelet = Pagelet.extend({});
      assume(pagelet.prototype.directory).to.equal('');

      pagelet.prototype.directory = 'foo';
      assume(pagelet.prototype.directory).to.equal('foo');

      pagelet.on(module);

      assume(pagelet.prototype.directory).to.be.a('string');
      assume(pagelet.prototype.directory).to.equal(__dirname);
    });

    it('resolves the `error` view');
    it('resolves the `css` files in to an array');
    it('resolves the `js` files in to an array');
    it('resolves the `dependencies` files in to an array');
  });

  describe('.resolve', function () {
    it('is a function', function () {
      assume(Pagelet.resolve).to.be.a('function');
      assume(P.resolve).to.be.a('function');
      assume(Pagelet.resolve).to.equal(P.resolve);
    });

    it('will resolve provided property on prototype', function () {
      var result = P.resolve('css');

      assume(result).to.equal(P);
      assume(P.prototype.css).to.be.an('array');
      assume(P.prototype.css.length).to.equal(1);
      assume(P.prototype.css[0]).to.equal(__dirname + '/fixtures/style.css');
    });

    it('can resolve multiple properties at once', function () {
      P.resolve(['css', 'js']);

      assume(P.prototype.css).to.be.an('array');
      assume(P.prototype.js).to.be.an('array');
      assume(P.prototype.css.length).to.equal(1);
      assume(P.prototype.js.length).to.equal(1);
    });

    it('can be provided with a custom source directory', function () {
      P.resolve('css', custom);

      assume(P.prototype.css[0]).to.equal(custom + '/fixtures/style.css');
    });

    it('only resolves local files', function () {
      P.resolve('js', custom);

      assume(P.prototype.js[0]).to.not.include(custom);
      assume(P.prototype.js[0]).to.equal('//cdnjs.cloudflare.com/ajax/libs/d3/3.4.8/d3.min.js');
    });

    it('can handle property values that are already an array', function () {
      P.resolve('dependencies', custom);

      assume(P.prototype.dependencies.length).to.equal(2);
      assume(P.prototype.dependencies[0]).to.not.include(custom);
      assume(P.prototype.dependencies[0]).to.equal('http://code.jquery.com/jquery-2.0.0.js');
      assume(P.prototype.dependencies[1]).to.equal(custom + '/fixtures/custom.js');
    });

    it('removes undefined values from the array before processing', function () {
      var Undef = P.extend({
        dependencies: P.prototype.dependencies.concat(
          undefined
        )
      });

      assume(Undef.prototype.dependencies.length).to.equal(3);

      Undef.resolve('dependencies', custom);
      assume(Undef.prototype.dependencies.length).to.equal(2);
      assume(Undef.prototype.dependencies).to.not.include(undefined);
    });

    it('can be overriden', function () {
      P.resolve = function () {
        throw new Error('fucked');
      };

      P.on({});
    });
  });

  describe('.optimize', function () {
    it('is a function', function () {
      assume(Pagelet.optimize).to.be.a('function');
      assume(P.optimize).to.be.a('function');
      assume(Pagelet.optimize).to.equal(P.optimize);
    });

    it('uses the supplied temper for prefetching', function (next) {
      var calls = 0;
      P.optimize({
        temper: {
          prefetch: function () {
            ++calls;
          }
        }
      }, function (err) {
        if (err) return next(err);

        assume(calls).to.equal(2);
        next();
      });
    });

    it('resolves the view', function (next) {
      assume(P.prototype.view).to.equal('fixtures/view.html');
      P.optimize({}, function () {
        assume(P.prototype.view).to.equal(__dirname +'/fixtures/view.html');
        next();
      });
    });

    it('prefetches the `view`');
    it('prefetches the `error` view');

    it('allows rpc as a string', function (next) {
      var X = P.extend({
        RPC: 'fixtures, bar',
        fixtures: function () {},
        bar: function () {}
      });

      X.optimize({ temper: temper }, function (err) {
        if (err) return next(err);

        assume(X.prototype.RPC).to.be.a('array');
        assume(X.prototype.RPC).to.have.length(2);
        assume(X.prototype.RPC).to.include('bar');
        assume(X.prototype.RPC).to.include('fixtures');

        next();
      });
    });

    it('checks if all rpc functions are available', function (next) {
      var X = P.extend({
        RPC: 'fixtures, bar',
        bar: function () {}
      });

      X.optimize({ temper: temper }, function (err) {
        assume(err).to.be.a('error');
        assume(err.message).to.include('fixtures');

        next();
      });
    });

    it('allows lowercase rpc', function (next) {
      var X = P.extend({
        rpc: ['fixtures', 'bar'],
        bar: function () {}
      });

      X.optimize({ temper: temper }, function (err) {
        assume(err).to.be.a('error');
        assume(err.message).to.include('fixtures');

        next();
      });
    });
  });

  describe('.traverse', function () {
    it('is a function', function () {
      assume(Pagelet.traverse).to.be.a('function');
      assume(P.traverse).to.be.a('function');
      assume(Pagelet.traverse).to.equal(P.traverse);
    });

    it('returns an array', function () {
      var one = P.traverse()
        , recur = P.extend({
            pagelets: {
              child: P.extend({ name: 'child' })
            }
          }).traverse('this one');

      assume(one).to.be.an('array');
      assume(one.length).to.equal(1);

      assume(recur).to.be.an('array');
      assume(recur.length).to.equal(2);
    });

    it('will at least return the pagelet', function () {
      var single = P.traverse();

      assume(single[0].prototype._parent).to.equal(undefined);
      assume(single[0].prototype.directory).to.equal(__dirname);
      assume(single[0].prototype.view).to.equal('fixtures/view.html');
    });

    it('does recursive pagelet discovery', function () {
      var recur = P.extend({
        pagelets: {
          child: P.extend({
            name: 'child' ,
            pagelets: {
              another: P.extend({ name: 'another' })
            }
          }),
        }
      }).traverse('multiple');

      assume(recur).is.an('array');
      assume(recur.length).to.equal(3);

      assume(recur[1].prototype.name).to.equal('child');
      assume(recur[2].prototype.name).to.equal('another');
    });

    it('sets the pagelets parent name on `_parent`', function () {
      var recur = P.extend({
        pagelets: {
          child: P.extend({
            name: 'child'
          })
        }
      }).traverse('parental');

      assume(recur[0].prototype._parent).to.equal(undefined);
      assume(recur[1].prototype._parent).to.equal('parental');
    });
  });
});
<commit_msg>[test] add resolve view test to .on<commit_after>describe('Pagelet', function () {
  'use strict';

  var Pagelet = require('../').extend({ name: 'test' })
    , custom = '/unexisting/absolute/path/to/prepend'
    , assume = require('assume')
    , pagelet
    , P;

  //
  // A lazy mans temper, we just want ignore all temper actions sometimes
  // because our pagelet is not exported using `.on(module)`
  //
  var temper = { prefetch: function () {} };

  beforeEach(function () {
    P = Pagelet.extend({
      directory: __dirname,
      view: 'fixtures/view.html',
      css: 'fixtures/style.css',
      js: '//cdnjs.cloudflare.com/ajax/libs/d3/3.4.8/d3.min.js',
      dependencies: [
        'http://code.jquery.com/jquery-2.0.0.js',
        'fixtures/custom.js'
      ]
    });

    pagelet = new P();
  });

  afterEach(function each() {
    pagelet = null;
  });

  it('rendering is asynchronously', function (done) {
    pagelet.get(pagelet.emits('called'));

    // Listening only till after the event is potentially emitted, will ensure
    // callbacks are called asynchronously by pagelet#render.
    pagelet.on('called', done);
  });

  describe('.on', function () {
    it('sets the pathname', function () {
      var pagelet = Pagelet.extend({});
      assume(pagelet.prototype.directory).to.equal('');

      pagelet.prototype.directory = 'foo';
      assume(pagelet.prototype.directory).to.equal('foo');

      pagelet.on(module);

      assume(pagelet.prototype.directory).to.be.a('string');
      assume(pagelet.prototype.directory).to.equal(__dirname);
    });

    it('resolves the view', function () {
      assume(P.prototype.view).to.equal('fixtures/view.html');

      P.on(module);
      assume(P.prototype.view).to.equal(__dirname +'/fixtures/view.html');
    });

    it('resolves the `error` view');
    it('resolves the `css` files in to an array');
    it('resolves the `js` files in to an array');
    it('resolves the `dependencies` files in to an array');
  });

  describe('.resolve', function () {
    it('is a function', function () {
      assume(Pagelet.resolve).to.be.a('function');
      assume(P.resolve).to.be.a('function');
      assume(Pagelet.resolve).to.equal(P.resolve);
    });

    it('will resolve provided property on prototype', function () {
      var result = P.resolve('css');

      assume(result).to.equal(P);
      assume(P.prototype.css).to.be.an('array');
      assume(P.prototype.css.length).to.equal(1);
      assume(P.prototype.css[0]).to.equal(__dirname + '/fixtures/style.css');
    });

    it('can resolve multiple properties at once', function () {
      P.resolve(['css', 'js']);

      assume(P.prototype.css).to.be.an('array');
      assume(P.prototype.js).to.be.an('array');
      assume(P.prototype.css.length).to.equal(1);
      assume(P.prototype.js.length).to.equal(1);
    });

    it('can be provided with a custom source directory', function () {
      P.resolve('css', custom);

      assume(P.prototype.css[0]).to.equal(custom + '/fixtures/style.css');
    });

    it('only resolves local files', function () {
      P.resolve('js', custom);

      assume(P.prototype.js[0]).to.not.include(custom);
      assume(P.prototype.js[0]).to.equal('//cdnjs.cloudflare.com/ajax/libs/d3/3.4.8/d3.min.js');
    });

    it('can handle property values that are already an array', function () {
      P.resolve('dependencies', custom);

      assume(P.prototype.dependencies.length).to.equal(2);
      assume(P.prototype.dependencies[0]).to.not.include(custom);
      assume(P.prototype.dependencies[0]).to.equal('http://code.jquery.com/jquery-2.0.0.js');
      assume(P.prototype.dependencies[1]).to.equal(custom + '/fixtures/custom.js');
    });

    it('removes undefined values from the array before processing', function () {
      var Undef = P.extend({
        dependencies: P.prototype.dependencies.concat(
          undefined
        )
      });

      assume(Undef.prototype.dependencies.length).to.equal(3);

      Undef.resolve('dependencies', custom);
      assume(Undef.prototype.dependencies.length).to.equal(2);
      assume(Undef.prototype.dependencies).to.not.include(undefined);
    });

    it('can be overriden', function () {
      P.resolve = function () {
        throw new Error('fucked');
      };

      P.on({});
    });
  });

  describe('.optimize', function () {
    it('is a function', function () {
      assume(Pagelet.optimize).to.be.a('function');
      assume(P.optimize).to.be.a('function');
      assume(Pagelet.optimize).to.equal(P.optimize);
    });

    it('uses the supplied temper for prefetching', function (next) {
      var calls = 0;
      P.optimize({
        temper: {
          prefetch: function () {
            ++calls;
          }
        }
      }, function (err) {
        if (err) return next(err);

        assume(calls).to.equal(2);
        next();
      });
    });

    it('resolves the view', function (next) {
      assume(P.prototype.view).to.equal('fixtures/view.html');
      P.optimize({}, function () {
        assume(P.prototype.view).to.equal(__dirname +'/fixtures/view.html');
        next();
      });
    });

    it('prefetches the `view`');
    it('prefetches the `error` view');

    it('allows rpc as a string', function (next) {
      var X = P.extend({
        RPC: 'fixtures, bar',
        fixtures: function () {},
        bar: function () {}
      });

      X.optimize({ temper: temper }, function (err) {
        if (err) return next(err);

        assume(X.prototype.RPC).to.be.a('array');
        assume(X.prototype.RPC).to.have.length(2);
        assume(X.prototype.RPC).to.include('bar');
        assume(X.prototype.RPC).to.include('fixtures');

        next();
      });
    });

    it('checks if all rpc functions are available', function (next) {
      var X = P.extend({
        RPC: 'fixtures, bar',
        bar: function () {}
      });

      X.optimize({ temper: temper }, function (err) {
        assume(err).to.be.a('error');
        assume(err.message).to.include('fixtures');

        next();
      });
    });

    it('allows lowercase rpc', function (next) {
      var X = P.extend({
        rpc: ['fixtures', 'bar'],
        bar: function () {}
      });

      X.optimize({ temper: temper }, function (err) {
        assume(err).to.be.a('error');
        assume(err.message).to.include('fixtures');

        next();
      });
    });
  });

  describe('.traverse', function () {
    it('is a function', function () {
      assume(Pagelet.traverse).to.be.a('function');
      assume(P.traverse).to.be.a('function');
      assume(Pagelet.traverse).to.equal(P.traverse);
    });

    it('returns an array', function () {
      var one = P.traverse()
        , recur = P.extend({
            pagelets: {
              child: P.extend({ name: 'child' })
            }
          }).traverse('this one');

      assume(one).to.be.an('array');
      assume(one.length).to.equal(1);

      assume(recur).to.be.an('array');
      assume(recur.length).to.equal(2);
    });

    it('will at least return the pagelet', function () {
      var single = P.traverse();

      assume(single[0].prototype._parent).to.equal(undefined);
      assume(single[0].prototype.directory).to.equal(__dirname);
      assume(single[0].prototype.view).to.equal('fixtures/view.html');
    });

    it('does recursive pagelet discovery', function () {
      var recur = P.extend({
        pagelets: {
          child: P.extend({
            name: 'child' ,
            pagelets: {
              another: P.extend({ name: 'another' })
            }
          }),
        }
      }).traverse('multiple');

      assume(recur).is.an('array');
      assume(recur.length).to.equal(3);

      assume(recur[1].prototype.name).to.equal('child');
      assume(recur[2].prototype.name).to.equal('another');
    });

    it('sets the pagelets parent name on `_parent`', function () {
      var recur = P.extend({
        pagelets: {
          child: P.extend({
            name: 'child'
          })
        }
      }).traverse('parental');

      assume(recur[0].prototype._parent).to.equal(undefined);
      assume(recur[1].prototype._parent).to.equal('parental');
    });
  });
});
<|endoftext|>


<commit_before>'use strict'
const test = require('tape')
const subsTest = require('../util')
const field = require('../util/field')

module.exports = function (type) {
  test(type, function (t) {
    const s = subsTest(
      t,
      {
        sibbling: {
          text: true
        },
        top: {
          a: 'its d!',
          b: {
            c: {
              d: {}
            }
          }
        }
      },
      field({
        top: {
          b: {
            c: {
              d: {
                $remove: true,
                $parent: {
                  $remove: true,
                  val: true,
                  $parent: {
                    $parent: {
                      a: { val: true }
                    }
                  }
                }
              }
            }
          }
        }
      }, type, '$parent')
    )
    const r = s('initial subscription', [ { path: 'top/a', type: 'new' } ])

    // for normal parent allways needs to flavour tree
    t.equal('$c' in r.tree.top, type === 'parent', 'correct $c in top')

    t.equal(
      '$c' in r.tree.top.b && 'c' in r.tree.top.b.$c,
      true,
      'got b in top/a/$c'
    )
    s('update top/a', [
      { path: 'top/a', type: 'update' }
    ], { top: { a: 'its more a!' } })

    s('remove top/b/c/d',
      // this is a bit weird as behvaeiour but ok...
      [ { path: 'top/b/c/d', type: 'remove' } ],
      { top: { b: { c: { d: null } } }
    })
    t.end()
  })

  test(type + ' - type', function (t) {
    // prop somehting with sid
    const s = subsTest(
      t,
      {
        types: {
          swag: {
            val: ''
          }
        },
        a: {
          b: {
            d: 'yes!',
            c: {
              type: 'swag'
            }
          }
        }
      },
      field({
        a: {
          b: {
            c: {
              $parent: {
                d: { val: true }
              }
            }
          }
        }
      }, type, '$parent')
    )
    s('initial subscription', [ { path: 'a/b/d', type: 'new' } ])
    t.end()
  })

  test(type + ' - $any', function (t) {
    const s = subsTest(
      t,
      {
        collection: {
          a: true,
          b: true
        }
      },
      field({
        collection: {
          $any: {
            $parent: {
              $parent: {
                focus: { val: true }
              }
            }
          }
        }
      }, type, '$parent')
    )
    s('initial subscription', [], {})
    s(
      'create a collection',
      [
        { path: 'focus', type: 'new' },
        { path: 'focus', type: 'new' }
      ],
      { focus: true }
    )
    t.end()
  })
}
<commit_msg>update<commit_after>'use strict'
const test = require('tape')
const subsTest = require('../util')
const field = require('../util/field')

module.exports = function (type) {
  test(type, function (t) {
    const s = subsTest(
      t,
      {
        sibbling: {
          text: true
        },
        top: {
          a: 'its d!',
          b: {
            c: {
              d: {}
            }
          }
        }
      },
      field({
        top: {
          b: {
            c: {
              d: {
                $remove: true,
                $parent: {
                  $remove: true,
                  val: true,
                  $parent: {
                    $parent: {
                      a: { val: true }
                    }
                  }
                }
              }
            }
          }
        }
      }, type, '$parent')
    )
    const r = s('initial subscription', [ { path: 'top/a', type: 'new' } ])

    // for normal parent allways needs to flavour tree
    t.equal('$c' in r.tree.top, type === 'parent', 'correct $c in top')

    t.equal(
      '$c' in r.tree.top.b && 'c' in r.tree.top.b.$c,
      true,
      'got b in top/a/$c'
    )
    s('update top/a', [
      { path: 'top/a', type: 'update' }
    ], { top: { a: 'its more a!' } })

    s('remove top/b/c/d',
      // this is a bit weird as behvaeiour but ok...
      [ { path: 'top/b/c/d', type: 'remove' } ],
      { top: { b: { c: { d: null } } }
    })
    t.end()
  })

  test(type + ' - type', function (t) {
    // prop somehting with sid
    const s = subsTest(
      t,
      {
        types: {
          swag: {
            val: ''
          }
        },
        a: {
          b: {
            d: 'yes!',
            c: {
              type: 'swag'
            }
          }
        }
      },
      field({
        a: {
          b: {
            c: {
              $parent: {
                d: { val: true }
              }
            }
          }
        }
      }, type, '$parent')
    )
    s('initial subscription', [ { path: 'a/b/d', type: 'new' } ])
    t.end()
  })

  test(type + ' - $any', function (t) {
    const s = subsTest(
      t,
      {
        collection: {
          a: true,
          b: true
        }
      },
      field({
        collection: {
          $any: {
            $parent: {
              $parent: {
                focus: { val: true }
              }
            }
          }
        }
      }, type, '$parent')
    )

    s('initial subscription', [], {})

    s(
      'create a collection',
      [
        { path: 'focus', type: 'new' },
        { path: 'focus', type: 'new' }
      ],
      { focus: true }
    )
    t.end()
  })
}
<|endoftext|>


<commit_before>var rp = require('../lib/rp.js');

describe('request tests', function () {

    it('should request google.com', function (done) {
        rp('http://www.google.com')
		    .then(done.bind(null, null))
		    .catch(done);
    });

    it('should catch errors', function (done) {
        rp('http://googl')
		    .then(done.bind(null, 'then callback was called'))
		    .catch(done.bind(null, null));
    });

});<commit_msg>Added tests around specified 'simple' behavior (which fail)<commit_after>var rp = require('../lib/rp.js');
var http = require('http');
var url = require('url');
var assert = require('assert');

describe('request tests', function () {
    var server;

    before(function(){
        // This creates a local server to test for various status codes. A request to /404 returns a 404, etc
        server = http.createServer(function(request, response){
            var path = url.parse(request.url).pathname;
            var status = parseInt(path.split('/')[1]);
            if(isNaN(status)) status = 555;
            response.writeHead(status);
            response.end();
        });
        server.listen(4000);
    });

    after(function(){
        server.close();
    })

    it('should resolve for 200 status code', function (done) {
        rp('http://localhost:4000/200')
            .then(function(){
                done();
            }).catch(function(){
                done(new Error('A 200 response should resolve, not reject'));
            });
    });

    it('should reject for http errors', function(done){
        rp('http://localhost:1/200')
            .then(function(){
                done(new Error('A failed request should reject, not resolve'))
            }).catch(function(){
                done();
            });
    })

    describe('simple tests', function(){

        it('should reject for 500 status code', function (done) {
            rp('http://localhost:4000/500')
                .then(function(){
                    done(new Error('A 500 response code should reject, not resolve'));
                }).catch(function(){
                    done();
                });
        });

    });

    describe('non-simple tests', function(){
        it('should resolve for 500 status code', function(done){
            var options = {
                url: 'http://localhost:4000/500',
                simple: false
            };
            rp(options)
                .then(function(){
                    done();
                }).catch(function(){
                    done(new Error('A 500 response code should resolve, not reject'));
                });
        })
    })

});<|endoftext|>


<commit_before>
var express = require('../')
  , request = require('./support/http')
  , assert = require('assert');

describe('res', function(){
  describe('.download(path)', function(){
    it('should transfer as an attachment', function(done){
      var app = express();

      app.use(function(req, res){
        res.download('test/fixtures/user.html');
      });

      request(app)
      .get('/')
      .end(function(err, res){
        res.should.have.header('Content-Type', 'text/html; charset=UTF-8');
        res.should.have.header('Content-Disposition', 'attachment; filename="user.html"');
        res.text.should.equal('
{{user.name}}
');
        done();
      });
    })
  })

  describe('.download(path, filename)', function(){
    it('should provide an alternate filename', function(done){
      var app = express();

      app.use(function(req, res){
        res.download('test/fixtures/user.html', 'document');
      });

      request(app)
      .get('/')
      .end(function(err, res){
        res.should.have.header('Content-Type', 'text/html; charset=UTF-8');
        res.should.have.header('Content-Disposition', 'attachment; filename="document"');
        done();
      });
    })
  })

  describe('.download(path, fn)', function(){
    it('should invoke the callback', function(done){
      var app = express()
        , calls = 0;

      app.use(function(req, res){
        res.download('test/fixtures/user.html', done);
      });

      request(app)
      .get('/')
      .end(function(err, res){
        res.should.have.header('Content-Type', 'text/html; charset=UTF-8');
        res.should.have.header('Content-Disposition', 'attachment; filename="user.html"');
      });
    })
  })

  describe('.download(path, filename, fn)', function(){
    it('should invoke the callback', function(done){
      var app = express()
        , calls = 0;

      app.use(function(req, res){
        res.download('test/fixtures/user.html', 'document', done);
      });

      request(app)
      .get('/')
      .end(function(err, res){
        res.should.have.header('Content-Type', 'text/html; charset=UTF-8');
        res.should.have.header('Content-Disposition', 'attachment; filename="document"');
      });
    })
  })
})
<commit_msg>add res.download() content-disposition on error removal test<commit_after>
var express = require('../')
  , request = require('./support/http')
  , assert = require('assert');

describe('res', function(){
  describe('.download(path)', function(){
    it('should transfer as an attachment', function(done){
      var app = express();

      app.use(function(req, res){
        res.download('test/fixtures/user.html');
      });

      request(app)
      .get('/')
      .end(function(err, res){
        res.should.have.header('Content-Type', 'text/html; charset=UTF-8');
        res.should.have.header('Content-Disposition', 'attachment; filename="user.html"');
        res.text.should.equal('
{{user.name}}
');
        done();
      });
    })
  })

  describe('.download(path, filename)', function(){
    it('should provide an alternate filename', function(done){
      var app = express();

      app.use(function(req, res){
        res.download('test/fixtures/user.html', 'document');
      });

      request(app)
      .get('/')
      .end(function(err, res){
        res.should.have.header('Content-Type', 'text/html; charset=UTF-8');
        res.should.have.header('Content-Disposition', 'attachment; filename="document"');
        done();
      });
    })
  })

  describe('.download(path, fn)', function(){
    it('should invoke the callback', function(done){
      var app = express()
        , calls = 0;

      app.use(function(req, res){
        res.download('test/fixtures/user.html', done);
      });

      request(app)
      .get('/')
      .end(function(err, res){
        res.should.have.header('Content-Type', 'text/html; charset=UTF-8');
        res.should.have.header('Content-Disposition', 'attachment; filename="user.html"');
      });
    })
  })

  describe('.download(path, filename, fn)', function(){
    it('should invoke the callback', function(done){
      var app = express()
        , calls = 0;

      app.use(function(req, res){
        res.download('test/fixtures/user.html', 'document', done);
      });

      request(app)
      .get('/')
      .end(function(err, res){
        res.should.have.header('Content-Type', 'text/html; charset=UTF-8');
        res.should.have.header('Content-Disposition', 'attachment; filename="document"');
      });
    })
  })

  describe('on failure', function(){
    it('should invoke the callback', function(done){
      var app = express()
        , calls = 0;

      app.use(function(req, res){
        res.download('test/fixtures/foobar.html', function(err){
          assert(404 == err.status);
          assert('ENOENT' == err.code);
          done();
        });
      });

      request(app)
      .get('/')
      .end(function(){});
    })

    it('should remove Content-Disposition', function(done){
      var app = express()
        , calls = 0;

      app.use(function(req, res){
        res.download('test/fixtures/foobar.html', function(err){
          res.end('failed');
        });
      });

      request(app)
      .get('/')
      .expect('failed')
      .end(function(err, res){
        if (err) return done(err);
        res.header.should.not.have.property('content-disposition');
        done();
      });
    })
  })
})
<|endoftext|>


<commit_before><commit_msg>Containment test<commit_after><|endoftext|>


<commit_before>'use strict';

const path = require('path');
const fs = require('fs');
const MongoClient = require('../..').MongoClient;
const TestConfiguration = require('./config');
const parseConnectionString = require('../../lib/core/uri_parser');
const eachAsync = require('../../lib/core/utils').eachAsync;
const mock = require('mongodb-mock-server');

const MONGODB_URI = process.env.MONGODB_URI || 'mongodb://localhost:27017';
const filters = [];

function initializeFilters(client, callback) {
  const filterFiles = fs
    .readdirSync(path.join(__dirname, 'filters'))
    .filter(x => x.indexOf('js') !== -1);

  // context object that can be appended to as part of filter initialization
  const context = {};

  eachAsync(
    filterFiles,
    (filterName, cb) => {
      const FilterModule = require(path.join(__dirname, 'filters', filterName));
      const filter = new FilterModule();

      if (typeof filter !== 'object') {
        throw new TypeError('Type of filter must be an object');
      }

      if (!filter.filter || typeof filter.filter !== 'function') {
        throw new TypeError('Object filters must have a function named filter');
      }

      filters.push(filter);
      if (typeof filter.initializeFilter === 'function') {
        filter.initializeFilter(client, context, cb);
      } else {
        cb();
      }
    },
    err => callback(err, context)
  );
}

function filterOutTests(suite) {
  suite.tests = suite.tests.filter(test => filters.every(f => f.filter(test)));
  suite.suites.forEach(suite => filterOutTests(suite));
}

before(function(_done) {
  console.log(`connection string: ${MONGODB_URI}`);
  const client = new MongoClient(MONGODB_URI, { useNewUrlParser: true, useUnifiedTopology: true });
  const done = err => client.close(err2 => _done(err || err2));

  client.connect(err => {
    if (err) {
      done(err);
      return;
    }

    initializeFilters(client, (err, context) => {
      if (err) {
        done(err);
        return;
      }

      // replace this when mocha supports dynamic skipping with `afterEach`
      filterOutTests(this._runnable.parent);

      parseConnectionString(MONGODB_URI, (err, parsedURI) => {
        if (err) {
          done(err);
          return;
        }

        this.configuration = new TestConfiguration(parsedURI, context);
        done();
      });
    });
  });
});

// ensure all mock connections are closed after the suite is run
after(() => mock.cleanup());

// optionally enable test runner-wide plugins
require('./plugins/session_leak_checker');
require('./plugins/client_leak_checker');
<commit_msg>test: don't throw errors in `eachAsync` in new test runner<commit_after>'use strict';

const path = require('path');
const fs = require('fs');
const MongoClient = require('../..').MongoClient;
const TestConfiguration = require('./config');
const parseConnectionString = require('../../lib/core/uri_parser');
const eachAsync = require('../../lib/core/utils').eachAsync;
const mock = require('mongodb-mock-server');

const MONGODB_URI = process.env.MONGODB_URI || 'mongodb://localhost:27017';
const filters = [];

function initializeFilters(client, callback) {
  const filterFiles = fs
    .readdirSync(path.join(__dirname, 'filters'))
    .filter(x => x.indexOf('js') !== -1);

  // context object that can be appended to as part of filter initialization
  const context = {};

  eachAsync(
    filterFiles,
    (filterName, cb) => {
      const FilterModule = require(path.join(__dirname, 'filters', filterName));
      const filter = new FilterModule();

      if (typeof filter !== 'object') {
        cb(new TypeError('Type of filter must be an object'));
        return;
      }

      if (!filter.filter || typeof filter.filter !== 'function') {
        cb(new TypeError('Object filters must have a function named filter'));
        return;
      }

      filters.push(filter);
      if (typeof filter.initializeFilter === 'function') {
        filter.initializeFilter(client, context, cb);
      } else {
        cb();
      }
    },
    err => callback(err, context)
  );
}

function filterOutTests(suite) {
  suite.tests = suite.tests.filter(test => filters.every(f => f.filter(test)));
  suite.suites.forEach(suite => filterOutTests(suite));
}

before(function(_done) {
  console.log(`connection string: ${MONGODB_URI}`);
  const client = new MongoClient(MONGODB_URI, { useNewUrlParser: true, useUnifiedTopology: true });
  const done = err => client.close(err2 => _done(err || err2));

  client.connect(err => {
    if (err) {
      done(err);
      return;
    }

    initializeFilters(client, (err, context) => {
      if (err) {
        done(err);
        return;
      }

      // replace this when mocha supports dynamic skipping with `afterEach`
      filterOutTests(this._runnable.parent);

      parseConnectionString(MONGODB_URI, (err, parsedURI) => {
        if (err) {
          done(err);
          return;
        }

        this.configuration = new TestConfiguration(parsedURI, context);
        done();
      });
    });
  });
});

// ensure all mock connections are closed after the suite is run
after(() => mock.cleanup());

// optionally enable test runner-wide plugins
require('./plugins/session_leak_checker');
require('./plugins/client_leak_checker');
<|endoftext|>


<commit_before>const { expect } = require('chai');
const sinon = require('sinon');
const mock = require('mock-require');

let parser;
let ParserSpy;
let parserEndSpy;
let DomHandlerSpy;

const html = '<html>';
const dom = [
  {
    type: 'tag',
    name: 'html',
    attribs: {},
    children: [],
    next: null,
    prev: null,
    parent: null
  }
];

function clearRequireCache() {
  Object.keys(require.cache).forEach(function(key) {
    delete require.cache[key];
  });
}

describe('server parser', () => {
  // before
  parserEndSpy = sinon.spy();
  ParserSpy = sinon.spy(function() {
    this.end = parserEndSpy;
  });
  DomHandlerSpy = sinon.spy(function() {
    this.dom = dom;
  });

  // tests
  mock('htmlparser2/lib/Parser', ParserSpy);
  mock('domhandler', DomHandlerSpy);
  parser = require('../..');

  it('calls `domhandler` and `htmlparser2/lib/Parser`', () => {
    parser(html);
    expect(DomHandlerSpy.called).to.equal(true);
    expect(ParserSpy.called).to.equal(true);
    expect(parserEndSpy.called).to.equal(true);
  });

  it.skip('uses the cached instance of `domhandler` if options is undefined', () => {
    expect(DomHandlerSpy.callCount).to.equal(1);
    expect(ParserSpy.callCount).to.equal(1);
    parser(html);
    expect(DomHandlerSpy.callCount).to.equal(1);
    expect(ParserSpy.callCount).to.equal(2);
  });

  it('passes options to `domhandler` and arguments to `htmlparser2/lib/Parser`', () => {
    const options = { decodeEntities: true };
    parser(html, options);
    expect(DomHandlerSpy.calledWith(options)).to.equal(true);
    expect(ParserSpy.calledWith(DomHandlerSpy, options));
  });

  it('passes html to `htmlparser2/lib/Parser` end', () => {
    parser(html);
    expect(parserEndSpy.calledWith(html)).to.equal(true);
  });

  it('returns `domhandler` dom', () => {
    expect(parser(html)).to.equal(DomHandlerSpy.lastCall.returnValue.dom);
  });

  // after
  mock.stopAll();
  clearRequireCache();
});
<commit_msg>test(server): remove skipped test<commit_after>const { expect } = require('chai');
const sinon = require('sinon');
const mock = require('mock-require');

let parser;
let ParserSpy;
let parserEndSpy;
let DomHandlerSpy;

const html = '<html>';
const dom = [
  {
    type: 'tag',
    name: 'html',
    attribs: {},
    children: [],
    next: null,
    prev: null,
    parent: null
  }
];

function clearRequireCache() {
  Object.keys(require.cache).forEach(function(key) {
    delete require.cache[key];
  });
}

describe('server parser', () => {
  // before
  parserEndSpy = sinon.spy();
  ParserSpy = sinon.spy(function() {
    this.end = parserEndSpy;
  });
  DomHandlerSpy = sinon.spy(function() {
    this.dom = dom;
  });

  // tests
  mock('htmlparser2/lib/Parser', ParserSpy);
  mock('domhandler', DomHandlerSpy);
  parser = require('../..');

  it('calls `domhandler` and `htmlparser2/lib/Parser`', () => {
    parser(html);
    expect(DomHandlerSpy.called).to.equal(true);
    expect(ParserSpy.called).to.equal(true);
    expect(parserEndSpy.called).to.equal(true);
  });

  it('passes options to `domhandler` and arguments to `htmlparser2/lib/Parser`', () => {
    const options = { decodeEntities: true };
    parser(html, options);
    expect(DomHandlerSpy.calledWith(options)).to.equal(true);
    expect(ParserSpy.calledWith(DomHandlerSpy, options));
  });

  it('passes html to `htmlparser2/lib/Parser` end', () => {
    parser(html);
    expect(parserEndSpy.calledWith(html)).to.equal(true);
  });

  it('returns `domhandler` dom', () => {
    expect(parser(html)).to.equal(DomHandlerSpy.lastCall.returnValue.dom);
  });

  // after
  mock.stopAll();
  clearRequireCache();
});
<|endoftext|>


<commit_before>/* jasmine-given - 2.5.1
 * Adds a Given-When-Then DSL to jasmine as an alternative style for specs
 * https://github.com/searls/jasmine-given
 */
(function() {
  var __bind = function(fn, me){ return function(){ return fn.apply(me, arguments); }; };

  (function(jasmine) {
    var Waterfall, additionalInsightsForErrorMessage, apparentReferenceError, attemptedEquality, comparisonInsight, declareJasmineSpec, deepEqualsNotice, doneWrapperFor, evalInContextOfSpec, finalStatementFrom, getBlock, invariantList, mostRecentExpectations, mostRecentlyUsed, o, root, stringifyExpectation, wasComparison, whenList, wrapAsExpectations;
    mostRecentlyUsed = null;
    beforeEach(function() {
      return this.addMatchers(jasmine._given.matchers);
    });
    root = this;
    root.Given = function() {
      mostRecentlyUsed = root.Given;
      return beforeEach(getBlock(arguments));
    };
    whenList = [];
    root.When = function() {
      var b;
      mostRecentlyUsed = root.When;
      b = getBlock(arguments);
      beforeEach(function() {
        return whenList.push(b);
      });
      return afterEach(function() {
        return whenList.pop();
      });
    };
    invariantList = [];
    root.Invariant = function() {
      var invariantBehavior;
      mostRecentlyUsed = root.Invariant;
      invariantBehavior = getBlock(arguments);
      beforeEach(function() {
        return invariantList.push(invariantBehavior);
      });
      return afterEach(function() {
        return invariantList.pop();
      });
    };
    getBlock = function(thing) {
      var assignResultTo, setupFunction;
      setupFunction = o(thing).firstThat(function(arg) {
        return o(arg).isFunction();
      });
      assignResultTo = o(thing).firstThat(function(arg) {
        return o(arg).isString();
      });
      return doneWrapperFor(setupFunction, function(done) {
        var context, result;
        context = jasmine.getEnv().currentSpec;
        result = setupFunction.call(context, done);
        if (assignResultTo) {
          if (!context[assignResultTo]) {
            return context[assignResultTo] = result;
          } else {
            throw new Error("Unfortunately, the variable '" + assignResultTo + "' is already assigned to: " + context[assignResultTo]);
          }
        }
      });
    };
    mostRecentExpectations = null;
    declareJasmineSpec = function(specArgs, itFunction) {
      var expectationFunction, expectations, label;
      if (itFunction == null) {
        itFunction = it;
      }
      label = o(specArgs).firstThat(function(arg) {
        return o(arg).isString();
      });
      expectationFunction = o(specArgs).firstThat(function(arg) {
        return o(arg).isFunction();
      });
      mostRecentlyUsed = root.subsequentThen;
      mostRecentExpectations = expectations = [expectationFunction];
      itFunction("then " + (label != null ? label : stringifyExpectation(expectations)), function(jasmineDone) {
        var userCommands;
        userCommands = [].concat(whenList, invariantList, wrapAsExpectations(expectations));
        return new Waterfall(userCommands, jasmineDone).flow();
      });
      return {
        Then: subsequentThen,
        And: subsequentThen
      };
    };
    wrapAsExpectations = function(expectations) {
      var expectation, i, _i, _len, _results;
      _results = [];
      for (i = _i = 0, _len = expectations.length; _i < _len; i = ++_i) {
        expectation = expectations[i];
        _results.push((function(expectation, i) {
          return doneWrapperFor(expectation, function(maybeDone) {
            return expect(expectation).not.toHaveReturnedFalseFromThen(jasmine.getEnv().currentSpec, i + 1, maybeDone);
          });
        })(expectation, i));
      }
      return _results;
    };
    doneWrapperFor = function(func, toWrap) {
      if (func.length === 0) {
        return function() {
          return toWrap();
        };
      } else {
        return function(done) {
          return toWrap(done);
        };
      }
    };
    root.Then = function() {
      return declareJasmineSpec(arguments);
    };
    root.Then.only = function() {
      return declareJasmineSpec(arguments, it.only);
    };
    root.subsequentThen = function(additionalExpectation) {
      mostRecentExpectations.push(additionalExpectation);
      return this;
    };
    mostRecentlyUsed = root.Given;
    root.And = function() {
      return mostRecentlyUsed.apply(this, jasmine.util.argsToArray(arguments));
    };
    o = function(thing) {
      return {
        isFunction: function() {
          return Object.prototype.toString.call(thing) === "[object Function]";
        },
        isString: function() {
          return Object.prototype.toString.call(thing) === "[object String]";
        },
        firstThat: function(test) {
          var i;
          i = 0;
          while (i < thing.length) {
            if (test(thing[i]) === true) {
              return thing[i];
            }
            i++;
          }
          return void 0;
        }
      };
    };
    jasmine._given = {
      matchers: {
        toHaveReturnedFalseFromThen: function(context, n, done) {
          var e, exception, result;
          result = false;
          exception = void 0;
          try {
            result = this.actual.call(context, done);
          } catch (_error) {
            e = _error;
            exception = e;
          }
          this.message = function() {
            var msg, stringyExpectation;
            stringyExpectation = stringifyExpectation(this.actual);
            msg = "Then clause" + (n > 1 ? " #" + n : "") + " `" + stringyExpectation + "` failed by ";
            if (exception) {
              msg += "throwing: " + exception.toString();
            } else {
              msg += "returning false";
            }
            msg += additionalInsightsForErrorMessage(stringyExpectation);
            return msg;
          };
          return result === false;
        }
      }
    };
    stringifyExpectation = function(expectation) {
      var matches;
      matches = expectation.toString().replace(/\n/g, '').match(/function\s?\(.*\)\s?{\s*(return\s+)?(.*?)(;)?\s*}/i);
      if (matches && matches.length >= 3) {
        return matches[2].replace(/\s+/g, ' ');
      } else {
        return "";
      }
    };
    additionalInsightsForErrorMessage = function(expectationString) {
      var comparison, expectation;
      expectation = finalStatementFrom(expectationString);
      if (comparison = wasComparison(expectation)) {
        return comparisonInsight(expectation, comparison);
      } else {
        return "";
      }
    };
    finalStatementFrom = function(expectationString) {
      var multiStatement;
      if (multiStatement = expectationString.match(/.*return (.*)/)) {
        return multiStatement[multiStatement.length - 1];
      } else {
        return expectationString;
      }
    };
    wasComparison = function(expectation) {
      var comparator, comparison, left, right, s;
      if (comparison = expectation.match(/(.*) (===|!==|==|!=|>|>=|<|<=) (.*)/)) {
        s = comparison[0], left = comparison[1], comparator = comparison[2], right = comparison[3];
        return {
          left: left,
          comparator: comparator,
          right: right
        };
      }
    };
    comparisonInsight = function(expectation, comparison) {
      var left, msg, right;
      left = evalInContextOfSpec(comparison.left);
      right = evalInContextOfSpec(comparison.right);
      if (apparentReferenceError(left) && apparentReferenceError(right)) {
        return "";
      }
      msg = "\n\nThis comparison was detected:\n  " + expectation + "\n  " + left + " " + comparison.comparator + " " + right;
      if (attemptedEquality(left, right, comparison.comparator)) {
        msg += "\n\n" + (deepEqualsNotice(comparison.left, comparison.right));
      }
      return msg;
    };
    apparentReferenceError = function(result) {
      return /^<Error: "ReferenceError/.test(result);
    };
    evalInContextOfSpec = function(operand) {
      var e;
      try {
        return (function() {
          return eval(operand);
        }).call(jasmine.getEnv().currentSpec);
      } catch (_error) {
        e = _error;
        return "<Error: \"" + ((e != null ? typeof e.message === "function" ? e.message() : void 0 : void 0) || e) + "\">";
      }
    };
    attemptedEquality = function(left, right, comparator) {
      return (comparator === "==" || comparator === "===") && jasmine.getEnv().equals_(left, right);
    };
    deepEqualsNotice = function(left, right) {
      return "However, these items are deeply equal! Try an expectation like this instead:\n  expect(" + left + ").toEqual(" + right + ")";
    };
    return Waterfall = (function() {
      function Waterfall(functions, finalCallback) {
        var func, _i, _len, _ref;
        if (functions == null) {
          functions = [];
        }
        this.flow = __bind(this.flow, this);
        this.invokeFinalCallbackIfNecessary = __bind(this.invokeFinalCallbackIfNecessary, this);
        this.asyncTaskCompleted = __bind(this.asyncTaskCompleted, this);
        this.functions = functions.slice(0);
        this.finalCallback = finalCallback;
        this.asyncCount = 0;
        _ref = this.functions;
        for (_i = 0, _len = _ref.length; _i < _len; _i++) {
          func = _ref[_i];
          if (func.length > 0) {
            this.asyncCount += 1;
          }
        }
      }

      Waterfall.prototype.asyncTaskCompleted = function() {
        this.asyncCount -= 1;
        return this.flow();
      };

      Waterfall.prototype.invokeFinalCallbackIfNecessary = function() {
        if (this.asyncCount === 0) {
          if (typeof this.finalCallback === "function") {
            this.finalCallback();
          }
          return this.finalCallback = void 0;
        }
      };

      Waterfall.prototype.flow = function() {
        var func;
        if (this.functions.length === 0) {
          return this.invokeFinalCallbackIfNecessary();
        }
        func = this.functions.shift();
        if (func.length > 0) {
          return func(this.asyncTaskCompleted);
        } else {
          func();
          return this.flow();
        }
      };

      return Waterfall;

    })();
  })(jasmine);

}).call(this);
<commit_msg>Upgrade jasmine-given in the archetype<commit_after>/* jasmine-given - 2.6.0
 * Adds a Given-When-Then DSL to jasmine as an alternative style for specs
 * https://github.com/searls/jasmine-given
 */
/* jasmine-matcher-wrapper - 0.0.2
 * Wraps Jasmine 1.x matchers for use with Jasmine 2
 * https://github.com/testdouble/jasmine-matcher-wrapper
 */
(function() {
  var __slice = [].slice,
    __hasProp = {}.hasOwnProperty;

  (function(jasmine) {
    var comparatorFor;
    if (jasmine == null) {
      return typeof console !== "undefined" && console !== null ? console.warn("jasmine was not found. Skipping jasmine-matcher-wrapper. Verify your script load order.") : void 0;
    }
    if (jasmine.matcherWrapper != null) {
      return;
    }
    comparatorFor = function(matcher, isNot) {
      return function() {
        var actual, context, message, params, pass, _ref;
        actual = arguments[0], params = 2 <= arguments.length ? __slice.call(arguments, 1) : [];
        context = {
          actual: actual,
          isNot: isNot
        };
        pass = matcher.apply(context, params);
        if (isNot) {
          pass = !pass;
        }
        if (!pass) {
          message = (_ref = context.message) != null ? _ref.apply(context, params) : void 0;
        }
        return {
          pass: pass,
          message: message
        };
      };
    };
    return jasmine.matcherWrapper = {
      wrap: function(matchers) {
        var matcher, name, wrappedMatchers;
        if (jasmine.addMatchers == null) {
          return matchers;
        }
        wrappedMatchers = {};
        for (name in matchers) {
          if (!__hasProp.call(matchers, name)) continue;
          matcher = matchers[name];
          wrappedMatchers[name] = function() {
            return {
              compare: comparatorFor(matcher, false),
              negativeCompare: comparatorFor(matcher, true)
            };
          };
        }
        return wrappedMatchers;
      }
    };
  })(jasmine || getJasmineRequireObj());

}).call(this);

(function() {
  var __bind = function(fn, me){ return function(){ return fn.apply(me, arguments); }; };

  (function(jasmine) {
    var Waterfall, additionalInsightsForErrorMessage, apparentReferenceError, attemptedEquality, comparisonInsight, currentSpec, declareJasmineSpec, deepEqualsNotice, doneWrapperFor, evalInContextOfSpec, finalStatementFrom, getBlock, invariantList, mostRecentExpectations, mostRecentlyUsed, o, root, stringifyExpectation, wasComparison, whenList, wrapAsExpectations;
    mostRecentlyUsed = null;
    root = this;
    currentSpec = null;
    beforeEach(function() {
      return currentSpec = this;
    });
    root.Given = function() {
      mostRecentlyUsed = root.Given;
      return beforeEach(getBlock(arguments));
    };
    whenList = [];
    root.When = function() {
      var b;
      mostRecentlyUsed = root.When;
      b = getBlock(arguments);
      beforeEach(function() {
        return whenList.push(b);
      });
      return afterEach(function() {
        return whenList.pop();
      });
    };
    invariantList = [];
    root.Invariant = function() {
      var invariantBehavior;
      mostRecentlyUsed = root.Invariant;
      invariantBehavior = getBlock(arguments);
      beforeEach(function() {
        return invariantList.push(invariantBehavior);
      });
      return afterEach(function() {
        return invariantList.pop();
      });
    };
    getBlock = function(thing) {
      var assignResultTo, setupFunction;
      setupFunction = o(thing).firstThat(function(arg) {
        return o(arg).isFunction();
      });
      assignResultTo = o(thing).firstThat(function(arg) {
        return o(arg).isString();
      });
      return doneWrapperFor(setupFunction, function(done) {
        var context, result;
        context = currentSpec;
        result = setupFunction.call(context, done);
        if (assignResultTo) {
          if (!context[assignResultTo]) {
            return context[assignResultTo] = result;
          } else {
            throw new Error("Unfortunately, the variable '" + assignResultTo + "' is already assigned to: " + context[assignResultTo]);
          }
        }
      });
    };
    mostRecentExpectations = null;
    declareJasmineSpec = function(specArgs, itFunction) {
      var expectationFunction, expectations, label;
      if (itFunction == null) {
        itFunction = it;
      }
      label = o(specArgs).firstThat(function(arg) {
        return o(arg).isString();
      });
      expectationFunction = o(specArgs).firstThat(function(arg) {
        return o(arg).isFunction();
      });
      mostRecentlyUsed = root.subsequentThen;
      mostRecentExpectations = expectations = [expectationFunction];
      itFunction("then " + (label != null ? label : stringifyExpectation(expectations)), function(jasmineDone) {
        var userCommands;
        userCommands = [].concat(whenList, invariantList, wrapAsExpectations(expectations));
        return new Waterfall(userCommands, jasmineDone).flow();
      });
      return {
        Then: subsequentThen,
        And: subsequentThen
      };
    };
    wrapAsExpectations = function(expectations) {
      var expectation, i, _i, _len, _results;
      _results = [];
      for (i = _i = 0, _len = expectations.length; _i < _len; i = ++_i) {
        expectation = expectations[i];
        _results.push((function(expectation, i) {
          return doneWrapperFor(expectation, function(maybeDone) {
            return expect(expectation).not.toHaveReturnedFalseFromThen(currentSpec, i + 1, maybeDone);
          });
        })(expectation, i));
      }
      return _results;
    };
    doneWrapperFor = function(func, toWrap) {
      if (func.length === 0) {
        return function() {
          return toWrap();
        };
      } else {
        return function(done) {
          return toWrap(done);
        };
      }
    };
    root.Then = function() {
      return declareJasmineSpec(arguments);
    };
    root.Then.only = function() {
      return declareJasmineSpec(arguments, it.only);
    };
    root.subsequentThen = function(additionalExpectation) {
      mostRecentExpectations.push(additionalExpectation);
      return this;
    };
    mostRecentlyUsed = root.Given;
    root.And = function() {
      return mostRecentlyUsed.apply(this, jasmine.util.argsToArray(arguments));
    };
    o = function(thing) {
      return {
        isFunction: function() {
          return Object.prototype.toString.call(thing) === "[object Function]";
        },
        isString: function() {
          return Object.prototype.toString.call(thing) === "[object String]";
        },
        firstThat: function(test) {
          var i;
          i = 0;
          while (i < thing.length) {
            if (test(thing[i]) === true) {
              return thing[i];
            }
            i++;
          }
          return void 0;
        }
      };
    };
    jasmine._given = {
      matchers: {
        toHaveReturnedFalseFromThen: function(context, n, done) {
          var e, exception, result;
          result = false;
          exception = void 0;
          try {
            result = this.actual.call(context, done);
          } catch (_error) {
            e = _error;
            exception = e;
          }
          this.message = function() {
            var msg, stringyExpectation;
            stringyExpectation = stringifyExpectation(this.actual);
            msg = "Then clause" + (n > 1 ? " #" + n : "") + " `" + stringyExpectation + "` failed by ";
            if (exception) {
              msg += "throwing: " + exception.toString();
            } else {
              msg += "returning false";
            }
            msg += additionalInsightsForErrorMessage(stringyExpectation);
            return msg;
          };
          return result === false;
        }
      }
    };
    stringifyExpectation = function(expectation) {
      var matches;
      matches = expectation.toString().replace(/\n/g, '').match(/function\s?\(.*\)\s?{\s*(return\s+)?(.*?)(;)?\s*}/i);
      if (matches && matches.length >= 3) {
        return matches[2].replace(/\s+/g, ' ');
      } else {
        return "";
      }
    };
    additionalInsightsForErrorMessage = function(expectationString) {
      var comparison, expectation;
      expectation = finalStatementFrom(expectationString);
      if (comparison = wasComparison(expectation)) {
        return comparisonInsight(expectation, comparison);
      } else {
        return "";
      }
    };
    finalStatementFrom = function(expectationString) {
      var multiStatement;
      if (multiStatement = expectationString.match(/.*return (.*)/)) {
        return multiStatement[multiStatement.length - 1];
      } else {
        return expectationString;
      }
    };
    wasComparison = function(expectation) {
      var comparator, comparison, left, right, s;
      if (comparison = expectation.match(/(.*) (===|!==|==|!=|>|>=|<|<=) (.*)/)) {
        s = comparison[0], left = comparison[1], comparator = comparison[2], right = comparison[3];
        return {
          left: left,
          comparator: comparator,
          right: right
        };
      }
    };
    comparisonInsight = function(expectation, comparison) {
      var left, msg, right;
      left = evalInContextOfSpec(comparison.left);
      right = evalInContextOfSpec(comparison.right);
      if (apparentReferenceError(left) && apparentReferenceError(right)) {
        return "";
      }
      msg = "\n\nThis comparison was detected:\n  " + expectation + "\n  " + left + " " + comparison.comparator + " " + right;
      if (attemptedEquality(left, right, comparison.comparator)) {
        msg += "\n\n" + (deepEqualsNotice(comparison.left, comparison.right));
      }
      return msg;
    };
    apparentReferenceError = function(result) {
      return /^<Error: "ReferenceError/.test(result);
    };
    evalInContextOfSpec = function(operand) {
      var e;
      try {
        return (function() {
          return eval(operand);
        }).call(currentSpec);
      } catch (_error) {
        e = _error;
        return "<Error: \"" + ((e != null ? typeof e.message === "function" ? e.message() : void 0 : void 0) || e) + "\">";
      }
    };
    attemptedEquality = function(left, right, comparator) {
      var _ref;
      if (!(comparator === "==" || comparator === "===")) {
        return false;
      }
      if (((_ref = jasmine.matchersUtil) != null ? _ref.equals : void 0) != null) {
        return jasmine.matchersUtil.equals(left, right);
      } else {
        return jasmine.getEnv().equals_(left, right);
      }
    };
    deepEqualsNotice = function(left, right) {
      return "However, these items are deeply equal! Try an expectation like this instead:\n  expect(" + left + ").toEqual(" + right + ")";
    };
    Waterfall = (function() {
      function Waterfall(functions, finalCallback) {
        var func, _i, _len, _ref;
        if (functions == null) {
          functions = [];
        }
        this.flow = __bind(this.flow, this);
        this.invokeFinalCallbackIfNecessary = __bind(this.invokeFinalCallbackIfNecessary, this);
        this.asyncTaskCompleted = __bind(this.asyncTaskCompleted, this);
        this.functions = functions.slice(0);
        this.finalCallback = finalCallback;
        this.asyncCount = 0;
        _ref = this.functions;
        for (_i = 0, _len = _ref.length; _i < _len; _i++) {
          func = _ref[_i];
          if (func.length > 0) {
            this.asyncCount += 1;
          }
        }
      }

      Waterfall.prototype.asyncTaskCompleted = function() {
        this.asyncCount -= 1;
        return this.flow();
      };

      Waterfall.prototype.invokeFinalCallbackIfNecessary = function() {
        if (this.asyncCount === 0) {
          if (typeof this.finalCallback === "function") {
            this.finalCallback();
          }
          return this.finalCallback = void 0;
        }
      };

      Waterfall.prototype.flow = function() {
        var func;
        if (this.functions.length === 0) {
          return this.invokeFinalCallbackIfNecessary();
        }
        func = this.functions.shift();
        if (func.length > 0) {
          return func(this.asyncTaskCompleted);
        } else {
          func();
          return this.flow();
        }
      };

      return Waterfall;

    })();
    return beforeEach(function() {
      if (jasmine.addMatchers != null) {
        return jasmine.addMatchers(jasmine.matcherWrapper.wrap(jasmine._given.matchers));
      } else {
        return this.addMatchers(jasmine._given.matchers);
      }
    });
  })(jasmine);

}).call(this);
<|endoftext|>


<commit_before>require('should')

const wdSparqlQuery = require('../lib/queries/sparql_query')
console.log('wdSparqlQuery', wdSparqlQuery)

const sparqlExemple = `
  PREFIX wikibase: <http://wikiba.se/ontology#>
  PREFIX wd: <http://www.wikidata.org/entity/>
  PREFIX wdt: <http://www.wikidata.org/prop/direct/>
  PREFIX rdfs: <http://www.w3.org/2000/01/rdf-schema#>

  SELECT DISTINCT ?entity ?entityLabel (year(?date) as ?year)
  WHERE
  {
     ?entity wdt:P569 ?date .
     ?book wdt:P50 ?entity .
     ?book wdt:P31/wdt:P279* wd:Q571 .
     SERVICE wikibase:label {
       bd:serviceParam wikibase:language "en" .
     }
     FILTER (datatype(?date) = xsd:dateTime)
     FILTER (month(?date) = month(now()))
     FILTER (day(?date) = day(now()))
  }
`

describe('wdSparqlQuery', function () {
  it('env', function (done) {
    wdSparqlQuery.should.be.a.Function()
    done()
  })

  it('should return a url', function (done) {
    const url = wdSparqlQuery(sparqlExemple)
    url.should.be.a.String()
    url.should.match(new RegExp('https://'))
    done()
  })
})
<commit_msg>cleaning<commit_after>require('should')

const wdSparqlQuery = require('../lib/queries/sparql_query')

const sparqlExemple = `
  PREFIX wikibase: <http://wikiba.se/ontology#>
  PREFIX wd: <http://www.wikidata.org/entity/>
  PREFIX wdt: <http://www.wikidata.org/prop/direct/>
  PREFIX rdfs: <http://www.w3.org/2000/01/rdf-schema#>

  SELECT DISTINCT ?entity ?entityLabel (year(?date) as ?year)
  WHERE
  {
     ?entity wdt:P569 ?date .
     ?book wdt:P50 ?entity .
     ?book wdt:P31/wdt:P279* wd:Q571 .
     SERVICE wikibase:label {
       bd:serviceParam wikibase:language "en" .
     }
     FILTER (datatype(?date) = xsd:dateTime)
     FILTER (month(?date) = month(now()))
     FILTER (day(?date) = day(now()))
  }
`

describe('wdSparqlQuery', function () {
  it('env', function (done) {
    wdSparqlQuery.should.be.a.Function()
    done()
  })

  it('should return a url', function (done) {
    const url = wdSparqlQuery(sparqlExemple)
    url.should.be.a.String()
    url.should.match(new RegExp('https://'))
    done()
  })
})
<|endoftext|>


<commit_before>/* eslint-env mocha */
'use strict'

const assert = require('assert')
const co = require('co')
const moment = require('moment')
const mongo = require('mongodb').MongoClient
const Tailer = require('../../lib/tailer.js')
const wait = require('../wait')
const MysqlConnector = require('../mysql-connector')
const config = require('../momyfile.json')

const waitingTime = 500 // waiting time for syncing from Mongo to MySQL

describe('Momy Tailer: basic', () => {
  let mo
  let my
  let tailer

  before(co.wrap(function* () {
    mo = yield mongo.connect(config.src)
    // clear existing records
    yield mo.collection('colBasicTypes').deleteMany({})
    yield mo.collection('colNumberTypes').deleteMany({})
    yield mo.collection('colDateTypes').deleteMany({})
    yield mo.collection('colStringTypes').deleteMany({})
    my = new MysqlConnector(config.dist)
    tailer = new Tailer(config, false)
    tailer.importAndStart(false)
    yield wait(1000) // wait for syncing
  }))

  it('syncs a single doc with basic types', co.wrap(function* () {
    const colName = 'colBasicTypes'
    const doc = {
      field1: true, // boolean
      field2: 123, // number
      field3: 'Tom' // string
    }
    const r0 = yield mo.collection(colName).insertOne(doc)
    yield wait(waitingTime) // wait for syncing
    const r1 = yield my.query(`SELECT * FROM ${colName} WHERE id = "${r0.insertedId}"`)

    assert.equal(r1[0].field1, 1)
    assert.equal(r1[0].field2, doc.field2)
    assert.equal(r1[0].field3, doc.field3)
  }))

  it('syncs a single doc with number types', co.wrap(function* () {
    const colName = 'colNumberTypes'
    const doc = {
      field1: 1234567, // BIGINT
      field2: 123.4567, // DOUBLE
      field3: true // TINYINT
    }
    const r0 = yield mo.collection(colName).insertOne(doc)
    yield wait(waitingTime) // wait for syncing
    const r1 = yield my.query(`SELECT * FROM ${colName} WHERE id = "${r0.insertedId}"`)

    assert.equal(r1[0].field1, 1234567)
    assert.equal(r1[0].field2, 123.4567)
    assert.equal(r1[0].field3, 1)
  }))

  it('syncs a single doc with date types', co.wrap(function* () {
    const colName = 'colDateTypes'
    const now = Date.now()
    const doc = {
      field1: now, // DATE
      field2: now, // DATETIME
      field3: now // TIME
    }
    const r0 = yield mo.collection(colName).insertOne(doc)
    yield wait(waitingTime) // wait for syncing
    const r1 = yield my.query(`SELECT * FROM ${colName} WHERE id = "${r0.insertedId}"`)

    assert.equal(
      moment(r1[0].field1).format('YYYY-MM-DD'),
      moment(now).format('YYYY-MM-DD'))
    assert.equal(
      moment(r1[0].field2).format('YYYY-MM-DD HH:mm:ss'),
      moment(now).format('YYYY-MM-DD HH:mm:ss'))
    assert.equal(r1[0].field3, moment(now).format('HH:mm:ss'))
  }))

  it('syncs a single doc with string types', co.wrap(function* () {
    const colName = 'colStringTypes'
    const allAscii = Array.from(Array(95)).map((_, i) => String.fromCharCode(32 + i)).join('')
    const string285 = allAscii + allAscii + allAscii
    const doc = {
      field1: string285, // VARCHAR
      field2: string285 // TEXT
    }
    const r0 = yield mo.collection(colName).insertOne(doc)
    yield wait(waitingTime) // wait for syncing
    const r1 = yield my.query(`SELECT * FROM ${colName} WHERE id = "${r0.insertedId}"`)

    assert.equal(r1[0].field1, string285.substring(0, 255))
    assert.equal(r1[0].field2, string285)
  }))

  it('syncs a doc updated', co.wrap(function* () {
    const colName = 'colBasicTypes'
    const doc = {
      field1: true, // boolean
      field2: 123, // number
      field3: 'Tom' // string
    }
    const r0 = yield mo.collection(colName).insertOne(doc)
    yield wait(waitingTime) // wait for syncing
    const r1 = yield my.query(`SELECT * FROM ${colName} WHERE id = "${r0.insertedId}"`)
    assert.equal(r1[0].field3, 'Tom')

    yield mo.collection(colName).update({_id: r0.insertedId}, {$set: {field3: 'John'}})
    yield wait(waitingTime) // wait for syncing
    const r2 = yield my.query(`SELECT * FROM ${colName} WHERE id = "${r0.insertedId}"`)
    assert.equal(r2[0].field3, 'John')

    yield mo.collection(colName).update({_id: r0.insertedId}, {$unset: {field3: true}})
    yield wait(waitingTime) // wait for syncing
    const r3 = yield my.query(`SELECT * FROM ${colName} WHERE id = "${r0.insertedId}"`)
    assert.equal(r3[0].field3, '')

    yield mo.collection(colName).update({_id: r0.insertedId}, doc)
    yield wait(waitingTime) // wait for syncing
    const r4 = yield my.query(`SELECT * FROM ${colName} WHERE id = "${r0.insertedId}"`)
    assert.equal(r4[0].field3, 'Tom')
  }))

  it('inserts and remove a doc', co.wrap(function* () {
    const colName = 'colBasicTypes'
    const doc = {
      field1: true, // boolean
      field2: 123, // number
      field3: 'Tom' // string
    }
    const r0 = yield mo.collection(colName).insertOne(doc)
    yield wait(waitingTime) // wait for syncing
    const r1 = yield my.query(`SELECT * FROM ${colName} WHERE id = "${r0.insertedId}"`)
    assert.equal(r1[0].field3, 'Tom')

    yield mo.collection(colName).removeOne({_id: r0.insertedId})
    yield wait(waitingTime) // wait for syncing
    const r2 = yield my.query(`SELECT * FROM ${colName} WHERE id = "${r0.insertedId}"`)
    assert.equal(r2.length, 0)
  }))

  it('inserts multiple docs', co.wrap(function* () {
    const colName = 'colBasicTypes'
    const docs = [...Array(10)].map((_, i) => ({
      field1: true,
      field2: i,
      field3: `Tom-${i}`
    }))
    for (const doc of docs) {
      const r = yield mo.collection(colName).insertOne(doc)
      doc._id = r.insertedId
    }
    yield wait(waitingTime) // wait for syncing
    for (const doc of docs) {
      const r = yield my.query(`SELECT * FROM ${colName} WHERE id = "${doc._id}"`)
      assert.equal(r[0].field2, doc.field2)
    }
  }))

  it('inserts 1000 docs', co.wrap(function* () {
    const colName = 'colBasicTypes'
    const docs = [...Array(1000)].map((_, i) => ({
      field1: true,
      field2: i,
      field3: `Tom-${i}`
    }))
    for (const doc of docs) {
      const r = yield mo.collection(colName).insertOne(doc)
      doc._id = r.insertedId
    }
    yield wait(waitingTime * 4) // wait for syncing
    for (const doc of docs) {
      const r = yield my.query(`SELECT * FROM ${colName} WHERE id = "${doc._id}"`)
      assert.equal(r[0].field2, doc.field2)
    }
  }))

  after(co.wrap(function* () {
    tailer.stop()
    yield wait(waitingTime * 2)
  }))
})

describe('Momy Tailer: importing', () => {
  it('imports all docs already exist', co.wrap(function* () {
    const mo = yield mongo.connect(config.src)
    const colName = 'colBasicTypes'

    // clear existing records
    yield mo.collection(colName).deleteMany({})

    const docs = Array.from(Array(10)).map((_, i) => ({
      field1: true,
      field2: i,
      field3: `Tom-${i}`
    }))
    for (const doc of docs) {
      const r = yield mo.collection(colName).insertOne(doc)
      doc._id = r.insertedId
    }

    const tailer = new Tailer(config, false)
    tailer.importAndStart(false)
    yield wait(1000) // wait for syncing

    const my = new MysqlConnector(config.dist)
    for (const doc of docs) {
      const r = yield my.query(`SELECT * FROM ${colName} WHERE id = "${doc._id}"`)
      assert.equal(r[0].field2, doc.field2)
    }
    tailer.stop()
  }))
})
<commit_msg>Fixes tests for Node v4<commit_after>/* eslint-env mocha */
'use strict'

const assert = require('assert')
const co = require('co')
const moment = require('moment')
const mongo = require('mongodb').MongoClient
const Tailer = require('../../lib/tailer.js')
const wait = require('../wait')
const MysqlConnector = require('../mysql-connector')
const config = require('../momyfile.json')

const waitingTime = 500 // waiting time for syncing from Mongo to MySQL

describe('Momy Tailer: basic', () => {
  let mo
  let my
  let tailer

  before(co.wrap(function* () {
    mo = yield mongo.connect(config.src)
    // clear existing records
    yield mo.collection('colBasicTypes').deleteMany({})
    yield mo.collection('colNumberTypes').deleteMany({})
    yield mo.collection('colDateTypes').deleteMany({})
    yield mo.collection('colStringTypes').deleteMany({})
    my = new MysqlConnector(config.dist)
    tailer = new Tailer(config, false)
    tailer.importAndStart(false)
    yield wait(1000) // wait for syncing
  }))

  it('syncs a single doc with basic types', co.wrap(function* () {
    const colName = 'colBasicTypes'
    const doc = {
      field1: true, // boolean
      field2: 123, // number
      field3: 'Tom' // string
    }
    const r0 = yield mo.collection(colName).insertOne(doc)
    yield wait(waitingTime) // wait for syncing
    const r1 = yield my.query(`SELECT * FROM ${colName} WHERE id = "${r0.insertedId}"`)

    assert.equal(r1[0].field1, 1)
    assert.equal(r1[0].field2, doc.field2)
    assert.equal(r1[0].field3, doc.field3)
  }))

  it('syncs a single doc with number types', co.wrap(function* () {
    const colName = 'colNumberTypes'
    const doc = {
      field1: 1234567, // BIGINT
      field2: 123.4567, // DOUBLE
      field3: true // TINYINT
    }
    const r0 = yield mo.collection(colName).insertOne(doc)
    yield wait(waitingTime) // wait for syncing
    const r1 = yield my.query(`SELECT * FROM ${colName} WHERE id = "${r0.insertedId}"`)

    assert.equal(r1[0].field1, 1234567)
    assert.equal(r1[0].field2, 123.4567)
    assert.equal(r1[0].field3, 1)
  }))

  it('syncs a single doc with date types', co.wrap(function* () {
    const colName = 'colDateTypes'
    const now = Date.now()
    const doc = {
      field1: now, // DATE
      field2: now, // DATETIME
      field3: now // TIME
    }
    const r0 = yield mo.collection(colName).insertOne(doc)
    yield wait(waitingTime) // wait for syncing
    const r1 = yield my.query(`SELECT * FROM ${colName} WHERE id = "${r0.insertedId}"`)

    assert.equal(
      moment(r1[0].field1).format('YYYY-MM-DD'),
      moment(now).format('YYYY-MM-DD'))
    assert.equal(
      moment(r1[0].field2).format('YYYY-MM-DD HH:mm:ss'),
      moment(now).format('YYYY-MM-DD HH:mm:ss'))
    assert.equal(r1[0].field3, moment(now).format('HH:mm:ss'))
  }))

  it('syncs a single doc with string types', co.wrap(function* () {
    const colName = 'colStringTypes'
    const allAscii = Array.from(Array(95)).map((_, i) => String.fromCharCode(32 + i)).join('')
    const string285 = allAscii + allAscii + allAscii
    const doc = {
      field1: string285, // VARCHAR
      field2: string285 // TEXT
    }
    const r0 = yield mo.collection(colName).insertOne(doc)
    yield wait(waitingTime) // wait for syncing
    const r1 = yield my.query(`SELECT * FROM ${colName} WHERE id = "${r0.insertedId}"`)

    assert.equal(r1[0].field1, string285.substring(0, 255))
    assert.equal(r1[0].field2, string285)
  }))

  it('syncs a doc updated', co.wrap(function* () {
    const colName = 'colBasicTypes'
    const doc = {
      field1: true, // boolean
      field2: 123, // number
      field3: 'Tom' // string
    }
    const r0 = yield mo.collection(colName).insertOne(doc)
    yield wait(waitingTime) // wait for syncing
    const r1 = yield my.query(`SELECT * FROM ${colName} WHERE id = "${r0.insertedId}"`)
    assert.equal(r1[0].field3, 'Tom')

    yield mo.collection(colName).update({_id: r0.insertedId}, {$set: {field3: 'John'}})
    yield wait(waitingTime) // wait for syncing
    const r2 = yield my.query(`SELECT * FROM ${colName} WHERE id = "${r0.insertedId}"`)
    assert.equal(r2[0].field3, 'John')

    yield mo.collection(colName).update({_id: r0.insertedId}, {$unset: {field3: true}})
    yield wait(waitingTime) // wait for syncing
    const r3 = yield my.query(`SELECT * FROM ${colName} WHERE id = "${r0.insertedId}"`)
    assert.equal(r3[0].field3, '')

    yield mo.collection(colName).update({_id: r0.insertedId}, doc)
    yield wait(waitingTime) // wait for syncing
    const r4 = yield my.query(`SELECT * FROM ${colName} WHERE id = "${r0.insertedId}"`)
    assert.equal(r4[0].field3, 'Tom')
  }))

  it('inserts and remove a doc', co.wrap(function* () {
    const colName = 'colBasicTypes'
    const doc = {
      field1: true, // boolean
      field2: 123, // number
      field3: 'Tom' // string
    }
    const r0 = yield mo.collection(colName).insertOne(doc)
    yield wait(waitingTime) // wait for syncing
    const r1 = yield my.query(`SELECT * FROM ${colName} WHERE id = "${r0.insertedId}"`)
    assert.equal(r1[0].field3, 'Tom')

    yield mo.collection(colName).removeOne({_id: r0.insertedId})
    yield wait(waitingTime) // wait for syncing
    const r2 = yield my.query(`SELECT * FROM ${colName} WHERE id = "${r0.insertedId}"`)
    assert.equal(r2.length, 0)
  }))

  it('inserts multiple docs', co.wrap(function* () {
    const colName = 'colBasicTypes'
    const docs = Array.from(Array(10)).map((_, i) => ({
      field1: true,
      field2: i,
      field3: `Tom-${i}`
    }))
    for (const doc of docs) {
      const r = yield mo.collection(colName).insertOne(doc)
      doc._id = r.insertedId
    }
    yield wait(waitingTime) // wait for syncing
    for (const doc of docs) {
      const r = yield my.query(`SELECT * FROM ${colName} WHERE id = "${doc._id}"`)
      assert.equal(r[0].field2, doc.field2)
    }
  }))

  it('inserts 1000 docs', co.wrap(function* () {
    const colName = 'colBasicTypes'
    const docs = Array.from(Array(1000)).map((_, i) => ({
      field1: true,
      field2: i,
      field3: `Tom-${i}`
    }))
    for (const doc of docs) {
      const r = yield mo.collection(colName).insertOne(doc)
      doc._id = r.insertedId
    }
    yield wait(waitingTime * 4) // wait for syncing
    for (const doc of docs) {
      const r = yield my.query(`SELECT * FROM ${colName} WHERE id = "${doc._id}"`)
      assert.equal(r[0].field2, doc.field2)
    }
  }))

  after(co.wrap(function* () {
    tailer.stop()
    yield wait(waitingTime * 2)
  }))
})

describe('Momy Tailer: importing', () => {
  it('imports all docs already exist', co.wrap(function* () {
    const mo = yield mongo.connect(config.src)
    const colName = 'colBasicTypes'

    // clear existing records
    yield mo.collection(colName).deleteMany({})

    const docs = Array.from(Array(10)).map((_, i) => ({
      field1: true,
      field2: i,
      field3: `Tom-${i}`
    }))
    for (const doc of docs) {
      const r = yield mo.collection(colName).insertOne(doc)
      doc._id = r.insertedId
    }

    const tailer = new Tailer(config, false)
    tailer.importAndStart(false)
    yield wait(1000) // wait for syncing

    const my = new MysqlConnector(config.dist)
    for (const doc of docs) {
      const r = yield my.query(`SELECT * FROM ${colName} WHERE id = "${doc._id}"`)
      assert.equal(r[0].field2, doc.field2)
    }
    tailer.stop()
  }))
})
<|endoftext|>


<commit_before>/* globals systems path sync persistent */
/* eslint camelcase: [2, {properties: "never"}] */
/* eslint comma-dangle: [0, {properties: "never"}] */

/* see Azkfile.md */
systems({
  feedbin: {
    // Dependent systems
    depends: ["clock", "worker-slow", "worker", "redis", "postgres", "elasticsearch", "memcached"],
    // More images:  http://images.azk.io
    image: {"docker": "azukiapp/ruby:2.2"},
    // Steps to execute before running instances
    provision: [],
    workdir: "/azk/#{manifest.dir}",
    shell: "/bin/bash",
    command: "bundle exec rackup config.ru --pid /tmp/ruby.pid --port $HTTP_PORT --host 0.0.0.0",
    wait: {"retry": 40, "timeout": 10000},
    mounts: {
      // Uncomment the line below to use with two-way share (slower)
      //'/azk/#{manifest.dir}': path("."),
      // Run with one-way share rsync (faster)
      '/azk/#{manifest.dir}'        : sync("."),
      '/azk/bundler'                : persistent("bundler"),
      '/azk/#{manifest.dir}/tmp'    : persistent("tmp"),
      '/azk/#{manifest.dir}/.bundle': path(".bundle"),
      '/azk/#{manifest.dir}/log'    : path("log"),
    },
    scalable: {"default": 1},
    http: {
      domains: [
        "#{system.name}.#{azk.default_domain}", // default azk domain
        '#{process.env.HOST_DOMAIN}',           // used if deployed
        '#{process.env.HOST_IP}',               // used if deployed
      ]
    },
    envs: {
      // set instances variables
      RACK_ENV: "development",
      RUBY_ENV: "development",
    },
  },
  worker: {
    extends: 'feedbin',
    provision: [
      "bundle install --path /azk/bundler",
      "bundle exec rake db:setup",
    ],
    depends: ["postgres", "redis", "elasticsearch", "memcached"],
    command: 'bundle exec sidekiq -c 12 -q critical,3 -q feed_refresher_receiver,2 -q default',
    scalable: { limit: 1, default: 1},
    http: null,
    envs: {
      RACK_ENV: "development",
      RUBY_ENV: "development",
      DB_POOL: 12,
      LIBRATO_AUTORUN: 1,
    }
  },
  "worker-slow": {
    extends: 'feedbin',
    depends: ["postgres", "redis", "elasticsearch", "memcached"],
    command: 'bundle exec sidekiq -c 2 -q worker_slow_critical,3 -q worker_slow,2 -q favicon,1',
    scalable: { default: 1,  limit: 1 },
    http: null,
    envs: {
      RACK_ENV: "development",
      RUBY_ENV: "development",
      DB_POOL: 2
    }
  },
  clock: {
    extends: 'feedbin',
    depends: ["postgres", "redis", "elasticsearch", "memcached"],
    command: 'bundle exec clockwork lib/clock.rb',
    scalable: { default: 1,  limit: 1 },
    http: null,
    envs: {
      RACK_ENV: "development",
      RUBY_ENV: "development",
    }
  },
  redis: {
    image: {"docker": "redis"},
    export_envs: {
      "REDIS_HOST": "#{net.host}",
      "REDIS_PORT": "#{net.port.data}",
      "REDIS_URL": "redis://#{net.host}:#{net.port[6379]}",
    },
  },
  postgres: {
    // Dependent systems
    depends: [],
    // More images:  http://images.azk.io
    image: {"docker": "azukiapp/postgres:9.3"},
    shell: "/bin/bash",
    wait: {"retry": 40, "timeout": 1000},
    mounts: {
      '/var/lib/postgresql': persistent("postgresql"),
      '/var/log/postgresql': path("./log/postgresql"),
    },
    ports: {
      // exports global variables
      data: "5432/tcp",
    },
    envs: {
      // set instances variables
      POSTGRES_USER: "azk",
      POSTGRES_PASS: "azk",
      POSTGRES_DB  : "#{manifest.dir}",
    },
    export_envs: {
      // check this gist to configure your database
      // https://gist.github.com/gullitmiranda/62082f2e47c364ef9617
      DATABASE_URL: "postgres://#{envs.POSTGRES_USER}:#{envs.POSTGRES_PASS}@#{net.host}:#{net.port.data}/${envs.POSTGRES_DB}",
    },
  },
  elasticsearch: {
    image: { "docker": "barnybug/elasticsearch:0.90.13" },
    http: {
      domains: [ "#{system.name}.#{azk.default_domain}" ]
    },
    ports: {
      http: "9200",
    },
    wait: {"retry": 80, "timeout": 1000},
    export_envs : {
      ELASTICSEARCH_URL: "#{system.name}.#{azk.default_domain}:#{net.port[9200]}",
    },
  },
  memcached: {
    image: { "docker": "memcached" },
    ports: {
      http: "11211",
    },
    export_envs: {
      MEMCACHED_HOSTS: "#{system.name}.#{azk.default_domain}:#{net.port[11211]}"
    }
  },

  deploy: {
    image: {"docker": "azukiapp/deploy-digitalocean"},
    mounts: {

      // your files on remote machine
      // will be on /home/git folder
      "/azk/deploy/src":  path("."),

      // will use your public key on server
      // that way you can connect with:
      // $ ssh git@REMOTE.IP
      // $ bash
      "/azk/deploy/.ssh": path("#{process.env.HOME}/.ssh")
    },

    // this is not a server
    // just call with azk shell deploy
    scalable: {"default": 0, "limit": 0},

    envs: {
      BOX_SIZE: '2gb',
      GIT_CHECKOUT_COMMIT_BRANCH_TAG: 'azkfile',
      AZK_RESTART_COMMAND: 'azk restart -Rvv',
      RUN_SETUP: 'true',
      RUN_CONFIGURE: 'true',
      RUN_DEPLOY: 'true',
    }
  },
  "fast-deploy": {
    extends: 'deploy',
    envs: {
      BOX_SIZE: '2gb',
      GIT_CHECKOUT_COMMIT_BRANCH_TAG: 'azkfile',
      AZK_RESTART_COMMAND: 'azk restart -Rvv',
      RUN_SETUP: 'false',
      RUN_CONFIGURE: 'false',
      RUN_DEPLOY: 'true',
    }
  },

});
<commit_msg>Replacing process.env to env in Azkfile.js<commit_after>/* globals systems path sync persistent */
/* eslint camelcase: [2, {properties: "never"}] */
/* eslint comma-dangle: [0, {properties: "never"}] */

/* see Azkfile.md */
systems({
  feedbin: {
    // Dependent systems
    depends: ["clock", "worker-slow", "worker", "redis", "postgres", "elasticsearch", "memcached"],
    // More images:  http://images.azk.io
    image: {"docker": "azukiapp/ruby:2.2"},
    // Steps to execute before running instances
    provision: [],
    workdir: "/azk/#{manifest.dir}",
    shell: "/bin/bash",
    command: "bundle exec rackup config.ru --pid /tmp/ruby.pid --port $HTTP_PORT --host 0.0.0.0",
    wait: {"retry": 40, "timeout": 10000},
    mounts: {
      // Uncomment the line below to use with two-way share (slower)
      //'/azk/#{manifest.dir}': path("."),
      // Run with one-way share rsync (faster)
      '/azk/#{manifest.dir}'        : sync("."),
      '/azk/bundler'                : persistent("bundler"),
      '/azk/#{manifest.dir}/tmp'    : persistent("tmp"),
      '/azk/#{manifest.dir}/.bundle': path(".bundle"),
      '/azk/#{manifest.dir}/log'    : path("log"),
    },
    scalable: {"default": 1},
    http: {
      domains: [
        "#{system.name}.#{azk.default_domain}", // default azk domain
        '#{env.HOST_DOMAIN}',                   // used if deployed
        '#{env.HOST_IP}',                       // used if deployed
      ]
    },
    envs: {
      // set instances variables
      RACK_ENV: "development",
      RUBY_ENV: "development",
    },
  },
  worker: {
    extends: 'feedbin',
    provision: [
      "bundle install --path /azk/bundler",
      "bundle exec rake db:setup",
    ],
    depends: ["postgres", "redis", "elasticsearch", "memcached"],
    command: 'bundle exec sidekiq -c 12 -q critical,3 -q feed_refresher_receiver,2 -q default',
    scalable: { limit: 1, default: 1},
    http: null,
    envs: {
      RACK_ENV: "development",
      RUBY_ENV: "development",
      DB_POOL: 12,
      LIBRATO_AUTORUN: 1,
    }
  },
  "worker-slow": {
    extends: 'feedbin',
    depends: ["postgres", "redis", "elasticsearch", "memcached"],
    command: 'bundle exec sidekiq -c 2 -q worker_slow_critical,3 -q worker_slow,2 -q favicon,1',
    scalable: { default: 1,  limit: 1 },
    http: null,
    envs: {
      RACK_ENV: "development",
      RUBY_ENV: "development",
      DB_POOL: 2
    }
  },
  clock: {
    extends: 'feedbin',
    depends: ["postgres", "redis", "elasticsearch", "memcached"],
    command: 'bundle exec clockwork lib/clock.rb',
    scalable: { default: 1,  limit: 1 },
    http: null,
    envs: {
      RACK_ENV: "development",
      RUBY_ENV: "development",
    }
  },
  redis: {
    image: {"docker": "redis"},
    export_envs: {
      "REDIS_HOST": "#{net.host}",
      "REDIS_PORT": "#{net.port.data}",
      "REDIS_URL": "redis://#{net.host}:#{net.port[6379]}",
    },
  },
  postgres: {
    // Dependent systems
    depends: [],
    // More images:  http://images.azk.io
    image: {"docker": "azukiapp/postgres:9.3"},
    shell: "/bin/bash",
    wait: {"retry": 40, "timeout": 1000},
    mounts: {
      '/var/lib/postgresql': persistent("postgresql"),
      '/var/log/postgresql': path("./log/postgresql"),
    },
    ports: {
      // exports global variables
      data: "5432/tcp",
    },
    envs: {
      // set instances variables
      POSTGRES_USER: "azk",
      POSTGRES_PASS: "azk",
      POSTGRES_DB  : "#{manifest.dir}",
    },
    export_envs: {
      // check this gist to configure your database
      // https://gist.github.com/gullitmiranda/62082f2e47c364ef9617
      DATABASE_URL: "postgres://#{envs.POSTGRES_USER}:#{envs.POSTGRES_PASS}@#{net.host}:#{net.port.data}/${envs.POSTGRES_DB}",
    },
  },
  elasticsearch: {
    image: { "docker": "barnybug/elasticsearch:0.90.13" },
    http: {
      domains: [ "#{system.name}.#{azk.default_domain}" ]
    },
    ports: {
      http: "9200",
    },
    wait: {"retry": 80, "timeout": 1000},
    export_envs : {
      ELASTICSEARCH_URL: "#{system.name}.#{azk.default_domain}:#{net.port[9200]}",
    },
  },
  memcached: {
    image: { "docker": "memcached" },
    ports: {
      http: "11211",
    },
    export_envs: {
      MEMCACHED_HOSTS: "#{system.name}.#{azk.default_domain}:#{net.port[11211]}"
    }
  },

  deploy: {
    image: {"docker": "azukiapp/deploy-digitalocean"},
    mounts: {

      // your files on remote machine
      // will be on /home/git folder
      "/azk/deploy/src":  path("."),

      // will use your public key on server
      // that way you can connect with:
      // $ ssh git@REMOTE.IP
      // $ bash
      "/azk/deploy/.ssh": path("#{env.HOME}/.ssh")
    },

    // this is not a server
    // just call with azk shell deploy
    scalable: {"default": 0, "limit": 0},

    envs: {
      BOX_SIZE: '2gb',
      GIT_CHECKOUT_COMMIT_BRANCH_TAG: 'azkfile',
      AZK_RESTART_COMMAND: 'azk restart -Rvv',
      RUN_SETUP: 'true',
      RUN_CONFIGURE: 'true',
      RUN_DEPLOY: 'true',
    }
  },
  "fast-deploy": {
    extends: 'deploy',
    envs: {
      BOX_SIZE: '2gb',
      GIT_CHECKOUT_COMMIT_BRANCH_TAG: 'azkfile',
      AZK_RESTART_COMMAND: 'azk restart -Rvv',
      RUN_SETUP: 'false',
      RUN_CONFIGURE: 'false',
      RUN_DEPLOY: 'true',
    }
  },

});
<|endoftext|>


<commit_before>/**
 * Documentation: http://docs.azk.io/Azkfile.js
 */

// Global image to reuse
//addImage('base', { repository: "cevich/empty_base_image" }); // tag: latest

  var join = require('path').join;
var config = require('azk').config;

var mounts = (function() {
  var _    = require('lodash');
  var glob = require('glob');

  var mounts = {
    "/.tmux.conf"      : join(env.HOME, ".tmux.conf"),
    "/azk/demos"       : "../demos",
    "/azk/build"       : persistent('build-#{system.name}'),
    "/azk/lib"         : persistent('lib-#{system.name}'),
    "/azk/data"        : persistent('data-#{system.name}'),
    "/var/lib/docker"  : persistent('docker_files-#{system.name}'),
    "/azk/#{manifest.dir}/node_modules": persistent('node_modules-#{system.name}'),
    "/azk/#{manifest.dir}/.nvmrc" : ".nvmrc",
  }

  var itens = glob.sync("./!(lib|data|node_modules|npm-debug.log)");
  mounts = _.reduce(itens, function(mount, item) {
    var key = join("/azk", "#{manifest.dir}", item);
    mount[key] = item;
    return mount;
  }, mounts);

  return mounts;
})();

var agent_system = function(image) {
  return {
    image: image,
    provision: [
      "azk check-install",
    ],
    scale: false,
    workdir: "/azk/#{manifest.dir}",
    shell: "/usr/local/bin/wrapdocker",
    mounts: mounts,
    envs: {
      PATH: "/azk/#{manifest.dir}/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin",
      AZK_DATA_PATH: "/azk/data",
      AZK_LIB_PATH : "/azk/lib",
      AZK_NAMESPACE: "azk.linux",
      AZK_PACKAGE_PATH: "/azk/build",
      AZK_BALANCER_PORT: 8080,
      LOG: "file",
      NODE_ENV: "test",
      EXTRA_SCRIPT: "/azk/#{manifest.dir}/src/libexec/init_azk",
    },
    docker_extra: {
      start: { Privileged: true },
    }
  };
}

var test_package_system = function(image){
  return {
    image: image,
    workdir: "/azk/#{manifest.dir}",
    shell: "/usr/local/bin/wrapdocker",
    mounts: {
      "/azk/demos"          : "../demos",
      "/azk/#{manifest.dir}": ".",
      "/azk/data"           : persistent('data-#{system.name}'),
      "/var/lib/docker"     : persistent('docker_files-#{system.name}'),
    },
    envs: {
      AZK_DATA_PATH: "/azk/data",
      LOG: "file", // Log docker to file
    },
    docker_extra: {
      start: { Privileged: true },
    }
  }
}

systems({
  'dind-ubuntu': agent_system('azukiapp/dind:ubuntu14'),
  'dind-fedora': agent_system('azukiapp/dind:fedora20'),

  package: agent_system('azukiapp/fpm'),
  'pkg-ubuntu12-test': test_package_system('azukiapp/dind:ubuntu12'),
  'pkg-ubuntu14-test': test_package_system('azukiapp/dind:ubuntu14'),
  'pkg-fedora-test': test_package_system('azukiapp/dind:fedora20'),

  grunt: {
    image: "dockerfile/nodejs",
    workdir: "/azk/#{manifest.dir}",
    mounts: {
      "/azk/#{manifest.dir}": ".",
    },
    envs: {
      PATH: "/bin:/sbin:/usr/bin:/usr/sbin:/usr/local/bin:/azk/#{manifest.dir}/node_modules/.bin"
    }
  },

  docs: {
    image: "dockerfile/python",
    //provision: [
      //'export INSTALL_DIR=/azk/<%= manifest.dir %>/vendor/python',
      //'pip install --target=$INSTALL_DIR --install-option="--install-scripts=$INSTALL_DIR/bin" sphinx',
    //],
    workdir: "/azk/#{manifest.dir}",
    mounts: {
      "/azk/#{manifest.dir}": ".",
    },
    //envs: {
      //PYTHONPATH: "/azk/<%= manifest.dir %>/vendor/python",
      //PATH: "/bin:/sbin:/usr/bin:/usr/sbin:/azk/<%= manifest.dir %>/vendor/python/bin"
    //}
  },
});

setDefault('docs');
<commit_msg>Setting “/bin/bash” as a default shell for “package” sister.<commit_after>/**
 * Documentation: http://docs.azk.io/Azkfile.js
 */

// Global image to reuse
//addImage('base', { repository: "cevich/empty_base_image" }); // tag: latest

var lodash = require('lodash');
var join   = require('path').join;
var config = require('azk').config;

var mounts = (function() {
  var glob = require('glob');
  var mounts = {
    "/.tmux.conf"      : join(env.HOME, ".tmux.conf"),
    "/azk/demos"       : "../demos",
    "/azk/build"       : persistent('build-#{system.name}'),
    "/azk/lib"         : persistent('lib-#{system.name}'),
    "/azk/data"        : persistent('data-#{system.name}'),
    "/var/lib/docker"  : persistent('docker_files-#{system.name}'),
    "/azk/#{manifest.dir}/node_modules": persistent('node_modules-#{system.name}'),
    "/azk/#{manifest.dir}/.nvmrc" : ".nvmrc",
  }

  var itens = glob.sync("./!(lib|data|node_modules|npm-debug.log)");
  mounts = lodash.reduce(itens, function(mount, item) {
    var key = join("/azk", "#{manifest.dir}", item);
    mount[key] = item;
    return mount;
  }, mounts);

  return mounts;
})();

var agent_system = function(image, extras) {
  extras = extras || {};

  return lodash.merge({
    image: image,
    provision: [
      "azk check-install",
    ],
    scale: false,
    workdir: "/azk/#{manifest.dir}",
    shell: "/usr/local/bin/wrapdocker",
    mounts: mounts,
    envs: {
      PATH: "/azk/#{manifest.dir}/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin",
      AZK_DATA_PATH: "/azk/data",
      AZK_LIB_PATH : "/azk/lib",
      AZK_NAMESPACE: "azk.linux",
      AZK_PACKAGE_PATH: "/azk/build",
      AZK_BALANCER_PORT: 8080,
      LOG: "file",
      NODE_ENV: "test",
      EXTRA_SCRIPT: "/azk/#{manifest.dir}/src/libexec/init_azk",
    },
    docker_extra: {
      start: { Privileged: true },
    }
  }, extras);
}

var test_package_system = function(image){
  return {
    image: image,
    workdir: "/azk/#{manifest.dir}",
    shell: "/usr/local/bin/wrapdocker",
    mounts: {
      "/azk/demos"          : "../demos",
      "/azk/#{manifest.dir}": ".",
      "/azk/data"           : persistent('data-#{system.name}'),
      "/var/lib/docker"     : persistent('docker_files-#{system.name}'),
    },
    envs: {
      AZK_DATA_PATH: "/azk/data",
      LOG: "file", // Log docker to file
    },
    docker_extra: {
      start: { Privileged: true },
    }
  }
}

systems({
  'dind-ubuntu': agent_system('azukiapp/dind:ubuntu14'),
  'dind-fedora': agent_system('azukiapp/dind:fedora20'),

  package: agent_system('azukiapp/fpm', {
    shell: "/bin/bash",
  }),
  'pkg-ubuntu12-test': test_package_system('azukiapp/dind:ubuntu12'),
  'pkg-ubuntu14-test': test_package_system('azukiapp/dind:ubuntu14'),
  'pkg-fedora-test': test_package_system('azukiapp/dind:fedora20'),

  grunt: {
    image: "dockerfile/nodejs",
    workdir: "/azk/#{manifest.dir}",
    mounts: {
      "/azk/#{manifest.dir}": ".",
    },
    envs: {
      PATH: "/bin:/sbin:/usr/bin:/usr/sbin:/usr/local/bin:/azk/#{manifest.dir}/node_modules/.bin"
    }
  },

  docs: {
    image: "dockerfile/python",
    //provision: [
      //'export INSTALL_DIR=/azk/<%= manifest.dir %>/vendor/python',
      //'pip install --target=$INSTALL_DIR --install-option="--install-scripts=$INSTALL_DIR/bin" sphinx',
    //],
    workdir: "/azk/#{manifest.dir}",
    mounts: {
      "/azk/#{manifest.dir}": ".",
    },
    //envs: {
      //PYTHONPATH: "/azk/<%= manifest.dir %>/vendor/python",
      //PATH: "/bin:/sbin:/usr/bin:/usr/sbin:/azk/<%= manifest.dir %>/vendor/python/bin"
    //}
  },
});

setDefault('docs');
<|endoftext|>


<commit_before>class Fixture extends React.Component {
  render () {
    return (

    )
  }
}

const it = createTest(<Fixture />)

describe('#tagName', () => {
  describe('(tagName)', () => {
    it('passes when the actual matches the expected', (wrapper) => {
      expect(wrapper).to.have.tagName('div')
      expect(wrapper.find('span')).to.have.tagName('span')
    })

    it('passes negated when the actual does not match the expected', (wrapper) => {
      expect(wrapper).to.not.have.tagName('span')
      expect(wrapper.find('span')).to.not.have.tagName('div')
    })

    it('fails when the actual does not match the expected', (wrapper) => {
      expect(() => {
        expect(wrapper).to.have.tagName('a')
      }).to.throw(`to have a 'a' tag name, but it has 'div'`)

      expect(() => {
        expect(wrapper.find('span')).to.have.tagName('a')
      }).to.throw(`to have a 'a' tag name, but it has 'span'`)
    })
  })
})
<commit_msg>Use a more clear assertion<commit_after>class Fixture extends React.Component {
  render () {
    return (

    )
  }
}

const it = createTest(<Fixture />)

describe('#tagName', () => {
  describe('(tagName)', () => {
    it('passes when the actual matches the expected', (wrapper) => {
      expect(wrapper).to.have.tagName('div')
      expect(wrapper.find('span')).to.have.tagName('span')
    })

    it('passes negated when the actual does not match the expected', (wrapper) => {
      expect(wrapper).to.not.have.tagName('a')
      expect(wrapper.find('span')).to.not.have.tagName('a')
    })

    it('fails when the actual does not match the expected', (wrapper) => {
      expect(() => {
        expect(wrapper).to.have.tagName('a')
      }).to.throw(`to have a 'a' tag name, but it has 'div'`)

      expect(() => {
        expect(wrapper.find('span')).to.have.tagName('a')
      }).to.throw(`to have a 'a' tag name, but it has 'span'`)
    })
  })
})
<|endoftext|>