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

  var superagent = require('superagent');
  var expect = require('expect.js');
  var testData = require('../include/testData.js');

  describe('Project API tests', function () {
    var id;
    var users = testData.testUsers;
    var projects = testData.testProjects;
    var agent = superagent.agent();

    it('Reset test', function (done) {
      agent.get('http://localhost:3000/test/project_api/reset/')
        .end(function (e, res) {
          expect(e)
            .to.eql(null);
          expect(res.ok)
            .to.be.ok();
          done();
        });
    });

    it('List projects', function (done) {
      agent.get('http://localhost:3000/projects/')
        .end(function (e, res) {
          expect(e)
            .to.eql(null);
          expect(res.ok)
            .to.be.ok();
          expect(res.body.length)
            .to.be(0);
          //console.log('\nCurrent Projects:\n' + JSON.stringify(res.body));

          done();
        });
    });

    it('Create project [0]', function (done) {
      var project = projects[0];

      agent.put('http://localhost:3000/projects/' + project.name + '/' +
        project.version + '/')
        .send(project)
        .end(function (e, res) {
          expect(e)
            .to.eql(null);
          expect(res.ok)
            .to.be.ok();
          done();
        });

    });

    it('Create project [1]', function (done) {
      var project = projects[1];

      agent.put('http://localhost:3000/projects/' + project.name + '/' +
        project.version + '/')
        .send(project)
        .end(function (e, res) {
          expect(e)
            .to.eql(null);
          expect(res.ok)
            .to.be.ok();
          done();
        });

    });

    it('Create project [2]', function (done) {
      var project = projects[2];

      agent.put('http://localhost:3000/projects/' + project.name + '/' +
        project.version + '/')
        .send(project)
        .end(function (e, res) {
          expect(e)
            .to.eql(null);
          expect(res.ok)
            .to.be.ok();
          done();
        });

    });

    it('List projects', function (done) {
      agent.get('http://localhost:3000/projects/')
        .end(function (e, res) {
          expect(e)
            .to.eql(null);
          expect(res.ok)
            .to.be.ok();

          //console.log('\nCurrent Projects:\n' + JSON.stringify(res.body));
          expect(res.body.length)
            .to.be(3);
          for (var i = 0; i < res.body.length; i++) {
            var a = res.body[i];
            var match = false;

            for (var j = 0; j < projects.length; j++) {
              var b = projects[j];
              if (a.name === b.name &&
                a.version === b.version) {
                match = true;
                break;
              }
            }
            expect(match)
              .to.be(true);
          }

          done();
        });
    });

    it('Create existing project [0]', function (done) {
      var project = projects[0];

      agent.put('http://localhost:3000/projects/' + project.name + '/' +
        project.version + '/')
        .send(project)
        .end(function (e, res) {
          expect(e)
            .to.eql(null);
          expect(res.status)
            .to.be(409);
          done();
        });

    });

    it('Create existing project [1]', function (done) {
      var project = projects[0];

      agent.put('http://localhost:3000/projects/' + project.name + '/' +
        project.version + '/')
        .send(project)
        .end(function (e, res) {
          expect(e)
            .to.eql(null);
          expect(res.status)
            .to.be(409);
          done();
        });

    });

    it('Create existing project [2]', function (done) {
      var project = projects[0];

      agent.put('http://localhost:3000/projects/' + project.name + '/' +
        project.version + '/')
        .send(project)
        .end(function (e, res) {
          expect(e)
            .to.eql(null);
          expect(res.status)
            .to.be(409);
          done();
        });

    });

    it('Increment version of project [0] to 1', function (done) {
      var project = projects[0];
      project.version += 1;

      agent.put('http://localhost:3000/projects/' + project.name + '/' +
        project.version + '/')
        .send(project)
        .end(function (e, res) {
          expect(e)
            .to.eql(null);
          expect(res.ok)
            .to.be.ok();
          done();
        });

    });

    it('Increment version of project [0] to 2', function (done) {
      var project = projects[0];
      project.version += 1;

      agent.put('http://localhost:3000/projects/' + project.name + '/' +
        project.version + '/')
        .send(project)
        .end(function (e, res) {
          expect(e)
            .to.eql(null);
          expect(res.ok)
            .to.be.ok();
          done();
        });

    });

    it('List projects (Should only show latest versions)', function (done) {
      agent.get('http://localhost:3000/projects/')
        .end(function (e, res) {
          expect(e)
            .to.eql(null);
          expect(res.ok)
            .to.be.ok();

          //console.log('\nCurrent Projects:\n' + JSON.stringify(projects));
          expect(res.body.length)
            .to.be(3);

          for (var i = 0; i < res.body.length; i++) {
            var a = res.body[i];
            var match = false;

            for (var j = 0; j < projects.length; j++) {
              var b = projects[j];
              if (a.name === b.name &&
                a.version === b.version) {
                match = true;
                break;
              }
            }
            if (!match) {
              console.log('\'' + JSON.stringify(a) + '\'not in \'' +
                JSON.stringify(projects) + '\'');
            }
            expect(match)
              .to.be(true);
          }

          done();
        });
    });

  });

})(require, describe, it);
<commit_msg>Fixed some references in project test<commit_after>(function (require, describe, it) {
  'use strict';

  var superagent = require('superagent');
  var expect = require('expect.js');
  var testData = require('../include/testData.js');

  describe('Project API tests', function () {
    var id;
    var users = testData.testUsers;
    var projects = testData.testProjects;
    var agent = superagent.agent();

    it('Reset test', function (done) {
      agent.get('http://localhost:3000/test/project_api/reset/')
        .end(function (e, res) {
          expect(e)
            .to.eql(null);
          expect(res.ok)
            .to.be.ok();
          done();
        });
    });

    it('List projects', function (done) {
      agent.get('http://localhost:3000/projects/')
        .end(function (e, res) {
          expect(e)
            .to.eql(null);
          expect(res.ok)
            .to.be.ok();
          expect(res.body.length)
            .to.be(0);
          //console.log('\nCurrent Projects:\n' + JSON.stringify(res.body));

          done();
        });
    });

    it('Create project [0]', function (done) {
      var project = projects[0];

      agent.put('http://localhost:3000/projects/' + project.name + '/' +
        project.version + '/')
        .send(project)
        .end(function (e, res) {
          expect(e)
            .to.eql(null);
          expect(res.ok)
            .to.be.ok();
          done();
        });

    });

    it('Create project [1]', function (done) {
      var project = projects[1];

      agent.put('http://localhost:3000/projects/' + project.name + '/' +
        project.version + '/')
        .send(project)
        .end(function (e, res) {
          expect(e)
            .to.eql(null);
          expect(res.ok)
            .to.be.ok();
          done();
        });

    });

    it('Create project [2]', function (done) {
      var project = projects[2];

      agent.put('http://localhost:3000/projects/' + project.name + '/' +
        project.version + '/')
        .send(project)
        .end(function (e, res) {
          expect(e)
            .to.eql(null);
          expect(res.ok)
            .to.be.ok();
          done();
        });

    });

    it('List projects', function (done) {
      agent.get('http://localhost:3000/projects/')
        .end(function (e, res) {
          expect(e)
            .to.eql(null);
          expect(res.ok)
            .to.be.ok();

          //console.log('\nCurrent Projects:\n' + JSON.stringify(res.body));
          expect(res.body.length)
            .to.be(3);
          for (var i = 0; i < res.body.length; i++) {
            var a = res.body[i];
            var match = false;

            for (var j = 0; j < projects.length; j++) {
              var b = projects[j];
              if (a.name === b.name &&
                a.version === b.version) {
                match = true;
                break;
              }
            }
            expect(match)
              .to.be(true);
          }

          done();
        });
    });

    it('Create existing project [0]', function (done) {
      var project = projects[0];

      agent.put('http://localhost:3000/projects/' + project.name + '/' +
        project.version + '/')
        .send(project)
        .end(function (e, res) {
          expect(e)
            .to.eql(null);
          expect(res.status)
            .to.be(409);
          done();
        });

    });

    it('Create existing project [1]', function (done) {
      var project = projects[1];

      agent.put('http://localhost:3000/projects/' + project.name + '/' +
        project.version + '/')
        .send(project)
        .end(function (e, res) {
          expect(e)
            .to.eql(null);
          expect(res.status)
            .to.be(409);
          done();
        });

    });

    it('Create existing project [2]', function (done) {
      var project = projects[2];

      agent.put('http://localhost:3000/projects/' + project.name + '/' +
        project.version + '/')
        .send(project)
        .end(function (e, res) {
          expect(e)
            .to.eql(null);
          expect(res.status)
            .to.be(409);
          done();
        });

    });

    it('Increment version of project [0] to 1', function (done) {
      var project = projects[0];
      project.version += 1;

      agent.put('http://localhost:3000/projects/' + project.name + '/' +
        project.version + '/')
        .send(project)
        .end(function (e, res) {
          expect(e)
            .to.eql(null);
          expect(res.ok)
            .to.be.ok();
          done();
        });

    });

    it('Increment version of project [0] to 2', function (done) {
      var project = projects[0];
      project.version += 1;

      agent.put('http://localhost:3000/projects/' + project.name + '/' +
        project.version + '/')
        .send(project)
        .end(function (e, res) {
          expect(e)
            .to.eql(null);
          expect(res.ok)
            .to.be.ok();
          done();
        });

    });

    it('List projects (Should only show latest versions)', function (done) {
      agent.get('http://localhost:3000/projects/')
        .end(function (e, res) {
          expect(e)
            .to.eql(null);
          expect(res.ok)
            .to.be.ok();

          //console.log('\nCurrent Projects:\n' + JSON.stringify(projects));
          expect(res.body.length)
            .to.be(3);

          for (var i = 0; i < res.body.length; i++) {
            var a = res.body[i];
            var match = false;

            for (var j = 0; j < projects.length; j++) {
              var b = projects[j];
              if (a.name === b.name &&
                a.version === b.version) {
                match = true;
                break;
              }
            }
            if (!match) {
              console.log('\'' + JSON.stringify(a) + '\'not in \'' +
                JSON.stringify(projects) + '\'');
            }
            expect(match)
              .to.be(true);
          }

          done();
        });
    });

  });

})(require, describe, it);
<|endoftext|>


<commit_before>this.adminAnnounce = function(message){
  jQuery(document).ready(function(){
    jQuery('body').prepend(
      jQuery('<div>')
	.text(message)
	.addClass('admin-announce'));
  });
};
<commit_msg>removed whitespace<commit_after>this.adminAnnounce = function(message){
  jQuery(document).ready(function(){
    jQuery('body').prepend(
      jQuery('<div>')
	.text(message)
	.addClass('admin-announce'));
  });
};
<|endoftext|>


<commit_before>/* @flow */

const timestamp = require('../../../../core/timestamp')

/*::
import type fs from 'fs-extra'
import type { Metadata, MetadataSidesInfo } from '../../../../core/metadata'
import type Pouch from '../../../../core/pouch'
*/

