<commit_before>/* jshint node:true, mocha:true */

'use strict';

var http = require('http').Server;
var io = require('socket.io');
var ioc = require('socket.io-client');
var expect = require('expect.js');
var SocketModel = require('../lib/socket.model');
var Q = require('q');
var _ = require('lodash');

var sio;
var port;

beforeEach(function (done) {
  var srv = http();
  sio = io(srv);

  srv.listen(function () {
    port = srv.address().port;
    done();
  });
});

function createClient() {
  return ioc('ws://127.0.0.1:' + port, {
    multiplex: false
  });
}

var expectedPost = {
  id: 1234,
  content: 'post content'
};

describe('model', function () {

  var Post;

  beforeEach(function () {
    Post = new SocketModel(sio, 'post');
  });

  describe('constructor', function () {

    it('should construct an object', function () {
      expect(Post).to.be.an('object');
      expect(Post).to.be.a(SocketModel);
    });

    it('should bind socket.io server on model constructor', function () {
      var ShortcutModel = SocketModel.bind(sio);
      var Post = new ShortcutModel('post');
      expect(Post).to.be.a(SocketModel);
    });

    it('should construct instance without `new` keyword', function () {
      var model = SocketModel;
      var Post = model(sio, 'post');
      expect(Post).to.be.a(SocketModel);
    });

  });

  describe('property', function () {

    it('should have a name property', function () {
      expect(Post).to.have.property('name');
    });

    it('should have collection property as an empty array', function () {
      expect(Post).to.have.property('collection');
      expect(Post.collection).to.be.an('array').and.to.have.length(0);
    });

    it('should have a mode property', function () {
      expect(Post).to.have.property('mode');
    });

  });

  describe('method', function () {

    it('should return `this` in `on` method', function () {
      var returned = Post.on('event', function () {});
      expect(returned).to.equal(Post);
    });

    it('should return `this` in `emit` method', function () {
      var returned = Post.emit('event');
      expect(returned).to.equal(Post);
    });

  });

});

describe('server', function () {

  var Post;

  beforeEach(function () {
    Post = new SocketModel(sio, 'post');
  });

  it('should be with server mode', function () {
    expect(Post.mode).to.be('server');
  });

  describe('connect', function () {

    it('should trigger connect event when a client connects', function (done) {
      Post.on('connect', function () {
        done();
      });

      createClient();
    });

    it('should trigger connect event on the connected client', function (done) {
      var client = createClient();
      client.on('connect', function () {
        // new socket model after client is connected
        Post.on('connect', function () {
          done();
        });
      });
    });

    it('should trigger client connect event when response', function (done) {
      var expectedPosts = ['p1', 'p2', 'p3'];

      Post.on('connect', function (req, res) {
        res(expectedPosts);
      });

      var client = createClient();
      client.on('post:connect', function (actualPosts) {
        expect(actualPosts).to.eql(expectedPosts);
        done();
      });
    });

    it('should get request context when connected', function (done) {
      Post.on('connect', function (req, res) {
        expect(req).to.be.an('object');
        expect(req.headers).to.be.an('object');
        done();
      });

      createClient();
    });

  });

  describe('create', function () {

    it('should not trigger any event handler when client connect', function (done) {
      Post.on('create', function () {
        expect().fail('');
      });

      Post.on('edit', function () {
        done();
      });

      var client = createClient();
      client.on('connect', function () {
        client.emit('post:edit');
      });
    });

    it('should trigger create handler when client emit event', function (done) {
      Post.on('create', function () {
        done();
      });

      var client = createClient();
      client.emit('post:create');
    });

    it('should register event handler on connected sockets', function (done) {
      var client = createClient();
      client.on('connect', function () {
        Post.on('create', function () {
          done();
        });

        client.emit('post:create');
      });
    });

  });

  describe('communication', function () {

    it('should communicate between server and client via callback', function (done) {
      Post.on('create', function (req, res, actualPost, fn) {
        expect(actualPost).to.eql(expectedPost);
        fn(true);
      });

      var client = createClient();
      client.emit('post:create', expectedPost, function (result) {
        expect(result).to.be(true);
        done();
      });
    });

    it('should broadcast every socket that something is created', function (done) {
      Post.on('create', function (req, res, actualPost) {
        expect(actualPost).to.eql(expectedPost);
        res(actualPost);
      });

      var client1 = createClient();
      var defer1 = Q.defer();
      client1.on('post:create', function (actualPost) {
        expect(actualPost).to.eql(expectedPost);
        defer1.resolve();
      });

      var client2 = createClient();
      var defer2 = Q.defer();
      client2.on('post:create', function (actualPost) {
        expect(actualPost).to.eql(expectedPost);
        defer2.resolve();
      });

      expect(client1).to.not.equal(client2);

      client2.emit('post:create', expectedPost);
      Q.all([defer1.promise, defer2.promise]).then(function () {
        done();
      });
    });

    it('should get request context when event triggered', function (done) {
      Post.on('create', function (req, res) {
        expect(req).to.be.an('object');
        expect(req.headers).to.be.an('object');
        done();
      });

      var client = createClient();
      client.emit('post:create');
    });

  });

});

describe('client', function () {

  var client;
  var Post;

  beforeEach(function () {
    client = createClient();
    Post = new SocketModel(client, 'post');
  });

  it('should be with client mode', function () {
    expect(Post.mode).to.be('client');
  });

  describe('register event handler', function () {

    it('should get data from connect event', function (done) {
      var expectedPosts = ['p1', 'p2', 'p3'];

      sio.on('connect', function (socket) {
        socket.emit('post:connect', expectedPosts);
      });

      Post.on('connect', function (req, res, actualPosts) {
        expect(actualPosts).to.be.eql(expectedPosts);
        done();
      });
    });

    it('should register event handler after connected', function (done) {
      sio.on('connect', function (socket) {
        socket.emit('post:create', true);
      });

      client.on('connect', function () {
        var Post = new SocketModel(client, 'post');
        Post.on('create', function (req, res, result) {
          expect(result).to.be(true);
          done();
        });
      });
    });

  });

  describe('trigger', function () {

    it('should trigger server-side create event handler', function (done) {
      sio.on('connect', function (socket) {
        socket.on('post:create', function (actualPost) {
          expect(actualPost).to.eql(expectedPost);
          socket.emit('post:create', true);
          done();
        });
      });

      Post.emit('create', expectedPost);
    });

    it('should trigger event when socket.io server broadcast', function (done) {
      Post.on('create', function () {
        done();
      });

      client.on('connect', function () {
        sio.emit('post:create');
      });
    });

    it('should trigger event, and then get it back on listener', function (done) {
      sio.on('connect', function (socket) {
        socket.on('post:create', function (actualPost) {
          expect(actualPost).to.eql(expectedPost);
          socket.emit('post:create', true);
        });
      });

      Post.on('create', function (req, res, result) {
        expect(result).to.be(true);
        done();
      });

      Post.emit('create', expectedPost);
    });

    it('should queue the firing event till connected, then re-fire them');

  });

  describe('request', function () {

    it('should get request context when event triggered', function (done) {
      sio.on('connect', function (socket) {
        socket.emit('post:create', true);
      });

      Post.on('create', function (req, res) {
        expect(req).to.be.an('object');
        expect(req.uri).to.be.a('string');
        done();
      });
    });

  });

});

describe('meta-class', function () {

  it('should be a constructor', function () {
    var client = createClient();
    var Post = new SocketModel(client, 'post').class;
    var post = new Post();

    expect(post).to.be.an('object');
    expect(post).to.be.a(Post);
  });

  describe('field', function () {

    it('should initialize from the constructor', function () {
      var client = createClient();
      var Post = new SocketModel(client, 'post').class;
      var post = new Post({
        property1: 123,
        property2: 'abc',
        property3: true
      });

      expect(post).to.have.property('property1', 123);
      expect(post).to.have.property('property2', 'abc');
      expect(post).to.have.property('property3', true);
    });

    it('should access the fields from the methods in constructor', function () {
      var client = createClient();
      var Post = new SocketModel(client, 'post').class;
      var post = new Post({
        property: 100,
        add: function () {
          this.property++;
          return this.property;
        }
      });

      expect(post).to.have.property('add');
      expect(post.add).to.be.a('function');

      var result = post.add();

      expect(result).to.be(101);
      expect(post.property).to.be(101);
    });

  });

  describe('method', function () {

    function setUpAndCreatePost(method, done) {
      sio.on('connect', function (socket) {
        socket.on('post:' + method, function (actualPost, fn) {
          expect(actualPost).to.eql(expectedPost);
          done();

          if (typeof fn === 'function') {
            fn(actualPost);
          }
        });
      });

      var client = createClient();
      var Post = new SocketModel(client, 'post').class;
      var post = new Post();

      return post;
    }

    it('should have save method', function (done) {
      var post = setUpAndCreatePost('save', done);

      expect(post).to.have.property('save');
      expect(post.save).to.be.a('function');

      post.save(expectedPost);
    });

    it('should have delete method', function (done) {
      var post = setUpAndCreatePost('delete', done);

      expect(post).to.have.property('delete');
      expect(post.delete).to.be.a('function');

      post.delete(expectedPost);
    });

    it('should emit object fields when invoke without parameters', function (done) {
      var post = setUpAndCreatePost('save', done);

      _.extend(post, expectedPost);

      post.save();
    });

    it('should invoke callback after server-side response', function (done) {
      var post = setUpAndCreatePost('save', _.noop);

      post.save(expectedPost, function (actualPost) {
        expect(actualPost).to.be.eql(expectedPost);
        done();
      });
    });

  });

});
<commit_msg>Add test about queue waiting event until connected.<commit_after>/* jshint node:true, mocha:true */

'use strict';

var http = require('http').Server;
var io = require('socket.io');
var ioc = require('socket.io-client');
var expect = require('expect.js');
var SocketModel = require('../lib/socket.model');
var Q = require('q');
var _ = require('lodash');

var sio;
var port;

beforeEach(function (done) {
  var srv = http();
  sio = io(srv);

  srv.listen(function () {
    port = srv.address().port;
    done();
  });
});

function createClient() {
  return ioc('ws://127.0.0.1:' + port, {
    multiplex: false
  });
}

var expectedPost = {
  id: 1234,
  content: 'post content'
};