module.exports = class BaseMetadataBuilder {
  /*::
  pouch: ?Pouch
  opts: {
    path: string,
    ino?: number,
    updated_at?: string|Date,
    trashed?: true,
    sides: MetadataSidesInfo
  }
  */

  constructor (pouch /*: ?Pouch */) {
    this.pouch = pouch
    this.opts = {
      path: 'foo',
      sides: {},
      updated_at: timestamp.current()
    }
  }

  ino (ino /*: number */) /*: this */ {
    this.opts.ino = ino
    return this
  }

  stats ({ino, mtime, ctime} /*: fs.Stats */) /*: this */ {
    return this.ino(ino).updatedAt(timestamp.maxDate(mtime, ctime))
  }

  path (path /*: string */) /*: this */ {
    this.opts.path = path
    return this
  }

  trashed () /*: this */ {
    this.opts.trashed = true
    return this
  }

  updatedAt (date /*: Date */) /*: this */ {
    date = new Date(date)
    date.setMilliseconds(0)
    this.opts.updated_at = date.toISOString()
    return this
  }

  upToDate () /*: this */ {
    this.opts.sides = {local: 1, remote: 1}
    return this
  }

  notUpToDate () /*: this */ {
    this.opts.sides = {remote: 1}
    return this
  }

  build () /*: Metadata */ {
    throw new Error('BaseMetadataBuilder#build() not implemented')
  }

  async create () /*: Promise<Metadata> */ {
    if (this.pouch == null) {
      throw new Error('Cannot create dir metadata without Pouch')
    }
    const doc = this.build()
    // $FlowFixMe
    const {rev} = await this.pouch.put(doc)
    doc._rev = rev
    return doc
  }
}
<commit_msg>test/support/builders/metadata: Reuse timestamp.fromDate()<commit_after>/* @flow */

const timestamp = require('../../../../core/timestamp')

/*::
import type fs from 'fs-extra'
import type { Metadata, MetadataSidesInfo } from '../../../../core/metadata'
import type Pouch from '../../../../core/pouch'
*/

module.exports = class BaseMetadataBuilder {
  /*::
  pouch: ?Pouch
  opts: {
    path: string,
    ino?: number,
    updated_at?: string|Date,
    trashed?: true,
    sides: MetadataSidesInfo
  }
  */

  constructor (pouch /*: ?Pouch */) {
    this.pouch = pouch
    this.opts = {
      path: 'foo',
      sides: {},
      updated_at: timestamp.current()
    }
  }

  ino (ino /*: number */) /*: this */ {
    this.opts.ino = ino
    return this
  }

  stats ({ino, mtime, ctime} /*: fs.Stats */) /*: this */ {
    return this.ino(ino).updatedAt(timestamp.maxDate(mtime, ctime))
  }

  path (path /*: string */) /*: this */ {
    this.opts.path = path
    return this
  }

  trashed () /*: this */ {
    this.opts.trashed = true
    return this
  }

  updatedAt (date /*: Date */) /*: this */ {
    this.opts.updated_at = timestamp.fromDate(date).toISOString()
    return this
  }

  upToDate () /*: this */ {
    this.opts.sides = {local: 1, remote: 1}
    return this
  }

  notUpToDate () /*: this */ {
    this.opts.sides = {remote: 1}
    return this
  }

  build () /*: Metadata */ {
    throw new Error('BaseMetadataBuilder#build() not implemented')
  }

  async create () /*: Promise<Metadata> */ {
    if (this.pouch == null) {
      throw new Error('Cannot create dir metadata without Pouch')
    }
    const doc = this.build()
    // $FlowFixMe
    const {rev} = await this.pouch.put(doc)
    doc._rev = rev
    return doc
  }
}
<|endoftext|>


<commit_before>var limiter = require('limiter');
var request = require('request');
var util = require('util');

var _ = require('underscore');

var settings = require('./settings');

var QUERY_STRING_EXIST = /\?/;

var facebookQueue = [];

function facebookRequest(url_orig, limit, cb, payload) {
    var url = url_orig;
    if (url.substring(0, 4) !== 'http') {
        url = 'https://graph.facebook.com/' + url;
    }

    if (QUERY_STRING_EXIST.test(url)) {
        url += '&access_token=' + settings.FACEBOOK_ACCESS_TOKEN;
    }
    else {
        url += '?access_token=' + settings.FACEBOOK_ACCESS_TOKEN;
    }

    if (_.isFinite(limit)) {
        // If limit === 0 we want to fetch multiple pages, everything, so we go for 5000 per page
        url += '&limit=' + (limit || 5000);
    }

    function page(url, cb) {
        request({
            'url': url,
            'method': _.isObject(payload) ? 'POST' : 'GET',
            'form': payload
        }, function (error, res, body) {
            if (error || !res || res.statusCode !== 200) {
                cb("Facebook request (" + url_orig + ") error, error: " + error + ", status: " + (res && res.statusCode) + ", body: " + util.inspect(body));
                return;
            }

            try {
                body = JSON.parse(body);
            }
            catch (e) {
                cb("Facebook request (" + url_orig + ") parse error: " + e);
                return;
            }

            // If limit === 0 we want to fetch multiple pages, everything, so we go for next page, if available
            if (limit === 0 && body.data && body.data.length !== 0 && body.paging && body.paging.next) {
                page(body.paging.next, function (err, next_body) {
                    if (err) {
                        cb(err);
                        return;
                    }

                    // We take only body.data from next pages
                    body.data.push.apply(body.data, next_body.data);

                    cb(null, body);
                });
            }
            else {
                cb(null, body);
            }
        });
    }

    page(url, cb);
}

var facebookLimiter = new limiter.RateLimiter(settings.FACEBOOK_THROTTLE.requests, settings.FACEBOOK_THROTTLE.interval);

var queueWarning = _.throttle(function () {
    console.warn("Queue has grown to %s elements", facebookQueue.length);
}, 10 * 1000); // Warn only once per 10 s

var limiterWarning = _.throttle(function (remainingRequests) {
    console.warn("Limiter has only %s requests left", remainingRequests);
}, 10 * 1000); // Warn only once per 10 s

function processQueue() {
    var f = facebookQueue.pop();
    if (!f) {
        return;
    }

    if (facebookQueue.length > 1000) {
        // Ups, queue is really long
        queueWarning();
    }

    facebookLimiter.removeTokens(1, function(err, remainingRequests) {
        f();

        if (remainingRequests < 10) {
            limiterWarning(remainingRequests);
        }
    });
}

exports.request = function (url_orig, limit, cb, payload) {
    facebookQueue.unshift(function () {
        facebookRequest(url_orig, limit, function () {
            processQueue();
            cb.apply(this, arguments);
        }, payload);
    });
    processQueue();
};

exports.request.post = function (url, cb, payload) {
    payload = payload || {};
    exports.request(url, null, cb, payload);
};
<commit_msg>Output number of elements in the queue when limiting is in the effect.<commit_after>var limiter = require('limiter');
var request = require('request');
var util = require('util');

var _ = require('underscore');

var settings = require('./settings');

var QUERY_STRING_EXIST = /\?/;

var facebookQueue = [];

function facebookRequest(url_orig, limit, cb, payload) {
    var url = url_orig;
    if (url.substring(0, 4) !== 'http') {
        url = 'https://graph.facebook.com/' + url;
    }

    if (QUERY_STRING_EXIST.test(url)) {
        url += '&access_token=' + settings.FACEBOOK_ACCESS_TOKEN;
    }
    else {
        url += '?access_token=' + settings.FACEBOOK_ACCESS_TOKEN;
    }

    if (_.isFinite(limit)) {
        // If limit === 0 we want to fetch multiple pages, everything, so we go for 5000 per page
        url += '&limit=' + (limit || 5000);
    }

    function page(url, cb) {
        request({
            'url': url,
            'method': _.isObject(payload) ? 'POST' : 'GET',
            'form': payload
        }, function (error, res, body) {
            if (error || !res || res.statusCode !== 200) {
                cb("Facebook request (" + url_orig + ") error, error: " + error + ", status: " + (res && res.statusCode) + ", body: " + util.inspect(body));
                return;
            }

            try {
                body = JSON.parse(body);
            }
            catch (e) {
                cb("Facebook request (" + url_orig + ") parse error: " + e);
                return;
            }

            // If limit === 0 we want to fetch multiple pages, everything, so we go for next page, if available
            if (limit === 0 && body.data && body.data.length !== 0 && body.paging && body.paging.next) {
                page(body.paging.next, function (err, next_body) {
                    if (err) {
                        cb(err);
                        return;
                    }

                    // We take only body.data from next pages
                    body.data.push.apply(body.data, next_body.data);

                    cb(null, body);
                });
            }
            else {
                cb(null, body);
            }
        });
    }

    page(url, cb);
}

var facebookLimiter = new limiter.RateLimiter(settings.FACEBOOK_THROTTLE.requests, settings.FACEBOOK_THROTTLE.interval);

var queueWarning = _.throttle(function () {
    console.warn("Queue has grown to %s elements", facebookQueue.length);
}, 10 * 1000); // Warn only once per 10 s

var limiterWarning = _.throttle(function (remainingRequests) {
    console.warn("Limiter has only %s requests left, %s in the queue", remainingRequests, acebookQueue.length);
}, 10 * 1000); // Warn only once per 10 s

function processQueue() {
    var f = facebookQueue.pop();
    if (!f) {
        return;
    }

    if (facebookQueue.length > 1000) {
        // Ups, queue is really long
        queueWarning();
    }

    facebookLimiter.removeTokens(1, function(err, remainingRequests) {
        f();

        if (remainingRequests < 10) {
            limiterWarning(remainingRequests);
        }
    });
}

exports.request = function (url_orig, limit, cb, payload) {
    facebookQueue.unshift(function () {
        facebookRequest(url_orig, limit, function () {
            processQueue();
            cb.apply(this, arguments);
        }, payload);
    });
    processQueue();
};

exports.request.post = function (url, cb, payload) {
    payload = payload || {};
    exports.request(url, null, cb, payload);
};
<|endoftext|>


<commit_before>// test-onm.Store.createComponent.js
//

var assert = require('chai').assert;
var expect = require('chai').expect;
var should = require('chai').should;
var uuid = require('node-uuid');
var onm = require('../onm');
var testData = require('./fixture/test-data');