describe('model', function () {

  var Post;

  beforeEach(function () {
    Post = new SocketModel(sio, 'post');
  });

  describe('constructor', function () {

    it('should construct an object', function () {
      expect(Post).to.be.an('object');
      expect(Post).to.be.a(SocketModel);
    });

    it('should bind socket.io server on model constructor', function () {
      var ShortcutModel = SocketModel.bind(sio);
      var Post = new ShortcutModel('post');
      expect(Post).to.be.a(SocketModel);
    });

    it('should construct instance without `new` keyword', function () {
      var model = SocketModel;
      var Post = model(sio, 'post');
      expect(Post).to.be.a(SocketModel);
    });

  });

  describe('property', function () {

    it('should have a name property', function () {
      expect(Post).to.have.property('name');
    });

    it('should have collection property as an empty array', function () {
      expect(Post).to.have.property('collection');
      expect(Post.collection).to.be.an('array').and.to.have.length(0);
    });

    it('should have a mode property', function () {
      expect(Post).to.have.property('mode');
    });

  });

  describe('method', function () {

    it('should return `this` in `on` method', function () {
      var returned = Post.on('event', function () {});
      expect(returned).to.equal(Post);
    });

    it('should return `this` in `emit` method', function () {
      var returned = Post.emit('event');
      expect(returned).to.equal(Post);
    });

  });

});

describe('server', function () {

  var Post;

  beforeEach(function () {
    Post = new SocketModel(sio, 'post');
  });

  it('should be with server mode', function () {
    expect(Post.mode).to.be('server');
  });

  describe('connect', function () {

    it('should trigger connect event when a client connects', function (done) {
      Post.on('connect', function () {
        done();
      });

      createClient();
    });

    it('should trigger connect event on the connected client', function (done) {
      var client = createClient();
      client.on('connect', function () {
        // new socket model after client is connected
        Post.on('connect', function () {
          done();
        });
      });
    });

    it('should trigger client connect event when response', function (done) {
      var expectedPosts = ['p1', 'p2', 'p3'];

      Post.on('connect', function (req, res) {
        res(expectedPosts);
      });

      var client = createClient();
      client.on('post:connect', function (actualPosts) {
        expect(actualPosts).to.eql(expectedPosts);
        done();
      });
    });

    it('should get request context when connected', function (done) {
      Post.on('connect', function (req, res) {
        expect(req).to.be.an('object');
        expect(req.headers).to.be.an('object');
        done();
      });

      createClient();
    });

  });

  describe('create', function () {

    it('should not trigger any event handler when client connect', function (done) {
      Post.on('create', function () {
        expect().fail('');
      });

      Post.on('edit', function () {
        done();
      });

      var client = createClient();
      client.on('connect', function () {
        client.emit('post:edit');
      });
    });

    it('should trigger create handler when client emit event', function (done) {
      Post.on('create', function () {
        done();
      });

      var client = createClient();
      client.emit('post:create');
    });

    it('should register event handler on connected sockets', function (done) {
      var client = createClient();
      client.on('connect', function () {
        Post.on('create', function () {
          done();
        });

        client.emit('post:create');
      });
    });

  });

  describe('communication', function () {

    it('should communicate between server and client via callback', function (done) {
      Post.on('create', function (req, res, actualPost, fn) {
        expect(actualPost).to.eql(expectedPost);
        fn(true);
      });

      var client = createClient();
      client.emit('post:create', expectedPost, function (result) {
        expect(result).to.be(true);
        done();
      });
    });

    it('should broadcast every socket that something is created', function (done) {
      Post.on('create', function (req, res, actualPost) {
        expect(actualPost).to.eql(expectedPost);
        res(actualPost);
      });

      var client1 = createClient();
      var defer1 = Q.defer();
      client1.on('post:create', function (actualPost) {
        expect(actualPost).to.eql(expectedPost);
        defer1.resolve();
      });

      var client2 = createClient();
      var defer2 = Q.defer();
      client2.on('post:create', function (actualPost) {
        expect(actualPost).to.eql(expectedPost);
        defer2.resolve();
      });

      expect(client1).to.not.equal(client2);

      client2.emit('post:create', expectedPost);
      Q.all([defer1.promise, defer2.promise]).then(function () {
        done();
      });
    });

    it('should get request context when event triggered', function (done) {
      Post.on('create', function (req, res) {
        expect(req).to.be.an('object');
        expect(req.headers).to.be.an('object');
        done();
      });

      var client = createClient();
      client.emit('post:create');
    });

  });

});

describe('client', function () {

  var client;
  var Post;

  beforeEach(function () {
    client = createClient();
    Post = new SocketModel(client, 'post');
  });

  it('should be with client mode', function () {
    expect(Post.mode).to.be('client');
  });

  describe('register event handler', function () {

    it('should get data from connect event', function (done) {
      var expectedPosts = ['p1', 'p2', 'p3'];

      sio.on('connect', function (socket) {
        socket.emit('post:connect', expectedPosts);
      });

      Post.on('connect', function (req, res, actualPosts) {
        expect(actualPosts).to.be.eql(expectedPosts);
        done();
      });
    });

    it('should register event handler after connected', function (done) {
      sio.on('connect', function (socket) {
        socket.emit('post:create', true);
      });

      client.on('connect', function () {
        var Post = new SocketModel(client, 'post');
        Post.on('create', function (req, res, result) {
          expect(result).to.be(true);
          done();
        });
      });
    });

  });

  describe('trigger', function () {

    it('should trigger server-side create event handler', function (done) {
      sio.on('connect', function (socket) {
        socket.on('post:create', function (actualPost) {
          expect(actualPost).to.eql(expectedPost);
          socket.emit('post:create', true);
          done();
        });
      });

      Post.emit('create', expectedPost);
    });

    it('should trigger event when socket.io server broadcast', function (done) {
      Post.on('create', function () {
        done();
      });

      client.on('connect', function () {
        sio.emit('post:create');
      });
    });

    it('should trigger event, and then get it back on listener', function (done) {
      sio.on('connect', function (socket) {
        socket.on('post:create', function (actualPost) {
          expect(actualPost).to.eql(expectedPost);
          socket.emit('post:create', true);
        });
      });

      Post.on('create', function (req, res, result) {
        expect(result).to.be(true);
        done();
      });

      Post.emit('create', expectedPost);
    });

    it('should queue the firing event till connected, then re-fire them', function (done) {
      var createDefer = Q.defer();
      var editDefer = Q.defer();
      var deleteDefer = Q.defer();

      sio.on('connect', function (socket) {
        socket
          .on('post:create', function (data) {
            expect(data).to.be(1);
            createDefer.resolve();
          })
          .on('post:edit', function (data) {
            expect(data).to.be(2);
            editDefer.resolve();
          })
          .on('post:delete', function (data) {
            expect(data).to.be(3);
            deleteDefer.resolve();
          });
      });

      Post.emit('create', 1);
      Post.emit('edit', 2);
      Post.emit('delete', 3);

      // ensure the model emit the events before client connected
      expect(client.connected).to.be(false);

      // when client connected, no serve-side event is triggered
      client.on('connect', function () {
        expect(createDefer.promise.isFulfilled()).to.be(false);
        expect(editDefer.promise.isFulfilled()).to.be(false);
        expect(deleteDefer.promise.isFulfilled()).to.be(false);
      });

      Q.all([createDefer.promise, editDefer.promise, deleteDefer.promise]).then(function () {
        expect(client.connected).to.be(true);
        done();
      });
    });

  });

  describe('request', function () {

    it('should get request context when event triggered', function (done) {
      sio.on('connect', function (socket) {
        socket.emit('post:create', true);
      });

      Post.on('create', function (req, res) {
        expect(req).to.be.an('object');
        expect(req.uri).to.be.a('string');
        done();
      });
    });

  });

});

describe('meta-class', function () {

  it('should be a constructor', function () {
    var client = createClient();
    var Post = new SocketModel(client, 'post').class;
    var post = new Post();

    expect(post).to.be.an('object');
    expect(post).to.be.a(Post);
  });

  describe('field', function () {

    it('should initialize from the constructor', function () {
      var client = createClient();
      var Post = new SocketModel(client, 'post').class;
      var post = new Post({
        property1: 123,
        property2: 'abc',
        property3: true
      });

      expect(post).to.have.property('property1', 123);
      expect(post).to.have.property('property2', 'abc');
      expect(post).to.have.property('property3', true);
    });

    it('should access the fields from the methods in constructor', function () {
      var client = createClient();
      var Post = new SocketModel(client, 'post').class;
      var post = new Post({
        property: 100,
        add: function () {
          this.property++;
          return this.property;
        }
      });

      expect(post).to.have.property('add');
      expect(post.add).to.be.a('function');

      var result = post.add();

      expect(result).to.be(101);
      expect(post.property).to.be(101);
    });

  });

  describe('method', function () {

    function setUpAndCreatePost(method, done) {
      sio.on('connect', function (socket) {
        socket.on('post:' + method, function (actualPost, fn) {
          expect(actualPost).to.eql(expectedPost);
          done();

          if (typeof fn === 'function') {
            fn(actualPost);
          }
        });
      });

      var client = createClient();
      var Post = new SocketModel(client, 'post').class;
      var post = new Post();

      return post;
    }

    it('should have save method', function (done) {
      var post = setUpAndCreatePost('save', done);

      expect(post).to.have.property('save');
      expect(post.save).to.be.a('function');

      post.save(expectedPost);
    });

    it('should have delete method', function (done) {
      var post = setUpAndCreatePost('delete', done);

      expect(post).to.have.property('delete');
      expect(post.delete).to.be.a('function');

      post.delete(expectedPost);
    });

    it('should emit object fields when invoke without parameters', function (done) {
      var post = setUpAndCreatePost('save', done);

      _.extend(post, expectedPost);

      post.save();
    });

    it('should invoke callback after server-side response', function (done) {
      var post = setUpAndCreatePost('save', _.noop);

      post.save(expectedPost, function (actualPost) {
        expect(actualPost).to.be.eql(expectedPost);
        done();
      });
    });

  });

});
<|endoftext|>


<commit_before>var request = require('request');
var baseUrl = 'http://localhost:5000/';

describe('Test Index', function() {
    it('should return a 200', function() {
        request.get(baseUrl, function(error, response, body) {
            expect(response.statusCode).toBe(200);
        });
    });
});
<commit_msg>Updating test<commit_after>var request = require('request');
var baseUrl = 'http://localhost:5000/';

describe('Test Index', function() {
    it('should return a 200', function(done) {
        request.get(baseUrl, function(error, response, body) {
            expect(response.statusCode).toBe(200);
            done();
        });
    });
});
<|endoftext|>


<commit_before>define(["helper/Basic", "Tone/source/Noise", "helper/SourceTests", "helper/OutputAudio", "helper/CompareToFile"],
	function(BasicTests, Noise, SourceTests, OutputAudio, CompareToFile) {

		describe("Noise", function(){

		//run the common tests
			BasicTests(Noise);
			SourceTests(Noise);

			it("matches a file", function(){
				return CompareToFile(function(){
					const noise = new Noise().toMaster();
					noise.start(0.1).stop(0.2);
				}, "noise.wav", 150);
			});

			context("Get/Set", function(){

				it("can be constructed with an options object", function(){
					var noise = new Noise({
						"type" : "brown"
					});
					expect(noise.type).to.equal("brown");
					noise.dispose();
				});

				it("can set the playbackRate in the constructor", function(){
					var noise = new Noise({
						"playbackRate" : 2
					});
					expect(noise.playbackRate).to.equal(2);
					noise.dispose();
				});

				it("can set the playbackRate", function(){
					var noise = new Noise();
					noise.playbackRate = 3;
					expect(noise.playbackRate).to.equal(3);
					noise.dispose();
				});

			});

			context("Type", function(){

				it("can be set to 3 noise types", function(){
					var noise = new Noise();
					var types = ["white", "brown", "pink"];
					for (var i = 0; i < types.length; i++){
						noise.type = types[i];
						expect(noise.type).to.equal(types[i]);

					}
					noise.dispose();
				});

				it("cant set invalid type", function(){
					var noise = new Noise();
					expect(function(){
						noise.type = "else";
					}).to.throw(Error);
					noise.dispose();
				});

				it("outputs white noise", function(){
					return OutputAudio(function(){
						var noise = new Noise("white");
						noise.toMaster();
						noise.start();
					});
				});

				it("outputs pink noise", function(){
					return OutputAudio(function(){
						var noise = new Noise("pink");
						noise.toMaster();
						noise.start();
					});
				});

				it("outputs brown noise", function(){
					return OutputAudio(function(){
						var noise = new Noise("brown");
						noise.toMaster();
						noise.start();
					});
				});
			});
		});
	});
<commit_msg>increasing test coverage<commit_after>define(["helper/Basic", "Tone/source/Noise", "helper/SourceTests", "helper/OutputAudio", "helper/CompareToFile"],
	function(BasicTests, Noise, SourceTests, OutputAudio, CompareToFile) {

		describe("Noise", function(){

		//run the common tests
			BasicTests(Noise);
			SourceTests(Noise);

			it("matches a file", function(){
				return CompareToFile(function(){
					const noise = new Noise().toMaster();
					noise.start(0.1).stop(0.2);
				}, "noise.wav", 150);
			});

			context("Get/Set", function(){

				it("can be constructed with an options object", function(){
					var noise = new Noise({
						"type" : "brown"
					});
					expect(noise.type).to.equal("brown");
					noise.dispose();
				});

				it("can set the playbackRate in the constructor", function(){
					var noise = new Noise({
						"playbackRate" : 2
					});
					expect(noise.playbackRate).to.equal(2);
					noise.dispose();
				});

				it("can set the playbackRate after the noise is started", function(){
					return OutputAudio(function(){
						var noise = new Noise().toMaster();
						noise.start();
						noise.playbackRate = 3;
						expect(noise.playbackRate).to.equal(3);
					});
				});

			});

			context("Type", function(){

				it("can be set to 3 noise types", function(){
					var noise = new Noise();
					var types = ["white", "brown", "pink"];
					for (var i = 0; i < types.length; i++){
						noise.type = types[i];
						expect(noise.type).to.equal(types[i]);

					}
					noise.dispose();
				});

				it("cant set invalid type", function(){
					var noise = new Noise();
					expect(function(){
						noise.type = "else";
					}).to.throw(Error);
					noise.dispose();
				});

				it("outputs white noise", function(){
					return OutputAudio(function(){
						var noise = new Noise("white");
						noise.toMaster();
						noise.start();
					});
				});

				it("outputs pink noise", function(){
					return OutputAudio(function(){
						var noise = new Noise("pink");
						noise.toMaster();
						noise.start();
					});
				});

				it("outputs brown noise", function(){
					return OutputAudio(function(){
						var noise = new Noise("brown");
						noise.toMaster();
						noise.start();
					});
				});

				it("can set the type after the noise is started", function(){
					return OutputAudio(function(){
						var noise = new Noise();
						noise.toMaster();
						noise.start();
						noise.type = "brown";
					});
				});
			});
		});
	});
<|endoftext|>


<commit_before>/**
 * Start the Tangelo Hub backbone app.
 */
var app;
$(function () {
    girder.apiRoot = '/girder/api/v1';
    girder.handleRouting = false;
    app = new flow.App();
    app.render();
});

describe('App is running', function () {
    it('app had rendered', function () {
        runs(function () {
            expect($('#control-panel').length).toBe(1);
        });
    });
});

describe('Logo is present', function () {
    it("Make an AJAX request to load arbor.jpg", function () {
        var callback = jasmine.createSpy();
        getLogo(callback);
        waitsFor(function() {
            return callback.callCount > 0;
        });
        runs(function() {
            expect(callback).toHaveBeenCalled();
        });

        function getLogo(callback) {
            $.get("/arbor.jpg", function() {
                callback();
            })
        }
    });
});

describe('Able to create account', function () {
    it('account created',
        tangeloHubTest.createUser(
            'admin',
            'admin@email.com',
            'Admin',
            'Admin',
            'adminpassword!'
        )
    );
});

describe('Able to upload data', function () {
    it('data uploaded', function () {
        runs(function () {
            var file = new Blob(['a,b,c\n1,2,3']);
            file.name = 'test.csv';
            app.datasetsView.upload(file);
        });

        waitsFor(function () {
            return app.datasetsView.datasets.length === 1;
        }, 'dataset model to be available');

        runs(function () {
            var table = app.datasetsView.datasets.at(0);
            expect(table.get('data')).toBe('a,b,c\n1,2,3');
            expect(table.get('type')).toBe('table');
            expect(table.get('format')).toBe('csv');
        });
    });

    it('data downloaded', function () {
        var blob = null,
            data = null,
            URL = window.URL || window.webkitURL;

        if (!HTMLElement.prototype.click) {
            HTMLElement.prototype.click = function () {
                var ev = document.createEvent('MouseEvent');
                ev.initMouseEvent('click', true, true);
                this.dispatchEvent(ev);
            };
        }

        URL.createObjectURL = function (b) {
            blob = b;
            return "blob:";
        };

        runs(function () {
            $('.dataset-format-select').val('rows.json');
            $('.dataset-download').trigger('click');
        });

        waitsFor(function () {
            return $(':last').attr('download') === 'test.csv.rows-json';
        }, 'converted data to be stored');

        runs(function () {
            var reader = new window.FileReader();

            reader.onerror = function (event) {
                console.log("File could not be read! Code " + event.target.error.code);
            };

            reader.onload = function (event) {
                data = JSON.parse(reader.result);
            };
            reader.readAsText(blob);
        });

        waitsFor(function () {
            return data !== null;
        });

        runs(function () {
            expect(data).toEqual({
                fields: ['a', 'b', 'c'],
                rows: [{a: 1, b: 2, c: 3}]
            });
        });
    });

});

describe('Able to create collection', function () {
    it('collection created', function () {
        runs(function () {
            $('.new-collection-name').val('Collection');
            $('.new-collection').click();
        });

        waitsFor(function () {
            return $('#collections .name').text() === 'Collection';
        }, 'collection to be available');

        runs(function () {
            expect(app.collection.length).toBe(1);
            expect(app.collection.at(0).get('name')).toBe('Collection');
        });
    });
});

describe('Able to create analysis', function () {
    it('analysis created', function () {
        runs(function () {
            $('.save-location').first().click();
        });

        waitsFor(function () {
            return flow.saveLocation !== null && flow.saveLocation.get('analysisFolder') !== undefined;
        }, 'save location to be updated');

        runs(function () {
            $('#analysis-name').val('Test');
            $('#analysis-new').click();
        });

        waitsFor(function () {
            return app.analysesView.analyses.findWhere({name: 'Test'}) !== undefined;
        }, 'test analysis to be created');

        runs(function () {
            $('#show-script').click();
            $('#edit').click();
            app.analysesView.editor.setValue('output = 2 + 2');
            $('.add-output-variable').click();
            var controls = $('#output-variable-edit-dialog .form-control');
            controls.eq(0).val('output');
            controls.eq(1).val('number:number');
            $('#output-variable-edit-dialog .update').click();
            $('#save').click();
        });

        waitsFor(function () {
            return !$('#save').hasClass('disabled');
        }, 'save to complete');

        runs(function () {
            $('#setup').click();
            $('#analysis-setup-dialog .run').click();
        });

        waitsFor(function () {
            return !$('#analysis-setup-dialog .success-message').hasClass("hidden");
        }, 'success message');

        runs(function () {
            expect(app.datasetsView.datasets.findWhere({type: 'number'}).get('data')).toBe(4);
        });
    });
});

describe('Able to delete collection', function () {
    it('collection deleted', function () {
        runs(function () {
            $('#collections .delete').click();
        });

        waitsFor(function () {
            return $('#g-confirm-button').length > 0;
        }, 'confirm dialog to appear');

        runs(function () {
            $('#g-confirm-button').click();
        });

        waitsFor(function () {
            return $('#collections .name').text() === '';
        }, 'collection to be deleted');

        runs(function () {
            expect(app.collection.length).toBe(0);
        });
    });
});
<commit_msg>update logo test to reflect new file name<commit_after>/**
 * Start the Tangelo Hub backbone app.
 */
var app;
$(function () {
    girder.apiRoot = '/girder/api/v1';
    girder.handleRouting = false;
    app = new flow.App();
    app.render();
});

describe('App is running', function () {
    it('app had rendered', function () {
        runs(function () {
            expect($('#control-panel').length).toBe(1);
        });
    });
});

describe('Logo is present', function () {
    it("Make an AJAX request to load logo.png", function () {
        var callback = jasmine.createSpy();
        getLogo(callback);
        waitsFor(function() {
            return callback.callCount > 0;
        });
        runs(function() {
            expect(callback).toHaveBeenCalled();
        });

        function getLogo(callback) {
            $.get("/logo.png", function() {
                callback();
            })
        }
    });
});

describe('Able to create account', function () {
    it('account created',
        tangeloHubTest.createUser(
            'admin',
            'admin@email.com',
            'Admin',
            'Admin',
            'adminpassword!'
        )
    );
});

describe('Able to upload data', function () {
    it('data uploaded', function () {
        runs(function () {
            var file = new Blob(['a,b,c\n1,2,3']);
            file.name = 'test.csv';
            app.datasetsView.upload(file);
        });

        waitsFor(function () {
            return app.datasetsView.datasets.length === 1;
        }, 'dataset model to be available');

        runs(function () {
            var table = app.datasetsView.datasets.at(0);
            expect(table.get('data')).toBe('a,b,c\n1,2,3');
            expect(table.get('type')).toBe('table');
            expect(table.get('format')).toBe('csv');
        });
    });

    it('data downloaded', function () {
        var blob = null,
            data = null,
            URL = window.URL || window.webkitURL;

        if (!HTMLElement.prototype.click) {
            HTMLElement.prototype.click = function () {
                var ev = document.createEvent('MouseEvent');
                ev.initMouseEvent('click', true, true);
                this.dispatchEvent(ev);
            };
        }

        URL.createObjectURL = function (b) {
            blob = b;
            return "blob:";
        };

        runs(function () {
            $('.dataset-format-select').val('rows.json');
            $('.dataset-download').trigger('click');
        });

        waitsFor(function () {
            return $(':last').attr('download') === 'test.csv.rows-json';
        }, 'converted data to be stored');

        runs(function () {
            var reader = new window.FileReader();

            reader.onerror = function (event) {
                console.log("File could not be read! Code " + event.target.error.code);
            };

            reader.onload = function (event) {
                data = JSON.parse(reader.result);
            };
            reader.readAsText(blob);
        });

        waitsFor(function () {
            return data !== null;
        });

        runs(function () {
            expect(data).toEqual({
                fields: ['a', 'b', 'c'],
                rows: [{a: 1, b: 2, c: 3}]
            });
        });
    });

});