module.exports = describe("onm.Store.createComponent method tests", function() {

    var store = null;
    var addressRoot = null;
    var badDataModel = null;
    var badAddress = null;

    before(function() {
        store = testData.createStore();
        assert.isNotNull(store);
        assert.instanceOf(store, onm.Store);
        addressRoot = store.model.createRootAddress();
        assert.isNotNull(addressRoot);
        assert.instanceOf(addressRoot, onm.Address);
        badDataModel = new onm.Model({ jsonTag: 'bogus' });
        badAddress = badDataModel.createRootAddress();
    });

    it("Attempt to call onm.Store.createComponent with a null onm.Address parameter should throw.", function() {
        assert.throws(function () { store.createComponent(); }, Error);
    });

    it("Attempt to call onm.Store.createComponent with an address of a non 'addressBook' data model should throw.", function() {
        assert.throws(function () { store.createComponent(badAddress); }, Error);
    });

    it("Attempt to call onm.Store.createComponent with a qualified address should throw.", function() {
        assert.throws(function() { store.createComponent(addressRoot); }, Error);
    });

    it("Attempt to call onm.Store.createComponent with a non-component address should throw.", function() {
        var address = addressRoot.createSubpathAddress('properties.subproperties');
        assert.throws(function() { store.createComponent(address); }, Error);
    });

    describe("Call onm.Store.createComponent to create a new 'contact'.", function() {

        var addressNewContact = null;
        var namespaceContact = null;

        before(function() {
            addressNewContact = addressRoot.createSubpathAddress("contacts.contact");
            namespaceContact  = store.createComponent(addressNewContact);
        });

        it("We should be able to create a contact component.", function() {
            assert.isDefined(namespaceContact);
            assert.isNotNull(namespaceContact);
            assert.instanceOf(namespaceContact, onm.Namespace);
        });

        describe("Call onm.Store.createComponent with a single-key key array parameter.", function() {
            var keyArray = [ 'test' ];
            before(function() {
                namespaceContact = store.createComponent(addressNewContact, keyArray);
            });
            it("We should be able to create a contact component.", function() {
                assert.isDefined(namespaceContact);
                assert.isNotNull(namespaceContact);
                assert.instanceOf(namespaceContact, onm.Namespace);
            });
        });

    });
});

<commit_msg>A few more tests for onm.Store.createComponent.<commit_after>// test-onm.Store.createComponent.js
//

var assert = require('chai').assert;
var expect = require('chai').expect;
var should = require('chai').should;
var uuid = require('node-uuid');
var onm = require('../onm');
var testData = require('./fixture/test-data');

module.exports = describe("onm.Store.createComponent method tests", function() {

    var store = null;
    var addressRoot = null;
    var badDataModel = null;
    var badAddress = null;

    before(function() {
        store = testData.createStore();
        assert.isNotNull(store);
        assert.instanceOf(store, onm.Store);
        addressRoot = store.model.createRootAddress();
        assert.isNotNull(addressRoot);
        assert.instanceOf(addressRoot, onm.Address);
        badDataModel = new onm.Model({ jsonTag: 'bogus' });
        badAddress = badDataModel.createRootAddress();
    });

    it("Attempt to call onm.Store.createComponent with a null onm.Address parameter should throw.", function() {
        assert.throws(function () { store.createComponent(); }, Error);
    });

    it("Attempt to call onm.Store.createComponent with an address of a non 'addressBook' data model should throw.", function() {
        assert.throws(function () { store.createComponent(badAddress); }, Error);
    });

    it("Attempt to call onm.Store.createComponent with a qualified address should throw.", function() {
        assert.throws(function() { store.createComponent(addressRoot); }, Error);
    });

    it("Attempt to call onm.Store.createComponent with a non-component address should throw.", function() {
        var address = addressRoot.createSubpathAddress('properties.subproperties');
        assert.throws(function() { store.createComponent(address); }, Error);
    });

    describe("Call onm.Store.createComponent to create a new 'contact'.", function() {

        var addressNewContact = null;
        var namespaceContact = null;

        before(function() {
            addressNewContact = addressRoot.createSubpathAddress("contacts.contact");
            namespaceContact  = store.createComponent(addressNewContact);
        });

        it("We should be able to create a contact component.", function() {
            assert.isDefined(namespaceContact);
            assert.isNotNull(namespaceContact);
            assert.instanceOf(namespaceContact, onm.Namespace);
        });

        describe("Call onm.Store.createComponent with a single-key key array parameter.", function() {
            var keyArray = [ 'test' ];
            before(function() {
                namespaceContact = store.createComponent(addressNewContact, keyArray);
            });
            it("We should be able to create a contact component.", function() {
                assert.isDefined(namespaceContact);
                assert.isNotNull(namespaceContact);
                assert.instanceOf(namespaceContact, onm.Namespace);
            });
            it("The component key of the newly-created component should be 'test'.", function() {
                assert.equal(namespaceContact.getComponentKey(), "test");
            });
        });

        describe("Call onm.Store.createComponent with too many optional component override keys.", function() {
            var keyArray = [ 'test', 'error' ];
            it("The key array should be rejected because it is too long.", function() {
                assert.throws(function() { store.createComponent(addressNewContact, keyArray); }, Error);
            });
        });

        describe("Call onm.Store.createComponent with two optional override component keys.", function() {
            var keyArray = [ 'JoeSmith', 'primary' ];
            var addressNewEmail = null;
            before(function() {
                addressNewEmail = addressRoot.createSubpathAddress("contacts.contact.emails.email");
                namespaceContact = store.createComponent(addressNewEmail, keyArray);
            });
            it("We should be able to create a contact component.", function() {
                assert.isDefined(namespaceContact);
                assert.isNotNull(namespaceContact);
                assert.instanceOf(namespaceContact, onm.Namespace);
            });
            it("The component key of the newly-created component should be 'primary'.", function() {
                assert.equal(namespaceContact.getComponentKey(), "primary");
            });

        });

        describe("Serialize the test data store to JSON and compare the results against a known good snapshot.", function() {
            var expectedJSON = '{"addressBook":{"properties":{"name":"","description":"","subproperties":{"collection":{}}},"contacts":{"5":{"firstName":"","lastName":"","key":"5","emails":{},"addresses":{}},"test":{"firstName":"","lastName":"","key":"test","emails":{},"addresses":{}},"JoeSmith":{"firstName":"","lastName":"","key":"JoeSmith","emails":{"primary":{"key":"primary"}},"addresses":{}}}}}';
            var actualJSON = null;
            before(function() {
                actualJSON = store.toJSON();
            });
            it("The data store's JSON data should match the test's control JSON.", function() {
                assert.equal(actualJSON, expectedJSON);
            });
        });

    });
});

<|endoftext|>


<commit_before>'use strict';

var Mongo, Tracker;

describe('Given the Angular Meteor Utils Service', function () {

  var $meteorUtils, $scope;

  beforeEach(function () {

    module('angular-meteor.utils');
    // Injecting Services to use
    inject(function (_$meteorUtils_, _$rootScope_) {
      $meteorUtils = _$meteorUtils_;
      // Creates a new child scope.
      $scope = _$rootScope_.$new();
    });

  });

  describe('when using GetCollectionByName(collectionName)', function () {

    beforeEach(function () {

      // Mocking Collection
      function Collection() {
      }

      Collection.prototype._name = 'myCollection';
      Mongo = {Collection: Collection};
      window.myCol = new Mongo.Collection;
    });

    it('should find and return a mongo collection by name', function () {
      var output = $meteorUtils.getCollectionByName('myCollection');
      expect(output).toEqual(window.myCol);

    });

    it('should return "undefined" if it can\'t find the collection', function () {

      var output = $meteorUtils.getCollectionByName('myCollectionFake');
      expect(output).toBeUndefined();

    })
  });

  describe('when using autorun(scope, function)', function () {

    beforeEach(function () {

      // Mocking Tracker behavior
      Tracker = {
        autorun: function (fn) {
          return 'autorun';
        }
      }
    });

    it('should return the "autorun" object so that can be stopped manually', function () {

      function fn() {
      }

      var output = $meteorUtils.autorun($scope, fn);
      expect(output).toEqual('autorun');

    });

  });

});
<commit_msg>Tests: Meteor Utils, Case where firstRun is false, to make sure that $scope.$apply() gets called.<commit_after>'use strict';

var Mongo, Tracker;

describe('Given the Angular Meteor Utils Service', function () {

  var $meteorUtils, $scope;

  beforeEach(function () {

    module('angular-meteor.utils');
    // Injecting Services to use
    inject(function (_$meteorUtils_, _$rootScope_) {
      $meteorUtils = _$meteorUtils_;
      // Creates a new child scope.
      $scope = _$rootScope_.$new();
    });

  });

  describe('when using GetCollectionByName(collectionName)', function () {

    beforeEach(function () {

      // Mocking Collection
      function Collection() {
      }

      Collection.prototype._name = 'myCollection';
      Mongo = {Collection: Collection};
      window.myCol = new Mongo.Collection;
    });

    it('should find and return a mongo collection by name', function () {
      var output = $meteorUtils.getCollectionByName('myCollection');
      expect(output).toEqual(window.myCol);

    });

    it('should return "undefined" if it can\'t find the collection', function () {

      var output = $meteorUtils.getCollectionByName('myCollectionFake');
      expect(output).toBeUndefined();

    })
  });

  describe('when using autorun(scope, function)', function () {

    beforeEach(function () {

      // Mocking Tracker behavior
      Tracker = {
        autorun: function (fn) {
          return 'autorun';
        }
      }
    });

    it('should return the "autorun" object so that can be stopped manually', function () {

      var output = $meteorUtils.autorun($scope, function fn() {});
      expect(output).toEqual('autorun');

    });

    describe('when firstRun is set to: false', function() {

      beforeEach(function() {

        Tracker = {
          autorun: function (fn) {
            fn({firstRun: false})
          }
        };

        spyOn($scope, '$apply');

      });

      it('should call $scope.$apply()', function(done) {

        $meteorUtils.autorun($scope, function fn() {});

        setTimeout(function() {
          expect($scope.$apply).toHaveBeenCalled();
          done()
        }, 0);
      });

    });

  });

});
<|endoftext|>


<commit_before>var APILightbox = window.APILightbox ? window.APILightbox : {};

// function called by eval-ing response from Flickr
function jsonFlickrApi(response) {
  if(response.stat == 'ok') {
    APILightbox.populateResults(response);
  }
}