describe('Able to create collection', function () {
    it('collection created', function () {
        runs(function () {
            $('.new-collection-name').val('Collection');
            $('.new-collection').click();
        });

        waitsFor(function () {
            return $('#collections .name').text() === 'Collection';
        }, 'collection to be available');

        runs(function () {
            expect(app.collection.length).toBe(1);
            expect(app.collection.at(0).get('name')).toBe('Collection');
        });
    });
});

describe('Able to create analysis', function () {
    it('analysis created', function () {
        runs(function () {
            $('.save-location').first().click();
        });

        waitsFor(function () {
            return flow.saveLocation !== null && flow.saveLocation.get('analysisFolder') !== undefined;
        }, 'save location to be updated');

        runs(function () {
            $('#analysis-name').val('Test');
            $('#analysis-new').click();
        });

        waitsFor(function () {
            return app.analysesView.analyses.findWhere({name: 'Test'}) !== undefined;
        }, 'test analysis to be created');

        runs(function () {
            $('#show-script').click();
            $('#edit').click();
            app.analysesView.editor.setValue('output = 2 + 2');
            $('.add-output-variable').click();
            var controls = $('#output-variable-edit-dialog .form-control');
            controls.eq(0).val('output');
            controls.eq(1).val('number:number');
            $('#output-variable-edit-dialog .update').click();
            $('#save').click();
        });

        waitsFor(function () {
            return !$('#save').hasClass('disabled');
        }, 'save to complete');

        runs(function () {
            $('#setup').click();
            $('#analysis-setup-dialog .run').click();
        });

        waitsFor(function () {
            return !$('#analysis-setup-dialog .success-message').hasClass("hidden");
        }, 'success message');

        runs(function () {
            expect(app.datasetsView.datasets.findWhere({type: 'number'}).get('data')).toBe(4);
        });
    });
});

describe('Able to delete collection', function () {
    it('collection deleted', function () {
        runs(function () {
            $('#collections .delete').click();
        });

        waitsFor(function () {
            return $('#g-confirm-button').length > 0;
        }, 'confirm dialog to appear');

        runs(function () {
            $('#g-confirm-button').click();
        });

        waitsFor(function () {
            return $('#collections .name').text() === '';
        }, 'collection to be deleted');

        runs(function () {
            expect(app.collection.length).toBe(0);
        });
    });
});
<|endoftext|>


<commit_before>var Connection = require( './connection' ),
	events = require( 'events' ),
	util = require( 'util' );

/**
 * MessageConnector that uses Redis' pub-sub capabilities for deepstream
 * messaging.
 *
 * Due to the forever blocking "subscriber only" nature of Redis this
 * establishes two connections to the redis server, one for up and one for
 * downstream
 *
 * @param {Object} options Redis connection options. See connection.js for details
 *
 * @author Wolfram Hempel
 * @copyright 2015 Hoxton One Ltd.
 *
 * @constructor
 */
var MessageConnector = function( options ) {
	Connection.call( this, options );

	this.name = 'deepstream.io-msg-redis';
	this.version = '0.2.3';

	this._senderId = options.serverName || ( Math.random() * 10000000000000000000 ).toString( 36 );
	this._eventEmitter = new events.EventEmitter();
	this._publishConnection = new Connection( options );
	this.client.on( 'message', this._onMessage.bind( this ) );
};

util.inherits( MessageConnector, Connection );

/**
 * Removes <callback> as a listener and notifies the server
 * that the client is no longer interested in messages for <topic>
 *
 * @param   {String}   topic
 * @param   {Function} callback
 *
 * @public
 * @returns {void}
 */
MessageConnector.prototype.unsubscribe = function( topic, callback ) {
	this.client.unsubscribe( topic );
	this._eventEmitter.removeListener( topic, callback );
};

/**
 * Subscribe as a listener to <topic>. Multiple subscriptions
 * to the same topic are allowed. It's up to this class
 * to ensure that <callback> won't receive any messages published
 * by itself
 *
 * @param   {String}   topic
 * @param   {Function} callback
 *
 * @public
 * @returns {void}
 */
MessageConnector.prototype.subscribe = function( topic, callback ) {
	this._eventEmitter.on( topic, callback );
	this.client.subscribe( topic );
};

/**
 * Publish messages on a topic.
 *
 * This implementation will add the server name to the message to make sure
 * that the client doesn't receive messages that where send by itself
 *
 * @param   {String}   topic
 * @param   {Function} callback
 *
 * @public
 * @returns {void}
 */
MessageConnector.prototype.publish = function( topic, message ) {
	message._s = this._senderId;
	this._publishConnection.client.publish( topic, JSON.stringify( message ) );
};

/**
 * Callback for incoming messages. Parses the JSON stringified message,
 * checks that it hasn't been send by itself and is meant for a topic
 * that the client is subscribed to and - if so - notifies the callbacks
 *
 * @param   {String}   topic
 * @param   {Function} callback
 *
 * @private
 * @returns {void}
 */
MessageConnector.prototype._onMessage = function( topic, message ) {
	var parsedMessage;

	try{
		parsedMessage = JSON.parse( message );
	} catch ( e ) {
		this._onError( 'Error parsing message ' + e.toString() );
		return;
	}

	if( parsedMessage._s === this._senderId ) {
		return;
	}

	delete parsedMessage._s;

	if( this._eventEmitter.listeners( topic ).length === 0 ) {
		this._onError( 'Received message for unknown topic ' + topic );
		return;
	}

	this._eventEmitter.emit( topic, parsedMessage );
};

module.exports = MessageConnector;<commit_msg>read package<commit_after>var Connection = require( './connection' ),
	events = require( 'events' ),
	pckg = require( '../package.json' ),
	util = require( 'util' );

/**
 * MessageConnector that uses Redis' pub-sub capabilities for deepstream
 * messaging.
 *
 * Due to the forever blocking "subscriber only" nature of Redis this
 * establishes two connections to the redis server, one for up and one for
 * downstream
 *
 * @param {Object} options Redis connection options. See connection.js for details
 *
 * @author Wolfram Hempel
 * @copyright 2015 Hoxton One Ltd.
 *
 * @constructor
 */
var MessageConnector = function( options ) {
	Connection.call( this, options );

	this.name = pckg.name;
	this.version = pckg.version;

	this._senderId = options.serverName || ( Math.random() * 10000000000000000000 ).toString( 36 );
	this._eventEmitter = new events.EventEmitter();
	this._publishConnection = new Connection( options );
	this.client.on( 'message', this._onMessage.bind( this ) );
};

util.inherits( MessageConnector, Connection );

/**
 * Removes <callback> as a listener and notifies the server
 * that the client is no longer interested in messages for <topic>
 *
 * @param   {String}   topic
 * @param   {Function} callback
 *
 * @public
 * @returns {void}
 */
MessageConnector.prototype.unsubscribe = function( topic, callback ) {
	this.client.unsubscribe( topic );
	this._eventEmitter.removeListener( topic, callback );
};

/**
 * Subscribe as a listener to <topic>. Multiple subscriptions
 * to the same topic are allowed. It's up to this class
 * to ensure that <callback> won't receive any messages published
 * by itself
 *
 * @param   {String}   topic
 * @param   {Function} callback
 *
 * @public
 * @returns {void}
 */
MessageConnector.prototype.subscribe = function( topic, callback ) {
	this._eventEmitter.on( topic, callback );
	this.client.subscribe( topic );
};

/**
 * Publish messages on a topic.
 *
 * This implementation will add the server name to the message to make sure
 * that the client doesn't receive messages that where send by itself
 *
 * @param   {String}   topic
 * @param   {Function} callback
 *
 * @public
 * @returns {void}
 */
MessageConnector.prototype.publish = function( topic, message ) {
	message._s = this._senderId;
	this._publishConnection.client.publish( topic, JSON.stringify( message ) );
};

/**
 * Callback for incoming messages. Parses the JSON stringified message,
 * checks that it hasn't been send by itself and is meant for a topic
 * that the client is subscribed to and - if so - notifies the callbacks
 *
 * @param   {String}   topic
 * @param   {Function} callback
 *
 * @private
 * @returns {void}
 */
MessageConnector.prototype._onMessage = function( topic, message ) {
	var parsedMessage;

	try{
		parsedMessage = JSON.parse( message );
	} catch ( e ) {
		this._onError( 'Error parsing message ' + e.toString() );
		return;
	}

	if( parsedMessage._s === this._senderId ) {
		return;
	}

	delete parsedMessage._s;

	if( this._eventEmitter.listeners( topic ).length === 0 ) {
		this._onError( 'Received message for unknown topic ' + topic );
		return;
	}

	this._eventEmitter.emit( topic, parsedMessage );
};

module.exports = MessageConnector;<|endoftext|>


<commit_before>var path = require('path');
var expect = require('chai').expect;
var pkgpath = path.join(__dirname, '..', '..', 'package.json')
var pkg = require('../../package.json');
var define = require('../..');

describe('cli-define:', function() {
  it('should define subcommands', function(done) {
    var semver = '1.0.0';
    var cli = define(pkgpath, 'mock-program');
    expect(cli.name()).to.eql('mock-program');

    cli.version(semver);
    expect(cli.version()).to.eql(semver)

    var ls = cli.command('ls, list')
      .description('list packages');
    expect(ls.getLongName()).to.eql('list');
    expect(cli.commands().list).to.equal(ls);
    var deps = ls.command('deps, dependencies')
      .description('list package dependencies')
    expect(deps.getLongName()).to.eql('dependencies');
    expect(ls.commands().dependencies).to.equal(deps);
    var parents = deps.getParents();
    expect(parents[0]).to.equal(ls);
    expect(parents[1]).to.equal(cli);
    parents = deps.getParents(true);
    expect(parents[0]).to.equal(cli);
    expect(parents[1]).to.equal(ls);
    expect(cli.getFullName()).to.eql('mock-program')
    expect(ls.getFullName()).to.eql('mock-program-list')
    expect(deps.getFullName()).to.eql('mock-program-list-dependencies');
    done();
  });
})
<commit_msg>Assert on assign().<commit_after>var path = require('path');
var expect = require('chai').expect;
var pkgpath = path.join(__dirname, '..', '..', 'package.json')
var pkg = require('../../package.json');
var define = require('../..');