APILightbox = {
  flickrApiKey:      '7b491816b7ce18f1f848e52962352ee7',
  flickrRestUrlBase: 'https://www.flickr.com/services/rest/',
  searchText:        'delphinium',
  currentPhotoIndex: 0,
  maxPhotoIndex:     24,
  photos:            {},

  utils: {
    hide: function(element) {
      element.className = element.className.replace(/\sshow/i, '');
      element.className += ' hide';
    },

    show: function(element, height) {
      element.className = element.className.replace(/\shide/i, '');
      element.className += ' show';
      element.style     = "height: " + height + ";";
    },

    sanitizeInput: function(string) {
      danger = [
        /<script[^>]*?>.*?<\/script>/gi, // Strip out javascript
        /<style[^>]*?>.*?<\/style>/gi,   // Strip style tags
        /<![\s\S]*?--[ \t\n\r]*>/gi,     // Strip multi-line comments
        /<[\/\!]*?[^<>]*?>/gi            // Strip out HTML tags
      ];

      for(var i = 0; i < danger.length; i++) {
        string = string.replace(danger[i], '');
      }

      // Also collapse multiple spaces down to one
      string = string.replace(/\s+/, ' ');

      return string;
    },

    ajax: function(method, url, data, callback, type) {
      var xhr                = new XMLHttpRequest();
      xhr.onreadystatechange = readystatechange;
      xhr.responseType       = type ? type : "";
      xhr.open(method, url);
      xhr.send(data && JSON.stringify(data));

      function readystatechange() {
        if(xhr.readyState == xhr.DONE) {
          if(xhr.status == 200) {
            callback(xhr.status, xhr.response);
          } else {
            callback(xhr.status, null);
          }
        }
      }
    },

    buildUrlParams: function(options) {
      var params = "?";
      for(var key in options) {
        value = options[key];

        if(typeof key == "string" && typeof value == "string") {
          params += key + "=" + value + "&";
        }
      }
      // Remove that extraneous last '&'
      params = params.replace(/&$/, '');

      return params;
    },

    buildFlickrOptions: function(options) {
      options         = options ? options : {};

      options.format  = 'json';
      options.api_key = APILightbox.flickrApiKey;

      return options;
    },

    buildFlickrPhotoUrl: function(photo) {
      /*
      ** Flickr photo urls take the following format:
      **
      ** https://farm{farm-id}.staticflickr.com/{server-id}/{id}_{secret}_{size}.jpg
      */

      return "https://farm" + photo.farm +
             ".staticflickr.com/" + photo.server + "/" +
             photo.id + "_" + photo.secret + "_" + "c.jpg";
    }
  },

  getImages: function(searchText, maxCount) {
    var flickrMaxCountPerPage = 500;

    if(maxCount && typeof (maxCount * 1) == 'number' &&
       maxCount <= flickrMaxCountPerPage &&
       maxCount != APILightbox.maxPhotoIndex + 1) {
      APILightbox.maxPhotoIndex = maxCount;
    }

    if(searchText && typeof searchText == 'string') {
      APILightbox.searchText = searchText;
    }

    var flickrOptions = {
      method:       'flickr.photos.search',
      text:         searchText ? searchText : APILightbox.searchText,
      page:         1,
      per_page:     maxCount ? maxCount : APILightbox.maxPhotoIndex + 1,
      media:        'photos',
      content_type: 1
    };

    flickrOptions = APILightbox.utils.buildFlickrOptions(flickrOptions);

    var url = APILightbox.flickrRestUrlBase;

    url += APILightbox.utils.buildUrlParams(flickrOptions);

    APILightbox.utils.ajax('get', url, null, function(status, response) {
      if(status == 200) {

      }
    });
  },

  populateResults: function(response) {
    var searchString = document.querySelectorAll('h1 .search-string')[0];

    if(response.photos.total * 1 > 0) {
      APILightbox.photos = response.photos;
      APILightbox.showImage(0, response.photos);
      searchString.innerText = APILightbox.searchText;
    } else {
      searchString.innerText = "No results found.";
    }
  },

  showImage: function(index) {
    var title = document.querySelectorAll('.lightbox .title')[0],
        image = document.querySelectorAll('.response .photo')[0];

    APILightbox.currentPhotoIndex = index;
    photo                         = APILightbox.photos.photo[index];
    title.innerText               = photo.title;
    image.src                     = APILightbox.utils.buildFlickrPhotoUrl(photo);
  },

  showPreviousImage: function() {
    var previousIndex = APILightbox.currentPhotoIndex - 1;
    if(previousIndex < 0) previousIndex = APILightbox.maxPhotoIndex;

    APILightbox.showImage(previousIndex);
  },

  showNextImage: function() {
    var nextIndex = APILightbox.currentPhotoIndex + 1;
    if(nextIndex > APILightbox.maxPhotoIndex) nextIndex = 0;

    APILightbox.showImage(nextIndex);
  },

  showSearchForm: function() {
    var searchForm  = document.querySelectorAll('.search-form')[0],
        searchInput = document.querySelectorAll('.search-form .search-keywords')[0];

    searchInput.value = '';
    APILightbox.utils.show(searchForm, '30px');
    searchInput.focus();
  },

  checkEnter: function(event) {
    var characterCode = event.keyCode;

    if(characterCode == 13) { // if enter key
      APILightbox.doSearch();
      return false;
    } else {
      return true;
    }
  },

  doSearch: function() {
    var searchForm   = document.querySelectorAll('.search-form')[0],
        searchString = document.querySelectorAll('.page-title .search-string')[0],
        searchInput  = document.querySelectorAll('.search-form .search-keywords')[0];

    var keywords = APILightbox.utils.sanitizeInput(searchInput.value);
    if(keywords != '' && keywords != ' ')
    {
      APILightbox.getImages(keywords);
      APILightbox.utils.hide(searchForm);
    }
  },

  initialize: function() {
    var edit        = document.querySelectorAll('.page-title .edit')[0],
        searchInput = document.querySelectorAll('.search-form .search-keywords')[0],
        search      = document.querySelectorAll('.search-form .search')[0],
        previous    = document.querySelectorAll('.lightbox .paging-controls .previous')[0],
        next        = document.querySelectorAll('.lightbox .paging-controls .next')[0];

    edit.addEventListener('click', APILightbox.showSearchForm, false);
    searchInput.addEventListener('keypress', APILightbox.checkEnter, false);
    search.addEventListener('click', APILightbox.doSearch, false);
    previous.addEventListener('click', APILightbox.showPreviousImage, false);
    next.addEventListener('click', APILightbox.showNextImage, false);
  }
};
<commit_msg>Make it work like it should.<commit_after>var APILightbox = window.APILightbox ? window.APILightbox : {};

APILightbox = {
  flickrApiKey:      '7b491816b7ce18f1f848e52962352ee7',
  flickrRestUrlBase: 'https://www.flickr.com/services/rest/',
  searchText:        'delphinium',
  currentPhotoIndex: 0,
  maxPhotoIndex:     24,
  photos:            {},

  utils: {
    hide: function(element) {
      element.className = element.className.replace(/\sshow/i, '');
      element.className += ' hide';
    },

    show: function(element, height) {
      element.className = element.className.replace(/\shide/i, '');
      element.className += ' show';
      element.style     = "height: " + height + ";";
    },

    sanitizeInput: function(string) {
      danger = [
        /<script[^>]*?>.*?<\/script>/gi, // Strip out javascript
        /<style[^>]*?>.*?<\/style>/gi,   // Strip style tags
        /<![\s\S]*?--[ \t\n\r]*>/gi,     // Strip multi-line comments
        /<[\/\!]*?[^<>]*?>/gi            // Strip out HTML tags
      ];

      for(var i = 0; i < danger.length; i++) {
        string = string.replace(danger[i], '');
      }

      // Also collapse multiple spaces down to one
      string = string.replace(/\s+/, ' ');

      return string;
    },

    ajax: function(method, url, data, callback, type) {
      var xhr                = new XMLHttpRequest();
      xhr.onreadystatechange = readystatechange;
      xhr.responseType       = type ? type : "";
      xhr.open(method, url);
      xhr.send(data && JSON.stringify(data));

      function readystatechange() {
        if(xhr.readyState == xhr.DONE) {
          if(xhr.status == 200) {
            callback(xhr.status, xhr.response);
          } else {
            callback(xhr.status, null);
          }
        }
      }
    },

    buildUrlParams: function(options) {
      var params = "?";
      for(var key in options) {
        value = options[key];
        value = (value + "").replace(/\s+/g, '+');
        params += key + "=" + value + "&";
      }
      // Remove that extraneous last '&'
      params = params.replace(/&$/, '');

      return params;
    },

    buildFlickrOptions: function(options) {
      options                = options ? options : {};

      options.format         = 'json';
      options.api_key        = APILightbox.flickrApiKey;
      options.nojsoncallback = 1;

      return options;
    },

    buildFlickrPhotoUrl: function(photo) {
      /*
      ** Flickr photo urls take the following format:
      **
      ** https://farm{farm-id}.staticflickr.com/{server-id}/{id}_{secret}_{size}.jpg
      */

      return "https://farm" + photo.farm +
             ".staticflickr.com/" + photo.server + "/" +
             photo.id + "_" + photo.secret + "_" + "c.jpg";
    }
  },

  getImages: function(searchText, maxCount) {
    var flickrMaxCountPerPage = 500;

    if(maxCount && typeof (maxCount * 1) == 'number' &&
       maxCount <= flickrMaxCountPerPage &&
       maxCount != APILightbox.maxPhotoIndex + 1) {
      APILightbox.maxPhotoIndex = maxCount - 1;
    }

    if(searchText && typeof searchText == 'string') {
      APILightbox.searchText = searchText;
    }

    var flickrOptions = {
      method:       'flickr.photos.search',
      text:         searchText ? searchText : APILightbox.searchText,
      page:         1,
      per_page:     maxCount ? maxCount : APILightbox.maxPhotoIndex + 1,
      media:        'photos',
      content_type: 1
    };

    flickrOptions = APILightbox.utils.buildFlickrOptions(flickrOptions);

    var url = APILightbox.flickrRestUrlBase;

    url += APILightbox.utils.buildUrlParams(flickrOptions);

    APILightbox.utils.ajax('get', url, null, function(status, response) {
      response = JSON.parse(response);
      if(status == 200 && response.stat == 'ok') {
        APILightbox.populateResults(response);
      }
    });
  },

  populateResults: function(response) {
    var searchString = document.querySelectorAll('h1 .search-string')[0];

    if(response.photos.total * 1 > 0) {
      APILightbox.photos = response.photos;
      APILightbox.showImage(0, response.photos);
      searchString.innerText = APILightbox.searchText;
    } else {
      searchString.innerText = "No results found.";
    }
  },

  showImage: function(index) {
    var title = document.querySelectorAll('.lightbox .title')[0],
        image = document.querySelectorAll('.response .photo')[0];

    APILightbox.currentPhotoIndex = index;
    photo                         = APILightbox.photos.photo[index];
    title.innerText               = photo.title;
    image.src                     = APILightbox.utils.buildFlickrPhotoUrl(photo);
  },

  showPreviousImage: function() {
    var previousIndex = APILightbox.currentPhotoIndex - 1;
    if(previousIndex < 0) previousIndex = APILightbox.maxPhotoIndex;

    APILightbox.showImage(previousIndex);
  },

  showNextImage: function() {
    var nextIndex = APILightbox.currentPhotoIndex + 1;
    if(nextIndex > APILightbox.maxPhotoIndex) nextIndex = 0;

    APILightbox.showImage(nextIndex);
  },

  showSearchForm: function() {
    var searchForm  = document.querySelectorAll('.search-form')[0],
        searchInput = document.querySelectorAll('.search-form .search-keywords')[0];

    searchInput.value = '';
    APILightbox.utils.show(searchForm, '30px');
    searchInput.focus();
  },

  checkEnter: function(event) {
    var characterCode = event.keyCode;

    if(characterCode == 13) { // if enter key
      APILightbox.doSearch();
      return false;
    } else {
      return true;
    }
  },

  doSearch: function() {
    var searchForm   = document.querySelectorAll('.search-form')[0],
        searchString = document.querySelectorAll('.page-title .search-string')[0],
        searchInput  = document.querySelectorAll('.search-form .search-keywords')[0];

    var keywords = APILightbox.utils.sanitizeInput(searchInput.value);
    if(keywords != '' && keywords != ' ')
    {
      APILightbox.getImages(keywords);
      APILightbox.utils.hide(searchForm);
    }
  },

  initialize: function() {
    var edit        = document.querySelectorAll('.page-title .edit')[0],
        searchInput = document.querySelectorAll('.search-form .search-keywords')[0],
        search      = document.querySelectorAll('.search-form .search')[0],
        previous    = document.querySelectorAll('.lightbox .paging-controls .previous')[0],
        next        = document.querySelectorAll('.lightbox .paging-controls .next')[0];

    edit.addEventListener('click', APILightbox.showSearchForm, false);
    searchInput.addEventListener('keypress', APILightbox.checkEnter, false);
    search.addEventListener('click', APILightbox.doSearch, false);
    previous.addEventListener('click', APILightbox.showPreviousImage, false);
    next.addEventListener('click', APILightbox.showNextImage, false);
  }
};
<|endoftext|>


<commit_before>exports['Project.prototype.collect'] = {
  setUp: function(done) {
    this.sandbox = sinon.sandbox.create();
    this.project = new Project({
      entry: path.join(process.cwd(), 'eg/project-conditional/index.js'),
    });
    done();
  },

  tearDown: function(done) {
    this.sandbox.restore();
    done();
  },

  returnsPromise: function(test) {
    test.expect(5);
    var p = this.project.collect();

    test.equal(p instanceof Promise, true);

    p.then((entries) => {
      ['a', 'b', 'c', 'index'].forEach((name) => {
        test.ok(entries.find(entry => entry.id.endsWith(name + '.js')));
      });
      test.done();
    });
  },

  acceptsCallback: function(test) {
    test.expect(5);
    this.project.collect(function(error, entries) {

      test.equal(error, null);

      ['a', 'b', 'c', 'index'].forEach((name) => {
        test.ok(entries.find(entry => entry.id.endsWith(name + '.js')));
      });

      test.done();
    });
  },

  removesExcludedFiles: function(test) {
    test.expect(6);

    this.project.exclude(['b.js', 'c.js']);

    this.project.collect(function(error, entries) {

      test.equal(error, null);
      test.equal(entries.length, 2);
      ['a', 'index'].forEach((name) => {
        test.ok(entries.find(entry => entry.id.endsWith(name + '.js')));
      });

      // These will not be present
      ['b', 'c'].forEach((name) => {
        test.equal(entries.find(entry => entry.id.endsWith(name + '.js')), undefined);
      });

      test.done();
    });
  },
};

exports['Project.prototype.collect with node_modules'] = {
  setUp: function(done) {
    this.sandbox = sinon.sandbox.create();
    this.project = new Project({
      entry: path.join(process.cwd(), 'eg/project-simple/index.js'),
    });
    done();
  },

  tearDown: function(done) {
    this.sandbox.restore();
    done();
  },

  // returnsPromise: function(test) {
  //   test.expect(5);
  //   var p = this.project.collect();

  //   test.equal(p instanceof Promise, true);

  //   p.then((entries) => {
  //     ['a', 'b', 'c', 'index'].forEach((name) => {
  //       test.ok(entries.find(entry => entry.id.endsWith(name + '.js')));
  //     });
  //     test.done();
  //   });
  // },

  providesPackageJson: function(test) {
    // test.expect(5);
    this.project.collect(function(error, entries) {

      test.equal(error, null);

      console.log(entries.length);
      ['', 'index'].forEach((name) => {
        test.ok(entries.find(entry => entry.id.endsWith(name + '.js')));
      });
      test.done();
    });
  },

  // removesExcludedFiles: function(test) {
  //   test.expect(6);

  //   this.project.exclude(['b.js', 'c.js']);

  //   this.project.collect(function(error, entries) {

  //     test.equal(error, null);
  //     test.equal(entries.length, 2);

  //     ['a', 'index'].forEach((name) => {
  //       test.ok(entries.find(entry => entry.id.endsWith(name + '.js')));
  //     });

  //     // These will not be present
  //     ['b', 'c'].forEach((name) => {
  //       test.equal(entries.find(entry => entry.id.endsWith(name + '.js')), undefined);
  //     });

  //     test.done();
  //   });
  // },
};
<commit_msg>Tests for package.json inclusion<commit_after>exports['Project.prototype.collect'] = {
  setUp: function(done) {
    this.sandbox = sinon.sandbox.create();
    this.project = new Project({
      entry: path.join(process.cwd(), 'eg/project-conditional/index.js'),
    });
    done();
  },

  tearDown: function(done) {
    this.sandbox.restore();
    done();
  },

  returnsPromise: function(test) {
    test.expect(5);
    var p = this.project.collect();

    test.equal(p instanceof Promise, true);

    p.then((entries) => {
      ['a', 'b', 'c', 'index'].forEach((name) => {
        test.ok(entries.find(entry => entry.id.endsWith(name + '.js')));
      });
      test.done();
    });
  },

  acceptsCallback: function(test) {
    test.expect(5);
    this.project.collect(function(error, entries) {

      test.equal(error, null);

      ['a', 'b', 'c', 'index'].forEach((name) => {
        test.ok(entries.find(entry => entry.id.endsWith(name + '.js')));
      });

      test.done();
    });
  },

  removesExcludedFiles: function(test) {
    test.expect(6);

    this.project.exclude(['b.js', 'c.js']);

    this.project.collect(function(error, entries) {

      test.equal(error, null);
      test.equal(entries.length, 2);
      ['a', 'index'].forEach((name) => {
        test.ok(entries.find(entry => entry.id.endsWith(name + '.js')));
      });

      // These will not be present
      ['b', 'c'].forEach((name) => {
        test.equal(entries.find(entry => entry.id.endsWith(name + '.js')), undefined);
      });

      test.done();
    });
  },
};

exports['Project.prototype.collect with node_modules'] = {
  setUp: function(done) {
    this.sandbox = sinon.sandbox.create();
    this.project = new Project({
      entry: path.join(process.cwd(), 'eg/project-simple/index.js'),
    });
    done();
  },

  tearDown: function(done) {
    this.sandbox.restore();
    done();
  },

  providesPackageJson: function(test) {
    test.expect(6);

    this.project.collect(function(error, entries) {

      test.equal(error, null);

      var expected = [
        '/package.json',
        '/node_modules/math-euler/package.json',
        '/node_modules/math-euler/euler.js',
        '/index.js',
      ];

      test.equal(entries.length, 4);

      expected.forEach((name) => {
        test.ok(entries.find(entry => entry.id.endsWith(name)), name);
      });
      test.done();
    });
  },
};
<|endoftext|>


<commit_before>// game engine
FloatyDuck.prototype = new FloatyElement();

function FloatyDuck() {
  // call extender class
  FloatyElement.apply(this,['play_area']);

  this.DEBUG = true;
  this.DEVICE_TYPE = 'phone';
  this.UPDATES_PER_SECOND = 60;
  this.INTERVAL_ID = 0;
  this.TIMEOUT_ID = 0;
  this.FIRST_OBSTACLE = 2500;
  this.SCROLL_RATE = 1.4;
  this.OBSTACLE_WIDTH = 50;
  this.OBSTACLE_GAP_SIZE = 170;

  this.frameCount = 0;
  this.obstacleCount = 0;

  this.size = { w: 320, h: 480 };
  this.setBoundMod( {'b': -35 } );

}

// Initialize
FloatyDuck.prototype.init = function() {

  this.elems = [];

  // when overriding init, pass child init as an argument so we can do pre_ and post_ hooks in order
  FloatyElement.prototype.init.apply(this,[function() {
    if(this.DEBUG) {
      $('#debug_data').css('display', 'block');
    }

    // generate game area
    this.Scroll = new Scroll();
    this.Scroll.setSize('w',this.getSize('w')*1+10);
    this.Scroll.setSize('h',this.getSize('h')-2);
    this.Scroll.setRate(this.SCROLL_RATE);
    this.elems.push(this.Scroll);

    // create duck and position in center
    this.Duck = new Duck();
    this.Duck.setPos('x',this.getSize('w')/2);
    this.Duck.setPos('y',this.getSize('h')/2);
    this.elems.push(this.Duck);

    this.StartScreen = new StartScreen();
    this.StartScreen.setPos('x',this.getSize('w')/2);
    this.StartScreen.setPos('y',this.getSize('h')/2);
    this.elems.push(this.StartScreen);

    // set structure
    $('body').append(this.obj);

    this.started = false;
    this.collision = false;

    this.InputManager = new InputManager(this.DEVICE_TYPE);
    // need to track only once per press
    this.InputManager.onTapEnd(function() {
      this.registeredDown = false;;
    }.bind(this));

    if(this.DEBUG) {
      this.obj.css('overflow','visible');
    }
  }.bind(this)]);
}

// This method updates the world (i.e., input, physics, etc)
FloatyDuck.prototype.update = function() {

  // run parent update
  FloatyElement.prototype.update.apply(this,arguments);

  // check for collisions
  var collision = false;
  if( !this.Duck.isInside(this) ) {
    collision = true;
  }

  this.elems.forEach(function(elem) {

    if(elem.collidable && this.Duck.isTouching(elem)) {
      collision = true;
    }
  }.bind(this));

  if( collision ) {
    this.collision = true;

    if(this.DEBUG) {
      $('#collision').html("COLLISION");
    }

    this.stop();
    this.run();
  }

  if (this.InputManager.isTapped()) {
    if(!this.started) {
      this.start();
    }

    if( this.registeredDown == false ) {
      this.registeredDown = true;
      this.Duck.flap();
    }
  }

}

// This method draws the current scene
FloatyDuck.prototype.render = function() {

  // run parent render
  FloatyElement.prototype.render.apply(this,arguments);

  if(this.DEBUG) {

    // Record current frame render for debug
    this.frameCount++;

    // Write out debug data
    $('#frame_count').html(this.frameCount);
    var activeKeys = "";
    if(this.InputManager.isTapped()) {
      activeKeys += "TAP!";
    }
    $('#active_keys').html(activeKeys);
    // TODO: Duck X and Y
    // TODO: Canvas size
  }
}

FloatyDuck.prototype.run = function() {
  this.init();

  var updateEvery = 1000 / this.UPDATES_PER_SECOND;

  this.INTERVAL_ID = setInterval(function() {
    this.update();
    this.render();
  }.bind(this), updateEvery);

}
FloatyDuck.prototype.start = function() {
  this.Duck.start();
  this.StartScreen.hide();
  this.started = true;
  // this.TIMEOUT_ID = setTimeout(this.addObstacle.bind(this),this.FIRST_OBSTACLE);
  this.TIMEOUT_ID = setTimeout(this.addObstaclePair.bind(this),this.FIRST_OBSTACLE);
}
FloatyDuck.prototype.stop = function() {
  clearTimeout(this.TIMEOUT_ID);
  clearInterval(this.INTERVAL_ID);
  this.started = false;

  this.elems.forEach(function(elem){
    elem.obj.remove();
  });

}