describe('cli-define:', function() {
  it('should define subcommands', function(done) {
    var semver = '1.0.0';
    var cli = define(pkgpath, 'mock-program');
    expect(cli.name()).to.eql('mock-program');

    cli.version(semver);
    expect(cli.version()).to.eql(semver)

    var ls = cli.command('ls, list')
      .description('list packages');
    expect(ls.getLongName()).to.eql('list');
    expect(cli.commands().list).to.equal(ls);
    var deps = ls.command('deps, dependencies')
      .description('list package dependencies')
    expect(deps.getLongName()).to.eql('dependencies');
    expect(ls.commands().dependencies).to.equal(deps);
    var parents = deps.getParents();
    expect(parents[0]).to.equal(ls);
    expect(parents[1]).to.equal(cli);
    parents = deps.getParents(true);
    expect(parents[0]).to.equal(cli);
    expect(parents[1]).to.equal(ls);
    expect(cli.getFullName()).to.eql('mock-program')
    expect(ls.getFullName()).to.eql('mock-program-list')
    expect(deps.getFullName()).to.eql('mock-program-list-dependencies');

    // assign to program: no arg and no stash
    cli.assign(null, 'mockProgramOption', '/mock/file/program/assign');

    expect(cli.mockProgramOption).to.eql('/mock/file/program/assign');

    cli.configure({stash: {}});

    // assign to stash no arg
    cli.assign(null, 'mockOption', '/mock/file/stash/assign');

    expect(cli.configure().stash.mockOption).to.eql('/mock/file/stash/assign');

    // assign to stash and arg
    var opt = cli.createOption('--mock-option <value>', 'Mock option');
    cli.option(opt);
    cli.assign(opt, opt.key(), '/mock/file');

    expect(cli.configure().stash.mockOption)
      .to.eql(opt.value())
      .to.eql('/mock/file');

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


<commit_before>describe("Events", function(){
  var EventTest, ListenTest;
  var spy;

  beforeEach(function(){
    spy = jasmine.createSpy();
    EventTest = Spine.Class.create();
    EventTest.extend(Spine.Events);
  });

  it("can bind/trigger events", function(){
    var spy2 = jasmine.createSpy('globalSpy');
    Spine.bind('notify', spy2);
    EventTest.bind("daddyo", spy);
    EventTest.trigger("daddyo");
    expect(spy).toHaveBeenCalled();
    expect(spy2).not.toHaveBeenCalled();
  });

  it("can bind/trigger global events", function(){
    var spy2 = jasmine.createSpy('globalSpy');
    Spine.bind('notify', spy2);
    EventTest.bind("daddyo", spy);
    Spine.trigger("notify");
    expect(spy2).toHaveBeenCalled();
    expect(spy).not.toHaveBeenCalled();
  });

  it("can listen for events on other objects", function(){
    ListenTest = Spine.Class.create();
    ListenTest.extend(Spine.Events);
    ListenTest.listenTo(EventTest, "daddyo", spy);
    EventTest.trigger("daddyo");
    expect(spy).toHaveBeenCalled();
  });

  it("should trigger correct events", function(){
    EventTest.bind("daddyo", spy);
    EventTest.trigger("motherio");
    expect(spy).not.toHaveBeenCalled();
  });

  it("can bind/trigger multiple events", function(){
    EventTest.bind("house car windows", spy);
    EventTest.trigger("car");
    expect(spy).toHaveBeenCalled();
    EventTest.trigger("house");
    EventTest.trigger("windows");
    expect(spy.calls.count()).toBe(3);
  });

  it("can listen for multiple events on other objects", function(){
    ListenTest = Spine.Class.create();
    ListenTest.extend(Spine.Events);
    ListenTest.listenTo(EventTest, "house car windows", spy);
    EventTest.trigger("car");
    expect(spy).toHaveBeenCalled();
    EventTest.trigger("house");
    EventTest.trigger("windows");
    expect(spy.calls.count()).toBe(3);
  });

  it("can pass data to triggered events", function(){
    var spy2 = jasmine.createSpy();
    Spine.bind('notify', spy2);
    EventTest.bind("yoyo", spy);

    EventTest.trigger("yoyo", 5, 10);
    expect(spy).toHaveBeenCalledWith(5, 10);

    Spine.trigger("notify", 'a message');
    expect(spy2).toHaveBeenCalledWith('a message');
  });

  it("can unbind events", function(){
    EventTest.bind("daddyo", spy);
    EventTest.unbind("daddyo");
    EventTest.trigger("daddyo");
    expect(spy).not.toHaveBeenCalled();
  });

  it("can unbind all events if no arguments given", function() {
    EventTest.bind("yoyo daddyo", spy);
    EventTest.unbind();
    EventTest.trigger("yoyo");
    expect(spy).not.toHaveBeenCalled();
    spy.calls.reset();
    EventTest.trigger("daddyo");
    expect(spy).not.toHaveBeenCalled();
  });

  it("can stop listening to events", function(){
    ListenTest = Spine.Class.create();
    ListenTest.extend(Spine.Events);
    ListenTest.listenTo(EventTest, "daddyo", spy);
    EventTest.trigger("daddyo");
    expect(spy).toHaveBeenCalled();
    spy.calls.reset();
    ListenTest.stopListening(EventTest, "daddyo");
    EventTest.trigger("daddyo");
    expect(spy).not.toHaveBeenCalled();
  });

  it("can unbind one event", function(){
    EventTest.bind("house car windows", spy);
    EventTest.unbind("car windows");
    EventTest.trigger("car");
    EventTest.trigger("windows");
    expect(spy).not.toHaveBeenCalled();
    EventTest.trigger("house");
    expect(spy).toHaveBeenCalled();
  });

  it("can stopListening to one event", function(){
    ListenTest = Spine.Class.create();
    ListenTest.extend(Spine.Events);
    ListenTest.listenTo(EventTest, "house car windows", spy)
    ListenTest.stopListening(EventTest, "car windows");
    EventTest.trigger("car");
    EventTest.trigger("windows");
    expect(spy).not.toHaveBeenCalled();
    EventTest.trigger("house");
    expect(spy).toHaveBeenCalled();
  });

  it("can stopListening to a specific callback", function(){
    var spy2 = jasmine.createSpy();
    ListenTest = Spine.Class.create();
    ListenTest.extend(Spine.Events);
    ListenTest.listenTo(EventTest, "keep", spy);
    ListenTest.listenTo(EventTest, "keep", spy2);
    //EventTest.trigger("keep");
    //expect(spy).toHaveBeenCalled();
    //expect(spy2).toHaveBeenCalled();
    ListenTest.stopListening(EventTest, "keep", spy2);
    EventTest.trigger("keep");
    expect(spy).toHaveBeenCalled();
    expect(spy2).not.toHaveBeenCalled();
  });

  it("can stopListening to a specific object", function(){
    ListenTest = Spine.Class.create();
    var EventTest2 = Spine.Class.create();
    var spy2 = jasmine.createSpy();
    ListenTest.extend(Spine.Events);
    EventTest2.extend(Spine.Events);
    ListenTest.listenTo(EventTest, "keep", spy);
    ListenTest.listenTo(EventTest2, "keep", spy2);
    ListenTest.stopListening(EventTest);
    EventTest.trigger("keep");
    EventTest2.trigger("keep");
    expect(spy).not.toHaveBeenCalled();
    expect(spy2).toHaveBeenCalled();
  });

  it("can bind to an event only once", function(){
    EventTest.one("indahouse", spy);
    EventTest.trigger("indahouse");
    expect(spy).toHaveBeenCalled();
    spy.calls.reset();
    EventTest.trigger("indahouse");
    expect(spy).not.toHaveBeenCalled();
  });

  it("can listen to to a event only once", function(){
    ListenTest = Spine.Class.create();
    ListenTest.extend(Spine.Events);
    ListenTest.listenToOnce(EventTest, 'indahouse', spy)
    EventTest.trigger("indahouse");
    expect(spy).toHaveBeenCalled();
    spy.calls.reset();
    EventTest.trigger("indahouse");
    expect(spy).not.toHaveBeenCalled();
  });

  it("can stopListening to a event that is being listened to once", function(){
    ListenTest = Spine.Class.create();
    ListenTest.extend(Spine.Events);
    ListenTest.listenToOnce(EventTest, "indahouse", spy)
    ListenTest.stopListening(EventTest, "indahouse");
    EventTest.trigger("indahouse");
    expect(spy).not.toHaveBeenCalled();
  });

  it("can stopListening to all events if no arguments given", function(){
    ListenTest = Spine.Class.create();
    ListenTest.extend(Spine.Events);
    ListenTest.listenTo(EventTest, "house", spy);
    ListenTest.listenToOnce(EventTest, "indahouse", spy);
    ListenTest.stopListening();
    EventTest.trigger("house");
    expect(spy).not.toHaveBeenCalled();
    spy.calls.reset();
    EventTest.trigger("indahouse");
    expect(spy).not.toHaveBeenCalled();
  });

  it("should allow a callback to unbind itself", function(){
    var a = jasmine.createSpy("a");
    var b = jasmine.createSpy("b");
    var c = jasmine.createSpy("c");

    b.and.callFake(function() {
      EventTest.unbind("once", b);
    });

    EventTest.bind("once", a);
    EventTest.bind("once", b);
    EventTest.bind("once", c);
    EventTest.trigger("once");

    expect(a).toHaveBeenCalled();
    expect(b).toHaveBeenCalled();
    expect(c).toHaveBeenCalled();

    EventTest.trigger("once");

    expect(a.calls.count()).toBe(2);
    expect(b.calls.count()).toBe(1);
    expect(c.calls.count()).toBe(2);
  });

  it("can cancel propogation", function(){
    EventTest.bind("motherio", function(){ return false; });
    EventTest.bind("motherio", spy);
    EventTest.trigger("motherio");
    expect(spy).not.toHaveBeenCalled();
  });

  it("should clear events on inherited objects", function(){
    EventTest.bind("yoyo", spy);
    var Sub = EventTest.sub();
    Sub.trigger("yoyo");
    expect(spy).not.toHaveBeenCalled();
  });

  it("should not unbind all events if given and undefined object", function() {
    EventTest.bind("daddyo", spy);
    EventTest.unbind(undefined);
    EventTest.trigger("daddyo");
    expect(spy).toHaveBeenCalled();
  });

  it("should not stopListening to all events if given and undefined object", function() {
    ListenTest = Spine.Class.create();
    ListenTest.extend(Spine.Events);
    ListenTest.listenTo(EventTest, "house", spy);
    ListenTest.stopListening(undefined);
    EventTest.trigger("house");
    expect(spy).toHaveBeenCalled();
  });
});

<commit_msg>add few more tests for spine global events <commit_after>describe("Events", function(){
  var EventTest, ListenTest;
  var spy;

  beforeEach(function(){
    spy = jasmine.createSpy();
    EventTest = Spine.Class.create();
    EventTest.extend(Spine.Events);
  });

  it("can bind/trigger events", function(){
    var spy2 = jasmine.createSpy('globalSpy');
    Spine.bind('notify', spy2);
    EventTest.bind("daddyo", spy);

    EventTest.trigger("somethingElse");
    expect(spy).not.toHaveBeenCalled();

    EventTest.trigger("daddyo");
    expect(spy).toHaveBeenCalled();
    expect(spy2).not.toHaveBeenCalled();
  });

  it("can bind/trigger global events", function(){
    var spy2 = jasmine.createSpy('globalSpy');
    Spine.bind('notify', spy2);
    EventTest.bind("daddyo", spy);

    Spine.trigger('somethingElse')
    expect(spy2).not.toHaveBeenCalled();

    Spine.trigger("notify");
    expect(spy2).toHaveBeenCalled();
    expect(spy).not.toHaveBeenCalled();
  });

  it("can listen for events on other objects", function(){
    ListenTest = Spine.Class.create();
    ListenTest.extend(Spine.Events);
    ListenTest.listenTo(EventTest, "daddyo", spy);
    EventTest.trigger("daddyo");
    expect(spy).toHaveBeenCalled();
  });

  it("should trigger correct events", function(){
    EventTest.bind("daddyo", spy);
    EventTest.trigger("motherio");
    expect(spy).not.toHaveBeenCalled();
  });

  it("can bind/trigger multiple events", function(){
    EventTest.bind("house car windows", spy);
    EventTest.trigger("car");
    expect(spy).toHaveBeenCalled();
    EventTest.trigger("house");
    EventTest.trigger("windows");
    expect(spy.calls.count()).toBe(3);
  });

  it("can listen for multiple events on other objects", function(){
    ListenTest = Spine.Class.create();
    ListenTest.extend(Spine.Events);
    ListenTest.listenTo(EventTest, "house car windows", spy);
    EventTest.trigger("car");
    expect(spy).toHaveBeenCalled();
    EventTest.trigger("house");
    EventTest.trigger("windows");
    expect(spy.calls.count()).toBe(3);
  });

  it("can pass data to triggered events", function(){
    var spy2 = jasmine.createSpy('globalSpy');
    Spine.bind('notify', spy2);
    EventTest.bind("yoyo", spy);

    EventTest.trigger("yoyo", 5, 10);
    expect(spy).toHaveBeenCalledWith(5, 10);

    Spine.trigger("notify", 'a message');
    expect(spy2).toHaveBeenCalledWith('a message');
  });

  it("can unbind events", function(){
    EventTest.bind("daddyo", spy);
    var spy2 = jasmine.createSpy('globalSpy');
    Spine.bind('notify', spy2);

    EventTest.unbind("daddyo");
    Spine.unbind('notify');
    EventTest.trigger("daddyo");
    Spine.trigger("notify");
    expect(spy).not.toHaveBeenCalled();
    expect(spy2).not.toHaveBeenCalled();
  });

  it("can unbind all events if no arguments given", function() {
    EventTest.bind("yoyo daddyo", spy);
    EventTest.unbind();
    EventTest.trigger("yoyo");
    expect(spy).not.toHaveBeenCalled();
    spy.calls.reset();
    EventTest.trigger("daddyo");
    expect(spy).not.toHaveBeenCalled();
  });

  it("can stop listening to events", function(){
    ListenTest = Spine.Class.create();
    ListenTest.extend(Spine.Events);
    ListenTest.listenTo(EventTest, "daddyo", spy);
    EventTest.trigger("daddyo");
    expect(spy).toHaveBeenCalled();
    spy.calls.reset();
    ListenTest.stopListening(EventTest, "daddyo");
    EventTest.trigger("daddyo");
    expect(spy).not.toHaveBeenCalled();
  });

  it("can unbind one event", function(){
    EventTest.bind("house car windows", spy);
    EventTest.unbind("car windows");
    EventTest.trigger("car");
    EventTest.trigger("windows");
    expect(spy).not.toHaveBeenCalled();
    EventTest.trigger("house");
    expect(spy).toHaveBeenCalled();
  });

  it("can stopListening to one event", function(){
    ListenTest = Spine.Class.create();
    ListenTest.extend(Spine.Events);
    ListenTest.listenTo(EventTest, "house car windows", spy)
    ListenTest.stopListening(EventTest, "car windows");
    EventTest.trigger("car");
    EventTest.trigger("windows");
    expect(spy).not.toHaveBeenCalled();
    EventTest.trigger("house");
    expect(spy).toHaveBeenCalled();
  });

  it("can stopListening to a specific callback", function(){
    var spy2 = jasmine.createSpy();
    ListenTest = Spine.Class.create();
    ListenTest.extend(Spine.Events);
    ListenTest.listenTo(EventTest, "keep", spy);
    ListenTest.listenTo(EventTest, "keep", spy2);
    //EventTest.trigger("keep");
    //expect(spy).toHaveBeenCalled();
    //expect(spy2).toHaveBeenCalled();
    ListenTest.stopListening(EventTest, "keep", spy2);
    EventTest.trigger("keep");
    expect(spy).toHaveBeenCalled();
    expect(spy2).not.toHaveBeenCalled();
  });

  it("can stopListening to a specific object", function(){
    ListenTest = Spine.Class.create();
    var EventTest2 = Spine.Class.create();
    var spy2 = jasmine.createSpy();
    ListenTest.extend(Spine.Events);
    EventTest2.extend(Spine.Events);
    ListenTest.listenTo(EventTest, "keep", spy);
    ListenTest.listenTo(EventTest2, "keep", spy2);
    ListenTest.stopListening(EventTest);
    EventTest.trigger("keep");
    EventTest2.trigger("keep");
    expect(spy).not.toHaveBeenCalled();
    expect(spy2).toHaveBeenCalled();
  });

  it("can bind to an event only once", function(){
    EventTest.one("indahouse", spy);
    EventTest.trigger("indahouse");
    expect(spy).toHaveBeenCalled();
    spy.calls.reset();
    EventTest.trigger("indahouse");
    expect(spy).not.toHaveBeenCalled();
  });

  it("can bind to a global event only once", function(){
    var spy2 = jasmine.createSpy('globalSpy');
    Spine.one('notify', spy2);
    Spine.trigger("notify");
    expect(spy2).toHaveBeenCalled();
    spy2.calls.reset();
    Spine.trigger("notify");
    expect(spy2).not.toHaveBeenCalled();
  });

  it("can listen to to a event only once", function(){
    ListenTest = Spine.Class.create();
    ListenTest.extend(Spine.Events);
    ListenTest.listenToOnce(EventTest, 'indahouse', spy)
    EventTest.trigger("indahouse");
    expect(spy).toHaveBeenCalled();
    spy.calls.reset();
    EventTest.trigger("indahouse");
    expect(spy).not.toHaveBeenCalled();
  });

  it("can stopListening to a event that is being listened to once", function(){
    ListenTest = Spine.Class.create();
    ListenTest.extend(Spine.Events);
    ListenTest.listenToOnce(EventTest, "indahouse", spy)
    ListenTest.stopListening(EventTest, "indahouse");
    EventTest.trigger("indahouse");
    expect(spy).not.toHaveBeenCalled();
  });

  it("can stopListening to all events if no arguments given", function(){
    ListenTest = Spine.Class.create();
    ListenTest.extend(Spine.Events);
    ListenTest.listenTo(EventTest, "house", spy);
    ListenTest.listenToOnce(EventTest, "indahouse", spy);
    ListenTest.stopListening();
    EventTest.trigger("house");
    expect(spy).not.toHaveBeenCalled();
    spy.calls.reset();
    EventTest.trigger("indahouse");
    expect(spy).not.toHaveBeenCalled();
  });

  it("should allow a callback to unbind itself", function(){
    var a = jasmine.createSpy("a");
    var b = jasmine.createSpy("b");
    var c = jasmine.createSpy("c");

    b.and.callFake(function() {
      EventTest.unbind("once", b);
    });

    EventTest.bind("once", a);
    EventTest.bind("once", b);
    EventTest.bind("once", c);
    EventTest.trigger("once");

    expect(a).toHaveBeenCalled();
    expect(b).toHaveBeenCalled();
    expect(c).toHaveBeenCalled();

    EventTest.trigger("once");

    expect(a.calls.count()).toBe(2);
    expect(b.calls.count()).toBe(1);
    expect(c.calls.count()).toBe(2);
  });

  it("can cancel propogation", function(){
    EventTest.bind("motherio", function(){ return false; });
    EventTest.bind("motherio", spy);
    EventTest.trigger("motherio");
    expect(spy).not.toHaveBeenCalled();
  });

  it("should clear events on inherited objects", function(){
    EventTest.bind("yoyo", spy);
    var Sub = EventTest.sub();
    Sub.trigger("yoyo");
    expect(spy).not.toHaveBeenCalled();
  });

  it("should not unbind all events if given and undefined object", function() {
    EventTest.bind("daddyo", spy);
    EventTest.unbind(undefined);
    EventTest.trigger("daddyo");
    expect(spy).toHaveBeenCalled();
  });

  it("should not stopListening to all events if given and undefined object", function() {
    ListenTest = Spine.Class.create();
    ListenTest.extend(Spine.Events);
    ListenTest.listenTo(EventTest, "house", spy);
    ListenTest.stopListening(undefined);
    EventTest.trigger("house");
    expect(spy).toHaveBeenCalled();
  });
});

<|endoftext|>


<commit_before>define([
    'dojo/_base/declare',
    'dojo/_base/lang',
    'dojo/on',
    'dojo/dom',
    'dojo/dom-construct',
    'dojo/dom-class',
    'dojo/dom-geometry',
    './_WidgetBase',
    './_HideableMixin',
    'dojo/text!./template/Tooltip.html',
    '../less!./less/tooltip.less'
],
function(
    declare,
    lang,
    on,
    dom,
    domConstruct,
    domClass,
    domGeom,
    WidgetBase,
    HideableMixin,
    template
){
    // module:
    //		havok/widget/Tooltip

    return declare(
        [WidgetBase, HideableMixin],
        {
            // summary:
            //      Widget to display tooltips.

            // templateString: String
            templateString: template,

            // showOn: String
            //      The name of the event to trigger tooltip show
            showOn: 'mouseover',

            // hideOn: String
            //      The name of the event to trigger tooltip hide
            hideOn: 'mouseout',

            /*=====
            // title: String
            //      The content to show in the tooltip
            title: undefined,
            =====*/

            // placement: String
            //      Where to place the tooltip relative to target.
            //      May be top | bottom | left | right
            //      Defaults to `top`
            placement: 'top',

            // hidden: Boolean
            //      Is the tooltip hidden?
            //      Defalts to `true`
            hidden: true,

            /*=====
            // target: DomNode
            //      The dom node which the tooltip will be displayed next to
            target: undefined,
            =====*/

            // tag: String
            //      The tag that the tooltip will be rendered with.
            //      Defalts to 'span'
            tag: 'span',

            startup: function(){

                this.inherited(arguments);

                if (!this.target) this.target = this.domNode;
                if (typeof this.target == 'string') this.target = dom.byId(this.target);

                if (this.showOn) {
                    on(this.target, this.showOn, lang.hitch(this, function(e){
                        e.preventDefault();
                        this.set('hidden', false)
                    }))
                }
                if (this.hideOn) {
                    on(this.target, this.hideOn, lang.hitch(this, function(e){
                        e.preventDefault();
                        this.set('hidden', true)
                    }))
                }
            },

            _setTitleAttr: function(value){
                this.titleNode.innerHTML = value;
            },

            _getTitleAttr: function(){
                return this.titleNode.innerHTML;
            },

            _show: function(){
                domConstruct.place(this.tooltip, document.body, 'last');
                domClass.remove(this.tooltip, 'hidden');
                domClass.add(this.tooltip, 'in ' + this.placement);
                this._position();
            },

            _hide: function(){
                domClass.remove(this.tooltip, 'in top bottom left right');
                domClass.add(this.tooltip, 'hidden');
            },

            _position: function() {
                var targetPos = domGeom.position(this.target, true),
                    tooltipPos = domGeom.position(this.tooltip, true),
                    left,
                    top;

                switch (this.placement){
                    case 'left':
                    case 'right':
                        top = targetPos.y + targetPos.h /2 - tooltipPos.h /2;
                        break;
                    case 'top':
                        top = targetPos.y - tooltipPos.h;
                        break;
                    case 'bottom':
                        top = targetPos.y + targetPos.h;
                        break;
                }
                this.tooltip.style.top = top + 'px';

                switch (this.placement){
                    case 'left':
                        left = targetPos.x - tooltipPos.w;
                        break;
                    case 'right':
                        left = targetPos.x + targetPos.w;
                        break;
                    case 'top':
                    case 'bottom':
                        left = targetPos.x + targetPos.w / 2 - tooltipPos.w / 2;
                        break;
                }
                this.tooltip.style.left = left + 'px';
            }
        }
    );
});
<commit_msg>fix tooltip so it will hide if target is disabled<commit_after>define([
    'dojo/_base/declare',
    'dojo/_base/lang',
    'dojo/on',
    'dojo/dom',
    'dojo/dom-construct',
    'dojo/dom-class',
    'dojo/dom-geometry',
    './_WidgetBase',
    './_HideableMixin',
    'dojo/text!./template/Tooltip.html',
    '../less!./less/tooltip.less'
],
function(
    declare,
    lang,
    on,
    dom,
    domConstruct,
    domClass,
    domGeom,
    WidgetBase,
    HideableMixin,
    template
){
    // module:
    //		havok/widget/Tooltip

    return declare(
        [WidgetBase, HideableMixin],
        {
            // summary:
            //      Widget to display tooltips.

            // templateString: String
            templateString: template,

            // showOn: String
            //      The name of the event to trigger tooltip show
            showOn: 'mouseover',

            // hideOn: String
            //      The name of the event to trigger tooltip hide
            hideOn: 'mouseout',

            /*=====
            // title: String
            //      The content to show in the tooltip
            title: undefined,
            =====*/

            // placement: String
            //      Where to place the tooltip relative to target.
            //      May be top | bottom | left | right
            //      Defaults to `top`
            placement: 'top',

            // hidden: Boolean
            //      Is the tooltip hidden?
            //      Defalts to `true`
            hidden: true,

            /*=====
            // target: DomNode
            //      The dom node which the tooltip will be displayed next to
            target: undefined,
            =====*/

            // tag: String
            //      The tag that the tooltip will be rendered with.
            //      Defalts to 'span'
            tag: 'span',

            startup: function(){

                this.inherited(arguments);

                if (!this.target) this.target = this.domNode;
                if (typeof this.target == 'string') this.target = dom.byId(this.target);

                if (this.showOn) {
                    on(this.target, this.showOn, lang.hitch(this, function(e){
                        e.preventDefault();
                        this.show();
                    }))
                }
                if (this.hideOn) {
                    on(this.target, this.hideOn, lang.hitch(this, function(e){
                        e.preventDefault();
                        this.hide();
                    }))
                }
            },

            _setTitleAttr: function(value){
                this.titleNode.innerHTML = value;
            },

            _getTitleAttr: function(){
                return this.titleNode.innerHTML;
            },

            _show: function(){
                domConstruct.place(this.tooltip, document.body, 'last');
                domClass.remove(this.tooltip, 'hidden');
                domClass.add(this.tooltip, 'in ' + this.placement);
                this._position();

                //make sure tooltip gets hidden if target is disabled
                this._observer = new MutationObserver(lang.hitch(this, function(){
                    if (this.target.hasAttribute('disabled')){
                        this.hide();
                        this._observer.disconnect();
                    }
                }))
                this._observer.observe(this.target, {attributes: true});
            },

            _hide: function(){
                domClass.remove(this.tooltip, 'in top bottom left right');
                domClass.add(this.tooltip, 'hidden');
            },

            _position: function() {
                var targetPos = domGeom.position(this.target, true),
                    tooltipPos = domGeom.position(this.tooltip, true),
                    left,
                    top;

                switch (this.placement){
                    case 'left':
                    case 'right':
                        top = targetPos.y + targetPos.h /2 - tooltipPos.h /2;
                        break;
                    case 'top':
                        top = targetPos.y - tooltipPos.h;
                        break;
                    case 'bottom':
                        top = targetPos.y + targetPos.h;
                        break;
                }
                this.tooltip.style.top = top + 'px';

                switch (this.placement){
                    case 'left':
                        left = targetPos.x - tooltipPos.w;
                        break;
                    case 'right':
                        left = targetPos.x + targetPos.w;
                        break;
                    case 'top':
                    case 'bottom':
                        left = targetPos.x + targetPos.w / 2 - tooltipPos.w / 2;
                        break;
                }
                this.tooltip.style.left = left + 'px';
            }
        }
    );
});
<|endoftext|>


<commit_before>describe('SharePoint REST API Wrapper', function () {
  'use strict';
  it('should have a namespace', function () {
    expect(sputils).to.have.ownProperty('rest');
  });

  beforeEach(function () {
    initialize_jquery();
  });

  describe('get', function () {
    it('should have correct config settings', function (done) {
      // Mock jQuery ajax
      jQuery.ajax = function (config) {
        expect(config)
          .to.have.deep.property('headers.accept',
                                 'application/json;odata=verbose');
        expect(config)
          .to.have.property('url');
        expect(config)
          .to.have.property('type', 'GET');
      };

      sputils.rest.get("/")
        .then(function (res) {
          done();
        });
    });
  });

  describe('post', function () {
    it('should have correct config settings', function (done) {

      // Post requests require a request digest.
      // We manually write this to the document.
      /* jshint evil: true */
      document.write("<input id=__REQUESTDIGEST value=TestValue />");
      /* jshint evil: false */

      // Mock jQuery ajax
      jQuery.ajax = function (config) {
        console.log(config);
        expect(config)
          .to.have.deep.property('headers.accept',
                                 'application/json;odata=verbose');
        expect(config)
          .to.have.deep.property('headers.X-RequestDigest',
                                 'TestValue');
        expect(config)
          .to.have.property('url');
        expect(config)
          .to.have.property('type', 'POST');
        expect(config)
          .to.have.property('data', '{"test":"test"}');
      };

      sputils.rest.post("/", {"test":"test"})
        .then(function (res) {
          done();
        });
    });
  });
});
<commit_msg>Cleans up console.log<commit_after>describe('SharePoint REST API Wrapper', function () {
  'use strict';
  it('should have a namespace', function () {
    expect(sputils).to.have.ownProperty('rest');
  });

  beforeEach(function () {
    initialize_jquery();
  });

  describe('get', function () {
    it('should have correct config settings', function (done) {
      // Mock jQuery ajax
      jQuery.ajax = function (config) {
        expect(config)
          .to.have.deep.property('headers.accept',
                                 'application/json;odata=verbose');
        expect(config)
          .to.have.property('url');
        expect(config)
          .to.have.property('type', 'GET');
      };

      sputils.rest.get("/")
        .then(function (res) {
          done();
        });
    });
  });

  describe('post', function () {
    it('should have correct config settings', function (done) {

      // Post requests require a request digest.
      // We manually write this to the document.
      /* jshint evil: true */
      document.write("<input id=__REQUESTDIGEST value=TestValue />");
      /* jshint evil: false */

      // Mock jQuery ajax
      jQuery.ajax = function (config) {
        expect(config)
          .to.have.deep.property('headers.accept',
                                 'application/json;odata=verbose');
        expect(config)
          .to.have.deep.property('headers.X-RequestDigest',
                                 'TestValue');
        expect(config)
          .to.have.property('url');
        expect(config)
          .to.have.property('type', 'POST');
        expect(config)
          .to.have.property('data', '{"test":"test"}');
      };

      sputils.rest.post("/", {"test":"test"})
        .then(function (res) {
          done();
        });
    });
  });
});
<|endoftext|>


<commit_before>/* ========================================================================
 * StorageAPI: storage_test.js v0.0.1
 * Author: Mike Grabowski (@grabbou)
 * Created at: 16/08/2014
 * ========================================================================
 */

'use strict';

/* jshint expr:true */

var expect = require('chai').expect,
	stub = require('sinon').stub,
	spy = require('sinon').spy;

describe('Storage', function () {

	var Storage = require('../lib'),
		_init = stub(Storage.Providers.AmazonS3.prototype, '_init').callsArgWith(0, null),
		_cachedInstance = spy(Storage.Providers, 'AmazonS3');

	beforeEach(function () {
		Storage.init({
			amazon: {
				provider: Storage.Providers.AmazonS3,
				key: '',
				keyId: '',
				container: ''
			}
		});
	});

	describe('#init', function () {

		it('must set up variables correctly', function () {
			Storage.init('config');
			expect(Storage._config).to.equal('config');
		});

		it('should return {Storage} to allow method chaining', function () {
			expect(Storage.init('config')).to.equal(Storage);
		});

	});

	describe('#add', function () {

		it('must set up variables correctly', function () {
			Storage.add('amazon', 'config');
			expect(Storage._config.amazon).to.equal('config');
		});

		it('should return {Storage} to allow method chaining', function () {
			expect(Storage.add('amazon', '')).to.equal(Storage);
		});

	});

	describe('#_getInstance', function () {

		it('should throw an error if instance is missing a config', function () {
			delete Storage._config.amazon;
			expect(function () {
				Storage._getInstance('amazon');
			}).to.throw(/Configuration for amazon is missing/);
		});

		it('should throw an error if no provider set for an instance', function () {
			delete Storage._config.amazon.provider;
			expect(function () {
				Storage._getInstance('amazon');
			}).to.throw(/Provider for amazon is not specified/);
		});

		it('should cache instances', function () {
			Storage._getInstance('amazon');
			Storage._getInstance('amazon');
			expect(_cachedInstance.calledOnce).to.be.true;
		});

	});

	describe('#get', function () {

		it('should call _init on every get', function () {
			Storage.get('amazon', function () {});
			Storage.get('amazon', function () {});
			expect(_init.calledTwice).to.be.true;
		});

		it.skip('should assign default instance if null', function (next) {
			Storage.get(function (err, client) {
				expect(client).to.be.an.instanceof(Storage.Providers.AmazonS3);
				next();
			});
		});

	});

	describe('#pre', function () {

		it.skip('should set local hook', function () {

		});

		it.skip('should set global hook', function () {

		});

	});

	describe('#post', function () {

		it.skip('should set local hook', function () {

		});

		it.skip('should set global hook', function () {

		});

	});

});<commit_msg>Removed unnecessary test cases<commit_after>/* ========================================================================
 * StorageAPI: storage_test.js v0.0.1
 * Author: Mike Grabowski (@grabbou)
 * Created at: 16/08/2014
 * ========================================================================
 */

'use strict';

/* jshint expr:true */

var expect = require('chai').expect,
	stub = require('sinon').stub,
	spy = require('sinon').spy;

describe('Storage', function () {

	var Storage = require('../lib'),
		_init = stub(Storage.Providers.AmazonS3.prototype, '_init').callsArgWith(0, null),
		_cachedInstance = spy(Storage.Providers, 'AmazonS3');

	beforeEach(function () {
		Storage.init({
			amazon: {
				provider: Storage.Providers.AmazonS3,
				key: '',
				keyId: '',
				container: ''
			}
		});
	});

	describe('#init', function () {

		it('must set up variables correctly', function () {
			expect(Storage._config).to.have.property('amazon');
		});

	});

	describe('#add', function () {

		it('must set up variables correctly', function () {
			Storage.add('custom', '');
			expect(Storage._config).to.have.property('custom');
		});

	});

	describe('#_getInstance', function () {

		it('should throw an error if instance is missing a config', function () {
			delete Storage._config.amazon;
			expect(function () {
				Storage._getInstance('amazon');
			}).to.throw(/Configuration for amazon is missing/);
		});

		it('should throw an error if no provider set for an instance', function () {
			delete Storage._config.amazon.provider;
			expect(function () {
				Storage._getInstance('amazon');
			}).to.throw(/Provider for amazon is not specified/);
		});

		it('should cache instances', function () {
			Storage._getInstance('amazon');
			Storage._getInstance('amazon');
			expect(_cachedInstance.calledOnce).to.be.true;
		});

	});

	describe('#get', function () {

		it('should call _init on every get', function () {
			Storage.get('amazon', function () {});
			Storage.get('amazon', function () {});
			expect(_init.calledTwice).to.be.true;
		});

		it.skip('should assign default instance if null', function (next) {
			Storage.get(function (err, client) {
				expect(client).to.be.an.instanceof(Storage.Providers.AmazonS3);
				next();
			});
		});

	});

	describe('#pre', function () {

		it.skip('should set local hook', function () {

		});

		it.skip('should set global hook', function () {

		});

	});

	describe('#post', function () {

		it.skip('should set local hook', function () {

		});

		it.skip('should set global hook', function () {

		});

	});

});<|endoftext|>


<commit_before>d3plus.method.time = {
  "accepted"    : [ Array , Boolean , Function , Object , String ],
  "dataFilter"  : true,
  "deprecates"  : [ "year" , "year_var" ],
  "fixed"       : {
    "accepted"   : [ Boolean ],
    "deprecates" : [ "static_axis" , "static_axes" ],
    "value"      : true
  },
  "mute"        : d3plus.method.filter(false),
  "solo"        : d3plus.method.filter(false),
  "value"       : false
}
<commit_msg>added "format" variable to .time()<commit_after>d3plus.method.time = {
  "accepted"    : [ Array , Boolean , Function , Object , String ],
  "dataFilter"  : true,
  "deprecates"  : [ "year" , "year_var" ],
  "fixed"       : {
    "accepted"   : [ Boolean ],
    "deprecates" : [ "static_axis" , "static_axes" ],
    "value"      : true
  },
  "format"      : {
    "accepted" : [false, String],
    "value"    : false
  },
  "mute"        : d3plus.method.filter(false),
  "solo"        : d3plus.method.filter(false),
  "value"       : false
}
<|endoftext|>


<commit_before>const path = require('path')

/**
 * this file is supposed to be run in node to test the examples
 * one can run `npm run start vuex` and get the vuex example
 * launch `npm run build vuetify` and there you have it, the built vuetify example
 */

var examplePath = process.argv[3] || 'basic'
if (/^--/.test(examplePath)) {
	examplePath = 'basic'
}

if (examplePath.indexOf('examples/') !== 0) {
	examplePath = 'examples/' + examplePath
}

if (/^examples[\\/]vuecli3/.test(examplePath) || examplePath === 'examples/svg-loader') {
	process.chdir(`./${examplePath}`)
	const command = process.argv[2] === 'server' ? '' : `:${process.argv[2]}`
	process.argv[2] = `styleguidist${command}`
	require('@vue/cli-service/bin/vue-cli-service')
} else if (/^examples[\\/]docgen/.test(examplePath)) {
	const command = process.argv[2]
	process.argv[2] = process.argv[3]
	process.argv[3] = command === 'server' ? 'dev' : command
	require('./run.cli')
} else {
	process.chdir(path.join(__dirname, '..', `./${examplePath}`))
	require('../packages/vue-styleguidist/lib/bin/styleguidist')
}
<commit_msg>build: simplify styleguidist tester<commit_after>const path = require('path')

/**
 * this file is supposed to be run in node to test the examples
 * one can run `npm run start vuex` and get the vuex example
 * launch `npm run build vuetify` and there you have it, the built vuetify example
 */

var examplePath = process.argv[3] || 'basic'
if (/^--/.test(examplePath)) {
	examplePath = 'basic'
}

if (examplePath.indexOf('examples/') !== 0) {
	examplePath = 'examples/' + examplePath
}

if (/^examples[\\/]vuecli3/.test(examplePath) || examplePath === 'examples/svg-loader') {
	process.chdir(`./${examplePath}`)
	const command = process.argv[2] === 'server' ? '' : `:${process.argv[2]}`
	process.argv[2] = `styleguidist${command}`
	require('@vue/cli-service/bin/vue-cli-service')
} else if (/^examples[\\/]docgen/.test(examplePath)) {
	const command = process.argv[2]
	process.argv[2] = process.argv[3]
	process.argv[3] = command === 'server' ? 'dev' : command
	require('./run.cli')
} else {
	process.chdir(path.join(__dirname, `../${examplePath}`))
	require('../packages/vue-styleguidist/lib/bin/styleguidist')
}
<|endoftext|>


<commit_before>QUnit.test("cogroup()", function(assert)
{
	var result = Canal.of([ [ "a", 1 ], [ "b", 2 ], [ "b", 3 ], [ "c", 4 ] ])
			.cogroup(Canal.of([ [ "b", 1 ], [ "c", 2 ] ])).collect();
	assert.deepEqual(result, [ [ "a", [ [ 1 ], [] ] ],
			[ "b", [ [ 2, 3 ], [ 1 ] ] ], [ "c", [ [ 4 ], [ 2 ] ] ] ]);
});

QUnit.test("cogroup() 1 vs empty", function(assert)
{
	var result = Canal.of([ [ "a", 1 ] ]).cogroup(Canal.of([])).collect();
	assert.deepEqual(result, [ [ "a", [ [ 1 ], [] ] ] ]);
});

QUnit.test("cogroup() empty vs 1", function(assert)
{
	var result = Canal.of([]).cogroup(Canal.of([ [ "a", 1 ] ])).collect();
	assert.deepEqual(result, [ [ "a", [ [], [ 1 ] ] ] ]);
});

QUnit.test("cogroup() 2 vs 3 vs 1", function(assert)
{
	var result = Canal.of([ [ "a", 1 ], [ "b", 2 ] ]).cogroup(
			Canal.of([ [ "a", 1 ], [ "b", 2 ], [ "b", 3 ] ]),
			Canal.of([ [ "c", 4 ] ])).collect();
	assert.deepEqual(result, [ [ "a", [ [ 1 ], [ 1 ], [] ] ],
			[ "b", [ [ 2 ], [ 2, 3 ], [] ] ], [ "c", [ [], [], [ 4 ] ] ] ]);
});

QUnit.test("cogroup() empty vs empty", function(assert)
{
	var result = Canal.of([]).cogroup(Canal.of([])).collect();
	assert.deepEqual(result, []);
});
<commit_msg>Add stringify of json in cogroup test case.<commit_after>QUnit.test("cogroup()", function(assert)
{
	var result = Canal.of([ [ "a", 1 ], [ "b", 2 ], [ "b", 3 ], [ "c", 4 ] ])
			.cogroup(Canal.of([ [ "b", 1 ], [ "c", 2 ] ])).collect();
	console.log(JSON.stringify(result));
	assert.propEqual(result, [ [ "a", [ [ 1 ], [] ] ],
			[ "b", [ [ 2, 3 ], [ 1 ] ] ], [ "c", [ [ 4 ], [ 2 ] ] ] ]);
});

QUnit.test("cogroup() 1 vs empty", function(assert)
{
	var result = Canal.of([ [ "a", 1 ] ]).cogroup(Canal.of([])).collect();
	assert.propEqual(result, [ [ "a", [ [ 1 ], [] ] ] ]);
});

QUnit.test("cogroup() empty vs 1", function(assert)
{
	var result = Canal.of([]).cogroup(Canal.of([ [ "a", 1 ] ])).collect();
	assert.propEqual(result, [ [ "a", [ [], [ 1 ] ] ] ]);
});

QUnit.test("cogroup() 2 vs 3 vs 1", function(assert)
{
	var result = Canal.of([ [ "a", 1 ], [ "b", 2 ] ]).cogroup(
			Canal.of([ [ "a", 1 ], [ "b", 2 ], [ "b", 3 ] ]),
			Canal.of([ [ "c", 4 ] ])).collect();
	assert.propEqual(result, [ [ "a", [ [ 1 ], [ 1 ], [] ] ],
			[ "b", [ [ 2 ], [ 2, 3 ], [] ] ], [ "c", [ [], [], [ 4 ] ] ] ]);
});

QUnit.test("cogroup() empty vs empty", function(assert)
{
	var result = Canal.of([]).cogroup(Canal.of([])).collect();
	assert.propEqual(result, []);
});
<|endoftext|>