// Removed in favour of addObstaclePair
// FloatyDuck.prototype.addObstacle = function() {
//   this.Obstacle = new Obstacle(this.obstacleCount++);
//   this.Obstacle.setPos('x',this.getSize('w'));
//   this.Obstacle.setPos('y',0);
//   this.Obstacle.setSize('w',this.OBSTACLE_WIDTH);
//   this.Obstacle.setRate(this.SCROLL_RATE);

//   this.elems.push(this.Obstacle);
//   this.obj.append(this.Obstacle.obj);

//   this.Obstacle.init();

//   this.TIMEOUT_ID = setTimeout(this.addObstacle.bind(this),this.FIRST_OBSTACLE);
// }

FloatyDuck.prototype.addObstaclePair = function() {
  var maxHeight = this.getSize('h');
  var gapTop = Math.ceil(Math.random() * (maxHeight - this.OBSTACLE_GAP_SIZE));
  var startX = this.getSize('w');

  var topObstacle = new Obstacle(this.obstacleCount++);
  topObstacle.setPos('x',startX);
  topObstacle.setPos('y',0);
  topObstacle.setSize('w',this.OBSTACLE_WIDTH);
  topObstacle.setSize('h',gapTop);
  topObstacle.setRate(this.SCROLL_RATE);

  this.elems.push(topObstacle);
  this.obj.append(topObstacle.obj);

  var bottomY = gapTop + this.OBSTACLE_GAP_SIZE;
  var bottomObstacle = new Obstacle(this.obstacleCount++);
  bottomObstacle.setPos('x',startX);
  bottomObstacle.setPos('y',bottomY);
  bottomObstacle.setSize('w',this.OBSTACLE_WIDTH);
  bottomObstacle.setSize('h',maxHeight - bottomY);
  bottomObstacle.setRate(this.SCROLL_RATE);

  this.elems.push(bottomObstacle);
  this.obj.append(bottomObstacle.obj);

  this.TIMEOUT_ID = setTimeout(this.addObstaclePair.bind(this),this.FIRST_OBSTACLE);
}

function InputManager(device_type) {

  // Default is keyboard
  this.Input = undefined;

  if(device_type == 'phone') {
    this.Input = new TouchScreen();
  } else {
    this.Input = new Keyboard();
  }
}

InputManager.prototype.isTapped = function() {
  return this.Input.isTapped();
}

InputManager.prototype.onTapEnd = function(callback) {
  this.Input.onTapEnd(callback);
}

function Input() {
  this.onTapEnd = undefined;
}

Input.prototype.isTapped = function() {
  return false;
}

Input.prototype.onTapEnd = function(callback) {
  this.onTapEnd = callback;
}

// Extend Input
TouchScreen.prototype = new Input();

function TouchScreen() {
  this.mouseover = false;

  $(document).bind('touchstart', function() {
    this.mouseover = true;
  }.bind(this));

  $(document).bind('touchend', function() {
    this.mouseover = false;

    if(this.onTapEnd != undefined) {
      this.onTapEnd();
    }
  }.bind(this));
}

TouchScreen.prototype.isTapped = function() {
  return this.mouseover;
}

TouchScreen.prototype.onTapEnd = Input.prototype.onTapEnd;

// Extend Input
Keyboard.prototype = new Input();

// Keyboard input manager
function Keyboard() {
  this.downPressed = false;

  $(document).keydown(function(e) {
    switch(e.keyCode) {
      case 40: this.downPressed = true; break;
    }
  }.bind(this))

  $(document).keyup(function(e) {
    switch(e.keyCode) {
      case 40: {
        this.downPressed = false;

        if(this.onTapEnd != undefined) {
          this.onTapEnd();
        }
        break;
      }
    }
  }.bind(this))
}

Keyboard.prototype.isTapped = function() {
  return this.downPressed;
}

Keyboard.prototype.onTapEnd = Input.prototype.onTapEnd;
<commit_msg>Set device type to browser<commit_after>// game engine
FloatyDuck.prototype = new FloatyElement();

function FloatyDuck() {
  // call extender class
  FloatyElement.apply(this,['play_area']);

  this.DEBUG = true;
  this.DEVICE_TYPE = 'browser'; // Alternative: 'phone'
  this.UPDATES_PER_SECOND = 60;
  this.INTERVAL_ID = 0;
  this.TIMEOUT_ID = 0;
  this.FIRST_OBSTACLE = 2500;
  this.SCROLL_RATE = 1.4;
  this.OBSTACLE_WIDTH = 50;
  this.OBSTACLE_GAP_SIZE = 170;

  this.frameCount = 0;
  this.obstacleCount = 0;

  this.size = { w: 320, h: 480 };
  this.setBoundMod( {'b': -35 } );

}

// Initialize
FloatyDuck.prototype.init = function() {

  this.elems = [];

  // when overriding init, pass child init as an argument so we can do pre_ and post_ hooks in order
  FloatyElement.prototype.init.apply(this,[function() {
    if(this.DEBUG) {
      $('#debug_data').css('display', 'block');
    }

    // generate game area
    this.Scroll = new Scroll();
    this.Scroll.setSize('w',this.getSize('w')*1+10);
    this.Scroll.setSize('h',this.getSize('h')-2);
    this.Scroll.setRate(this.SCROLL_RATE);
    this.elems.push(this.Scroll);

    // create duck and position in center
    this.Duck = new Duck();
    this.Duck.setPos('x',this.getSize('w')/2);
    this.Duck.setPos('y',this.getSize('h')/2);
    this.elems.push(this.Duck);

    this.StartScreen = new StartScreen();
    this.StartScreen.setPos('x',this.getSize('w')/2);
    this.StartScreen.setPos('y',this.getSize('h')/2);
    this.elems.push(this.StartScreen);

    // set structure
    $('body').append(this.obj);

    this.started = false;
    this.collision = false;

    this.InputManager = new InputManager(this.DEVICE_TYPE);
    // need to track only once per press
    this.InputManager.onTapEnd(function() {
      this.registeredDown = false;;
    }.bind(this));

    if(this.DEBUG) {
      this.obj.css('overflow','visible');
    }
  }.bind(this)]);
}

// This method updates the world (i.e., input, physics, etc)
FloatyDuck.prototype.update = function() {

  // run parent update
  FloatyElement.prototype.update.apply(this,arguments);

  // check for collisions
  var collision = false;
  if( !this.Duck.isInside(this) ) {
    collision = true;
  }

  this.elems.forEach(function(elem) {

    if(elem.collidable && this.Duck.isTouching(elem)) {
      collision = true;
    }
  }.bind(this));

  if( collision ) {
    this.collision = true;

    if(this.DEBUG) {
      $('#collision').html("COLLISION");
    }

    this.stop();
    this.run();
  }

  if (this.InputManager.isTapped()) {
    if(!this.started) {
      this.start();
    }

    if( this.registeredDown == false ) {
      this.registeredDown = true;
      this.Duck.flap();
    }
  }

}

// This method draws the current scene
FloatyDuck.prototype.render = function() {

  // run parent render
  FloatyElement.prototype.render.apply(this,arguments);

  if(this.DEBUG) {

    // Record current frame render for debug
    this.frameCount++;

    // Write out debug data
    $('#frame_count').html(this.frameCount);
    var activeKeys = "";
    if(this.InputManager.isTapped()) {
      activeKeys += "TAP!";
    }
    $('#active_keys').html(activeKeys);
    // TODO: Duck X and Y
    // TODO: Canvas size
  }
}

FloatyDuck.prototype.run = function() {
  this.init();

  var updateEvery = 1000 / this.UPDATES_PER_SECOND;

  this.INTERVAL_ID = setInterval(function() {
    this.update();
    this.render();
  }.bind(this), updateEvery);

}
FloatyDuck.prototype.start = function() {
  this.Duck.start();
  this.StartScreen.hide();
  this.started = true;
  // this.TIMEOUT_ID = setTimeout(this.addObstacle.bind(this),this.FIRST_OBSTACLE);
  this.TIMEOUT_ID = setTimeout(this.addObstaclePair.bind(this),this.FIRST_OBSTACLE);
}
FloatyDuck.prototype.stop = function() {
  clearTimeout(this.TIMEOUT_ID);
  clearInterval(this.INTERVAL_ID);
  this.started = false;

  this.elems.forEach(function(elem){
    elem.obj.remove();
  });

}

// Removed in favour of addObstaclePair
// FloatyDuck.prototype.addObstacle = function() {
//   this.Obstacle = new Obstacle(this.obstacleCount++);
//   this.Obstacle.setPos('x',this.getSize('w'));
//   this.Obstacle.setPos('y',0);
//   this.Obstacle.setSize('w',this.OBSTACLE_WIDTH);
//   this.Obstacle.setRate(this.SCROLL_RATE);

//   this.elems.push(this.Obstacle);
//   this.obj.append(this.Obstacle.obj);

//   this.Obstacle.init();

//   this.TIMEOUT_ID = setTimeout(this.addObstacle.bind(this),this.FIRST_OBSTACLE);
// }

FloatyDuck.prototype.addObstaclePair = function() {
  var maxHeight = this.getSize('h');
  var gapTop = Math.ceil(Math.random() * (maxHeight - this.OBSTACLE_GAP_SIZE));
  var startX = this.getSize('w');

  var topObstacle = new Obstacle(this.obstacleCount++);
  topObstacle.setPos('x',startX);
  topObstacle.setPos('y',0);
  topObstacle.setSize('w',this.OBSTACLE_WIDTH);
  topObstacle.setSize('h',gapTop);
  topObstacle.setRate(this.SCROLL_RATE);

  this.elems.push(topObstacle);
  this.obj.append(topObstacle.obj);

  var bottomY = gapTop + this.OBSTACLE_GAP_SIZE;
  var bottomObstacle = new Obstacle(this.obstacleCount++);
  bottomObstacle.setPos('x',startX);
  bottomObstacle.setPos('y',bottomY);
  bottomObstacle.setSize('w',this.OBSTACLE_WIDTH);
  bottomObstacle.setSize('h',maxHeight - bottomY);
  bottomObstacle.setRate(this.SCROLL_RATE);

  this.elems.push(bottomObstacle);
  this.obj.append(bottomObstacle.obj);

  this.TIMEOUT_ID = setTimeout(this.addObstaclePair.bind(this),this.FIRST_OBSTACLE);
}

function InputManager(device_type) {

  // Default is keyboard
  this.Input = undefined;

  if(device_type == 'phone') {
    this.Input = new TouchScreen();
  } else {
    this.Input = new Keyboard();
  }
}

InputManager.prototype.isTapped = function() {
  return this.Input.isTapped();
}

InputManager.prototype.onTapEnd = function(callback) {
  this.Input.onTapEnd(callback);
}

function Input() {
  this.onTapEnd = undefined;
}

Input.prototype.isTapped = function() {
  return false;
}

Input.prototype.onTapEnd = function(callback) {
  this.onTapEnd = callback;
}

// Extend Input
TouchScreen.prototype = new Input();

function TouchScreen() {
  this.mouseover = false;

  $(document).bind('touchstart', function() {
    this.mouseover = true;
  }.bind(this));

  $(document).bind('touchend', function() {
    this.mouseover = false;

    if(this.onTapEnd != undefined) {
      this.onTapEnd();
    }
  }.bind(this));
}

TouchScreen.prototype.isTapped = function() {
  return this.mouseover;
}

TouchScreen.prototype.onTapEnd = Input.prototype.onTapEnd;

// Extend Input
Keyboard.prototype = new Input();

// Keyboard input manager
function Keyboard() {
  this.downPressed = false;

  $(document).keydown(function(e) {
    switch(e.keyCode) {
      case 40: this.downPressed = true; break;
    }
  }.bind(this))

  $(document).keyup(function(e) {
    switch(e.keyCode) {
      case 40: {
        this.downPressed = false;

        if(this.onTapEnd != undefined) {
          this.onTapEnd();
        }
        break;
      }
    }
  }.bind(this))
}

Keyboard.prototype.isTapped = function() {
  return this.downPressed;
}

Keyboard.prototype.onTapEnd = Input.prototype.onTapEnd;
<|endoftext|>


<commit_before>import React from 'react';
import {shallow} from 'enzyme';

import RecentCommitsView from '../../lib/views/recent-commits-view';

describe('RecentCommitsView', function() {
  let app;

  beforeEach(function() {
    app = <RecentCommitsView commits={[]} isLoading={false} />;
  });

  it('shows a placeholder while commits are empty and loading', function() {
    app = React.cloneElement(app, {commits: [], isLoading: true});
    const wrapper = shallow(app);

    assert.isFalse(wrapper.find('RecentCommitView').exists());
    assert.strictEqual(wrapper.find('.github-RecentCommit-message').text(), 'Recent commits');
  });

  it('shows a prompting message while commits are empty and not loading', function() {
    app = React.cloneElement(app, {commits: [], isLoading: false});
    const wrapper = shallow(app);

    assert.isFalse(wrapper.find('RecentCommitView').exists());
    assert.strictEqual(wrapper.find('.github-RecentCommit-message').text(), 'Make your first commit');
  });

  it('renders a RecentCommitView for each commit', function() {
    const commits = ['1', '2', '3'].map(sha => {
      return {
        getSha() { return sha; },
      };
    });

    app = React.cloneElement(app, {commits});
    const wrapper = shallow(app);

    assert.deepEqual(wrapper.find('RecentCommitView').map(w => w.prop('commit')), commits);
  });

  it('renders an avatar corresponding to the GitHub user who authored the commit');
});
<commit_msg>WIP test<commit_after>import React from 'react';
import {shallow, mount} from 'enzyme';

import RecentCommitsView from '../../lib/views/recent-commits-view';
import Commit from '../../lib/models/commit';

describe.only('RecentCommitsView', function() {
  let app;

  beforeEach(function() {
    app = <RecentCommitsView commits={[]} isLoading={false} />;
  });

  it('shows a placeholder while commits are empty and loading', function() {
    app = React.cloneElement(app, {commits: [], isLoading: true});
    const wrapper = shallow(app);

    assert.isFalse(wrapper.find('RecentCommitView').exists());
    assert.strictEqual(wrapper.find('.github-RecentCommit-message').text(), 'Recent commits');
  });

  it('shows a prompting message while commits are empty and not loading', function() {
    app = React.cloneElement(app, {commits: [], isLoading: false});
    const wrapper = shallow(app);

    assert.isFalse(wrapper.find('RecentCommitView').exists());
    assert.strictEqual(wrapper.find('.github-RecentCommit-message').text(), 'Make your first commit');
  });

  it('renders a RecentCommitView for each commit', function() {
    const commits = ['1', '2', '3'].map(sha => {
      return {
        getSha() { return sha; },
      };
    });

    app = React.cloneElement(app, {commits});
    const wrapper = shallow(app);

    assert.deepEqual(wrapper.find('RecentCommitView').map(w => w.prop('commit')), commits);
  });

  it.only('renders an avatar corresponding to the GitHub user who authored the commit', function() {
    const commits = ['one@x.com', 'two@y.com', 'thr&ee@z.com'].map(authorEmail => {
      return new Commit({sha: '1111111111', authorEmail, authorDate: 0, message: 'x'});
    });

    app = React.cloneElement(app, {commits});
    const wrapper = mount(app);
    assert.deepEqual(
      wrapper.find('img.github-RecentCommit-avatar').map(w => w.prop('src')),
      [
        'https://avatars.githubusercontent.com/u/e?email=thr%26ee%40z.com',
        'https://avatars.githubusercontent.com/u/e?email=two%40y.com',
        'https://avatars.githubusercontent.com/u/e?email=one%40x.com',
      ],
    );
  });
});
<|endoftext|>


<commit_before>/*
FILE NAME: breadbrumbs.js
WRITTEN BY: Thomas
WHEN: 2016 autumn
PURPOSE: Dynamic update of breadcrumb trail
*/

//  Run all functions on top while having function declarations on bottom (hoisting)
window.addEventListener(
  EVENT_ON_LOADED,
  function(ev){ updateBreadCrumbs(ev); }
);

/*******           FUNCTION DECLARATIONS          *******/

// Update breadcrumbs
function updateBreadCrumbs(){

  let eventus = arguments[0];
  let bread_tag = document.getElementById("breadcrumbs");
  displayElement(bread_tag);

  let bread_list = bread_tag.getElementsByTagName("ul");
  bread_list[0].innerHTML = "";

  var section = eventus.detail.section;
  var sectionname = eventus.detail.section_name;
  var page = eventus.detail.page;
  var pagename = eventus.detail.page_name;

  var link = 	FILE_PROTOCOL_PAGE_ROOT;
  addBreadCrumb(link, "Home", bread_list);

  let query = "";

  if(section && !page || page && page == section){
	query = "?section=" + section;
	link = link + query;
	addBreadCrumb(link, sectionname, bread_list);
  }
  else if(section && page){
	query = "?section=" + section;
	link = link + query;
	addBreadCrumb(link, sectionname, bread_list);
	query = query  + "&page=" + page;
	link = link + query;
	addBreadCrumb(link, pagename, bread_list);
  }
}

// Generic/modular extraction query from URL and return table with name/value-pairs
function getQueryPairs(){
  var query = window.location.search.substring(1);
  var queryTab = query.split("&");
  return queryTab;
}

// Append a hyperlinked breadcrumb to BrCr-trail
function addBreadCrumb(weblink, brCrName, brCrList){
  var list_element = document.createElement("LI");
  var anchor_element = document.createElement("A");
  list_element.appendChild(anchor_element);
  anchor_element.setAttribute("href", weblink);

  var txt_node = document.createTextNode(brCrName);
  anchor_element.appendChild(txt_node);
  brCrList[0].appendChild(list_element);
}

// Show/Hide breadcrumbs trail
function displayElement(elementID){
  var styleElement = elementID.style;
  styleElement.display = "block";
  styleElement.visibility = "visible";
}
<commit_msg>Fixed double ?section= in breadcrumbs<commit_after>/*
FILE NAME: breadbrumbs.js
WRITTEN BY: Thomas
WHEN: 2016 autumn
PURPOSE: Dynamic update of breadcrumb trail
*/

//  Run all functions on top while having function declarations on bottom (hoisting)
window.addEventListener(
  EVENT_ON_LOADED,
  function(ev){ updateBreadCrumbs(ev); }
);

/*******           FUNCTION DECLARATIONS          *******/

// Update breadcrumbs
function updateBreadCrumbs(){

  let eventus = arguments[0];
  let bread_tag = document.getElementById("breadcrumbs");
  displayElement(bread_tag);

  let bread_list = bread_tag.getElementsByTagName("ul");
  bread_list[0].innerHTML = "";

  var section = eventus.detail.section;
  var sectionname = eventus.detail.section_name;
  var page = eventus.detail.page;
  var pagename = eventus.detail.page_name;

  var link = 	FILE_PROTOCOL_PAGE_ROOT;
  addBreadCrumb(link, "Home", bread_list);

  let query = "";

  if(section && !page || page && page == section){
	query = "?section=" + section;
	link = link + query;
	addBreadCrumb(link, sectionname, bread_list);
  }
  else if(section && page){
	const link1 = link;
	query = "?section=" + section;
	link = link1 + query;
	addBreadCrumb(link, sectionname, bread_list);
	query = query  + "&page=" + page;
	link = link1 + query;
	addBreadCrumb(link, pagename, bread_list);
  }
}

// Generic/modular extraction query from URL and return table with name/value-pairs
function getQueryPairs(){
  var query = window.location.search.substring(1);
  var queryTab = query.split("&");
  return queryTab;
}

// Append a hyperlinked breadcrumb to BrCr-trail
function addBreadCrumb(weblink, brCrName, brCrList){
  var list_element = document.createElement("LI");
  var anchor_element = document.createElement("A");
  list_element.appendChild(anchor_element);
  anchor_element.setAttribute("href", weblink);

  var txt_node = document.createTextNode(brCrName);
  anchor_element.appendChild(txt_node);
  brCrList[0].appendChild(list_element);
}

// Show/Hide breadcrumbs trail
function displayElement(elementID){
  var styleElement = elementID.style;
  styleElement.display = "block";
  styleElement.visibility = "visible";
}
<|endoftext|>


<commit_before>/* global describe,expect,it,before,after,Buffer */
'use strict';

const Nodgine = require('../../src/nodgine');
const libHttp = require('http');

describe('End to end functionallity', () => {
    let httpServer;
    let instance;

    before(() => {
        instance = new Nodgine();
        httpServer = libHttp.createServer(instance.getRouter());

        instance.addMiddleware((aRequest, aResponse) => {
            aResponse
                .setStatusCode(200)
                .setHeader('isTest', 'yes')
                .write('Hello');
        });

        instance.addMiddleware('/test/:testid', (aRequest, aResponse, aParamsHash) => {
            aResponse.write('TestMiddleware' + aParamsHash.testid);
        });

        instance.addController('/test/*', {
            doGet: (aRequest, aResponse) => {
                aResponse.write('GeT');
            },
            doPost: (aRequest, aResponse) => {
                aResponse
                    .setStatusCode(201)
                    .write('PosT');
            }
        });

        instance.addController('/other', (aRequest, aResponse) => {
            aResponse.write('other');
        });

        instance.addController('/async', (aRequest, aResponse) => {
            return new Promise((aResolve) => {
                aResponse.write('async');
                process.nextTick(() => {
                    aResolve();
                })
            });
        });

        httpServer.listen(8765);
    });

    it('should answer correct requesting http://localhost:8765/test/mugglefugg', (done) => {
        let options = {
            hostname: '127.0.0.1',
            port: 8765,
            path: '/test/End2EndTestsAreSoCool',
            method: 'POST'
        };
        let request = libHttp.request(options, (aResponse) => {
            let receivedData = [];

            aResponse.on('data', (aChunk) => {
                receivedData.push(aChunk);
            });

            aResponse.on('end', () => {
                expect(aResponse.statusCode).to.equal(201);
                // here we expect istest completly lowercase, because nodejs makes everything lowercase
                expect(aResponse.headers.istest).to.equal('yes');
                expect(receivedData.toString()).to.equal('HelloTestMiddlewareEnd2EndTestsAreSoCoolPosT');
                done();
            });
        });

        request.on('error', (aError) => {
            // just throw the error to fail the test
            throw aError;
        });

        request.end();
    });

    it('should answer correct requesting http://localhost:8765/other', (done) => {
        let options = {
            hostname: '127.0.0.1',
            port: 8765,
            path: '/other',
            method: 'GET'
        };
        let request = libHttp.request(options, (aResponse) => {
            let receivedData = [];

            aResponse.on('data', (aChunk) => {
                receivedData.push(aChunk);
            });

            aResponse.on('end', () => {
                expect(aResponse.statusCode).to.equal(200);
                // here we expect istest completly lowercase, because nodejs makes everything lowercase
                expect(aResponse.headers.istest).to.equal('yes');
                expect(receivedData.toString()).to.equal('Helloother');
                done();
            });
        });

        request.on('error', (aError) => {
            // just throw the error to fail the test
            throw aError;
        });

        request.end();
    });

    it('should answer correct requesting http://localhost:8765/async', (done) => {
        let options = {
            hostname: '127.0.0.1',
            port: 8765,
            path: '/async',
            method: 'GET'
        };
        let request = libHttp.request(options, (aResponse) => {
            let receivedData = [];

            aResponse.on('data', (aChunk) => {
                receivedData.push(aChunk);
            });

            aResponse.on('end', () => {
                expect(aResponse.statusCode).to.equal(200);
                // here we expect istest completly lowercase, because nodejs makes everything lowercase
                expect(aResponse.headers.istest).to.equal('yes');
                expect(receivedData.toString()).to.equal('Helloasync');
                done();
            });
        });

        request.on('error', (aError) => {
            // just throw the error to fail the test
            throw aError;
        });

        request.end();
    });

    it('should answer with 404 requesting http://localhost:8765/does/not/exist', (done) => {
        let options = {
            hostname: '127.0.0.1',
            port: 8765,
            path: '/does/not/exist',
            method: 'GET'
        };
        let request = libHttp.request(options, (aResponse) => {
            let receivedData = [];

            aResponse.on('data', (aChunk) => {
                receivedData.push(aChunk);
            });

            aResponse.on('end', () => {
                expect(aResponse.statusCode).to.equal(404);
                // here we expect istest completly lowercase, because nodejs makes everything lowercase
                expect(aResponse.headers.istest).to.equal('yes');
                expect(receivedData.toString()).to.equal('HelloNot Found');
                done();
            });
        });

        request.on('error', (aError) => {
            // just throw the error to fail the test
            throw aError;
        });

        request.end();
    });

    after(() => {
        httpServer.close();
    });
});<commit_msg>Fixed an eslint error<commit_after>/* global describe,expect,it,before,after,Buffer */
'use strict';

const Nodgine = require('../../src/nodgine');
const libHttp = require('http');

describe('End to end functionallity', () => {
    let httpServer;
    let instance;

    before(() => {
        instance = new Nodgine();
        httpServer = libHttp.createServer(instance.getRouter());

        instance.addMiddleware((aRequest, aResponse) => {
            aResponse
                .setStatusCode(200)
                .setHeader('isTest', 'yes')
                .write('Hello');
        });

        instance.addMiddleware('/test/:testid', (aRequest, aResponse, aParamsHash) => {
            aResponse.write('TestMiddleware' + aParamsHash.testid);
        });

        instance.addController('/test/*', {
            doGet: (aRequest, aResponse) => {
                aResponse.write('GeT');
            },
            doPost: (aRequest, aResponse) => {
                aResponse
                    .setStatusCode(201)
                    .write('PosT');
            }
        });

        instance.addController('/other', (aRequest, aResponse) => {
            aResponse.write('other');
        });

        instance.addController('/async', (aRequest, aResponse) => {
            return new Promise((aResolve) => {
                aResponse.write('async');
                process.nextTick(() => {
                    aResolve();
                });
            });
        });

        httpServer.listen(8765);
    });

    it('should answer correct requesting http://localhost:8765/test/mugglefugg', (done) => {
        let options = {
            hostname: '127.0.0.1',
            port: 8765,
            path: '/test/End2EndTestsAreSoCool',
            method: 'POST'
        };
        let request = libHttp.request(options, (aResponse) => {
            let receivedData = [];

            aResponse.on('data', (aChunk) => {
                receivedData.push(aChunk);
            });

            aResponse.on('end', () => {
                expect(aResponse.statusCode).to.equal(201);
                // here we expect istest completly lowercase, because nodejs makes everything lowercase
                expect(aResponse.headers.istest).to.equal('yes');
                expect(receivedData.toString()).to.equal('HelloTestMiddlewareEnd2EndTestsAreSoCoolPosT');
                done();
            });
        });

        request.on('error', (aError) => {
            // just throw the error to fail the test
            throw aError;
        });

        request.end();
    });

    it('should answer correct requesting http://localhost:8765/other', (done) => {
        let options = {
            hostname: '127.0.0.1',
            port: 8765,
            path: '/other',
            method: 'GET'
        };
        let request = libHttp.request(options, (aResponse) => {
            let receivedData = [];

            aResponse.on('data', (aChunk) => {
                receivedData.push(aChunk);
            });

            aResponse.on('end', () => {
                expect(aResponse.statusCode).to.equal(200);
                // here we expect istest completly lowercase, because nodejs makes everything lowercase
                expect(aResponse.headers.istest).to.equal('yes');
                expect(receivedData.toString()).to.equal('Helloother');
                done();
            });
        });

        request.on('error', (aError) => {
            // just throw the error to fail the test
            throw aError;
        });

        request.end();
    });

    it('should answer correct requesting http://localhost:8765/async', (done) => {
        let options = {
            hostname: '127.0.0.1',
            port: 8765,
            path: '/async',
            method: 'GET'
        };
        let request = libHttp.request(options, (aResponse) => {
            let receivedData = [];

            aResponse.on('data', (aChunk) => {
                receivedData.push(aChunk);
            });

            aResponse.on('end', () => {
                expect(aResponse.statusCode).to.equal(200);
                // here we expect istest completly lowercase, because nodejs makes everything lowercase
                expect(aResponse.headers.istest).to.equal('yes');
                expect(receivedData.toString()).to.equal('Helloasync');
                done();
            });
        });

        request.on('error', (aError) => {
            // just throw the error to fail the test
            throw aError;
        });

        request.end();
    });

    it('should answer with 404 requesting http://localhost:8765/does/not/exist', (done) => {
        let options = {
            hostname: '127.0.0.1',
            port: 8765,
            path: '/does/not/exist',
            method: 'GET'
        };
        let request = libHttp.request(options, (aResponse) => {
            let receivedData = [];

            aResponse.on('data', (aChunk) => {
                receivedData.push(aChunk);
            });

            aResponse.on('end', () => {
                expect(aResponse.statusCode).to.equal(404);
                // here we expect istest completly lowercase, because nodejs makes everything lowercase
                expect(aResponse.headers.istest).to.equal('yes');
                expect(receivedData.toString()).to.equal('HelloNot Found');
                done();
            });
        });

        request.on('error', (aError) => {
            // just throw the error to fail the test
            throw aError;
        });

        request.end();
    });

    after(() => {
        httpServer.close();
    });
});<|endoftext|>


<commit_before>/* global describe: false, it: false */
var expect = require('chai').expect,
    server = require('../lib/tty-lean'),
    request = require('supertest');

describe("tty-lean", function() {
  var config = {
        localOnly: true,
        log: false,
        shell: "sh"
      },
      app = server(config).server;

  describe('/', function() {
    it('serves the HTML UI', function(done) {
      request(app)
        .get('/')
        .expect('Content-Type', 'text/html; charset=UTF-8')
        .expect(200, done);
    });
  });

  describe('/favicon.ico', function() {
    it('serves an icon', function(done) {
      request(app)
        .get('/favicon.ico')
        .expect('Content-Type', 'image/x-icon')
        .expect(200, done);
    });
  });

  describe('/socket.io', function() {
    it('serves Socket.IO websocket endpoint', function(done) {
      app.listen(0, function() {
        var port = app.address().port,
            socket = require('socket.io-client')('ws://localhost:'+port),
            ttyText = '';
        var ttyId;
        socket.on('connect', function() {
          socket.emit('start', 'd34db33f');
          socket.emit('create', 80, 25, function(err, data) {
            ttyId = data.id;
          });
        });
        socket.on('data', function(id, data) {
          // Check TTY is the one expected
          expect(ttyId).to.equal(id);
          ttyText += data;
          // Check we got a shell
          if (/\$ $/m.test(ttyText)) {
            // When this shell closes, disconnect
            socket.on('kill', function() {
              socket.close();
            });
            // Close the shell by entering "exit"
            socket.emit('data', ttyId, 'exit\r');
          }
        });
        socket.on('disconnect', function() {
          app.on('close', done);
          app.close();
        });
      });
    });
  });

});<commit_msg>Explicitly testing polling.<commit_after>/* global describe: false, it: false */
var expect = require('chai').expect,
    server = require('../lib/tty-lean'),
    request = require('supertest');

describe("tty-lean", function() {
  var config = {
        localOnly: true,
        log: false,
        shell: "sh"
      };

  describe('/', function() {
    it('serves the HTML UI', function(done) {
      var app = server(config).server;
      request(app)
        .get('/')
        .expect('Content-Type', 'text/html; charset=UTF-8')
        .expect(200, done);
    });
  });

  describe('/favicon.ico', function() {
    it('serves an icon', function(done) {
      var app = server(config).server;
      request(app)
        .get('/favicon.ico')
        .expect('Content-Type', 'image/x-icon')
        .expect(200, done);
    });
  });

  describe('/socket.io', function() {

    function runSocketTest(app, opts, done) {
      app.listen(0, function() {
        var port = app.address().port,
            socket = require('socket.io-client')('ws://localhost:'+port, opts),
            ttyText = '';
        var ttyId;
        socket.on('connect', function() {
          socket.emit('start', 'd34db33f');
          socket.emit('create', 80, 25, function(err, data) {
            ttyId = data.id;
          });
        });
        socket.on('data', function(id, data) {
          // Check TTY is the one expected
          expect(ttyId).to.equal(id);
          ttyText += data;
          // Check we got a shell
          if (/\$ $/m.test(ttyText)) {
            // When this shell closes, disconnect
            socket.on('kill', function() {
              socket.close();
            });
            // Close the shell by entering "exit"
            socket.emit('data', ttyId, 'exit\r');
          }
        });
        socket.on('disconnect', function() {
          app.on('close', done);
          app.close();
        });
      });
    }

    describe('Socket.IO websocket endpoint', function() {
      it('works when restricted to websockets', function(done) {
        runSocketTest(server(config).server, {
          transports: ['websocket']
        }, done);
      });

      it('works when restricted to polling', function(done) {
        runSocketTest(server(config).server, {
          transports: ['polling']
        }, done);
      });
    });

  });

});<|endoftext|>